fix: close competition cutover integrity gaps
This commit is contained in:
1 parent
7ea2002975
commit
683d602d63
57 files changed
+4805
-1582
No files matched your search
@@ -1,7 +1,9 @@
|
||||
import 'reflect-metadata';
|
||||
import { BadRequestException, ValidationPipe } from '@nestjs/common';
|
||||
import { plainToInstance } from 'class-transformer';
|
||||
import { validateSync } from 'class-validator';
|
||||
import { CreateMatchDto } from './create-match.dto';
|
||||
import mongoose from 'mongoose';
|
||||
import { CreateMatchDto, JoinMatchDto } from './create-match.dto';
|
||||
|
||||
describe('CreateMatchDto game mode cutover', () => {
|
||||
it('rejects the removed live bracket mode', () => {
|
||||
@@ -31,3 +33,31 @@ describe('CreateMatchDto game mode cutover', () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('JoinMatchDto self-join boundary', () => {
|
||||
it('rejects a caller-supplied userId', async () => {
|
||||
const pipe = new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
});
|
||||
|
||||
try {
|
||||
await pipe.transform(
|
||||
{
|
||||
preferredPositions: [{ position: 'MID', priority: 1 }],
|
||||
userId: new mongoose.Types.ObjectId().toString(),
|
||||
},
|
||||
{ type: 'body', metatype: JoinMatchDto },
|
||||
);
|
||||
throw new Error('Expected validation to reject userId.');
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(BadRequestException);
|
||||
expect((error as BadRequestException).getResponse()).toEqual({
|
||||
error: 'Bad Request',
|
||||
message: ['property userId should not exist'],
|
||||
statusCode: 400,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -215,10 +215,6 @@ export class JoinMatchDto {
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => PositionPreferenceDto)
|
||||
preferredPositions!: PositionPreferenceDto[];
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
userId?: string;
|
||||
}
|
||||
|
||||
export class AddParticipantDto {
|
||||
@@ -234,13 +230,3 @@ export class AddParticipantDto {
|
||||
@IsString()
|
||||
riotPuuid?: string;
|
||||
}
|
||||
|
||||
export class SwapDoubleEliminationSeedsDto {
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
leftSeedNumber!: number;
|
||||
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
rightSeedNumber!: number;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ describe('presentPublicMatch', () => {
|
||||
competitionId: oid('3'),
|
||||
shortCode: '33NW',
|
||||
title: '내전',
|
||||
joined: false,
|
||||
description: '설명',
|
||||
mapId: 11,
|
||||
status: 'in-progress',
|
||||
@@ -25,6 +26,16 @@ describe('presentPublicMatch', () => {
|
||||
gameName: '선수',
|
||||
tagLine: 'KR1',
|
||||
profileIconId: 1,
|
||||
tier: {
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'GOLD',
|
||||
rank: 'I',
|
||||
leaguePoints: 42,
|
||||
wins: 10,
|
||||
losses: 5,
|
||||
fetchedAt: new Date('2026-07-10T00:00:00.000Z'),
|
||||
puuid: 'secret-tier-puuid',
|
||||
},
|
||||
preferredPositions: [
|
||||
{ position: 'MID', priority: 1 },
|
||||
{ position: 'SUP', priority: 2 },
|
||||
@@ -65,6 +76,15 @@ describe('presentPublicMatch', () => {
|
||||
expect.objectContaining({
|
||||
userId: oid('5').toString(),
|
||||
joinedAt: '2026-07-01T00:00:00.000Z',
|
||||
tier: {
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'GOLD',
|
||||
rank: 'I',
|
||||
leaguePoints: 42,
|
||||
wins: 10,
|
||||
losses: 5,
|
||||
fetchedAt: '2026-07-10T00:00:00.000Z',
|
||||
},
|
||||
}),
|
||||
],
|
||||
teams: [
|
||||
@@ -89,6 +109,7 @@ describe('presentPublicMatch', () => {
|
||||
expect(response).not.toHaveProperty('resultPollState');
|
||||
expect(response).not.toHaveProperty('legacyImportSource');
|
||||
expect(response.participants[0]).not.toHaveProperty('puuid');
|
||||
expect(response.participants[0]?.tier).not.toHaveProperty('puuid');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { MatchDetailResponse, MatchTierView } from '@lolympus/contracts';
|
||||
import type {
|
||||
MatchGameMode,
|
||||
MatchStatus,
|
||||
@@ -57,12 +58,12 @@ interface PublicMatchSource {
|
||||
export function presentPublicMatch(
|
||||
source: PublicMatchSource,
|
||||
options: { joined?: boolean } = {},
|
||||
) {
|
||||
): MatchDetailResponse {
|
||||
return {
|
||||
_id: source._id.toString(),
|
||||
communityId: source.communityId.toString(),
|
||||
_id: source._id.toString() as never,
|
||||
communityId: source.communityId.toString() as never,
|
||||
...(source.competitionId
|
||||
? { competitionId: source.competitionId.toString() }
|
||||
? { competitionId: source.competitionId.toString() as never }
|
||||
: {}),
|
||||
...(source.shortCode ? { shortCode: source.shortCode } : {}),
|
||||
title: source.title,
|
||||
@@ -82,32 +83,37 @@ export function presentPublicMatch(
|
||||
source.doubleElimination?.resetFinalEnabled ?? false,
|
||||
}
|
||||
: {}),
|
||||
...(source.hostUserId ? { hostUserId: source.hostUserId.toString() } : {}),
|
||||
participants: source.participants.map((participant) => ({
|
||||
userId: participant.userId.toString(),
|
||||
...(participant.gameName ? { gameName: participant.gameName } : {}),
|
||||
...(participant.tagLine ? { tagLine: participant.tagLine } : {}),
|
||||
...(participant.profileIconId === undefined
|
||||
? {}
|
||||
: { profileIconId: participant.profileIconId }),
|
||||
...(participant.tier === undefined
|
||||
? {}
|
||||
: { tier: toWireValue(participant.tier) }),
|
||||
preferredPositions: participant.preferredPositions.map((preference) => ({
|
||||
position: preference.position,
|
||||
priority: preference.priority,
|
||||
})),
|
||||
joinedAt: asIso(participant.joinedAt),
|
||||
excluded: participant.excluded ?? false,
|
||||
})),
|
||||
...(source.hostUserId
|
||||
? { hostUserId: source.hostUserId.toString() as never }
|
||||
: {}),
|
||||
participants: source.participants.map((participant) => {
|
||||
const tier = toPublicTier(participant.tier);
|
||||
return {
|
||||
userId: participant.userId.toString() as never,
|
||||
...(participant.gameName ? { gameName: participant.gameName } : {}),
|
||||
...(participant.tagLine ? { tagLine: participant.tagLine } : {}),
|
||||
...(participant.profileIconId === undefined
|
||||
? {}
|
||||
: { profileIconId: participant.profileIconId }),
|
||||
...(tier ? { tier } : {}),
|
||||
preferredPositions: participant.preferredPositions.map(
|
||||
(preference) => ({
|
||||
position: preference.position,
|
||||
priority: preference.priority,
|
||||
}),
|
||||
),
|
||||
joinedAt: asIso(participant.joinedAt),
|
||||
excluded: participant.excluded ?? false,
|
||||
};
|
||||
}),
|
||||
teams: source.teams.map((team) => ({
|
||||
teamIndex: team.teamIndex,
|
||||
name: team.name,
|
||||
...(team.captainUserId
|
||||
? { captainUserId: team.captainUserId.toString() }
|
||||
? { captainUserId: team.captainUserId.toString() as never }
|
||||
: {}),
|
||||
members: team.members.map((member) => ({
|
||||
userId: member.userId.toString(),
|
||||
userId: member.userId.toString() as never,
|
||||
assignedPosition: member.assignedPosition,
|
||||
...(member.cost === undefined ? {} : { cost: member.cost }),
|
||||
})),
|
||||
@@ -115,7 +121,7 @@ export function presentPublicMatch(
|
||||
prizes: [...source.prizes],
|
||||
notices: [...source.notices],
|
||||
schedule: source.schedule.map(({ time, label }) => ({ time, label })),
|
||||
...(options.joined === undefined ? {} : { joined: options.joined }),
|
||||
joined: options.joined ?? false,
|
||||
createdAt: asIso(source.createdAt),
|
||||
updatedAt: asIso(source.updatedAt),
|
||||
};
|
||||
@@ -125,13 +131,29 @@ function asIso(value: Date | string): string {
|
||||
return value instanceof Date ? value.toISOString() : value;
|
||||
}
|
||||
|
||||
function toWireValue(value: unknown): unknown {
|
||||
if (value instanceof Date) return value.toISOString();
|
||||
if (Array.isArray(value)) return value.map(toWireValue);
|
||||
if (typeof value === 'object' && value !== null) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).map(([key, child]) => [key, toWireValue(child)]),
|
||||
);
|
||||
function toPublicTier(value: unknown): MatchTierView | undefined {
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||
return undefined;
|
||||
}
|
||||
return value;
|
||||
const tier = value as Record<string, unknown>;
|
||||
if (
|
||||
typeof tier.queueType !== 'string' ||
|
||||
typeof tier.tier !== 'string' ||
|
||||
typeof tier.rank !== 'string' ||
|
||||
typeof tier.leaguePoints !== 'number' ||
|
||||
typeof tier.wins !== 'number' ||
|
||||
typeof tier.losses !== 'number' ||
|
||||
!(typeof tier.fetchedAt === 'string' || tier.fetchedAt instanceof Date)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
queueType: tier.queueType,
|
||||
tier: tier.tier,
|
||||
rank: tier.rank,
|
||||
leaguePoints: tier.leaguePoints,
|
||||
wins: tier.wins,
|
||||
losses: tier.losses,
|
||||
fetchedAt: asIso(tier.fetchedAt),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import 'reflect-metadata';
|
||||
import { GUARDS_METADATA } from '@nestjs/common/constants';
|
||||
import mongoose from 'mongoose';
|
||||
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator';
|
||||
import { ROLES_KEY } from '../auth/roles.decorator';
|
||||
import { RolesGuard } from '../auth/roles.guard';
|
||||
import type { UserDocument } from '../global/database/schema';
|
||||
import { MatchController } from './match.controller';
|
||||
|
||||
describe('MatchController participant access', () => {
|
||||
function createController() {
|
||||
const joinedMatch = { _id: new mongoose.Types.ObjectId() };
|
||||
const response = { _id: joinedMatch._id.toString(), joined: true };
|
||||
const matchService = {
|
||||
join: jest.fn().mockResolvedValue(joinedMatch),
|
||||
serialize: jest.fn().mockReturnValue(response),
|
||||
};
|
||||
|
||||
return {
|
||||
controller: new MatchController(matchService as never),
|
||||
joinedMatch,
|
||||
matchService,
|
||||
response,
|
||||
};
|
||||
}
|
||||
|
||||
function createUser(communityId: mongoose.Types.ObjectId): UserDocument {
|
||||
return {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
communityId,
|
||||
role: 'member',
|
||||
} as UserDocument;
|
||||
}
|
||||
|
||||
it('requires an authenticated community member for the self-join route', () => {
|
||||
// Metadata must be read from the unbound prototype method itself.
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
const handler = MatchController.prototype.joinMatch;
|
||||
const roles = Reflect.getMetadata(ROLES_KEY, handler) as
|
||||
| string[]
|
||||
| undefined;
|
||||
const guards = Reflect.getMetadata(GUARDS_METADATA, handler) as
|
||||
| unknown[]
|
||||
| undefined;
|
||||
|
||||
expect(
|
||||
Reflect.getMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, handler),
|
||||
).not.toBe(true);
|
||||
expect(roles).toHaveLength(3);
|
||||
expect(roles).toEqual(expect.arrayContaining(['owner', 'admin', 'member']));
|
||||
expect(guards).toEqual(expect.arrayContaining([RolesGuard]));
|
||||
});
|
||||
|
||||
it('joins only the authenticated user', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const currentUser = createUser(communityId);
|
||||
const preferredPositions = [{ position: 'MID' as const, priority: 1 }];
|
||||
const { controller, joinedMatch, matchService, response } =
|
||||
createController();
|
||||
|
||||
await expect(
|
||||
controller.joinMatch(currentUser, communityId, matchId, {
|
||||
preferredPositions,
|
||||
}),
|
||||
).resolves.toBe(response);
|
||||
expect(matchService.join).toHaveBeenCalledWith({
|
||||
matchId,
|
||||
communityId,
|
||||
userId: currentUser._id,
|
||||
preferredPositions,
|
||||
});
|
||||
expect(matchService.serialize).toHaveBeenCalledWith(joinedMatch, {
|
||||
joined: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a dev-auth user from a different URL community', async () => {
|
||||
const currentUser = createUser(new mongoose.Types.ObjectId());
|
||||
const requestedCommunityId = new mongoose.Types.ObjectId();
|
||||
const { controller, matchService } = createController();
|
||||
|
||||
await expect(
|
||||
controller.joinMatch(
|
||||
currentUser,
|
||||
requestedCommunityId,
|
||||
new mongoose.Types.ObjectId(),
|
||||
{ preferredPositions: [{ position: 'TOP', priority: 1 }] },
|
||||
),
|
||||
).rejects.toThrow('Different community.');
|
||||
expect(matchService.join).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,7 @@
|
||||
import type {
|
||||
MatchDetailResponse,
|
||||
MatchListResponse,
|
||||
} from '@lolympus/contracts';
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
@@ -23,7 +27,6 @@ import {
|
||||
AddParticipantDto,
|
||||
CreateMatchDto,
|
||||
JoinMatchDto,
|
||||
SwapDoubleEliminationSeedsDto,
|
||||
UpdateMatchDto,
|
||||
UpdateParticipantDto,
|
||||
} from './dto/create-match.dto';
|
||||
@@ -41,9 +44,9 @@ export class MatchController {
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Body() body: CreateMatchDto,
|
||||
) {
|
||||
): Promise<MatchDetailResponse> {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
return this.matchService.create({
|
||||
const match = await this.matchService.create({
|
||||
communityId,
|
||||
hostUserId: currentUser._id,
|
||||
data: {
|
||||
@@ -62,6 +65,7 @@ export class MatchController {
|
||||
schedule: body.schedule ?? [],
|
||||
},
|
||||
});
|
||||
return this.matchService.serialize(match, { joined: false });
|
||||
}
|
||||
|
||||
// 공개 — 커뮤니티 내 매치 리스트. 로그인 시 본인 참여 여부를 함께 반환.
|
||||
@@ -78,7 +82,7 @@ export class MatchController {
|
||||
@Query('scheduledFrom') scheduledFrom?: string,
|
||||
@Query('scheduledTo') scheduledTo?: string,
|
||||
@Query('sort') sort?: 'asc' | 'desc',
|
||||
) {
|
||||
): Promise<MatchListResponse> {
|
||||
const result = await this.matchService.listPage({
|
||||
communityId,
|
||||
status,
|
||||
@@ -108,10 +112,20 @@ export class MatchController {
|
||||
@Get(':matchId')
|
||||
@AllowPublicAccess()
|
||||
public async getMatch(
|
||||
@CurrentUser() currentUser: UserDocument | undefined,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
) {
|
||||
const match = await this.matchService.getById(matchId);
|
||||
return this.matchService.serialize(match);
|
||||
): Promise<MatchDetailResponse> {
|
||||
const match = await this.matchService.getById(matchId, communityId);
|
||||
return this.matchService.serialize(match, {
|
||||
joined: Boolean(
|
||||
currentUser &&
|
||||
match.participants.some((participant) =>
|
||||
participant.userId.equals(currentUser._id),
|
||||
),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
@Patch(':matchId')
|
||||
@@ -123,48 +137,18 @@ export class MatchController {
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Body() body: UpdateMatchDto,
|
||||
) {
|
||||
): Promise<MatchDetailResponse> {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
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({
|
||||
const match = await this.matchService.update({
|
||||
matchId,
|
||||
communityId,
|
||||
actorUserId: currentUser._id,
|
||||
patch: body,
|
||||
});
|
||||
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, {
|
||||
joined: match.participants.some((participant) =>
|
||||
participant.userId.equals(currentUser._id),
|
||||
),
|
||||
});
|
||||
return this.matchService.serialize(match);
|
||||
}
|
||||
|
||||
@Delete(':matchId')
|
||||
@@ -181,20 +165,25 @@ export class MatchController {
|
||||
await this.matchService.remove({ matchId, communityId });
|
||||
}
|
||||
|
||||
// 공개 — 참여 (로그인된 유저는 자기 자신, 비로그인은 body.userId 사용).
|
||||
// 커뮤니티 멤버 본인 참여. 다른 유저 추가는 관리자 전용 경로를 사용한다.
|
||||
@Post(':matchId/participants')
|
||||
@AllowPublicAccess()
|
||||
@Roles('owner', 'admin', 'member')
|
||||
@UseGuards(RolesGuard)
|
||||
public async joinMatch(
|
||||
@CurrentUser() currentUser: UserDocument | undefined,
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Body() body: JoinMatchDto,
|
||||
) {
|
||||
const userId = this.resolveJoinerUserId(currentUser, body.userId);
|
||||
return this.matchService.join({
|
||||
): Promise<MatchDetailResponse> {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
const match = await this.matchService.join({
|
||||
matchId,
|
||||
userId,
|
||||
communityId,
|
||||
userId: currentUser._id,
|
||||
preferredPositions: body.preferredPositions,
|
||||
});
|
||||
return this.matchService.serialize(match, { joined: true });
|
||||
}
|
||||
|
||||
// 관리자 전용 — 커뮤니티 유저를 모집중 매치에 직접 추가한다.
|
||||
@@ -208,15 +197,20 @@ export class MatchController {
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
|
||||
@Body() body: AddParticipantDto | undefined,
|
||||
) {
|
||||
): Promise<MatchDetailResponse> {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
const match = await this.matchService.join({
|
||||
matchId,
|
||||
communityId,
|
||||
userId,
|
||||
preferredPositions: body?.preferredPositions,
|
||||
riotPuuid: body?.riotPuuid,
|
||||
});
|
||||
return this.matchService.serialize(match);
|
||||
return this.matchService.serialize(match, {
|
||||
joined: match.participants.some((participant) =>
|
||||
participant.userId.equals(currentUser._id),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
// 관리자 전용 — 참가자 주/부 포지션 변경.
|
||||
@@ -230,7 +224,7 @@ export class MatchController {
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
|
||||
@Body() body: UpdateParticipantDto,
|
||||
) {
|
||||
): Promise<MatchDetailResponse> {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
const match = await this.matchService.updateParticipantPositions({
|
||||
matchId,
|
||||
@@ -239,7 +233,11 @@ export class MatchController {
|
||||
mainPosition: body.mainPosition,
|
||||
subPosition: body.subPosition,
|
||||
});
|
||||
return this.matchService.serialize(match);
|
||||
return this.matchService.serialize(match, {
|
||||
joined: match.participants.some((participant) =>
|
||||
participant.userId.equals(currentUser._id),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
// 관리자 전용 — 참가자 강제 제외.
|
||||
@@ -262,19 +260,6 @@ export class MatchController {
|
||||
});
|
||||
}
|
||||
|
||||
private resolveJoinerUserId(
|
||||
currentUser: UserDocument | undefined,
|
||||
bodyUserId?: string,
|
||||
): mongoose.Types.ObjectId {
|
||||
if (currentUser) return currentUser._id;
|
||||
if (!bodyUserId || !mongoose.isValidObjectId(bodyUserId)) {
|
||||
throw new BadRequestException(
|
||||
'userId is required when not authenticated.',
|
||||
);
|
||||
}
|
||||
return new mongoose.Types.ObjectId(bodyUserId);
|
||||
}
|
||||
|
||||
private assertSameCommunity(
|
||||
user: UserDocument,
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
|
||||
@@ -57,6 +57,7 @@ describe('MatchService', () => {
|
||||
) {
|
||||
const MatchModel = {
|
||||
findById: jest.fn().mockResolvedValue(match),
|
||||
findOne: jest.fn().mockResolvedValue(match),
|
||||
findOneAndUpdate: jest.fn().mockResolvedValue(updatedMatch),
|
||||
};
|
||||
const connectionService = {
|
||||
@@ -203,6 +204,19 @@ describe('MatchService', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('scopes Match detail lookup to the URL community', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const match = { _id: matchId, communityId };
|
||||
const { service, MatchModel } = createService(match);
|
||||
|
||||
await expect(service.getById(matchId, communityId)).resolves.toBe(match);
|
||||
expect(MatchModel.findOne).toHaveBeenCalledWith({
|
||||
_id: matchId,
|
||||
communityId,
|
||||
});
|
||||
});
|
||||
|
||||
it('applies offset before page-based pagination', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const { service, skip } = createServiceWithListModel();
|
||||
@@ -344,6 +358,36 @@ describe('MatchService', () => {
|
||||
expect(match.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not join a user from a different community', async () => {
|
||||
const requestedCommunityId = new mongoose.Types.ObjectId();
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
const user = {
|
||||
_id: userId,
|
||||
communityId: new mongoose.Types.ObjectId(),
|
||||
preferredPositions: [],
|
||||
riotAccounts: [],
|
||||
};
|
||||
const match = {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
communityId: requestedCommunityId,
|
||||
status: 'recruiting',
|
||||
participants: [],
|
||||
};
|
||||
const { service, MatchModel } = createServiceWithJoinModels({
|
||||
user,
|
||||
match,
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.join({
|
||||
matchId: match._id,
|
||||
communityId: requestedCommunityId,
|
||||
userId,
|
||||
}),
|
||||
).rejects.toThrow('Match not found.');
|
||||
expect(MatchModel.findOneAndUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('cancels a join with an atomic participant pull', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
@@ -525,7 +569,7 @@ describe('MatchService', () => {
|
||||
expect(MatchModel.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clears game schedule when a built match returns to recruiting', async () => {
|
||||
it('rejects returning a finalized team build to recruiting', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const match = {
|
||||
communityId,
|
||||
@@ -547,20 +591,23 @@ describe('MatchService', () => {
|
||||
const { service, tournamentCodeService, matchStatsService } =
|
||||
createService(match);
|
||||
|
||||
await service.update({
|
||||
matchId: new mongoose.Types.ObjectId(),
|
||||
communityId,
|
||||
patch: { status: 'recruiting' },
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.update({
|
||||
matchId: new mongoose.Types.ObjectId(),
|
||||
communityId,
|
||||
patch: { status: 'recruiting' },
|
||||
}),
|
||||
).rejects.toThrow('cannot return to recruiting');
|
||||
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
|
||||
expect(match.tournamentCodeIds).toEqual([]);
|
||||
expect(match.gameSchedule).toEqual([]);
|
||||
expect(match.teamBuiltAt).toBeUndefined();
|
||||
expect(match.result).toBeUndefined();
|
||||
expect(match.resultPollState).toBeUndefined();
|
||||
expect(match.save).toHaveBeenCalledTimes(1);
|
||||
expect(matchStatsService.removeByMatch).toHaveBeenCalledWith(match._id);
|
||||
expect(match.gameSchedule).toEqual([
|
||||
{ gameNumber: 1, teamAIndex: 2, teamBIndex: 4 },
|
||||
]);
|
||||
expect(match.teamBuiltAt).toBeInstanceOf(Date);
|
||||
expect(match.result).toEqual({ games: [] });
|
||||
expect(match.resultPollState).toEqual({ state: 'polling' });
|
||||
expect(match.save).not.toHaveBeenCalled();
|
||||
expect(matchStatsService.removeByMatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects round-robin max round changes after recruiting', async () => {
|
||||
@@ -581,12 +628,77 @@ describe('MatchService', () => {
|
||||
patch: { roundRobinMaxRounds: 3 },
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
'maxParticipants, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
|
||||
'maxParticipants, gameCount, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
|
||||
);
|
||||
expect(match.set).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('releases reserved codes when returning a built match to recruiting', async () => {
|
||||
it('rejects game count changes after recruiting', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const match = {
|
||||
communityId,
|
||||
status: 'team-built',
|
||||
tournamentCodeIds: [],
|
||||
set: jest.fn(),
|
||||
save: jest.fn(),
|
||||
};
|
||||
const { service } = createService(match);
|
||||
|
||||
await expect(
|
||||
service.update({
|
||||
matchId: new mongoose.Types.ObjectId(),
|
||||
communityId,
|
||||
patch: { gameCount: 5 },
|
||||
}),
|
||||
).rejects.toThrow('gameCount');
|
||||
expect(match.set).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects returning to recruiting after Competition bootstrap', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const match = {
|
||||
communityId,
|
||||
competitionId: new mongoose.Types.ObjectId(),
|
||||
status: 'team-built',
|
||||
tournamentCodeIds: [],
|
||||
set: jest.fn(),
|
||||
save: jest.fn(),
|
||||
};
|
||||
const { service, tournamentCodeService } = createService(match);
|
||||
|
||||
await expect(
|
||||
service.update({
|
||||
matchId: new mongoose.Types.ObjectId(),
|
||||
communityId,
|
||||
patch: { status: 'recruiting' },
|
||||
}),
|
||||
).rejects.toThrow('cannot return to recruiting');
|
||||
expect(match.set).not.toHaveBeenCalled();
|
||||
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects hard deletion after Competition bootstrap', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const match = {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
communityId,
|
||||
competitionId: new mongoose.Types.ObjectId(),
|
||||
status: 'recruiting',
|
||||
tournamentCodeIds: [],
|
||||
deleteOne: jest.fn(),
|
||||
};
|
||||
const { service, tournamentCodeService, matchStatsService } =
|
||||
createService(match);
|
||||
|
||||
await expect(
|
||||
service.remove({ matchId: match._id, communityId }),
|
||||
).rejects.toThrow('cannot be hard-deleted');
|
||||
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
|
||||
expect(matchStatsService.removeByMatch).not.toHaveBeenCalled();
|
||||
expect(match.deleteOne).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('preserves reserved codes when a recruiting rollback is rejected', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const codeId = new mongoose.Types.ObjectId();
|
||||
const match = {
|
||||
@@ -604,14 +716,18 @@ describe('MatchService', () => {
|
||||
};
|
||||
const { service, tournamentCodeService } = createService(match);
|
||||
|
||||
await service.update({
|
||||
matchId: new mongoose.Types.ObjectId(),
|
||||
communityId,
|
||||
patch: { status: 'recruiting' },
|
||||
});
|
||||
|
||||
expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(match);
|
||||
expect(match.tournamentCodeIds).toEqual([]);
|
||||
expect(match.gameSchedule).toEqual([]);
|
||||
await expect(
|
||||
service.update({
|
||||
matchId: new mongoose.Types.ObjectId(),
|
||||
communityId,
|
||||
patch: { status: 'recruiting' },
|
||||
}),
|
||||
).rejects.toThrow('cannot return to recruiting');
|
||||
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
|
||||
expect(match.tournamentCodeIds).toEqual([codeId]);
|
||||
expect(match.gameSchedule).toEqual([
|
||||
{ gameNumber: 1, teamAIndex: 1, teamBIndex: 3 },
|
||||
]);
|
||||
expect(match.save).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,11 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import {
|
||||
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';
|
||||
@@ -76,6 +73,7 @@ interface MatchListFilter {
|
||||
|
||||
interface JoinMatchParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId?: mongoose.Types.ObjectId;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
preferredPositions?: PositionPreference[];
|
||||
// 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용.
|
||||
@@ -101,17 +99,6 @@ 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;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MatchService {
|
||||
constructor(
|
||||
@@ -197,9 +184,10 @@ export class MatchService {
|
||||
|
||||
public async getById(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): Promise<MatchDocument> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const match = await MatchModel.findById(matchId);
|
||||
const match = await MatchModel.findOne({ _id: matchId, communityId });
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
return match;
|
||||
}
|
||||
@@ -224,15 +212,24 @@ export class MatchService {
|
||||
throw new BadRequestException('Match does not belong to this community.');
|
||||
}
|
||||
const previousStatus = match.status;
|
||||
if (
|
||||
previousStatus !== 'recruiting' &&
|
||||
params.patch.status === 'recruiting'
|
||||
) {
|
||||
throw new ConflictException(
|
||||
'A finalized team build cannot return to recruiting. Preserve its immutable lifecycle and create a new Match instead.',
|
||||
);
|
||||
}
|
||||
if (
|
||||
previousStatus !== 'recruiting' &&
|
||||
('maxParticipants' in params.patch ||
|
||||
'gameCount' 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.',
|
||||
'maxParticipants, gameCount, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
|
||||
);
|
||||
}
|
||||
const patchToSet =
|
||||
@@ -252,21 +249,8 @@ export class MatchService {
|
||||
})
|
||||
: 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) {
|
||||
if (match.result?.games?.length) {
|
||||
await this.matchStatsService.buildAndUpsert(match._id);
|
||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||
}
|
||||
@@ -283,62 +267,31 @@ export class MatchService {
|
||||
if (!match.communityId.equals(params.communityId)) {
|
||||
throw new BadRequestException('Match does not belong to this community.');
|
||||
}
|
||||
if (match.status !== 'recruiting') {
|
||||
throw new ConflictException(
|
||||
'Only a recruiting Match can be hard-deleted. Finalized Match history must be preserved.',
|
||||
);
|
||||
}
|
||||
if (match.competitionId) {
|
||||
throw new ConflictException(
|
||||
'A Match with a Competition cannot be hard-deleted. Preserve the immutable ledger and archive the Match instead.',
|
||||
);
|
||||
}
|
||||
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 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.');
|
||||
if (params.communityId && !user.communityId.equals(params.communityId)) {
|
||||
throw new NotFoundException('Match not found.');
|
||||
}
|
||||
|
||||
const selectedRiot = params.riotPuuid
|
||||
? user.riotAccounts.find((a) => a.puuid === params.riotPuuid)
|
||||
@@ -362,7 +315,7 @@ export class MatchService {
|
||||
const updatedMatch = await MatchModel.findOneAndUpdate(
|
||||
{
|
||||
_id: params.matchId,
|
||||
communityId: user.communityId,
|
||||
communityId: params.communityId ?? user.communityId,
|
||||
status: 'recruiting',
|
||||
'participants.userId': { $ne: user._id },
|
||||
$expr: { $lt: [{ $size: '$participants' }, '$maxParticipants'] },
|
||||
@@ -438,85 +391,6 @@ export class MatchService {
|
||||
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 async releaseReservedDoubleEliminationCodes(
|
||||
match: MatchDocument,
|
||||
): 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',
|
||||
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()),
|
||||
);
|
||||
}
|
||||
|
||||
public async cancelJoin(
|
||||
params: CancelMatchJoinParams,
|
||||
): Promise<MatchDocument> {
|
||||
|
||||
Reference in new issue
Block a user