diff --git a/apps/api/src/modules/auction/auction.service.spec.ts b/apps/api/src/modules/auction/auction.service.spec.ts index f90d695c..b423e7cf 100644 --- a/apps/api/src/modules/auction/auction.service.spec.ts +++ b/apps/api/src/modules/auction/auction.service.spec.ts @@ -69,6 +69,95 @@ describe('AuctionService', () => { 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 () => { const matchId = new mongoose.Types.ObjectId(); const auction = { @@ -341,14 +430,15 @@ describe('AuctionService', () => { teams: [], save: jest.fn().mockResolvedValue(undefined), }; - const { service } = createService({ - auction: { - findOne: jest.fn().mockResolvedValue(auction), - }, - match: { - findById: jest.fn().mockResolvedValue(match), - }, - }); + const { service, tournamentCodeService, tournamentResultService } = + createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + match: { + findById: jest.fn().mockResolvedValue(match), + }, + }); 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 () => { @@ -416,6 +510,8 @@ describe('AuctionService', () => { members: [], }, ], + tournamentCodeIds: [new mongoose.Types.ObjectId()], + gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 2 }], participants: [], save: jest.fn().mockResolvedValue(undefined), }; @@ -439,6 +535,8 @@ describe('AuctionService', () => { expect(match.status).toBe('recruiting'); expect(match.teams).toEqual([]); + expect(match.tournamentCodeIds).toEqual([]); + expect(match.gameSchedule).toEqual([]); expect(match.save).toHaveBeenCalledWith({ session }); expect(session.commitTransaction).toHaveBeenCalledTimes(1); }); diff --git a/apps/api/src/modules/auction/auction.service.ts b/apps/api/src/modules/auction/auction.service.ts index df25faac..b4e587f1 100644 --- a/apps/api/src/modules/auction/auction.service.ts +++ b/apps/api/src/modules/auction/auction.service.ts @@ -201,8 +201,6 @@ export class AuctionService { match.status = 'team-built'; match.teamBuiltAt = match.teamBuiltAt ?? new Date(); await match.save(); - await this.tournamentCodeService.reserveForMatch(match); - await this.tournamentResultService.scheduleInitialPoll(match); this.enqueueBackgroundOrderEnrichment({ auctionId: auction._id, targets: enrichTargets, @@ -444,6 +442,7 @@ export class AuctionService { match.status = 'recruiting'; match.teams = []; match.tournamentCodeIds = []; + match.gameSchedule = []; match.participants.forEach((participant) => { participant.excluded = false; }); diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index d755a456..5855880c 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -396,6 +396,12 @@ export interface MatchSeriesResult { winnerTeamIndex?: number; } +export interface MatchGameAssignment { + gameNumber: number; + teamAIndex: number; + teamBIndex: number; +} + export interface MatchResult { winnerTeamIndex?: number; mvpUserId?: mongoose.Types.ObjectId; @@ -430,6 +436,7 @@ export interface Match extends MongooseTimestamps { gameCount: number; gameMode: MatchGameMode; tournamentCodeIds: mongoose.Types.ObjectId[]; + gameSchedule: MatchGameAssignment[]; teamBuiltAt?: Date; hostUserId?: mongoose.Types.ObjectId; participants: MatchParticipant[]; @@ -1008,6 +1015,15 @@ const MatchSeriesResultSubSchema = new Schema( { _id: false }, ); +const MatchGameAssignmentSubSchema = new Schema( + { + 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( { winnerTeamIndex: { type: Number, required: false, min: 1 }, @@ -1078,7 +1094,7 @@ export const MatchSchema = new Schema( maxlength: 6, }, title: { type: String, required: true }, - description: { type: String, required: true, default: '' }, + description: { type: String, required: false, default: '' }, mapId: { type: Number, required: true, default: 11 }, status: { type: String, @@ -1109,6 +1125,11 @@ export const MatchSchema = new Schema( required: true, default: [], }, + gameSchedule: { + type: [MatchGameAssignmentSubSchema], + required: true, + default: [], + }, teamBuiltAt: { type: Date }, hostUserId: { type: Schema.Types.ObjectId, ref: 'user' }, participants: { diff --git a/apps/api/src/modules/match/match.service.spec.ts b/apps/api/src/modules/match/match.service.spec.ts new file mode 100644 index 00000000..615dd350 --- /dev/null +++ b/apps/api/src/modules/match/match.service.spec.ts @@ -0,0 +1,97 @@ +import mongoose from 'mongoose'; +import { MatchService } from './match.service'; + +describe('MatchService', () => { + function createService(match: Record) { + 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, + patch: Record, + ) { + 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, + patch: Record, + ) { + 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([]); + }); +}); diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index 6dd038ed..1a945728 100644 --- a/apps/api/src/modules/match/match.service.ts +++ b/apps/api/src/modules/match/match.service.ts @@ -139,6 +139,7 @@ export class MatchService { teams: (obj.teams ?? []).map((team) => ({ ...team, })), + gameSchedule: obj.gameSchedule ?? [], tournamentCodes: await this.tournamentCodeService.buildSlots(match), }; } @@ -160,13 +161,12 @@ export class MatchService { ); } match.set(params.patch); - if ( - previousStatus !== 'recruiting' && - match.status === 'recruiting' && - match.tournamentCodeIds.length > 0 - ) { - await this.tournamentCodeService.releaseFromMatch(match); + 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; diff --git a/apps/api/src/modules/tournament-code/round-robin.util.spec.ts b/apps/api/src/modules/tournament-code/round-robin.util.spec.ts new file mode 100644 index 00000000..77691089 --- /dev/null +++ b/apps/api/src/modules/tournament-code/round-robin.util.spec.ts @@ -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]); + }); +}); diff --git a/apps/api/src/modules/tournament-code/round-robin.util.ts b/apps/api/src/modules/tournament-code/round-robin.util.ts new file mode 100644 index 00000000..4d928f50 --- /dev/null +++ b/apps/api/src/modules/tournament-code/round-robin.util.ts @@ -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( + 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; +} diff --git a/apps/api/src/modules/tournament-code/tournament-code.service.spec.ts b/apps/api/src/modules/tournament-code/tournament-code.service.spec.ts new file mode 100644 index 00000000..0e2c03e2 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.service.spec.ts @@ -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([]); + }); +}); diff --git a/apps/api/src/modules/tournament-code/tournament-code.service.ts b/apps/api/src/modules/tournament-code/tournament-code.service.ts index 42b66084..8801f7df 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.service.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.service.ts @@ -6,6 +6,7 @@ import { import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import type { + MatchGameAssignment, MatchDocument, TournamentCode, TournamentCodeDocument, @@ -23,6 +24,12 @@ import type { TournamentCodeSlotView, TournamentCodeUploadItem, } from './tournament-code.types'; +import { + resolveRoundRobinTeamCount, + roundRobinPairCount, + roundRobinPairs, + shuffleInPlace, +} from './round-robin.util'; const DEFAULT_REGION = 'kr'; const DEFAULT_SPECTATOR_TYPE: TournamentSpectatorType = 'ALL'; @@ -220,9 +227,16 @@ export class TournamentCodeService { if (!match) throw new NotFoundException('Match not found.'); 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 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 startGameNumber = match.tournamentCodeIds.length + 1; @@ -254,6 +268,8 @@ export class TournamentCodeService { if (reservedIds.length > 0) { match.tournamentCodeIds.push(...reservedIds); + } + if (reservedIds.length > 0 || shouldSaveMetadata) { await match.save(); } return match; @@ -324,6 +340,13 @@ export class TournamentCodeService { } public async buildSlots(match: MatchDocument): Promise { + if ( + (match.gameMode ?? 'pair') === 'round-robin' && + (match.gameSchedule?.length ?? 0) === 0 && + (match.tournamentCodeIds?.length ?? 0) === 0 + ) { + return []; + } const TournamentCodeModel = await this.connectionService.getModel('tournamentCode'); const gameCount = this.resolveRequiredSlots(match); @@ -369,6 +392,13 @@ export class TournamentCodeService { private resolveRequiredSlots(match: MatchDocument): number { 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 activeParticipantCount = (match.participants ?? []).filter( (participant) => !participant.excluded, @@ -383,6 +413,28 @@ export class TournamentCodeService { match: MatchDocument, gameNumber: 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 seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries)); return { @@ -390,4 +442,29 @@ export class TournamentCodeService { 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; + } } diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts new file mode 100644 index 00000000..baf5c0f2 --- /dev/null +++ b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts @@ -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, + }); + }); +}); diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.ts b/apps/api/src/modules/tournament-result/tournament-result.service.ts index 425d81da..9a4e6765 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.ts @@ -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 { RiotMatchService } from '../riot/riot-match.service'; import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types'; +import { + resolveRoundRobinTeamCount, + roundRobinPairCount, + roundRobinPairs, +} from '../tournament-code/round-robin.util'; import { collectCaptainUserIds, collectMatchUserIds, @@ -456,6 +461,27 @@ export class TournamentResultService { match: MatchDocument, gameNumber: 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 seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries)); return { @@ -465,6 +491,12 @@ export class TournamentResultService { } 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( (participant) => !participant.excluded, ).length; diff --git a/apps/project.env b/apps/project.env index 76b8b5d6..40dc3d0f 100644 --- a/apps/project.env +++ b/apps/project.env @@ -1,4 +1,6 @@ INFISICAL_PROJECT_ID=26a80d59-a424-4e33-adfc-2b6e84d6e25f SERVICE_NAME=lolympus-tournament-support -VERSION=0.1 \ No newline at end of file +VERSION=0.1 + +AUTH_DEV_HEADER_ENABLED=true \ No newline at end of file diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index 6375df2f..c10c4d16 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -199,6 +199,12 @@ export interface ApiMatchScheduleItem { label: string; } +export interface ApiMatchGameAssignment { + gameNumber: number; + teamAIndex: number; + teamBIndex: number; +} + export interface ApiMatch { _id: string; communityId: string; @@ -211,6 +217,7 @@ export interface ApiMatch { maxParticipants: number; gameCount: number; gameMode: MatchGameMode; + gameSchedule?: ApiMatchGameAssignment[]; tournamentCodes?: TournamentCodeSlotView[]; hostUserId?: string; participants: ApiMatchParticipant[]; diff --git a/apps/web/src/pages/admin/MatchAdminPage.tsx b/apps/web/src/pages/admin/MatchAdminPage.tsx index 5e134004..ac094df7 100644 --- a/apps/web/src/pages/admin/MatchAdminPage.tsx +++ b/apps/web/src/pages/admin/MatchAdminPage.tsx @@ -35,6 +35,14 @@ const GAME_MODE_LABEL: Record = { 'round-robin': '라운드 로빈', }; +function RequiredBadge() { + return ( + + 필수 + + ); +} + function toInputValue(value: string | Date) { const date = value instanceof Date ? value : new Date(value); const offset = date.getTimezoneOffset(); @@ -169,11 +177,16 @@ export default function MatchAdminPage() { function submit() { setMessage(null); - const payload = buildPayload(); - if (!payload.title) { + if (!form.title.trim()) { setMessage('제목을 입력해주세요.'); return; } + if (!form.scheduledAt) { + setMessage('시작 시간을 입력해주세요.'); + return; + } + + const payload = buildPayload(); const callbacks = { onSuccess: async () => { @@ -244,7 +257,9 @@ export default function MatchAdminPage() {