feat: add limited round-robin scheduling

This commit is contained in:
dahyeon committed 2026-06-19 01:13:50 -07:00
1 parent 24983aeb09
commit 658592973e
15 files changed
+403 -63

No files matched your search

@@ -487,6 +487,7 @@ export interface MatchSeriesResult {
export interface MatchGameAssignment { export interface MatchGameAssignment {
gameNumber: number; gameNumber: number;
roundNumber?: number;
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
} }
@@ -524,6 +525,7 @@ export interface Match extends MongooseTimestamps {
maxParticipants: number; maxParticipants: number;
gameCount: number; gameCount: number;
gameMode: MatchGameMode; gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
tournamentCodeIds: mongoose.Types.ObjectId[]; tournamentCodeIds: mongoose.Types.ObjectId[];
gameSchedule: MatchGameAssignment[]; gameSchedule: MatchGameAssignment[];
teamBuiltAt?: Date; teamBuiltAt?: Date;
@@ -1284,6 +1286,7 @@ const MatchSeriesResultSubSchema = new Schema<MatchSeriesResult>(
const MatchGameAssignmentSubSchema = new Schema<MatchGameAssignment>( const MatchGameAssignmentSubSchema = new Schema<MatchGameAssignment>(
{ {
gameNumber: { type: Number, required: true, min: 1 }, gameNumber: { type: Number, required: true, min: 1 },
roundNumber: { type: Number, required: false, min: 1 },
teamAIndex: { type: Number, required: true, min: 1 }, teamAIndex: { type: Number, required: true, min: 1 },
teamBIndex: { type: Number, required: true, min: 1 }, teamBIndex: { type: Number, required: true, min: 1 },
}, },
@@ -1389,6 +1392,7 @@ export const MatchSchema = new Schema<Match>(
required: true, required: true,
default: 'pair', default: 'pair',
}, },
roundRobinMaxRounds: { type: Number, required: false, min: 1 },
tournamentCodeIds: { tournamentCodeIds: {
type: [{ type: Schema.Types.ObjectId, ref: 'tournamentCode' }], type: [{ type: Schema.Types.ObjectId, ref: 'tournamentCode' }],
required: true, required: true,
@@ -101,6 +101,11 @@ export class CreateMatchDto {
@IsEnum(MATCH_GAME_MODES) @IsEnum(MATCH_GAME_MODES)
gameMode?: MatchGameMode; gameMode?: MatchGameMode;
@IsOptional()
@IsInt()
@Min(1)
roundRobinMaxRounds?: number;
@IsOptional() @IsOptional()
@IsArray() @IsArray()
@IsString({ each: true }) @IsString({ each: true })
@@ -156,6 +161,11 @@ export class UpdateMatchDto {
@IsEnum(MATCH_GAME_MODES) @IsEnum(MATCH_GAME_MODES)
gameMode?: MatchGameMode; gameMode?: MatchGameMode;
@IsOptional()
@IsInt()
@Min(1)
roundRobinMaxRounds?: number;
@IsOptional() @IsOptional()
@IsArray() @IsArray()
@IsString({ each: true }) @IsString({ each: true })
@@ -57,6 +57,7 @@ export class MatchController {
maxParticipants: body.maxParticipants ?? 10, maxParticipants: body.maxParticipants ?? 10,
gameCount: body.gameCount, gameCount: body.gameCount,
gameMode: body.gameMode ?? 'pair', gameMode: body.gameMode ?? 'pair',
roundRobinMaxRounds: body.roundRobinMaxRounds,
prizes: body.prizes ?? [], prizes: body.prizes ?? [],
notices: body.notices ?? [], notices: body.notices ?? [],
schedule: body.schedule ?? [], schedule: body.schedule ?? [],
@@ -292,6 +292,29 @@ describe('MatchService', () => {
expect(matchStatsService.removeByMatch).toHaveBeenCalledWith(match._id); expect(matchStatsService.removeByMatch).toHaveBeenCalledWith(match._id);
}); });
it('rejects round-robin max round changes after recruiting', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
communityId,
status: 'team-built',
tournamentCodeIds: [],
set: jest.fn(),
save: jest.fn().mockResolvedValue(undefined),
};
const { service } = createService(match);
await expect(
service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { roundRobinMaxRounds: 3 },
}),
).rejects.toThrow(
'maxParticipants, gameMode, and roundRobinMaxRounds can only be changed while recruiting.',
);
expect(match.set).not.toHaveBeenCalled();
});
it('releases reserved codes when returning a built match to recruiting', async () => { it('releases reserved codes when returning a built match to recruiting', async () => {
const communityId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId();
const codeId = new mongoose.Types.ObjectId(); const codeId = new mongoose.Types.ObjectId();
+4 -2
View File
@@ -214,10 +214,12 @@ export class MatchService {
const previousStatus = match.status; const previousStatus = match.status;
if ( if (
previousStatus !== 'recruiting' && previousStatus !== 'recruiting' &&
('maxParticipants' in params.patch || 'gameMode' in params.patch) ('maxParticipants' in params.patch ||
'gameMode' in params.patch ||
'roundRobinMaxRounds' in params.patch)
) { ) {
throw new BadRequestException( throw new BadRequestException(
'maxParticipants and gameMode can only be changed while recruiting.', 'maxParticipants, gameMode, and roundRobinMaxRounds can only be changed while recruiting.',
); );
} }
match.set(params.patch); match.set(params.patch);
@@ -1,5 +1,6 @@
import { import {
resolveRoundRobinTeamCount, resolveRoundRobinTeamCount,
roundRobinGameSchedule,
roundRobinPairCount, roundRobinPairCount,
roundRobinPairs, roundRobinPairs,
shuffleInPlace, shuffleInPlace,
@@ -25,6 +26,30 @@ describe('round-robin util', () => {
expect(roundRobinPairCount(6)).toBe(15); expect(roundRobinPairCount(6)).toBe(15);
}); });
it('builds round-robin games grouped into simultaneously playable rounds', () => {
const schedule = roundRobinGameSchedule(6, { gamesPerPair: 1 });
expect(schedule).toHaveLength(15);
for (const roundNumber of [1, 2, 3, 4, 5]) {
const round = schedule.filter((game) => game.roundNumber === roundNumber);
expect(round).toHaveLength(3);
expect(new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex])))
.toHaveProperty('size', 6);
}
});
it('limits round-robin games by max rounds', () => {
const schedule = roundRobinGameSchedule(8, {
gamesPerPair: 1,
maxRounds: 3,
});
expect(schedule).toHaveLength(12);
expect(new Set(schedule.map((game) => game.roundNumber))).toEqual(
new Set([1, 2, 3]),
);
});
it('resolves team count from teams first, then active participants', () => { it('resolves team count from teams first, then active participants', () => {
expect( expect(
resolveRoundRobinTeamCount({ resolveRoundRobinTeamCount({
@@ -3,11 +3,23 @@ export interface RoundRobinPair {
teamBIndex: number; teamBIndex: number;
} }
export interface RoundRobinGameAssignment extends RoundRobinPair {
gameNumber: number;
roundNumber: number;
}
export interface RoundRobinTeamCountInput { export interface RoundRobinTeamCountInput {
teams?: Array<{ teamIndex: number }>; teams?: Array<{ teamIndex: number }>;
participants: Array<{ excluded?: boolean }>; participants: Array<{ excluded?: boolean }>;
} }
export interface RoundRobinGameScheduleOptions {
gamesPerPair?: number;
maxRounds?: number;
rng?: () => number;
shuffleTeams?: boolean;
}
export function roundRobinPairs(teamCount: number): RoundRobinPair[] { export function roundRobinPairs(teamCount: number): RoundRobinPair[] {
const pairs: RoundRobinPair[] = []; const pairs: RoundRobinPair[] = [];
for (let teamAIndex = 1; teamAIndex <= teamCount; teamAIndex += 1) { for (let teamAIndex = 1; teamAIndex <= teamCount; teamAIndex += 1) {
@@ -27,6 +39,70 @@ export function roundRobinPairCount(teamCount: number): number {
return (teamCount * (teamCount - 1)) / 2; return (teamCount * (teamCount - 1)) / 2;
} }
export function roundRobinRoundCount(teamCount: number): number {
if (teamCount < 2) return 0;
return teamCount % 2 === 0 ? teamCount - 1 : teamCount;
}
export function roundRobinGameSchedule(
teamCount: number,
options: RoundRobinGameScheduleOptions = {},
): RoundRobinGameAssignment[] {
if (teamCount < 2) return [];
const rawGamesPerPair = options.gamesPerPair ?? 1;
const gamesPerPair = Number.isFinite(rawGamesPerPair)
? Math.max(1, Math.floor(rawGamesPerPair))
: 1;
const fullRoundCount = roundRobinRoundCount(teamCount);
const requestedRoundCount =
typeof options.maxRounds === 'number' && Number.isFinite(options.maxRounds)
? Math.floor(options.maxRounds)
: fullRoundCount;
const roundLimit = Math.max(
0,
Math.min(fullRoundCount, requestedRoundCount),
);
if (roundLimit === 0) return [];
const bye = 0;
const teams = Array.from({ length: teamCount }, (_, index) => index + 1);
if (options.shuffleTeams) shuffleInPlace(teams, options.rng);
if (teams.length % 2 === 1) teams.push(bye);
const rotating = [...teams];
const schedule: RoundRobinGameAssignment[] = [];
let gameNumber = 1;
for (let roundIndex = 0; roundIndex < roundLimit; roundIndex += 1) {
const roundNumber = roundIndex + 1;
for (let index = 0; index < rotating.length / 2; index += 1) {
const left = rotating[index];
const right = rotating[rotating.length - 1 - index];
if (left === bye || right === bye) continue;
const teamAIndex = Math.min(left, right);
const teamBIndex = Math.max(left, right);
for (let gameIndex = 0; gameIndex < gamesPerPair; gameIndex += 1) {
schedule.push({
gameNumber,
roundNumber,
teamAIndex,
teamBIndex,
});
gameNumber += 1;
}
}
const fixed = rotating[0];
const tail = rotating.slice(1);
tail.unshift(tail.pop() as number);
rotating.splice(0, rotating.length, fixed, ...tail);
}
return schedule;
}
export function resolveRoundRobinTeamCount( export function resolveRoundRobinTeamCount(
match: RoundRobinTeamCountInput, match: RoundRobinTeamCountInput,
): number { ): number {
@@ -19,10 +19,12 @@ function createService() {
interface MatchOverrides { interface MatchOverrides {
gameCount?: number; gameCount?: number;
gameMode?: 'pair' | 'bracket' | 'round-robin'; gameMode?: 'pair' | 'bracket' | 'round-robin';
roundRobinMaxRounds?: number;
participants?: Array<{ excluded?: boolean }>; participants?: Array<{ excluded?: boolean }>;
teams?: Array<{ teamIndex: number }>; teams?: Array<{ teamIndex: number }>;
gameSchedule?: Array<{ gameSchedule?: Array<{
gameNumber: number; gameNumber: number;
roundNumber?: number;
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
}>; }>;
@@ -102,6 +104,23 @@ describe('TournamentCodeService round-robin scheduling', () => {
).toBe(15); ).toBe(15);
}); });
it('calculates limited round-robin slots from max rounds', () => {
const service = createService();
expect(
service.resolveRequiredSlots(
createMatch({
gameMode: 'round-robin',
gameCount: 1,
roundRobinMaxRounds: 3,
teams: Array.from({ length: 8 }, (_, index) => ({
teamIndex: index + 1,
})),
}),
),
).toBe(12);
});
it('uses persisted round-robin game schedule for game refs', () => { it('uses persisted round-robin game schedule for game refs', () => {
const service = createService(); const service = createService();
const match = createMatch({ const match = createMatch({
@@ -124,7 +143,7 @@ describe('TournamentCodeService round-robin scheduling', () => {
}); });
}); });
it('falls back to lexicographic round-robin pairs before schedule is persisted', () => { it('falls back to round-based pairs before schedule is persisted', () => {
const service = createService(); const service = createService();
const match = createMatch({ const match = createMatch({
gameMode: 'round-robin', gameMode: 'round-robin',
@@ -137,10 +156,10 @@ describe('TournamentCodeService round-robin scheduling', () => {
expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({ expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({
teamAIndex: 1, teamAIndex: 1,
teamBIndex: 2, teamBIndex: 4,
}); });
expect(service.resolveSeriesRefForGameNumber(match, 2)).toEqual({ expect(service.resolveSeriesRefForGameNumber(match, 2)).toEqual({
teamAIndex: 1, teamAIndex: 2,
teamBIndex: 3, teamBIndex: 3,
}); });
}); });
@@ -173,6 +192,31 @@ describe('TournamentCodeService round-robin scheduling', () => {
expect(pair.gameSchedule).toEqual([]); expect(pair.gameSchedule).toEqual([]);
}); });
it('creates a limited round-robin schedule grouped by playable rounds', () => {
const service = createService();
const roundRobin = createMatch({
gameMode: 'round-robin',
gameCount: 1,
roundRobinMaxRounds: 3,
teams: Array.from({ length: 8 }, (_, index) => ({
teamIndex: index + 1,
})),
gameSchedule: [],
});
service.ensureGameSchedule(roundRobin);
expect(roundRobin.gameSchedule).toHaveLength(12);
for (const roundNumber of [1, 2, 3]) {
const round = roundRobin.gameSchedule.filter(
(game) => game.roundNumber === roundNumber,
);
expect(round).toHaveLength(4);
expect(new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex])).size)
.toBe(8);
}
});
it('does not expose fallback round-robin slots before the schedule is persisted', async () => { it('does not expose fallback round-robin slots before the schedule is persisted', async () => {
const service = createService(); const service = createService();
const slots = await service.buildSlots( const slots = await service.buildSlots(
@@ -25,10 +25,8 @@ import type {
TournamentCodeUploadItem, TournamentCodeUploadItem,
} from './tournament-code.types'; } from './tournament-code.types';
import { import {
roundRobinGameSchedule,
resolveRoundRobinTeamCount, resolveRoundRobinTeamCount,
roundRobinPairCount,
roundRobinPairs,
shuffleInPlace,
} from './round-robin.util'; } from './round-robin.util';
const DEFAULT_REGION = 'kr'; const DEFAULT_REGION = 'kr';
@@ -368,6 +366,7 @@ export class TournamentCodeService {
const seriesRef = this.resolveSeriesRefForGameNumber(match, gameNumber); const seriesRef = this.resolveSeriesRefForGameNumber(match, gameNumber);
return { return {
gameNumber, gameNumber,
roundNumber: this.resolveRoundNumberForGameNumber(match, gameNumber),
...seriesRef, ...seriesRef,
code: null, code: null,
expiresAt: null, expiresAt: null,
@@ -377,6 +376,7 @@ export class TournamentCodeService {
} }
return { return {
gameNumber, gameNumber,
roundNumber: this.resolveRoundNumberForGameNumber(match, gameNumber),
...this.resolveSeriesRefForGameNumber(match, gameNumber), ...this.resolveSeriesRefForGameNumber(match, gameNumber),
code: code.code, code: code.code,
expiresAt: code.expiresAt.toISOString(), expiresAt: code.expiresAt.toISOString(),
@@ -395,8 +395,10 @@ export class TournamentCodeService {
const gameMode = match.gameMode ?? 'pair'; const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'round-robin') { if (gameMode === 'round-robin') {
const teamCount = resolveRoundRobinTeamCount(match); if ((match.gameSchedule?.length ?? 0) > 0) {
return roundRobinPairCount(teamCount) * gameCount; return match.gameSchedule.length;
}
return this.buildRoundRobinGameSchedule(match).length;
} }
const teamCount = (match.teams ?? []).length; const teamCount = (match.teams ?? []).length;
@@ -426,13 +428,18 @@ export class TournamentCodeService {
}; };
} }
const teamCount = resolveRoundRobinTeamCount(match); const fallback = this.buildRoundRobinGameSchedule(match).find(
const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; (entry) => entry.gameNumber === gameNumber,
const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1); );
return roundRobinPairs(teamCount)[pairIndex] ?? { return fallback
teamAIndex: 1, ? {
teamBIndex: 2, teamAIndex: fallback.teamAIndex,
}; teamBIndex: fallback.teamBIndex,
}
: {
teamAIndex: 1,
teamBIndex: 2,
};
} }
const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
@@ -450,21 +457,33 @@ export class TournamentCodeService {
const teamCount = resolveRoundRobinTeamCount(match); const teamCount = resolveRoundRobinTeamCount(match);
if (teamCount < 2) return; if (teamCount < 2) return;
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; match.gameSchedule = this.buildRoundRobinGameSchedule(match, true);
const pairs = shuffleInPlace([...roundRobinPairs(teamCount)]); }
const schedule: MatchGameAssignment[] = [];
for (let pairIndex = 0; pairIndex < pairs.length; pairIndex += 1) { private resolveRoundNumberForGameNumber(
const pair = pairs[pairIndex]; match: MatchDocument,
for (let gameIndex = 0; gameIndex < gameCount; gameIndex += 1) { gameNumber: number,
schedule.push({ ): number | undefined {
gameNumber: pairIndex * gameCount + gameIndex + 1, if ((match.gameMode ?? 'pair') !== 'round-robin') return undefined;
teamAIndex: pair.teamAIndex,
teamBIndex: pair.teamBIndex,
});
}
}
match.gameSchedule = schedule; const persisted = match.gameSchedule?.find(
(entry) => entry.gameNumber === gameNumber,
);
if (persisted?.roundNumber) return persisted.roundNumber;
return this.buildRoundRobinGameSchedule(match).find(
(entry) => entry.gameNumber === gameNumber,
)?.roundNumber;
}
private buildRoundRobinGameSchedule(
match: MatchDocument,
shuffleTeams = false,
): MatchGameAssignment[] {
return roundRobinGameSchedule(resolveRoundRobinTeamCount(match), {
gamesPerPair: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
maxRounds: match.roundRobinMaxRounds,
shuffleTeams,
});
} }
} }
@@ -24,6 +24,7 @@ export interface BulkUploadTournamentCodesResponse {
export interface TournamentCodeSlotView { export interface TournamentCodeSlotView {
gameNumber: number; gameNumber: number;
roundNumber?: number;
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
code: string | null; code: string | null;
@@ -24,10 +24,12 @@ function createService() {
interface MatchOverrides { interface MatchOverrides {
gameCount?: number; gameCount?: number;
gameMode?: 'pair' | 'bracket' | 'round-robin'; gameMode?: 'pair' | 'bracket' | 'round-robin';
roundRobinMaxRounds?: number;
participants?: Array<{ excluded?: boolean }>; participants?: Array<{ excluded?: boolean }>;
teams?: Array<{ teamIndex: number }>; teams?: Array<{ teamIndex: number }>;
gameSchedule?: Array<{ gameSchedule?: Array<{
gameNumber: number; gameNumber: number;
roundNumber?: number;
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
}>; }>;
@@ -58,6 +60,20 @@ describe('TournamentResultService round-robin scheduling', () => {
expect(service.resolveRequiredGameSlots(match)).toBe(15); expect(service.resolveRequiredGameSlots(match)).toBe(15);
}); });
it('calculates limited round-robin slots for polling', () => {
const service = createService();
const match = createMatch({
gameMode: 'round-robin',
gameCount: 1,
roundRobinMaxRounds: 3,
teams: Array.from({ length: 8 }, (_, index) => ({
teamIndex: index + 1,
})),
});
expect(service.resolveRequiredGameSlots(match)).toBe(12);
});
it('uses persisted round-robin schedule when mapping a game number', () => { it('uses persisted round-robin schedule when mapping a game number', () => {
const service = createService(); const service = createService();
const match = createMatch({ const match = createMatch({
@@ -19,9 +19,8 @@ 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 { import {
roundRobinGameSchedule,
resolveRoundRobinTeamCount, resolveRoundRobinTeamCount,
roundRobinPairCount,
roundRobinPairs,
} from '../tournament-code/round-robin.util'; } from '../tournament-code/round-robin.util';
import { import {
collectCaptainUserIds, collectCaptainUserIds,
@@ -785,14 +784,18 @@ export class TournamentResultService {
}; };
} }
const perSeries = match.gameCount || 1; const fallback = this.buildRoundRobinGameSchedule(match).find(
const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1); (entry) => entry.gameNumber === gameNumber,
return (
roundRobinPairs(resolveRoundRobinTeamCount(match))[pairIndex] ?? {
teamAIndex: 1,
teamBIndex: 2,
}
); );
return fallback
? {
teamAIndex: fallback.teamAIndex,
teamBIndex: fallback.teamBIndex,
}
: {
teamAIndex: 1,
teamBIndex: 2,
};
} }
const perSeries = match.gameCount || 1; const perSeries = match.gameCount || 1;
@@ -806,8 +809,10 @@ export class TournamentResultService {
private resolveRequiredGameSlots(match: MatchDocument): number { private resolveRequiredGameSlots(match: MatchDocument): number {
const gameMode = match.gameMode ?? 'pair'; const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'round-robin') { if (gameMode === 'round-robin') {
const teamCount = resolveRoundRobinTeamCount(match); if ((match.gameSchedule?.length ?? 0) > 0) {
return roundRobinPairCount(teamCount) * (match.gameCount || 1); return match.gameSchedule.length;
}
return this.buildRoundRobinGameSchedule(match).length;
} }
const activeParticipantCount = match.participants.filter( const activeParticipantCount = match.participants.filter(
@@ -819,6 +824,13 @@ export class TournamentResultService {
return seriesCount * (match.gameCount || 1); return seriesCount * (match.gameCount || 1);
} }
private buildRoundRobinGameSchedule(match: MatchDocument) {
return roundRobinGameSchedule(resolveRoundRobinTeamCount(match), {
gamesPerPair: match.gameCount || 1,
maxRounds: match.roundRobinMaxRounds,
});
}
private resolveMatchWinnerTeamIndex( private resolveMatchWinnerTeamIndex(
seriesResults: NonNullable<MatchDocument['result']>['seriesResults'], seriesResults: NonNullable<MatchDocument['result']>['seriesResults'],
): number | undefined { ): number | undefined {
+4
View File
@@ -142,6 +142,7 @@ export type TournamentCodeSlotState = TournamentCodeState | 'pending';
export interface TournamentCodeSlotView { export interface TournamentCodeSlotView {
gameNumber: number; gameNumber: number;
roundNumber?: number;
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
code: string | null; code: string | null;
@@ -219,6 +220,7 @@ export interface ApiMatchScheduleItem {
export interface ApiMatchGameAssignment { export interface ApiMatchGameAssignment {
gameNumber: number; gameNumber: number;
roundNumber?: number;
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
} }
@@ -243,6 +245,7 @@ export interface ApiMatch {
maxParticipants: number; maxParticipants: number;
gameCount: number; gameCount: number;
gameMode: MatchGameMode; gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
gameSchedule?: ApiMatchGameAssignment[]; gameSchedule?: ApiMatchGameAssignment[];
tournamentCodes?: TournamentCodeSlotView[]; tournamentCodes?: TournamentCodeSlotView[];
hostUserId?: string; hostUserId?: string;
@@ -371,6 +374,7 @@ export interface MatchMutationRequest {
maxParticipants?: number; maxParticipants?: number;
gameCount?: number; gameCount?: number;
gameMode?: MatchGameMode; gameMode?: MatchGameMode;
roundRobinMaxRounds?: number;
prizes?: string[]; prizes?: string[];
notices?: string[]; notices?: string[];
schedule?: ApiMatchScheduleItem[]; schedule?: ApiMatchScheduleItem[];
+55 -20
View File
@@ -1467,28 +1467,63 @@ function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) {
); );
} }
return ( function renderSlot(slot: TournamentCodeSlotView) {
<div className="space-y-2"> return (
{slots.map((slot) => ( <div key={slot.gameNumber} className="flex items-start gap-2">
<div key={slot.gameNumber} className="flex items-start gap-2"> <span className="text-xs font-bold text-base-content/40 w-20 shrink-0 pt-1.5">
<span className="text-xs font-bold text-base-content/40 w-20 shrink-0 pt-1.5"> {slot.gameNumber}경기
{slot.gameNumber}경기 {(slot.teamAIndex > 1 || slot.teamBIndex > 2) && (
{(slot.teamAIndex > 1 || slot.teamBIndex > 2) && ( <span className="block text-xs font-normal text-base-content/25">
<span className="block text-xs font-normal text-base-content/25"> {teamIndexLabel(slot.teamAIndex)} vs{" "}
{teamIndexLabel(slot.teamAIndex)} vs{" "} {teamIndexLabel(slot.teamBIndex)}
{teamIndexLabel(slot.teamBIndex)}
</span>
)}
</span>
{slot.code ? (
<TournamentCodeDisplay slot={slot} />
) : (
<span className="text-xs text-base-content/30 border border-dashed border-base-content/10 px-2 py-2 flex-1">
발급 대기 중... 운영자가 코드를 채우면 자동으로 붙습니다.
</span> </span>
)} )}
</div> </span>
))} {slot.code ? (
<TournamentCodeDisplay slot={slot} />
) : (
<span className="text-xs text-base-content/30 border border-dashed border-base-content/10 px-2 py-2 flex-1">
발급 대기 중... 운영자가 코드를 채우면 자동으로 붙습니다.
</span>
)}
</div>
);
}
if (slots.some((slot) => slot.roundNumber)) {
const slotsByRound = slots.reduce<
Map<number, TournamentCodeSlotView[]>
>((map, slot) => {
const roundNumber = slot.roundNumber ?? 0;
const roundSlots = map.get(roundNumber) ?? [];
roundSlots.push(slot);
map.set(roundNumber, roundSlots);
return map;
}, new Map());
return (
<div className="space-y-3">
{[...slotsByRound.entries()]
.sort(([left], [right]) => left - right)
.map(([roundNumber, roundSlots]) => (
<div key={roundNumber}>
<div className="mb-1 text-xs font-bold text-base-content/45">
{roundNumber}라운드
</div>
<div className="space-y-2">
{roundSlots
.sort((left, right) => left.gameNumber - right.gameNumber)
.map(renderSlot)}
</div>
</div>
))}
</div>
);
}
return (
<div className="space-y-2">
{slots.map(renderSlot)}
</div> </div>
); );
} }
+69 -1
View File
@@ -35,6 +35,21 @@ const GAME_MODE_LABEL: Record<MatchGameMode, string> = {
'round-robin': '라운드 로빈', 'round-robin': '라운드 로빈',
}; };
function resolveRoundRobinFullRoundCount(maxParticipants?: number) {
const teamCount = Math.floor(Number(maxParticipants ?? 10) / 5);
if (teamCount < 2) return 0;
return teamCount % 2 === 0 ? teamCount - 1 : teamCount;
}
function normalizeRoundRobinMaxRounds(
value: number | undefined,
maxParticipants?: number,
) {
if (!value || !Number.isFinite(value)) return undefined;
const fullRoundCount = resolveRoundRobinFullRoundCount(maxParticipants);
return Math.max(1, Math.min(fullRoundCount, Math.floor(value)));
}
function RequiredBadge() { function RequiredBadge() {
return ( return (
<span className="ml-1 inline-flex items-center border border-primary/20 bg-primary/5 px-1.5 py-0.5 text-xs font-bold text-primary"> <span className="ml-1 inline-flex items-center border border-primary/20 bg-primary/5 px-1.5 py-0.5 text-xs font-bold text-primary">
@@ -106,6 +121,7 @@ function makeForm(match?: ApiMatch): MatchMutationRequest & {
maxParticipants: match.maxParticipants, maxParticipants: match.maxParticipants,
gameCount: match.gameCount, gameCount: match.gameCount,
gameMode: match.gameMode ?? 'pair', gameMode: match.gameMode ?? 'pair',
roundRobinMaxRounds: match.roundRobinMaxRounds,
prizes: match.prizes, prizes: match.prizes,
notices: match.notices, notices: match.notices,
schedule: match.schedule, schedule: match.schedule,
@@ -138,6 +154,9 @@ export default function MatchAdminPage() {
() => [...(matchesQuery.data ?? [])].sort((a, b) => new Date(b.scheduledAt).getTime() - new Date(a.scheduledAt).getTime()), () => [...(matchesQuery.data ?? [])].sort((a, b) => new Date(b.scheduledAt).getTime() - new Date(a.scheduledAt).getTime()),
[matchesQuery.data], [matchesQuery.data],
); );
const roundRobinFullRoundCount = resolveRoundRobinFullRoundCount(
form.maxParticipants,
);
async function invalidate() { async function invalidate() {
await Promise.all([ await Promise.all([
@@ -169,6 +188,13 @@ export default function MatchAdminPage() {
maxParticipants: Number(form.maxParticipants ?? 10), maxParticipants: Number(form.maxParticipants ?? 10),
gameCount: Number(form.gameCount ?? 3), gameCount: Number(form.gameCount ?? 3),
gameMode: form.gameMode, gameMode: form.gameMode,
roundRobinMaxRounds:
form.gameMode === 'round-robin'
? normalizeRoundRobinMaxRounds(
form.roundRobinMaxRounds,
form.maxParticipants,
)
: undefined,
prizes: parseLines(form.prizesText), prizes: parseLines(form.prizesText),
notices: parseLines(form.noticesText), notices: parseLines(form.noticesText),
schedule: parseSchedule(form.scheduleText), schedule: parseSchedule(form.scheduleText),
@@ -290,7 +316,17 @@ export default function MatchAdminPage() {
정원 정원
<select <select
value={form.maxParticipants} value={form.maxParticipants}
onChange={(event) => setForm((current) => ({ ...current, maxParticipants: Number(event.target.value) }))} onChange={(event) => {
const maxParticipants = Number(event.target.value);
setForm((current) => ({
...current,
maxParticipants,
roundRobinMaxRounds: normalizeRoundRobinMaxRounds(
current.roundRobinMaxRounds,
maxParticipants,
),
}));
}}
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"
> >
{[10, 20, 30, 40, 50, 60].map((value) => ( {[10, 20, 30, 40, 50, 60].map((value) => (
@@ -323,6 +359,32 @@ export default function MatchAdminPage() {
현재 경매/코드 연결은 페어 방식 기준으로 동작합니다. 현재 경매/코드 연결은 페어 방식 기준으로 동작합니다.
</span> </span>
</label> </label>
{form.gameMode === 'round-robin' && (
<label className="text-xs text-base-content/45">
최대 라운드 수
<span className="ml-1 text-xs text-base-content/25">선택</span>
<input
type="number"
min={1}
max={roundRobinFullRoundCount || undefined}
placeholder="예: 3"
value={form.roundRobinMaxRounds ?? ''}
onChange={(event) =>
setForm((current) => ({
...current,
roundRobinMaxRounds:
event.target.value === ''
? undefined
: Number(event.target.value),
}))
}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
/>
<span className="mt-1 block text-xs text-base-content/30">
비워두면 전체 {roundRobinFullRoundCount}라운드로 생성됩니다.
</span>
</label>
)}
<label className="text-xs text-base-content/45"> <label className="text-xs text-base-content/45">
상품 (줄바꿈 구분) 상품 (줄바꿈 구분)
<textarea <textarea
@@ -406,6 +468,12 @@ export default function MatchAdminPage() {
</td> </td>
<td className="px-3 py-2 text-xs"> <td className="px-3 py-2 text-xs">
{GAME_MODE_LABEL[match.gameMode ?? 'pair']} {GAME_MODE_LABEL[match.gameMode ?? 'pair']}
{match.gameMode === 'round-robin' &&
match.roundRobinMaxRounds && (
<span className="block text-xs text-base-content/30">
최대 {match.roundRobinMaxRounds}R
</span>
)}
</td> </td>
<td className="px-3 py-2 text-right"> <td className="px-3 py-2 text-right">
<div className="inline-flex gap-2"> <div className="inline-flex gap-2">