feat: allow tournament code replacement
This commit is contained in:
1 parent
1272c81fa9
commit
303886ed53
5 files changed
+537
-37
No files matched your search
@@ -7,6 +7,7 @@ import {
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
@@ -71,6 +72,21 @@ export class TournamentCodeController {
|
||||
return this.tournamentCodeService.stats();
|
||||
}
|
||||
|
||||
@Post('matches/:matchId/games/:gameNumber/replace')
|
||||
public async replaceForMatchGame(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Param('gameNumber', ParseIntPipe) gameNumber: number,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
return this.tournamentCodeService.replaceForMatchGame({
|
||||
matchId,
|
||||
gameNumber,
|
||||
});
|
||||
}
|
||||
|
||||
@Post(':id/release')
|
||||
public async restore(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { MatchDocument } from '../global/database/schema';
|
||||
import mongoose from 'mongoose';
|
||||
import { TournamentCodeService } from './tournament-code.service';
|
||||
|
||||
type TournamentCodeServiceInternals = TournamentCodeService & {
|
||||
@@ -8,6 +9,10 @@ type TournamentCodeServiceInternals = TournamentCodeService & {
|
||||
gameNumber: number,
|
||||
): { teamAIndex: number; teamBIndex: number };
|
||||
ensureGameSchedule(match: MatchDocument): void;
|
||||
replaceForMatchGame(params: {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
gameNumber: number;
|
||||
}): Promise<unknown>;
|
||||
};
|
||||
|
||||
function createService() {
|
||||
@@ -32,11 +37,15 @@ interface MatchOverrides {
|
||||
|
||||
function createMatch(overrides: MatchOverrides): MatchDocument {
|
||||
return {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
status: 'in-progress',
|
||||
gameCount: 1,
|
||||
gameMode: 'pair',
|
||||
participants: [],
|
||||
teams: [],
|
||||
tournamentCodeIds: [],
|
||||
gameSchedule: [],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
...overrides,
|
||||
} as unknown as MatchDocument;
|
||||
}
|
||||
@@ -307,3 +316,176 @@ describe('TournamentCodeService round-robin scheduling', () => {
|
||||
expect(slots).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TournamentCodeService code replacement', () => {
|
||||
function queryResult<T>(value: T) {
|
||||
return { exec: jest.fn().mockResolvedValue(value) };
|
||||
}
|
||||
|
||||
function createCode(overrides: Record<string, unknown>) {
|
||||
return {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
code: 'CODE',
|
||||
state: 'reserved',
|
||||
expiresAt: new Date(Date.now() + 60 * 60 * 1000),
|
||||
matchId: new mongoose.Types.ObjectId(),
|
||||
gameNumber: 1,
|
||||
reservedAt: new Date(),
|
||||
releasedAt: undefined,
|
||||
riotMatchId: undefined,
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createReplacementFixture(params?: {
|
||||
currentCode?: Record<string, unknown> | null;
|
||||
replacementCode?: Record<string, unknown> | null;
|
||||
match?: MatchDocument;
|
||||
}) {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const oldCodeId = new mongoose.Types.ObjectId();
|
||||
const newCodeId = new mongoose.Types.ObjectId();
|
||||
const match =
|
||||
params?.match ??
|
||||
createMatch({
|
||||
_id: matchId,
|
||||
status: 'in-progress',
|
||||
gameCount: 1,
|
||||
participants: Array.from({ length: 10 }, () => ({})),
|
||||
teams: [{ teamIndex: 1 }, { teamIndex: 2 }],
|
||||
tournamentCodeIds: [oldCodeId],
|
||||
} as unknown as MatchOverrides);
|
||||
const currentCode =
|
||||
params?.currentCode === null
|
||||
? null
|
||||
: createCode({
|
||||
_id: oldCodeId,
|
||||
code: 'OLD-CODE',
|
||||
matchId,
|
||||
gameNumber: 1,
|
||||
...(params?.currentCode ?? {}),
|
||||
});
|
||||
const replacementCode =
|
||||
params?.replacementCode === null
|
||||
? null
|
||||
: createCode({
|
||||
_id: newCodeId,
|
||||
code: 'NEW-CODE',
|
||||
matchId,
|
||||
gameNumber: 1,
|
||||
...(params?.replacementCode ?? {}),
|
||||
});
|
||||
|
||||
const MatchModel = {
|
||||
findById: jest.fn().mockReturnValue(queryResult(match)),
|
||||
};
|
||||
const TournamentCodeModel = {
|
||||
findOne: jest.fn().mockReturnValue(queryResult(currentCode)),
|
||||
findOneAndUpdate: jest.fn().mockReturnValue(queryResult(replacementCode)),
|
||||
};
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation((modelName: string) => {
|
||||
if (modelName === 'match') return Promise.resolve(MatchModel);
|
||||
if (modelName === 'tournamentCode') {
|
||||
return Promise.resolve(TournamentCodeModel);
|
||||
}
|
||||
throw new Error(`Unexpected model: ${modelName}`);
|
||||
}),
|
||||
};
|
||||
const service = new TournamentCodeService(
|
||||
connectionService as never,
|
||||
) as unknown as TournamentCodeServiceInternals;
|
||||
|
||||
return {
|
||||
match,
|
||||
matchId,
|
||||
currentCode,
|
||||
replacementCode,
|
||||
MatchModel,
|
||||
TournamentCodeModel,
|
||||
service,
|
||||
};
|
||||
}
|
||||
|
||||
it('replaces a reserved code on the same game slot', async () => {
|
||||
const { match, matchId, currentCode, replacementCode, TournamentCodeModel, service } =
|
||||
createReplacementFixture();
|
||||
|
||||
const slot = await service.replaceForMatchGame({
|
||||
matchId,
|
||||
gameNumber: 1,
|
||||
});
|
||||
|
||||
expect(slot).toEqual(
|
||||
expect.objectContaining({
|
||||
gameNumber: 1,
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
code: 'NEW-CODE',
|
||||
state: 'reserved',
|
||||
}),
|
||||
);
|
||||
expect(TournamentCodeModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
state: 'available',
|
||||
region: 'kr',
|
||||
mapType: 'SUMMONERS_RIFT',
|
||||
teamSize: 5,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
$set: expect.objectContaining({
|
||||
state: 'reserved',
|
||||
matchId,
|
||||
gameNumber: 1,
|
||||
}),
|
||||
}),
|
||||
expect.objectContaining({ returnDocument: 'after' }),
|
||||
);
|
||||
expect(currentCode?.state).toBe('released');
|
||||
expect(currentCode?.matchId).toBeUndefined();
|
||||
expect(currentCode?.gameNumber).toBeUndefined();
|
||||
expect(currentCode?.save).toHaveBeenCalled();
|
||||
expect(match.tournamentCodeIds.map((id) => id.toString())).toEqual([
|
||||
replacementCode?._id.toString(),
|
||||
]);
|
||||
expect(match.save).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects replacement after the game result is collected', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const fixture = createReplacementFixture({
|
||||
match: createMatch({
|
||||
_id: matchId,
|
||||
status: 'in-progress',
|
||||
gameCount: 1,
|
||||
participants: Array.from({ length: 10 }, () => ({})),
|
||||
teams: [{ teamIndex: 1 }, { teamIndex: 2 }],
|
||||
tournamentCodeIds: [new mongoose.Types.ObjectId()],
|
||||
result: {
|
||||
riotMatchIds: ['KR_1'],
|
||||
games: [{ gameNumber: 1 }],
|
||||
seriesResults: [],
|
||||
},
|
||||
} as unknown as MatchOverrides),
|
||||
});
|
||||
|
||||
await expect(
|
||||
fixture.service.replaceForMatchGame({ matchId, gameNumber: 1 }),
|
||||
).rejects.toThrow('already has a collected result');
|
||||
expect(fixture.TournamentCodeModel.findOne).not.toHaveBeenCalled();
|
||||
expect(fixture.TournamentCodeModel.findOneAndUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('leaves the current code untouched when no replacement code is available', async () => {
|
||||
const { match, matchId, currentCode, service } = createReplacementFixture({
|
||||
replacementCode: null,
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.replaceForMatchGame({ matchId, gameNumber: 1 }),
|
||||
).rejects.toThrow('No available tournament code');
|
||||
expect(currentCode?.save).not.toHaveBeenCalled();
|
||||
expect(match.save).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -273,6 +273,107 @@ export class TournamentCodeService {
|
||||
return match;
|
||||
}
|
||||
|
||||
public async replaceForMatchGame(params: {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
gameNumber: number;
|
||||
}): Promise<TournamentCodeSlotView> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const match = await MatchModel.findById(params.matchId).exec();
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
if (match.status !== 'team-built' && match.status !== 'in-progress') {
|
||||
throw new BadRequestException(
|
||||
'Tournament codes can only be replaced while the match is ready or in progress.',
|
||||
);
|
||||
}
|
||||
|
||||
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
||||
this.ensureGameSchedule(match);
|
||||
|
||||
const requiredSlots = this.resolveRequiredSlots(match);
|
||||
if (
|
||||
!Number.isInteger(params.gameNumber) ||
|
||||
params.gameNumber < 1 ||
|
||||
params.gameNumber > requiredSlots
|
||||
) {
|
||||
throw new BadRequestException('Invalid tournament code game number.');
|
||||
}
|
||||
if (
|
||||
(match.result?.games ?? []).some(
|
||||
(game) => game.gameNumber === params.gameNumber,
|
||||
)
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'This game already has a collected result and cannot be replaced.',
|
||||
);
|
||||
}
|
||||
|
||||
const currentCode = await TournamentCodeModel.findOne({
|
||||
_id: { $in: match.tournamentCodeIds },
|
||||
matchId: match._id,
|
||||
gameNumber: params.gameNumber,
|
||||
}).exec();
|
||||
if (!currentCode) {
|
||||
throw new NotFoundException('Assigned tournament code not found.');
|
||||
}
|
||||
if (currentCode.state === 'used' || currentCode.riotMatchId) {
|
||||
throw new BadRequestException('Used tournament codes cannot be replaced.');
|
||||
}
|
||||
|
||||
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
|
||||
const replacement = await TournamentCodeModel.findOneAndUpdate(
|
||||
{
|
||||
state: 'available',
|
||||
region: DEFAULT_REGION,
|
||||
mapType: 'SUMMONERS_RIFT',
|
||||
teamSize: 5,
|
||||
expiresAt: { $gt: expiresAfter },
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
state: 'reserved',
|
||||
matchId: match._id,
|
||||
gameNumber: params.gameNumber,
|
||||
reservedAt: new Date(),
|
||||
},
|
||||
$unset: { releasedAt: 1 },
|
||||
},
|
||||
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
|
||||
).exec();
|
||||
if (!replacement) {
|
||||
throw new BadRequestException('No available tournament code to replace with.');
|
||||
}
|
||||
|
||||
currentCode.state = 'released';
|
||||
currentCode.matchId = undefined;
|
||||
currentCode.gameNumber = undefined;
|
||||
currentCode.reservedAt = undefined;
|
||||
currentCode.releasedAt = new Date();
|
||||
currentCode.riotMatchId = undefined;
|
||||
match.tournamentCodeIds = this.replaceTournamentCodeId(
|
||||
match.tournamentCodeIds,
|
||||
currentCode._id,
|
||||
replacement._id,
|
||||
);
|
||||
await currentCode.save();
|
||||
await match.save();
|
||||
|
||||
return {
|
||||
gameNumber: params.gameNumber,
|
||||
roundNumber: this.resolveRoundNumberForGameNumber(
|
||||
match,
|
||||
params.gameNumber,
|
||||
),
|
||||
...this.resolveSeriesRefForGameNumber(match, params.gameNumber),
|
||||
code: replacement.code,
|
||||
expiresAt: replacement.expiresAt.toISOString(),
|
||||
state: replacement.state,
|
||||
riotMatchId: replacement.riotMatchId ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
public async releaseFromMatch(
|
||||
matchOrId: MatchDocument | mongoose.Types.ObjectId,
|
||||
): Promise<void> {
|
||||
@@ -390,6 +491,21 @@ export class TournamentCodeService {
|
||||
return (code ?? '').trim().toUpperCase();
|
||||
}
|
||||
|
||||
private replaceTournamentCodeId(
|
||||
currentIds: mongoose.Types.ObjectId[],
|
||||
oldId: mongoose.Types.ObjectId,
|
||||
newId: mongoose.Types.ObjectId,
|
||||
): mongoose.Types.ObjectId[] {
|
||||
let replaced = false;
|
||||
const next = currentIds.map((id) => {
|
||||
if (id.toString() !== oldId.toString()) return id;
|
||||
replaced = true;
|
||||
return newId;
|
||||
});
|
||||
if (!replaced) next.push(newId);
|
||||
return next;
|
||||
}
|
||||
|
||||
private resolveRequiredSlots(match: MatchDocument): number {
|
||||
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
const gameMode = match.gameMode ?? 'pair';
|
||||
|
||||
Reference in new issue
Block a user