This commit is contained in:
dahyeon committed 2026-05-03 02:45:52 -07:00
1 parent cf887b3acc
commit 6767a9f61b
14 files changed
+748 -20

No files matched your search

@@ -69,6 +69,95 @@ describe('AuctionService', () => {
jest.useRealTimers(); jest.useRealTimers();
}); });
it('starts an auction without reserving tournament codes before teams are complete', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const userIds = Array.from(
{ length: 10 },
() => new mongoose.Types.ObjectId(),
);
const participants = userIds.map((userId, index) => ({
userId,
preferredPositions: [{ position: 'MID', priority: 1 }],
joinedAt: new Date(index),
excluded: false,
}));
const match = {
_id: matchId,
communityId,
participants,
status: 'recruiting',
teamBuiltAt: undefined,
save: jest.fn().mockResolvedValue(undefined),
};
const users = userIds.slice(2).map((userId, index) => ({
_id: userId,
riotAccounts: [
{
puuid: `puuid-${index}`,
gameName: `Player${index}`,
tagLine: 'KR1',
profileIconId: index,
tiers: [],
championMasteries: [],
recentStatsSummary: undefined,
lastRefreshRequestedAt: new Date(),
isPrimary: true,
},
],
}));
const auction = {
_id: new mongoose.Types.ObjectId(),
matchId,
toObject: jest.fn().mockReturnValue({ matchId }),
};
const { service, tournamentCodeService, tournamentResultService } =
createService({
match: {
findById: jest.fn().mockResolvedValue(match),
},
user: {
find: jest.fn().mockResolvedValue(users),
},
auction: {
findOne: jest.fn().mockResolvedValue(null),
create: jest.fn().mockResolvedValue(auction),
},
community: {
findById: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({
riotPlatform: 'kr',
riotRegion: 'asia',
}),
}),
}),
}),
},
});
await service.start({
matchId,
communityId,
captains: [
{ teamIndex: 1, userId: userIds[0] },
{ teamIndex: 2, userId: userIds[1] },
],
initialPoints: 1000,
maxTimerSeconds: 30,
bidExtensionSeconds: 5,
topTierThreshold: 'NONE',
manualTopTierUserIds: [],
});
expect(match.status).toBe('team-built');
expect(match.teamBuiltAt).toBeInstanceOf(Date);
expect(match.save).toHaveBeenCalledTimes(1);
expect(tournamentCodeService.reserveForMatch).not.toHaveBeenCalled();
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
});
it('rejects bids when the team already has 5 members including captain', async () => { it('rejects bids when the team already has 5 members including captain', async () => {
const matchId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId();
const auction = { const auction = {
@@ -341,14 +430,15 @@ describe('AuctionService', () => {
teams: [], teams: [],
save: jest.fn().mockResolvedValue(undefined), save: jest.fn().mockResolvedValue(undefined),
}; };
const { service } = createService({ const { service, tournamentCodeService, tournamentResultService } =
auction: { createService({
findOne: jest.fn().mockResolvedValue(auction), auction: {
}, findOne: jest.fn().mockResolvedValue(auction),
match: { },
findById: jest.fn().mockResolvedValue(match), match: {
}, findById: jest.fn().mockResolvedValue(match),
}); },
});
await service.next(matchId); await service.next(matchId);
@@ -392,6 +482,10 @@ describe('AuctionService', () => {
], ],
}, },
]); ]);
expect(tournamentCodeService.reserveForMatch).toHaveBeenCalledWith(match);
expect(tournamentResultService.scheduleInitialPoll).toHaveBeenCalledWith(
match,
);
}); });
it('clears match teams when resetting an auction', async () => { it('clears match teams when resetting an auction', async () => {
@@ -416,6 +510,8 @@ describe('AuctionService', () => {
members: [], members: [],
}, },
], ],
tournamentCodeIds: [new mongoose.Types.ObjectId()],
gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 2 }],
participants: [], participants: [],
save: jest.fn().mockResolvedValue(undefined), save: jest.fn().mockResolvedValue(undefined),
}; };
@@ -439,6 +535,8 @@ describe('AuctionService', () => {
expect(match.status).toBe('recruiting'); expect(match.status).toBe('recruiting');
expect(match.teams).toEqual([]); expect(match.teams).toEqual([]);
expect(match.tournamentCodeIds).toEqual([]);
expect(match.gameSchedule).toEqual([]);
expect(match.save).toHaveBeenCalledWith({ session }); expect(match.save).toHaveBeenCalledWith({ session });
expect(session.commitTransaction).toHaveBeenCalledTimes(1); expect(session.commitTransaction).toHaveBeenCalledTimes(1);
}); });
@@ -201,8 +201,6 @@ export class AuctionService {
match.status = 'team-built'; match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date(); match.teamBuiltAt = match.teamBuiltAt ?? new Date();
await match.save(); await match.save();
await this.tournamentCodeService.reserveForMatch(match);
await this.tournamentResultService.scheduleInitialPoll(match);
this.enqueueBackgroundOrderEnrichment({ this.enqueueBackgroundOrderEnrichment({
auctionId: auction._id, auctionId: auction._id,
targets: enrichTargets, targets: enrichTargets,
@@ -444,6 +442,7 @@ export class AuctionService {
match.status = 'recruiting'; match.status = 'recruiting';
match.teams = []; match.teams = [];
match.tournamentCodeIds = []; match.tournamentCodeIds = [];
match.gameSchedule = [];
match.participants.forEach((participant) => { match.participants.forEach((participant) => {
participant.excluded = false; participant.excluded = false;
}); });
+22 -1
View File
@@ -396,6 +396,12 @@ export interface MatchSeriesResult {
winnerTeamIndex?: number; winnerTeamIndex?: number;
} }
export interface MatchGameAssignment {
gameNumber: number;
teamAIndex: number;
teamBIndex: number;
}
export interface MatchResult { export interface MatchResult {
winnerTeamIndex?: number; winnerTeamIndex?: number;
mvpUserId?: mongoose.Types.ObjectId; mvpUserId?: mongoose.Types.ObjectId;
@@ -430,6 +436,7 @@ export interface Match extends MongooseTimestamps {
gameCount: number; gameCount: number;
gameMode: MatchGameMode; gameMode: MatchGameMode;
tournamentCodeIds: mongoose.Types.ObjectId[]; tournamentCodeIds: mongoose.Types.ObjectId[];
gameSchedule: MatchGameAssignment[];
teamBuiltAt?: Date; teamBuiltAt?: Date;
hostUserId?: mongoose.Types.ObjectId; hostUserId?: mongoose.Types.ObjectId;
participants: MatchParticipant[]; participants: MatchParticipant[];
@@ -1008,6 +1015,15 @@ const MatchSeriesResultSubSchema = new Schema<MatchSeriesResult>(
{ _id: false }, { _id: false },
); );
const MatchGameAssignmentSubSchema = new Schema<MatchGameAssignment>(
{
gameNumber: { type: Number, required: true, min: 1 },
teamAIndex: { type: Number, required: true, min: 1 },
teamBIndex: { type: Number, required: true, min: 1 },
},
{ _id: false },
);
const MatchResultSubSchema = new Schema<MatchResult>( const MatchResultSubSchema = new Schema<MatchResult>(
{ {
winnerTeamIndex: { type: Number, required: false, min: 1 }, winnerTeamIndex: { type: Number, required: false, min: 1 },
@@ -1078,7 +1094,7 @@ export const MatchSchema = new Schema<Match>(
maxlength: 6, maxlength: 6,
}, },
title: { type: String, required: true }, title: { type: String, required: true },
description: { type: String, required: true, default: '' }, description: { type: String, required: false, default: '' },
mapId: { type: Number, required: true, default: 11 }, mapId: { type: Number, required: true, default: 11 },
status: { status: {
type: String, type: String,
@@ -1109,6 +1125,11 @@ export const MatchSchema = new Schema<Match>(
required: true, required: true,
default: [], default: [],
}, },
gameSchedule: {
type: [MatchGameAssignmentSubSchema],
required: true,
default: [],
},
teamBuiltAt: { type: Date }, teamBuiltAt: { type: Date },
hostUserId: { type: Schema.Types.ObjectId, ref: 'user' }, hostUserId: { type: Schema.Types.ObjectId, ref: 'user' },
participants: { participants: {
@@ -0,0 +1,97 @@
import mongoose from 'mongoose';
import { MatchService } from './match.service';
describe('MatchService', () => {
function createService(match: Record<string, unknown>) {
const MatchModel = {
findById: jest.fn().mockResolvedValue(match),
};
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return MatchModel;
return {};
}),
};
const tournamentCodeService = {
buildSlots: jest.fn().mockResolvedValue([]),
releaseFromMatch: jest.fn().mockResolvedValue(undefined),
};
const communityStatsService = {
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
};
return {
service: new MatchService(
connectionService as never,
tournamentCodeService as never,
communityStatsService as never,
),
tournamentCodeService,
};
}
it('clears game schedule when a built match returns to recruiting', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
communityId,
status: 'team-built',
tournamentCodeIds: [],
gameSchedule: [{ gameNumber: 1, teamAIndex: 2, teamBIndex: 4 }],
teams: [{ teamIndex: 1 }],
teamBuiltAt: new Date(),
result: { games: [] },
resultPollState: { state: 'polling' },
set: jest.fn(function (
this: Record<string, unknown>,
patch: Record<string, unknown>,
) {
Object.assign(this, patch);
}),
save: jest.fn().mockResolvedValue(undefined),
};
const { service, tournamentCodeService } = createService(match);
await service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { status: '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);
});
it('releases reserved codes when returning a built match to recruiting', async () => {
const communityId = new mongoose.Types.ObjectId();
const codeId = new mongoose.Types.ObjectId();
const match = {
communityId,
status: 'in-progress',
tournamentCodeIds: [codeId],
gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 3 }],
set: jest.fn(function (
this: Record<string, unknown>,
patch: Record<string, unknown>,
) {
Object.assign(this, patch);
}),
save: jest.fn().mockResolvedValue(undefined),
};
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([]);
});
});
+6 -6
View File
@@ -139,6 +139,7 @@ export class MatchService {
teams: (obj.teams ?? []).map((team) => ({ teams: (obj.teams ?? []).map((team) => ({
...team, ...team,
})), })),
gameSchedule: obj.gameSchedule ?? [],
tournamentCodes: await this.tournamentCodeService.buildSlots(match), tournamentCodes: await this.tournamentCodeService.buildSlots(match),
}; };
} }
@@ -160,13 +161,12 @@ export class MatchService {
); );
} }
match.set(params.patch); match.set(params.patch);
if ( if (previousStatus !== 'recruiting' && match.status === 'recruiting') {
previousStatus !== 'recruiting' && if (match.tournamentCodeIds.length > 0) {
match.status === 'recruiting' && await this.tournamentCodeService.releaseFromMatch(match);
match.tournamentCodeIds.length > 0 }
) {
await this.tournamentCodeService.releaseFromMatch(match);
match.tournamentCodeIds = []; match.tournamentCodeIds = [];
match.gameSchedule = [];
match.teamBuiltAt = undefined; match.teamBuiltAt = undefined;
match.result = undefined; match.result = undefined;
match.resultPollState = undefined; match.resultPollState = undefined;
@@ -0,0 +1,52 @@
import {
resolveRoundRobinTeamCount,
roundRobinPairCount,
roundRobinPairs,
shuffleInPlace,
} from './round-robin.util';
describe('round-robin util', () => {
it('builds every team pair in lexicographic order', () => {
expect(roundRobinPairs(2)).toEqual([
{ teamAIndex: 1, teamBIndex: 2 },
]);
expect(roundRobinPairs(4)).toEqual([
{ teamAIndex: 1, teamBIndex: 2 },
{ teamAIndex: 1, teamBIndex: 3 },
{ teamAIndex: 1, teamBIndex: 4 },
{ teamAIndex: 2, teamBIndex: 3 },
{ teamAIndex: 2, teamBIndex: 4 },
{ teamAIndex: 3, teamBIndex: 4 },
]);
});
it('counts round-robin pairs', () => {
expect(roundRobinPairCount(1)).toBe(0);
expect(roundRobinPairCount(6)).toBe(15);
});
it('resolves team count from teams first, then active participants', () => {
expect(
resolveRoundRobinTeamCount({
teams: [{ teamIndex: 1 }, { teamIndex: 2 }, { teamIndex: 3 }],
participants: Array.from({ length: 30 }, () => ({})),
}),
).toBe(3);
expect(
resolveRoundRobinTeamCount({
teams: [],
participants: [
...Array.from({ length: 29 }, () => ({})),
{ excluded: true },
],
}),
).toBe(5);
});
it('shuffles in place with an injectable rng', () => {
const items = [1, 2, 3, 4];
const result = shuffleInPlace(items, () => 0);
expect(result).toBe(items);
expect(items).toEqual([2, 3, 4, 1]);
});
});
@@ -0,0 +1,51 @@
export interface RoundRobinPair {
teamAIndex: number;
teamBIndex: number;
}
export interface RoundRobinTeamCountInput {
teams?: Array<{ teamIndex: number }>;
participants: Array<{ excluded?: boolean }>;
}
export function roundRobinPairs(teamCount: number): RoundRobinPair[] {
const pairs: RoundRobinPair[] = [];
for (let teamAIndex = 1; teamAIndex <= teamCount; teamAIndex += 1) {
for (
let teamBIndex = teamAIndex + 1;
teamBIndex <= teamCount;
teamBIndex += 1
) {
pairs.push({ teamAIndex, teamBIndex });
}
}
return pairs;
}
export function roundRobinPairCount(teamCount: number): number {
if (teamCount < 2) return 0;
return (teamCount * (teamCount - 1)) / 2;
}
export function resolveRoundRobinTeamCount(
match: RoundRobinTeamCountInput,
): number {
if (match.teams && match.teams.length > 0) {
return match.teams.length;
}
const activeParticipantCount = match.participants.filter(
(participant) => !participant.excluded,
).length;
return Math.floor(activeParticipantCount / 5);
}
export function shuffleInPlace<T>(
items: T[],
rng: () => number = Math.random,
): T[] {
for (let index = items.length - 1; index > 0; index -= 1) {
const swapIndex = Math.floor(rng() * (index + 1));
[items[index], items[swapIndex]] = [items[swapIndex], items[index]];
}
return items;
}
@@ -0,0 +1,191 @@
import type { MatchDocument } from '../global/database/schema';
import { TournamentCodeService } from './tournament-code.service';
type TournamentCodeServiceInternals = TournamentCodeService & {
resolveRequiredSlots(match: MatchDocument): number;
resolveSeriesRefForGameNumber(
match: MatchDocument,
gameNumber: number,
): { teamAIndex: number; teamBIndex: number };
ensureGameSchedule(match: MatchDocument): void;
};
function createService() {
return new TournamentCodeService(
{} as never,
) as unknown as TournamentCodeServiceInternals;
}
interface MatchOverrides {
gameCount?: number;
gameMode?: 'pair' | 'bracket' | 'round-robin';
participants?: Array<{ excluded?: boolean }>;
teams?: Array<{ teamIndex: number }>;
gameSchedule?: Array<{
gameNumber: number;
teamAIndex: number;
teamBIndex: number;
}>;
}
function createMatch(overrides: MatchOverrides): MatchDocument {
return {
gameCount: 1,
gameMode: 'pair',
participants: [],
teams: [],
gameSchedule: [],
...overrides,
} as unknown as MatchDocument;
}
describe('TournamentCodeService round-robin scheduling', () => {
it('keeps pair slot calculation unchanged', () => {
const service = createService();
const match = createMatch({
gameCount: 3,
teams: Array.from({ length: 6 }, (_, index) => ({
teamIndex: index + 1,
})),
participants: Array.from({ length: 30 }, () => ({})),
});
expect(service.resolveRequiredSlots(match)).toBe(9);
expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({
teamAIndex: 1,
teamBIndex: 2,
});
expect(service.resolveSeriesRefForGameNumber(match, 4)).toEqual({
teamAIndex: 3,
teamBIndex: 4,
});
expect(service.resolveSeriesRefForGameNumber(match, 7)).toEqual({
teamAIndex: 5,
teamBIndex: 6,
});
});
it('calculates round-robin slots from team pairs and per-pair game count', () => {
const service = createService();
expect(
service.resolveRequiredSlots(
createMatch({
gameMode: 'round-robin',
gameCount: 1,
teams: Array.from({ length: 6 }, (_, index) => ({
teamIndex: index + 1,
})),
}),
),
).toBe(15);
expect(
service.resolveRequiredSlots(
createMatch({
gameMode: 'round-robin',
gameCount: 2,
teams: Array.from({ length: 6 }, (_, index) => ({
teamIndex: index + 1,
})),
}),
),
).toBe(30);
expect(
service.resolveRequiredSlots(
createMatch({
gameMode: 'round-robin',
gameCount: 1,
teams: [],
participants: Array.from({ length: 30 }, () => ({})),
}),
),
).toBe(15);
});
it('uses persisted round-robin game schedule for game refs', () => {
const service = createService();
const match = createMatch({
gameMode: 'round-robin',
gameCount: 2,
gameSchedule: [
{ gameNumber: 1, teamAIndex: 2, teamBIndex: 5 },
{ gameNumber: 2, teamAIndex: 2, teamBIndex: 5 },
{ gameNumber: 3, teamAIndex: 1, teamBIndex: 4 },
],
});
expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({
teamAIndex: 2,
teamBIndex: 5,
});
expect(service.resolveSeriesRefForGameNumber(match, 3)).toEqual({
teamAIndex: 1,
teamBIndex: 4,
});
});
it('falls back to lexicographic round-robin pairs before schedule is persisted', () => {
const service = createService();
const match = createMatch({
gameMode: 'round-robin',
gameCount: 1,
teams: Array.from({ length: 4 }, (_, index) => ({
teamIndex: index + 1,
})),
gameSchedule: [],
});
expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({
teamAIndex: 1,
teamBIndex: 2,
});
expect(service.resolveSeriesRefForGameNumber(match, 2)).toEqual({
teamAIndex: 1,
teamBIndex: 3,
});
});
it('creates a round-robin schedule once and leaves pair matches empty', () => {
const service = createService();
const roundRobin = createMatch({
gameMode: 'round-robin',
gameCount: 2,
teams: Array.from({ length: 4 }, (_, index) => ({
teamIndex: index + 1,
})),
gameSchedule: [],
});
service.ensureGameSchedule(roundRobin);
expect(roundRobin.gameSchedule).toHaveLength(12);
const persisted = [...roundRobin.gameSchedule];
service.ensureGameSchedule(roundRobin);
expect(roundRobin.gameSchedule).toEqual(persisted);
const pair = createMatch({
gameMode: 'pair',
teams: Array.from({ length: 4 }, (_, index) => ({
teamIndex: index + 1,
})),
gameSchedule: [],
});
service.ensureGameSchedule(pair);
expect(pair.gameSchedule).toEqual([]);
});
it('does not expose fallback round-robin slots before the schedule is persisted', async () => {
const service = createService();
const slots = await service.buildSlots(
createMatch({
gameMode: 'round-robin',
gameCount: 1,
teams: Array.from({ length: 6 }, (_, index) => ({
teamIndex: index + 1,
})),
gameSchedule: [],
}),
);
expect(slots).toEqual([]);
});
});
@@ -6,6 +6,7 @@ import {
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import type { import type {
MatchGameAssignment,
MatchDocument, MatchDocument,
TournamentCode, TournamentCode,
TournamentCodeDocument, TournamentCodeDocument,
@@ -23,6 +24,12 @@ import type {
TournamentCodeSlotView, TournamentCodeSlotView,
TournamentCodeUploadItem, TournamentCodeUploadItem,
} from './tournament-code.types'; } from './tournament-code.types';
import {
resolveRoundRobinTeamCount,
roundRobinPairCount,
roundRobinPairs,
shuffleInPlace,
} from './round-robin.util';
const DEFAULT_REGION = 'kr'; const DEFAULT_REGION = 'kr';
const DEFAULT_SPECTATOR_TYPE: TournamentSpectatorType = 'ALL'; const DEFAULT_SPECTATOR_TYPE: TournamentSpectatorType = 'ALL';
@@ -220,9 +227,16 @@ export class TournamentCodeService {
if (!match) throw new NotFoundException('Match not found.'); if (!match) throw new NotFoundException('Match not found.');
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
this.ensureGameSchedule(match);
const shouldSaveMetadata =
match.isModified('gameCount') || match.isModified('gameSchedule');
const requiredSlots = this.resolveRequiredSlots(match); const requiredSlots = this.resolveRequiredSlots(match);
const need = requiredSlots - match.tournamentCodeIds.length; const need = requiredSlots - match.tournamentCodeIds.length;
if (need <= 0) return match; if (need <= 0) {
if (shouldSaveMetadata) await match.save();
return match;
}
const reservedIds: mongoose.Types.ObjectId[] = []; const reservedIds: mongoose.Types.ObjectId[] = [];
const startGameNumber = match.tournamentCodeIds.length + 1; const startGameNumber = match.tournamentCodeIds.length + 1;
@@ -254,6 +268,8 @@ export class TournamentCodeService {
if (reservedIds.length > 0) { if (reservedIds.length > 0) {
match.tournamentCodeIds.push(...reservedIds); match.tournamentCodeIds.push(...reservedIds);
}
if (reservedIds.length > 0 || shouldSaveMetadata) {
await match.save(); await match.save();
} }
return match; return match;
@@ -324,6 +340,13 @@ export class TournamentCodeService {
} }
public async buildSlots(match: MatchDocument): Promise<TournamentCodeSlotView[]> { public async buildSlots(match: MatchDocument): Promise<TournamentCodeSlotView[]> {
if (
(match.gameMode ?? 'pair') === 'round-robin' &&
(match.gameSchedule?.length ?? 0) === 0 &&
(match.tournamentCodeIds?.length ?? 0) === 0
) {
return [];
}
const TournamentCodeModel = const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode'); await this.connectionService.getModel('tournamentCode');
const gameCount = this.resolveRequiredSlots(match); const gameCount = this.resolveRequiredSlots(match);
@@ -369,6 +392,13 @@ export class TournamentCodeService {
private resolveRequiredSlots(match: MatchDocument): number { private resolveRequiredSlots(match: MatchDocument): number {
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'round-robin') {
const teamCount = resolveRoundRobinTeamCount(match);
return roundRobinPairCount(teamCount) * gameCount;
}
const teamCount = (match.teams ?? []).length; const teamCount = (match.teams ?? []).length;
const activeParticipantCount = (match.participants ?? []).filter( const activeParticipantCount = (match.participants ?? []).filter(
(participant) => !participant.excluded, (participant) => !participant.excluded,
@@ -383,6 +413,28 @@ export class TournamentCodeService {
match: MatchDocument, match: MatchDocument,
gameNumber: number, gameNumber: number,
): { teamAIndex: number; teamBIndex: number } { ): { teamAIndex: number; teamBIndex: number } {
const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'round-robin') {
const persisted = match.gameSchedule?.find(
(entry) => entry.gameNumber === gameNumber,
);
if (persisted) {
return {
teamAIndex: persisted.teamAIndex,
teamBIndex: persisted.teamBIndex,
};
}
const teamCount = resolveRoundRobinTeamCount(match);
const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1);
return roundRobinPairs(teamCount)[pairIndex] ?? {
teamAIndex: 1,
teamBIndex: 2,
};
}
const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
const seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries)); const seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries));
return { return {
@@ -390,4 +442,29 @@ export class TournamentCodeService {
teamBIndex: (seriesIndex - 1) * 2 + 2, teamBIndex: (seriesIndex - 1) * 2 + 2,
}; };
} }
private ensureGameSchedule(match: MatchDocument): void {
if ((match.gameMode ?? 'pair') !== 'round-robin') return;
if ((match.gameSchedule?.length ?? 0) > 0) return;
const teamCount = resolveRoundRobinTeamCount(match);
if (teamCount < 2) return;
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
const pairs = shuffleInPlace([...roundRobinPairs(teamCount)]);
const schedule: MatchGameAssignment[] = [];
for (let pairIndex = 0; pairIndex < pairs.length; pairIndex += 1) {
const pair = pairs[pairIndex];
for (let gameIndex = 0; gameIndex < gameCount; gameIndex += 1) {
schedule.push({
gameNumber: pairIndex * gameCount + gameIndex + 1,
teamAIndex: pair.teamAIndex,
teamBIndex: pair.teamBIndex,
});
}
}
match.gameSchedule = schedule;
}
} }
@@ -0,0 +1,83 @@
import type { MatchDocument } from '../global/database/schema';
import { TournamentResultService } from './tournament-result.service';
type TournamentResultServiceInternals = TournamentResultService & {
resolveRequiredGameSlots(match: MatchDocument): number;
resolveSeriesRefForGameNumber(
match: MatchDocument,
gameNumber: number,
): { teamAIndex: number; teamBIndex: number };
};
function createService() {
return new TournamentResultService(
{} as never,
{} as never,
{} as never,
{} as never,
) as unknown as TournamentResultServiceInternals;
}
interface MatchOverrides {
gameCount?: number;
gameMode?: 'pair' | 'bracket' | 'round-robin';
participants?: Array<{ excluded?: boolean }>;
teams?: Array<{ teamIndex: number }>;
gameSchedule?: Array<{
gameNumber: number;
teamAIndex: number;
teamBIndex: number;
}>;
}
function createMatch(overrides: MatchOverrides): MatchDocument {
return {
gameCount: 1,
gameMode: 'pair',
participants: [],
teams: [],
gameSchedule: [],
...overrides,
} as unknown as MatchDocument;
}
describe('TournamentResultService round-robin scheduling', () => {
it('calculates required slots for round-robin polling', () => {
const service = createService();
const match = createMatch({
gameMode: 'round-robin',
gameCount: 1,
teams: Array.from({ length: 6 }, (_, index) => ({
teamIndex: index + 1,
})),
});
expect(service.resolveRequiredGameSlots(match)).toBe(15);
});
it('uses persisted round-robin schedule when mapping a game number', () => {
const service = createService();
const match = createMatch({
gameMode: 'round-robin',
gameSchedule: [
{ gameNumber: 1, teamAIndex: 3, teamBIndex: 6 },
{ gameNumber: 2, teamAIndex: 1, teamBIndex: 5 },
],
});
expect(service.resolveSeriesRefForGameNumber(match, 2)).toEqual({
teamAIndex: 1,
teamBIndex: 5,
});
});
it('keeps pair game number mapping unchanged', () => {
const service = createService();
const match = createMatch({ gameCount: 3 });
expect(service.resolveSeriesRefForGameNumber(match, 4)).toEqual({
teamAIndex: 3,
teamBIndex: 4,
});
});
});
@@ -17,6 +17,11 @@ import { RiotJobQueueService } from '../riot-job-queue/riot-job-queue.service';
import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types'; import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types';
import { RiotMatchService } from '../riot/riot-match.service'; import { RiotMatchService } from '../riot/riot-match.service';
import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types'; import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types';
import {
resolveRoundRobinTeamCount,
roundRobinPairCount,
roundRobinPairs,
} from '../tournament-code/round-robin.util';
import { import {
collectCaptainUserIds, collectCaptainUserIds,
collectMatchUserIds, collectMatchUserIds,
@@ -456,6 +461,27 @@ export class TournamentResultService {
match: MatchDocument, match: MatchDocument,
gameNumber: number, gameNumber: number,
): { teamAIndex: number; teamBIndex: number } { ): { teamAIndex: number; teamBIndex: number } {
const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'round-robin') {
const persisted = match.gameSchedule?.find(
(entry) => entry.gameNumber === gameNumber,
);
if (persisted) {
return {
teamAIndex: persisted.teamAIndex,
teamBIndex: persisted.teamBIndex,
};
}
const perSeries = match.gameCount || 1;
const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1);
return roundRobinPairs(resolveRoundRobinTeamCount(match))[pairIndex] ?? {
teamAIndex: 1,
teamBIndex: 2,
};
}
const perSeries = match.gameCount || 1; const perSeries = match.gameCount || 1;
const seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries)); const seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries));
return { return {
@@ -465,6 +491,12 @@ export class TournamentResultService {
} }
private resolveRequiredGameSlots(match: MatchDocument): number { private resolveRequiredGameSlots(match: MatchDocument): number {
const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'round-robin') {
const teamCount = resolveRoundRobinTeamCount(match);
return roundRobinPairCount(teamCount) * (match.gameCount || 1);
}
const activeParticipantCount = match.participants.filter( const activeParticipantCount = match.participants.filter(
(participant) => !participant.excluded, (participant) => !participant.excluded,
).length; ).length;
+2
View File
@@ -2,3 +2,5 @@ INFISICAL_PROJECT_ID=26a80d59-a424-4e33-adfc-2b6e84d6e25f
SERVICE_NAME=lolympus-tournament-support SERVICE_NAME=lolympus-tournament-support
VERSION=0.1 VERSION=0.1
AUTH_DEV_HEADER_ENABLED=true
+7
View File
@@ -199,6 +199,12 @@ export interface ApiMatchScheduleItem {
label: string; label: string;
} }
export interface ApiMatchGameAssignment {
gameNumber: number;
teamAIndex: number;
teamBIndex: number;
}
export interface ApiMatch { export interface ApiMatch {
_id: string; _id: string;
communityId: string; communityId: string;
@@ -211,6 +217,7 @@ export interface ApiMatch {
maxParticipants: number; maxParticipants: number;
gameCount: number; gameCount: number;
gameMode: MatchGameMode; gameMode: MatchGameMode;
gameSchedule?: ApiMatchGameAssignment[];
tournamentCodes?: TournamentCodeSlotView[]; tournamentCodes?: TournamentCodeSlotView[];
hostUserId?: string; hostUserId?: string;
participants: ApiMatchParticipant[]; participants: ApiMatchParticipant[];
+20 -2
View File
@@ -35,6 +35,14 @@ const GAME_MODE_LABEL: Record<MatchGameMode, string> = {
'round-robin': '라운드 로빈', 'round-robin': '라운드 로빈',
}; };
function RequiredBadge() {
return (
<span className="ml-1 inline-flex items-center border border-primary/20 bg-primary/5 px-1.5 py-0.5 text-[10px] font-bold text-primary">
필수
</span>
);
}
function toInputValue(value: string | Date) { function toInputValue(value: string | Date) {
const date = value instanceof Date ? value : new Date(value); const date = value instanceof Date ? value : new Date(value);
const offset = date.getTimezoneOffset(); const offset = date.getTimezoneOffset();
@@ -169,11 +177,16 @@ export default function MatchAdminPage() {
function submit() { function submit() {
setMessage(null); setMessage(null);
const payload = buildPayload(); if (!form.title.trim()) {
if (!payload.title) {
setMessage('제목을 입력해주세요.'); setMessage('제목을 입력해주세요.');
return; return;
} }
if (!form.scheduledAt) {
setMessage('시작 시간을 입력해주세요.');
return;
}
const payload = buildPayload();
const callbacks = { const callbacks = {
onSuccess: async () => { onSuccess: async () => {
@@ -244,7 +257,9 @@ export default function MatchAdminPage() {
<div className="grid md:grid-cols-2 gap-3"> <div className="grid md:grid-cols-2 gap-3">
<label className="text-xs text-base-content/45 md:col-span-2"> <label className="text-xs text-base-content/45 md:col-span-2">
제목 제목
<RequiredBadge />
<input <input
required
value={form.title} value={form.title}
onChange={(event) => setForm((current) => ({ ...current, title: event.target.value }))} onChange={(event) => setForm((current) => ({ ...current, title: event.target.value }))}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm" className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
@@ -252,6 +267,7 @@ export default function MatchAdminPage() {
</label> </label>
<label className="text-xs text-base-content/45 md:col-span-2"> <label className="text-xs text-base-content/45 md:col-span-2">
설명 설명
<span className="ml-1 text-[10px] text-base-content/25">선택</span>
<textarea <textarea
value={form.description} value={form.description}
onChange={(event) => setForm((current) => ({ ...current, description: event.target.value }))} onChange={(event) => setForm((current) => ({ ...current, description: event.target.value }))}
@@ -261,7 +277,9 @@ export default function MatchAdminPage() {
</label> </label>
<label className="text-xs text-base-content/45"> <label className="text-xs text-base-content/45">
시작 시간 시작 시간
<RequiredBadge />
<input <input
required
type="datetime-local" type="datetime-local"
value={form.scheduledAt} value={form.scheduledAt}
onChange={(event) => setForm((current) => ({ ...current, scheduledAt: event.target.value }))} onChange={(event) => setForm((current) => ({ ...current, scheduledAt: event.target.value }))}