Compare commits

..
9 Commits
26 changed files with 3124 additions and 177 deletions

No files matched your search

@@ -0,0 +1,680 @@
import 'reflect-metadata';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import mongoose from 'mongoose';
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import {
ConnectionService,
resolveMongoDbName,
} from '../connection.service';
import type {
MatchDocument,
MatchGameAssignment,
MatchGameResult,
MatchSeriesResult,
TournamentCodeDocument,
} from '../schema';
import { SecretModule } from '../../secret/secret.module';
import { MatchStatsFragmentBuilder } from '../../../community-stats/match-stats-fragment.builder';
import { MatchStatsRepository } from '../../../community-stats/match-stats.repository';
import { MatchStatsService } from '../../../community-stats/match-stats.service';
interface CliOptions {
dryRun: boolean;
matchId: mongoose.Types.ObjectId;
maxRounds: number;
nodeEnv: string;
}
interface ResultGamePlan {
oldGameNumber: number;
newGameNumber: number;
roundNumber: number;
teamAIndex: number;
teamBIndex: number;
game: MatchGameResult;
}
interface RepairPlan {
schedule: MatchGameAssignment[];
gamePlans: ResultGamePlan[];
seriesResults: MatchSeriesResult[];
winnerTeamIndex?: number;
usedCodeByOldGameNumber: Map<number, TournamentCodeDocument>;
releasedCodes: TournamentCodeDocument[];
}
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: [
resolve(__dirname, '../../../../../../project.env'),
resolve(process.cwd(), '../project.env'),
resolve(process.cwd(), 'apps/project.env'),
resolve(process.cwd(), 'project.env'),
],
}),
SecretModule,
],
providers: [
ConnectionService,
MatchStatsFragmentBuilder,
MatchStatsRepository,
MatchStatsService,
],
})
class RepairModule {}
async function loadMachineEnvFile() {
const homeDir = process.env.HOME ?? process.env.USERPROFILE;
if (!homeDir) return;
const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt');
try {
const file = await readFile(machineEnvFile, 'utf8');
for (const rawLine of file.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith('#')) continue;
const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
if (!matched) continue;
const [, key, rawValue] = matched;
process.env[key] = rawValue.replace(/^["']|["']$/g, '');
}
} catch {
// 로컬 machine env 파일이 없으면 그냥 지나간다.
}
}
function parseArgs(argv: string[]): CliOptions {
let dryRun = true;
let matchId: mongoose.Types.ObjectId | undefined;
let maxRounds = 3;
let nodeEnv = process.env.NODE_ENV ?? 'dev';
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === '--apply') {
dryRun = false;
continue;
}
if (arg === '--dry-run') {
dryRun = true;
continue;
}
if (arg === '--match-id') {
const value = argv[index + 1];
if (!value || !mongoose.isValidObjectId(value)) {
throw new Error('--match-id requires a valid ObjectId.');
}
matchId = new mongoose.Types.ObjectId(value);
index += 1;
continue;
}
if (arg.startsWith('--match-id=')) {
const value = arg.slice('--match-id='.length);
if (!mongoose.isValidObjectId(value)) {
throw new Error('--match-id requires a valid ObjectId.');
}
matchId = new mongoose.Types.ObjectId(value);
continue;
}
if (arg === '--max-rounds') {
maxRounds = parsePositiveInteger(argv[index + 1], '--max-rounds');
index += 1;
continue;
}
if (arg.startsWith('--max-rounds=')) {
maxRounds = parsePositiveInteger(
arg.slice('--max-rounds='.length),
'--max-rounds',
);
continue;
}
if (arg === '--env') {
const value = argv[index + 1];
if (!value) throw new Error('--env requires dev, staging, or prod.');
nodeEnv = value;
index += 1;
continue;
}
if (arg.startsWith('--env=')) {
nodeEnv = arg.slice('--env='.length);
continue;
}
if (arg === '--help' || arg === '-h') {
printHelp();
process.exit(0);
}
throw new Error(`Unknown argument: ${arg}`);
}
if (!matchId) throw new Error('--match-id is required.');
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
throw new Error('--env must be dev, staging, or prod.');
}
return { dryRun, matchId, maxRounds, nodeEnv };
}
function parsePositiveInteger(value: string | undefined, label: string) {
const parsed = Number(value);
if (!Number.isInteger(parsed) || parsed < 1) {
throw new Error(`${label} requires a positive integer.`);
}
return parsed;
}
function printHelp() {
console.log(`Usage:
pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-limited-round-robin-finished-match.ts --match-id <id> --max-rounds 3 --dry-run
pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-limited-round-robin-finished-match.ts --match-id <id> --max-rounds 3 --env prod --apply
Options:
--match-id <id> Match ObjectId to repair.
--max-rounds <n> Number of round-robin rounds to keep. Default: 3.
--dry-run Print the repair plan without writing. Default.
--apply Apply match, tournament code, and stats updates.
--env <env> dev | staging | prod. Default: NODE_ENV or dev.
`);
}
async function main() {
const options = parseArgs(process.argv.slice(2));
process.env.NODE_ENV = options.nodeEnv;
await loadMachineEnvFile();
const app = await NestFactory.createApplicationContext(RepairModule, {
logger: ['log', 'warn', 'error'],
});
try {
const connectionService = app.get(ConnectionService);
const matchStatsService = app.get(MatchStatsService);
const MatchModel = await connectionService.getModel('match');
const TournamentCodeModel =
await connectionService.getModel('tournamentCode');
const match = await MatchModel.findById(options.matchId).exec();
if (!match) {
throw new Error(`Match not found: ${options.matchId.toString()}`);
}
const codes = await TournamentCodeModel.find({
_id: { $in: match.tournamentCodeIds ?? [] },
})
.sort({ gameNumber: 1, reservedAt: 1, _id: 1 })
.exec();
const plan = buildRepairPlan(match, codes, options.maxRounds);
printPlan(options, match, codes, plan);
if (options.dryRun) {
console.log('No writes were made. Re-run with --apply to update MongoDB.');
return;
}
const now = new Date();
const session = await (await connectionService.getConnection()).startSession();
try {
await session.withTransaction(async () => {
await applyTournamentCodeUpdates(plan, now, session);
await MatchModel.updateOne(
{ _id: match._id },
{
$set: {
status: 'finished',
roundRobinMaxRounds: options.maxRounds,
gameSchedule: plan.schedule,
tournamentCodeIds: [
...plan.usedCodeByOldGameNumber.values(),
].map((code) => code._id),
resultPollState: {
startedAt: match.resultPollState?.startedAt ?? now,
lastPolledAt: now,
lastPollOutcome: 'matched',
matchedCount: plan.gamePlans.length,
expandedToAllPuuids: true,
state: 'complete',
},
result: {
winnerTeamIndex: plan.winnerTeamIndex,
mvpUserId: match.result?.mvpUserId,
riotMatchIds: plan.gamePlans.map(
(gamePlan) => gamePlan.game.riotMatchId,
),
games: plan.gamePlans.map((gamePlan) => ({
...toPlainGame(gamePlan.game),
gameNumber: gamePlan.newGameNumber,
})),
seriesResults: plan.seriesResults,
},
},
},
{ session },
).exec();
});
} finally {
await session.endSession();
}
await matchStatsService.buildAndUpsert(match._id);
console.log('Repair applied and match stats rebuilt.');
} finally {
await app.close();
await mongoose.disconnect();
}
}
function buildRepairPlan(
match: MatchDocument,
codes: TournamentCodeDocument[],
maxRounds: number,
): RepairPlan {
if (match.gameMode !== 'round-robin') {
throw new Error(`Expected round-robin match, got ${match.gameMode}.`);
}
const games = [...(match.result?.games ?? [])]
.map(toPlainGame)
.sort((left, right) => left.gameNumber - right.gameNumber);
if (games.length === 0) {
throw new Error('Match has no result games to preserve.');
}
const teamIndexes = [...new Set(match.teams.map((team) => team.teamIndex))]
.filter((teamIndex) => Number.isInteger(teamIndex) && teamIndex > 0)
.sort((left, right) => left - right);
if (teamIndexes.length < 2) {
throw new Error('Match needs at least two teams.');
}
if (teamIndexes.length % 2 !== 0) {
throw new Error('This repair script currently expects an even team count.');
}
const gamesPerRound = teamIndexes.length / 2;
const requiredGames = gamesPerRound * maxRounds;
if (games.length !== requiredGames) {
throw new Error(
`Expected ${requiredGames} result games for ${maxRounds} rounds and ${teamIndexes.length} teams, got ${games.length}.`,
);
}
validateResultGames(games, teamIndexes);
const rounds = partitionIntoRounds(games, teamIndexes, maxRounds);
const gamePlans = rounds.flatMap((roundGames, roundIndex) =>
sortRoundGames(roundGames).map((game, gameIndex) => ({
oldGameNumber: game.gameNumber,
newGameNumber: roundIndex * gamesPerRound + gameIndex + 1,
roundNumber: roundIndex + 1,
teamAIndex: Math.min(game.blueTeamIndex, game.redTeamIndex),
teamBIndex: Math.max(game.blueTeamIndex, game.redTeamIndex),
game,
})),
);
const schedule = gamePlans.map(
({ newGameNumber, roundNumber, teamAIndex, teamBIndex }) => ({
gameNumber: newGameNumber,
roundNumber,
teamAIndex,
teamBIndex,
}),
);
const usedOldGameNumbers = new Set(
gamePlans.map((gamePlan) => gamePlan.oldGameNumber),
);
const usedCodeByOldGameNumber = resolveUsedCodesByOldGameNumber(
codes,
gamePlans,
);
const releasedCodes = codes.filter(
(code) => !usedOldGameNumbers.has(code.gameNumber ?? 0),
);
const unsafeReleased = releasedCodes.filter((code) => code.state === 'used');
if (unsafeReleased.length > 0) {
throw new Error(
`Refusing to release used tournament codes without matching result games: ${unsafeReleased
.map((code) => formatCode(code))
.join(', ')}`,
);
}
const updatedGames = gamePlans.map((gamePlan) => ({
...toPlainGame(gamePlan.game),
gameNumber: gamePlan.newGameNumber,
}));
const seriesResults = buildSeriesResults(updatedGames);
return {
schedule,
gamePlans,
seriesResults,
winnerTeamIndex: resolveMatchWinnerTeamIndex(seriesResults),
usedCodeByOldGameNumber,
releasedCodes,
};
}
function validateResultGames(games: MatchGameResult[], teamIndexes: number[]) {
const validTeamIndexes = new Set(teamIndexes);
const pairKeys = new Set<string>();
const gameNumbers = new Set<number>();
for (const game of games) {
if (gameNumbers.has(game.gameNumber)) {
throw new Error(`Duplicate result gameNumber: ${game.gameNumber}.`);
}
gameNumbers.add(game.gameNumber);
if (!validTeamIndexes.has(game.blueTeamIndex)) {
throw new Error(`Invalid blueTeamIndex ${game.blueTeamIndex}.`);
}
if (!validTeamIndexes.has(game.redTeamIndex)) {
throw new Error(`Invalid redTeamIndex ${game.redTeamIndex}.`);
}
if (game.blueTeamIndex === game.redTeamIndex) {
throw new Error(`Game ${game.gameNumber} has the same team twice.`);
}
const key = pairKey(game);
if (pairKeys.has(key)) {
throw new Error(`Duplicate team pair in results: ${key}.`);
}
pairKeys.add(key);
}
}
function partitionIntoRounds(
games: MatchGameResult[],
teamIndexes: number[],
maxRounds: number,
): MatchGameResult[][] {
const targetPerRound = teamIndexes.length / 2;
const unused = new Set(games.map((game) => game.gameNumber));
const byGameNumber = new Map(games.map((game) => [game.gameNumber, game]));
const rounds: MatchGameResult[][] = [];
function fillRound(roundIndex: number): boolean {
if (roundIndex === maxRounds) return unused.size === 0;
const candidates = enumerateRoundCandidates(
[...unused]
.map((gameNumber) => byGameNumber.get(gameNumber))
.filter((game): game is MatchGameResult => Boolean(game)),
teamIndexes,
targetPerRound,
);
for (const candidate of candidates) {
for (const game of candidate) unused.delete(game.gameNumber);
rounds[roundIndex] = candidate;
if (fillRound(roundIndex + 1)) return true;
for (const game of candidate) unused.add(game.gameNumber);
}
rounds.length = roundIndex;
return false;
}
if (!fillRound(0)) {
throw new Error('Could not partition result games into simultaneous rounds.');
}
return rounds;
}
function enumerateRoundCandidates(
availableGames: MatchGameResult[],
teamIndexes: number[],
targetPerRound: number,
): MatchGameResult[][] {
const candidates: MatchGameResult[][] = [];
function visit(usedTeams: Set<number>, chosen: MatchGameResult[]) {
if (chosen.length === targetPerRound) {
candidates.push([...chosen]);
return;
}
const nextTeam = teamIndexes.find((teamIndex) => !usedTeams.has(teamIndex));
if (!nextTeam) return;
const nextGames = availableGames
.filter((game) => {
if (!includesTeam(game, nextTeam)) return false;
return (
!usedTeams.has(game.blueTeamIndex) &&
!usedTeams.has(game.redTeamIndex)
);
})
.sort((left, right) => left.gameNumber - right.gameNumber);
for (const game of nextGames) {
chosen.push(game);
usedTeams.add(game.blueTeamIndex);
usedTeams.add(game.redTeamIndex);
visit(usedTeams, chosen);
usedTeams.delete(game.blueTeamIndex);
usedTeams.delete(game.redTeamIndex);
chosen.pop();
}
}
visit(new Set<number>(), []);
return candidates;
}
function sortRoundGames(games: MatchGameResult[]) {
return [...games].sort(
(left, right) =>
Math.min(left.blueTeamIndex, left.redTeamIndex) -
Math.min(right.blueTeamIndex, right.redTeamIndex) ||
Math.max(left.blueTeamIndex, left.redTeamIndex) -
Math.max(right.blueTeamIndex, right.redTeamIndex),
);
}
function resolveUsedCodesByOldGameNumber(
codes: TournamentCodeDocument[],
gamePlans: ResultGamePlan[],
): Map<number, TournamentCodeDocument> {
const byGameNumber = new Map<number, TournamentCodeDocument[]>();
for (const code of codes) {
if (!code.gameNumber) continue;
const existing = byGameNumber.get(code.gameNumber) ?? [];
existing.push(code);
byGameNumber.set(code.gameNumber, existing);
}
const result = new Map<number, TournamentCodeDocument>();
for (const gamePlan of gamePlans) {
const candidates = byGameNumber.get(gamePlan.oldGameNumber) ?? [];
if (candidates.length !== 1) {
throw new Error(
`Expected exactly one tournament code for old game ${gamePlan.oldGameNumber}, got ${candidates.length}.`,
);
}
const [code] = candidates;
if (code.riotMatchId && code.riotMatchId !== gamePlan.game.riotMatchId) {
throw new Error(
`Tournament code ${formatCode(code)} has riotMatchId ${code.riotMatchId}, expected ${gamePlan.game.riotMatchId}.`,
);
}
result.set(gamePlan.oldGameNumber, code);
}
return result;
}
async function applyTournamentCodeUpdates(
plan: RepairPlan,
now: Date,
session: mongoose.ClientSession,
) {
const usedOperations = plan.gamePlans.map((gamePlan) => {
const code = plan.usedCodeByOldGameNumber.get(gamePlan.oldGameNumber);
if (!code) {
throw new Error(`Missing tournament code for ${gamePlan.oldGameNumber}.`);
}
return code.updateOne(
{
$set: {
state: 'used',
gameNumber: gamePlan.newGameNumber,
riotMatchId: gamePlan.game.riotMatchId,
usedAt: resolveGameEndedAt(gamePlan.game),
},
$unset: {
releasedAt: '',
},
},
{ session },
);
});
const releasedOperations = plan.releasedCodes.map((code) =>
code.updateOne(
{
$set: {
state: 'released',
releasedAt: now,
},
$unset: {
matchId: '',
gameNumber: '',
reservedAt: '',
usedAt: '',
riotMatchId: '',
},
},
{ session },
),
);
await Promise.all([...usedOperations, ...releasedOperations]);
}
function buildSeriesResults(games: MatchGameResult[]): MatchSeriesResult[] {
const bySeries = new Map<string, MatchSeriesResult>();
for (const game of games) {
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
const key = `${teamAIndex}:${teamBIndex}`;
const current =
bySeries.get(key) ??
({
teamAIndex,
teamBIndex,
teamAWins: 0,
teamBWins: 0,
} satisfies MatchSeriesResult);
if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1;
if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1;
current.winnerTeamIndex =
current.teamAWins > current.teamBWins
? teamAIndex
: current.teamBWins > current.teamAWins
? teamBIndex
: undefined;
bySeries.set(key, current);
}
return [...bySeries.values()].sort(
(left, right) =>
left.teamAIndex - right.teamAIndex ||
left.teamBIndex - right.teamBIndex,
);
}
function resolveMatchWinnerTeamIndex(seriesResults: MatchSeriesResult[]) {
const winsByTeam = new Map<number, number>();
for (const series of seriesResults) {
if (!series.winnerTeamIndex) continue;
winsByTeam.set(
series.winnerTeamIndex,
(winsByTeam.get(series.winnerTeamIndex) ?? 0) + 1,
);
}
const sorted = [...winsByTeam.entries()].sort(
(left, right) => right[1] - left[1],
);
if (sorted.length === 0) return undefined;
if (sorted.length > 1 && sorted[0][1] === sorted[1][1]) return undefined;
return sorted[0][0];
}
function printPlan(
options: CliOptions,
match: MatchDocument,
codes: TournamentCodeDocument[],
plan: RepairPlan,
) {
console.log(
`[limited round-robin repair] mode=${options.dryRun ? 'dry-run' : 'apply'} env=${options.nodeEnv} db=${resolveMongoDbName(options.nodeEnv)}`,
);
console.log(
`[limited round-robin repair] match=${match._id.toString()} title="${match.title}"`,
);
console.log(
`[limited round-robin repair] status ${match.status} -> finished, maxRounds=${options.maxRounds}`,
);
console.log(
`[limited round-robin repair] resultGames=${plan.gamePlans.length} codes kept=${plan.usedCodeByOldGameNumber.size} codes released=${plan.releasedCodes.length} previousCodeIds=${codes.length}`,
);
console.log(
`[limited round-robin repair] winnerTeamIndex=${plan.winnerTeamIndex ?? '(tie)'}`,
);
for (const gamePlan of plan.gamePlans) {
console.log(
` R${gamePlan.roundNumber} G${gamePlan.newGameNumber}: ${gamePlan.teamAIndex}팀 vs ${gamePlan.teamBIndex}팀 (old G${gamePlan.oldGameNumber}, riot=${gamePlan.game.riotMatchId})`,
);
}
}
function toPlainGame(game: MatchGameResult): MatchGameResult {
const maybeSubdocument = game as unknown as {
toObject?: () => MatchGameResult;
};
const objectValue =
typeof maybeSubdocument.toObject === 'function'
? maybeSubdocument.toObject()
: game;
return {
...objectValue,
participants: [...(objectValue.participants ?? [])],
};
}
function includesTeam(game: MatchGameResult, teamIndex: number) {
return game.blueTeamIndex === teamIndex || game.redTeamIndex === teamIndex;
}
function pairKey(game: MatchGameResult) {
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
return `${teamAIndex}:${teamBIndex}`;
}
function resolveGameEndedAt(game: MatchGameResult) {
return new Date(game.gameCreation + game.gameDuration * 1000);
}
function formatCode(code: TournamentCodeDocument) {
return `${code._id.toString()}(gameNumber=${code.gameNumber ?? 'none'}, state=${code.state})`;
}
void main()
.then(() => {
process.exit(0);
})
.catch((error: unknown) => {
console.error(error instanceof Error ? error.message : error);
process.exit(1);
});
@@ -487,6 +487,7 @@ export interface MatchSeriesResult {
export interface MatchGameAssignment {
gameNumber: number;
roundNumber?: number;
teamAIndex: number;
teamBIndex: number;
}
@@ -524,6 +525,7 @@ export interface Match extends MongooseTimestamps {
maxParticipants: number;
gameCount: number;
gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
tournamentCodeIds: mongoose.Types.ObjectId[];
gameSchedule: MatchGameAssignment[];
teamBuiltAt?: Date;
@@ -1284,6 +1286,7 @@ const MatchSeriesResultSubSchema = new Schema<MatchSeriesResult>(
const MatchGameAssignmentSubSchema = new Schema<MatchGameAssignment>(
{
gameNumber: { type: Number, required: true, min: 1 },
roundNumber: { type: Number, required: false, min: 1 },
teamAIndex: { 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,
default: 'pair',
},
roundRobinMaxRounds: { type: Number, required: false, min: 1 },
tournamentCodeIds: {
type: [{ type: Schema.Types.ObjectId, ref: 'tournamentCode' }],
required: true,
@@ -101,6 +101,11 @@ export class CreateMatchDto {
@IsEnum(MATCH_GAME_MODES)
gameMode?: MatchGameMode;
@IsOptional()
@IsInt()
@Min(1)
roundRobinMaxRounds?: number;
@IsOptional()
@IsArray()
@IsString({ each: true })
@@ -156,6 +161,11 @@ export class UpdateMatchDto {
@IsEnum(MATCH_GAME_MODES)
gameMode?: MatchGameMode;
@IsOptional()
@IsInt()
@Min(1)
roundRobinMaxRounds?: number;
@IsOptional()
@IsArray()
@IsString({ each: true })
@@ -193,3 +203,17 @@ export class JoinMatchDto {
@IsString()
userId?: string;
}
export class AddParticipantDto {
@IsOptional()
@IsArray()
@ArrayMinSize(1)
@ArrayMaxSize(5)
@ValidateNested({ each: true })
@Type(() => PositionPreferenceDto)
preferredPositions?: PositionPreferenceDto[];
@IsOptional()
@IsString()
riotPuuid?: string;
}
@@ -24,6 +24,7 @@ import type {
UserDocument,
} from '../global/database/schema';
import {
AddParticipantDto,
CreateMatchDto,
JoinMatchDto,
UpdateMatchDto,
@@ -56,6 +57,7 @@ export class MatchController {
maxParticipants: body.maxParticipants ?? 10,
gameCount: body.gameCount,
gameMode: body.gameMode ?? 'pair',
roundRobinMaxRounds: body.roundRobinMaxRounds,
prizes: body.prizes ?? [],
notices: body.notices ?? [],
schedule: body.schedule ?? [],
@@ -149,6 +151,28 @@ export class MatchController {
});
}
// 관리자 전용 — 커뮤니티 유저를 모집중 매치에 직접 추가한다.
@Post(':matchId/participants/:userId')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
public async addParticipant(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Body() body: AddParticipantDto | undefined,
) {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.join({
matchId,
userId,
preferredPositions: body?.preferredPositions,
riotPuuid: body?.riotPuuid,
});
return this.matchService.serialize(match);
}
// 관리자 전용 — 참가자 주/부 포지션 변경.
@Patch(':matchId/participants/:userId')
@Roles('admin', 'owner')
@@ -80,6 +80,47 @@ describe('MatchService', () => {
};
}
function createServiceWithJoinModels(params: {
user: Record<string, unknown> | null;
match: Record<string, unknown> | null;
}) {
const UserModel = {
findById: jest.fn().mockResolvedValue(params.user),
};
const MatchModel = {
findById: jest.fn().mockResolvedValue(params.match),
};
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'user') return UserModel;
if (name === 'match') return MatchModel;
return {};
}),
};
const tournamentCodeService = {
buildSlots: jest.fn().mockResolvedValue([]),
releaseFromMatch: jest.fn().mockResolvedValue(undefined),
};
const communityStatsService = {
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
};
const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
removeByMatch: jest.fn().mockResolvedValue(undefined),
};
return {
service: new MatchService(
connectionService as never,
tournamentCodeService as never,
communityStatsService as never,
matchStatsService as never,
),
UserModel,
MatchModel,
};
}
it('returns a paginated match list with total count', async () => {
const communityId = new mongoose.Types.ObjectId();
const { service, MatchModel, sort, skip, limit } =
@@ -165,6 +206,54 @@ describe('MatchService', () => {
expect(sort).toHaveBeenCalledWith({ scheduledAt: -1 });
});
it('uses saved user preferences when joining without explicit positions', async () => {
const communityId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const user = {
_id: userId,
communityId,
preferredPositions: [{ position: 'MID', priority: 1 }],
riotAccounts: [
{
puuid: 'puuid-1',
gameName: 'Dahyeon',
tagLine: 'KR1',
profileIconId: 7,
isPrimary: true,
tiers: [],
},
],
};
const match = {
_id: matchId,
communityId,
status: 'recruiting',
maxParticipants: 10,
participants: [],
save: jest.fn().mockResolvedValue(undefined),
};
const { service } = createServiceWithJoinModels({ user, match });
await service.join({
matchId,
userId,
});
expect(match.participants).toEqual([
expect.objectContaining({
userId,
puuid: 'puuid-1',
gameName: 'Dahyeon',
tagLine: 'KR1',
profileIconId: 7,
preferredPositions: [{ position: 'MID', priority: 1 }],
excluded: false,
}),
]);
expect(match.save).toHaveBeenCalledTimes(1);
});
it('clears game schedule when a built match returns to recruiting', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
@@ -203,6 +292,29 @@ describe('MatchService', () => {
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 () => {
const communityId = new mongoose.Types.ObjectId();
const codeId = new mongoose.Types.ObjectId();
+32 -4
View File
@@ -13,6 +13,7 @@ import {
MatchDocument,
MatchSeriesResult,
MatchStatus,
POSITIONS,
Position,
PositionPreference,
TierInfo,
@@ -64,7 +65,7 @@ interface MatchListFilter {
interface JoinMatchParams {
matchId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
preferredPositions: PositionPreference[];
preferredPositions?: PositionPreference[];
// 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용.
riotPuuid?: string;
}
@@ -213,10 +214,12 @@ export class MatchService {
const previousStatus = match.status;
if (
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(
'maxParticipants and gameMode can only be changed while recruiting.',
'maxParticipants, gameMode, and roundRobinMaxRounds can only be changed while recruiting.',
);
}
match.set(params.patch);
@@ -293,7 +296,10 @@ export class MatchService {
tagLine: selectedRiot?.tagLine,
profileIconId: selectedRiot?.profileIconId,
tier: selectedTier,
preferredPositions: params.preferredPositions,
preferredPositions: this.resolveJoinPreferredPositions(
params.preferredPositions,
user.preferredPositions,
),
joinedAt: new Date(),
excluded: false,
});
@@ -436,6 +442,28 @@ export class MatchService {
};
}
private resolveJoinPreferredPositions(
requested: PositionPreference[] | undefined,
saved: PositionPreference[] | undefined,
): PositionPreference[] {
const source = requested?.length
? requested
: saved?.length
? saved
: POSITIONS.map((position, index) => ({
position,
priority: index + 1,
}));
return [...source]
.sort((left, right) => left.priority - right.priority)
.slice(0, 5)
.map((preference, index) => ({
position: preference.position,
priority: index + 1,
}));
}
private buildListFilter(query: ListMatchesQuery): MatchListFilter {
const filter: MatchListFilter = {
communityId: query.communityId,
@@ -1,5 +1,6 @@
import {
resolveRoundRobinTeamCount,
roundRobinGameSchedule,
roundRobinPairCount,
roundRobinPairs,
shuffleInPlace,
@@ -25,6 +26,30 @@ describe('round-robin util', () => {
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', () => {
expect(
resolveRoundRobinTeamCount({
@@ -3,11 +3,23 @@ export interface RoundRobinPair {
teamBIndex: number;
}
export interface RoundRobinGameAssignment extends RoundRobinPair {
gameNumber: number;
roundNumber: number;
}
export interface RoundRobinTeamCountInput {
teams?: Array<{ teamIndex: number }>;
participants: Array<{ excluded?: boolean }>;
}
export interface RoundRobinGameScheduleOptions {
gamesPerPair?: number;
maxRounds?: number;
rng?: () => number;
shuffleTeams?: boolean;
}
export function roundRobinPairs(teamCount: number): RoundRobinPair[] {
const pairs: RoundRobinPair[] = [];
for (let teamAIndex = 1; teamAIndex <= teamCount; teamAIndex += 1) {
@@ -27,6 +39,70 @@ export function roundRobinPairCount(teamCount: number): number {
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(
match: RoundRobinTeamCountInput,
): number {
@@ -0,0 +1,47 @@
import mongoose from 'mongoose';
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator';
import { TournamentCodeReplacementController } from './tournament-code-replacement.controller';
import type { TournamentCodeService } from './tournament-code.service';
describe('TournamentCodeReplacementController', () => {
function createFixture() {
const service = {
replaceForMatchGame: jest.fn().mockResolvedValue({
gameNumber: 1,
code: 'NEW-CODE',
}),
} as unknown as jest.Mocked<
Pick<TournamentCodeService, 'replaceForMatchGame'>
>;
const controller = new TournamentCodeReplacementController(
service as unknown as TournamentCodeService,
);
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
return { controller, service, communityId, matchId };
}
it('allows public replacement requests', async () => {
const { controller, service, communityId, matchId } = createFixture();
await expect(
controller.replaceForMatchGame(communityId, matchId, 1),
).resolves.toEqual(expect.objectContaining({ code: 'NEW-CODE' }));
expect(service.replaceForMatchGame).toHaveBeenCalledWith({
communityId,
matchId,
gameNumber: 1,
});
});
it('marks the replacement endpoint as public access', () => {
expect(
Reflect.getMetadata(
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
TournamentCodeReplacementController.prototype.replaceForMatchGame,
),
).toBe(true);
});
});
@@ -0,0 +1,30 @@
import {
Controller,
Param,
ParseIntPipe,
Post,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import { TournamentCodeService } from './tournament-code.service';
@Controller('communities/:communityId/tournament-codes')
export class TournamentCodeReplacementController {
constructor(private readonly tournamentCodeService: TournamentCodeService) {}
@Post('matches/:matchId/games/:gameNumber/replace')
@AllowPublicAccess()
public async replaceForMatchGame(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('gameNumber', ParseIntPipe) gameNumber: number,
) {
return this.tournamentCodeService.replaceForMatchGame({
communityId,
matchId,
gameNumber,
});
}
}
@@ -1,10 +1,11 @@
import { Module } from '@nestjs/common';
import { TournamentCodeController } from './tournament-code.controller';
import { TournamentCodeReplacementController } from './tournament-code-replacement.controller';
import { TournamentCodeScheduler } from './tournament-code.scheduler';
import { TournamentCodeService } from './tournament-code.service';
@Module({
controllers: [TournamentCodeController],
controllers: [TournamentCodeController, TournamentCodeReplacementController],
providers: [TournamentCodeService, TournamentCodeScheduler],
exports: [TournamentCodeService],
})
@@ -1,4 +1,5 @@
import type { MatchDocument } from '../global/database/schema';
import mongoose from 'mongoose';
import { TournamentCodeService } from './tournament-code.service';
type TournamentCodeServiceInternals = TournamentCodeService & {
@@ -8,6 +9,11 @@ type TournamentCodeServiceInternals = TournamentCodeService & {
gameNumber: number,
): { teamAIndex: number; teamBIndex: number };
ensureGameSchedule(match: MatchDocument): void;
replaceForMatchGame(params: {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
gameNumber: number;
}): Promise<unknown>;
};
function createService() {
@@ -19,10 +25,12 @@ function createService() {
interface MatchOverrides {
gameCount?: number;
gameMode?: 'pair' | 'bracket' | 'round-robin';
roundRobinMaxRounds?: number;
participants?: Array<{ excluded?: boolean }>;
teams?: Array<{ teamIndex: number }>;
gameSchedule?: Array<{
gameNumber: number;
roundNumber?: number;
teamAIndex: number;
teamBIndex: number;
}>;
@@ -30,11 +38,15 @@ interface MatchOverrides {
function createMatch(overrides: MatchOverrides): MatchDocument {
return {
_id: new mongoose.Types.ObjectId(),
status: 'in-progress',
gameCount: 1,
gameMode: 'pair',
participants: [],
teams: [],
tournamentCodeIds: [],
gameSchedule: [],
save: jest.fn().mockResolvedValue(undefined),
...overrides,
} as unknown as MatchDocument;
}
@@ -102,15 +114,32 @@ describe('TournamentCodeService round-robin scheduling', () => {
).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', () => {
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 },
{ gameNumber: 1, roundNumber: 1, teamAIndex: 2, teamBIndex: 5 },
{ gameNumber: 2, roundNumber: 1, teamAIndex: 2, teamBIndex: 5 },
{ gameNumber: 3, roundNumber: 2, teamAIndex: 1, teamBIndex: 4 },
],
});
@@ -124,7 +153,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 match = createMatch({
gameMode: 'round-robin',
@@ -137,10 +166,10 @@ describe('TournamentCodeService round-robin scheduling', () => {
expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({
teamAIndex: 1,
teamBIndex: 2,
teamBIndex: 4,
});
expect(service.resolveSeriesRefForGameNumber(match, 2)).toEqual({
teamAIndex: 1,
teamAIndex: 2,
teamBIndex: 3,
});
});
@@ -173,6 +202,105 @@ describe('TournamentCodeService round-robin scheduling', () => {
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('leaves legacy round-robin schedules without round numbers unchanged', () => {
const service = createService();
const roundRobin = createMatch({
gameMode: 'round-robin',
gameCount: 1,
teams: Array.from({ length: 6 }, (_, index) => ({
teamIndex: index + 1,
})),
gameSchedule: [
{ gameNumber: 1, teamAIndex: 2, teamBIndex: 5 },
{ gameNumber: 2, teamAIndex: 1, teamBIndex: 2 },
{ gameNumber: 3, teamAIndex: 4, teamBIndex: 5 },
{ gameNumber: 4, teamAIndex: 1, teamBIndex: 6 },
{ gameNumber: 5, teamAIndex: 5, teamBIndex: 6 },
{ gameNumber: 6, teamAIndex: 4, teamBIndex: 6 },
],
});
const persisted = [...roundRobin.gameSchedule];
service.ensureGameSchedule(roundRobin);
expect(roundRobin.gameSchedule).toEqual(persisted);
});
it('does not expose round numbers for legacy round-robin slots', async () => {
const codeFindExec = jest.fn().mockResolvedValue([]);
const connectionService = {
getModel: jest.fn().mockResolvedValue({
find: jest.fn().mockReturnValue({ exec: codeFindExec }),
}),
};
const service = new TournamentCodeService(
connectionService as never,
) as unknown as TournamentCodeServiceInternals;
const slots = await service.buildSlots(
createMatch({
gameMode: 'round-robin',
gameCount: 1,
teams: Array.from({ length: 6 }, (_, index) => ({
teamIndex: index + 1,
})),
gameSchedule: [
{ gameNumber: 1, teamAIndex: 2, teamBIndex: 5 },
{ gameNumber: 2, teamAIndex: 1, teamBIndex: 2 },
{ gameNumber: 3, teamAIndex: 4, teamBIndex: 5 },
{ gameNumber: 4, teamAIndex: 1, teamBIndex: 6 },
{ gameNumber: 5, teamAIndex: 5, teamBIndex: 6 },
{ gameNumber: 6, teamAIndex: 4, teamBIndex: 6 },
{ gameNumber: 7, teamAIndex: 2, teamBIndex: 6 },
{ gameNumber: 8, teamAIndex: 3, teamBIndex: 5 },
{ gameNumber: 9, teamAIndex: 2, teamBIndex: 3 },
{ gameNumber: 10, teamAIndex: 1, teamBIndex: 4 },
{ gameNumber: 11, teamAIndex: 3, teamBIndex: 6 },
{ gameNumber: 12, teamAIndex: 1, teamBIndex: 3 },
{ gameNumber: 13, teamAIndex: 3, teamBIndex: 4 },
{ gameNumber: 14, teamAIndex: 1, teamBIndex: 5 },
{ gameNumber: 15, teamAIndex: 2, teamBIndex: 4 },
],
}),
);
expect(slots).toHaveLength(15);
expect(slots[0]).toEqual(
expect.objectContaining({
gameNumber: 1,
roundNumber: undefined,
teamAIndex: 2,
teamBIndex: 5,
}),
);
expect(slots.every((slot) => slot.roundNumber === undefined)).toBe(true);
});
it('does not expose fallback round-robin slots before the schedule is persisted', async () => {
const service = createService();
const slots = await service.buildSlots(
@@ -189,3 +317,199 @@ describe('TournamentCodeService round-robin scheduling', () => {
expect(slots).toEqual([]);
});
});
describe('TournamentCodeService code replacement', () => {
function queryResult<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) };
}
function createCode(overrides: Record<string, unknown>) {
return {
_id: new mongoose.Types.ObjectId(),
code: 'CODE',
state: 'reserved',
expiresAt: new Date(Date.now() + 60 * 60 * 1000),
matchId: new mongoose.Types.ObjectId(),
gameNumber: 1,
reservedAt: new Date(),
releasedAt: undefined,
riotMatchId: undefined,
save: jest.fn().mockResolvedValue(undefined),
...overrides,
};
}
function createReplacementFixture(params?: {
currentCode?: Record<string, unknown> | null;
replacementCode?: Record<string, unknown> | null;
match?: MatchDocument;
}) {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const oldCodeId = new mongoose.Types.ObjectId();
const newCodeId = new mongoose.Types.ObjectId();
const match =
params?.match ??
createMatch({
_id: matchId,
communityId,
status: 'in-progress',
gameCount: 1,
participants: Array.from({ length: 10 }, () => ({})),
teams: [{ teamIndex: 1 }, { teamIndex: 2 }],
tournamentCodeIds: [oldCodeId],
} as unknown as MatchOverrides);
const currentCode =
params?.currentCode === null
? null
: createCode({
_id: oldCodeId,
code: 'OLD-CODE',
matchId,
gameNumber: 1,
...(params?.currentCode ?? {}),
});
const replacementCode =
params?.replacementCode === null
? null
: createCode({
_id: newCodeId,
code: 'NEW-CODE',
matchId,
gameNumber: 1,
...(params?.replacementCode ?? {}),
});
const MatchModel = {
findOne: jest.fn().mockReturnValue(queryResult(match)),
};
const TournamentCodeModel = {
findOne: jest.fn().mockReturnValue(queryResult(currentCode)),
findOneAndUpdate: jest.fn().mockReturnValue(queryResult(replacementCode)),
};
const connectionService = {
getModel: jest.fn().mockImplementation((modelName: string) => {
if (modelName === 'match') return Promise.resolve(MatchModel);
if (modelName === 'tournamentCode') {
return Promise.resolve(TournamentCodeModel);
}
throw new Error(`Unexpected model: ${modelName}`);
}),
};
const service = new TournamentCodeService(
connectionService as never,
) as unknown as TournamentCodeServiceInternals;
return {
match,
communityId,
matchId,
currentCode,
replacementCode,
MatchModel,
TournamentCodeModel,
service,
};
}
it('replaces a reserved code on the same game slot', async () => {
const {
match,
communityId,
matchId,
currentCode,
replacementCode,
MatchModel,
TournamentCodeModel,
service,
} = createReplacementFixture();
const slot = await service.replaceForMatchGame({
communityId,
matchId,
gameNumber: 1,
});
expect(slot).toEqual(
expect.objectContaining({
gameNumber: 1,
teamAIndex: 1,
teamBIndex: 2,
code: 'NEW-CODE',
state: 'reserved',
}),
);
expect(MatchModel.findOne).toHaveBeenCalledWith({
_id: matchId,
communityId,
});
expect(TournamentCodeModel.findOneAndUpdate).toHaveBeenCalledWith(
expect.objectContaining({
state: 'available',
region: 'kr',
mapType: 'SUMMONERS_RIFT',
teamSize: 5,
}),
expect.objectContaining({
$set: expect.objectContaining({
state: 'reserved',
matchId,
gameNumber: 1,
}),
}),
expect.objectContaining({ returnDocument: 'after' }),
);
expect(currentCode?.state).toBe('released');
expect(currentCode?.matchId).toBeUndefined();
expect(currentCode?.gameNumber).toBeUndefined();
expect(currentCode?.save).toHaveBeenCalled();
expect(match.tournamentCodeIds.map((id) => id.toString())).toEqual([
replacementCode?._id.toString(),
]);
expect(match.save).toHaveBeenCalled();
});
it('rejects replacement after the game result is collected', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const fixture = createReplacementFixture({
match: createMatch({
_id: matchId,
communityId,
status: 'in-progress',
gameCount: 1,
participants: Array.from({ length: 10 }, () => ({})),
teams: [{ teamIndex: 1 }, { teamIndex: 2 }],
tournamentCodeIds: [new mongoose.Types.ObjectId()],
result: {
riotMatchIds: ['KR_1'],
games: [{ gameNumber: 1 }],
seriesResults: [],
},
} as unknown as MatchOverrides),
});
await expect(
fixture.service.replaceForMatchGame({
communityId,
matchId,
gameNumber: 1,
}),
).rejects.toThrow('already has a collected result');
expect(fixture.TournamentCodeModel.findOne).not.toHaveBeenCalled();
expect(fixture.TournamentCodeModel.findOneAndUpdate).not.toHaveBeenCalled();
});
it('leaves the current code untouched when no replacement code is available', async () => {
const { match, communityId, matchId, currentCode, service } =
createReplacementFixture({
replacementCode: null,
});
await expect(
service.replaceForMatchGame({ communityId, matchId, gameNumber: 1 }),
).rejects.toThrow('No available tournament code');
expect(currentCode?.save).not.toHaveBeenCalled();
expect(match.save).not.toHaveBeenCalled();
});
});
@@ -25,10 +25,8 @@ import type {
TournamentCodeUploadItem,
} from './tournament-code.types';
import {
roundRobinGameSchedule,
resolveRoundRobinTeamCount,
roundRobinPairCount,
roundRobinPairs,
shuffleInPlace,
} from './round-robin.util';
const DEFAULT_REGION = 'kr';
@@ -275,6 +273,111 @@ export class TournamentCodeService {
return match;
}
public async replaceForMatchGame(params: {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
gameNumber: number;
}): Promise<TournamentCodeSlotView> {
const MatchModel = await this.connectionService.getModel('match');
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const match = await MatchModel.findOne({
_id: params.matchId,
communityId: params.communityId,
}).exec();
if (!match) throw new NotFoundException('Match not found.');
if (match.status !== 'team-built' && match.status !== 'in-progress') {
throw new BadRequestException(
'Tournament codes can only be replaced while the match is ready or in progress.',
);
}
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
this.ensureGameSchedule(match);
const requiredSlots = this.resolveRequiredSlots(match);
if (
!Number.isInteger(params.gameNumber) ||
params.gameNumber < 1 ||
params.gameNumber > requiredSlots
) {
throw new BadRequestException('Invalid tournament code game number.');
}
if (
(match.result?.games ?? []).some(
(game) => game.gameNumber === params.gameNumber,
)
) {
throw new BadRequestException(
'This game already has a collected result and cannot be replaced.',
);
}
const currentCode = await TournamentCodeModel.findOne({
_id: { $in: match.tournamentCodeIds },
matchId: match._id,
gameNumber: params.gameNumber,
}).exec();
if (!currentCode) {
throw new NotFoundException('Assigned tournament code not found.');
}
if (currentCode.state === 'used' || currentCode.riotMatchId) {
throw new BadRequestException('Used tournament codes cannot be replaced.');
}
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
const replacement = await TournamentCodeModel.findOneAndUpdate(
{
state: 'available',
region: DEFAULT_REGION,
mapType: 'SUMMONERS_RIFT',
teamSize: 5,
expiresAt: { $gt: expiresAfter },
},
{
$set: {
state: 'reserved',
matchId: match._id,
gameNumber: params.gameNumber,
reservedAt: new Date(),
},
$unset: { releasedAt: 1 },
},
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
).exec();
if (!replacement) {
throw new BadRequestException('No available tournament code to replace with.');
}
currentCode.state = 'released';
currentCode.matchId = undefined;
currentCode.gameNumber = undefined;
currentCode.reservedAt = undefined;
currentCode.releasedAt = new Date();
currentCode.riotMatchId = undefined;
match.tournamentCodeIds = this.replaceTournamentCodeId(
match.tournamentCodeIds,
currentCode._id,
replacement._id,
);
await currentCode.save();
await match.save();
return {
gameNumber: params.gameNumber,
roundNumber: this.resolveRoundNumberForGameNumber(
match,
params.gameNumber,
),
...this.resolveSeriesRefForGameNumber(match, params.gameNumber),
code: replacement.code,
expiresAt: replacement.expiresAt.toISOString(),
state: replacement.state,
riotMatchId: replacement.riotMatchId ?? null,
};
}
public async releaseFromMatch(
matchOrId: MatchDocument | mongoose.Types.ObjectId,
): Promise<void> {
@@ -368,6 +471,7 @@ export class TournamentCodeService {
const seriesRef = this.resolveSeriesRefForGameNumber(match, gameNumber);
return {
gameNumber,
roundNumber: this.resolveRoundNumberForGameNumber(match, gameNumber),
...seriesRef,
code: null,
expiresAt: null,
@@ -377,6 +481,7 @@ export class TournamentCodeService {
}
return {
gameNumber,
roundNumber: this.resolveRoundNumberForGameNumber(match, gameNumber),
...this.resolveSeriesRefForGameNumber(match, gameNumber),
code: code.code,
expiresAt: code.expiresAt.toISOString(),
@@ -390,13 +495,30 @@ export class TournamentCodeService {
return (code ?? '').trim().toUpperCase();
}
private replaceTournamentCodeId(
currentIds: mongoose.Types.ObjectId[],
oldId: mongoose.Types.ObjectId,
newId: mongoose.Types.ObjectId,
): mongoose.Types.ObjectId[] {
let replaced = false;
const next = currentIds.map((id) => {
if (id.toString() !== oldId.toString()) return id;
replaced = true;
return newId;
});
if (!replaced) next.push(newId);
return next;
}
private resolveRequiredSlots(match: MatchDocument): number {
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'round-robin') {
const teamCount = resolveRoundRobinTeamCount(match);
return roundRobinPairCount(teamCount) * gameCount;
if ((match.gameSchedule?.length ?? 0) > 0) {
return match.gameSchedule.length;
}
return this.buildRoundRobinGameSchedule(match).length;
}
const teamCount = (match.teams ?? []).length;
@@ -426,13 +548,18 @@ export class TournamentCodeService {
};
}
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 fallback = this.buildRoundRobinGameSchedule(match).find(
(entry) => entry.gameNumber === gameNumber,
);
return fallback
? {
teamAIndex: fallback.teamAIndex,
teamBIndex: fallback.teamBIndex,
}
: {
teamAIndex: 1,
teamBIndex: 2,
};
}
const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
@@ -450,21 +577,33 @@ export class TournamentCodeService {
const teamCount = resolveRoundRobinTeamCount(match);
if (teamCount < 2) return;
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
const pairs = shuffleInPlace([...roundRobinPairs(teamCount)]);
const schedule: MatchGameAssignment[] = [];
match.gameSchedule = this.buildRoundRobinGameSchedule(match);
}
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,
});
}
}
private resolveRoundNumberForGameNumber(
match: MatchDocument,
gameNumber: number,
): number | undefined {
if ((match.gameMode ?? 'pair') !== 'round-robin') return undefined;
match.gameSchedule = schedule;
const persisted = match.gameSchedule?.find(
(entry) => entry.gameNumber === gameNumber,
);
if (persisted) 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 {
gameNumber: number;
roundNumber?: number;
teamAIndex: number;
teamBIndex: number;
code: string | null;
@@ -24,10 +24,12 @@ function createService() {
interface MatchOverrides {
gameCount?: number;
gameMode?: 'pair' | 'bracket' | 'round-robin';
roundRobinMaxRounds?: number;
participants?: Array<{ excluded?: boolean }>;
teams?: Array<{ teamIndex: number }>;
gameSchedule?: Array<{
gameNumber: number;
roundNumber?: number;
teamAIndex: number;
teamBIndex: number;
}>;
@@ -58,6 +60,20 @@ describe('TournamentResultService round-robin scheduling', () => {
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', () => {
const service = createService();
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 type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types';
import {
roundRobinGameSchedule,
resolveRoundRobinTeamCount,
roundRobinPairCount,
roundRobinPairs,
} from '../tournament-code/round-robin.util';
import {
collectCaptainUserIds,
@@ -785,14 +784,18 @@ export class TournamentResultService {
};
}
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 fallback = this.buildRoundRobinGameSchedule(match).find(
(entry) => entry.gameNumber === gameNumber,
);
return fallback
? {
teamAIndex: fallback.teamAIndex,
teamBIndex: fallback.teamBIndex,
}
: {
teamAIndex: 1,
teamBIndex: 2,
};
}
const perSeries = match.gameCount || 1;
@@ -806,8 +809,10 @@ 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);
if ((match.gameSchedule?.length ?? 0) > 0) {
return match.gameSchedule.length;
}
return this.buildRoundRobinGameSchedule(match).length;
}
const activeParticipantCount = match.participants.filter(
@@ -819,6 +824,13 @@ export class TournamentResultService {
return seriesCount * (match.gameCount || 1);
}
private buildRoundRobinGameSchedule(match: MatchDocument) {
return roundRobinGameSchedule(resolveRoundRobinTeamCount(match), {
gamesPerPair: match.gameCount || 1,
maxRounds: match.roundRobinMaxRounds,
});
}
private resolveMatchWinnerTeamIndex(
seriesResults: NonNullable<MatchDocument['result']>['seriesResults'],
): number | undefined {
@@ -0,0 +1,61 @@
import {
BadRequestException,
Controller,
Get,
Param,
Query,
UseGuards,
} from '@nestjs/common';
import { Type } from 'class-transformer';
import {
IsInt,
IsOptional,
IsString,
Max,
MaxLength,
Min,
} from 'class-validator';
import mongoose from 'mongoose';
import { CurrentUser } from '../auth/current-user.decorator';
import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { UserDocument } from '../global/database/schema';
import { UserSearchService } from './user-search.service';
class SearchCommunityUsersQueryDto {
@IsString()
@MaxLength(80)
query!: string;
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
@Max(20)
limit?: number;
}
@Controller('communities/:communityId/users')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
export class CommunityUserController {
constructor(private readonly userSearchService: UserSearchService) {}
@Get('search')
public async searchUsers(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Query() query: SearchCommunityUsersQueryDto,
) {
if (!currentUser.communityId.equals(communityId)) {
throw new BadRequestException('Different community.');
}
return this.userSearchService.search({
communityId,
query: query.query,
limit: query.limit,
});
}
}
@@ -0,0 +1,143 @@
import mongoose from 'mongoose';
import { UserSearchService } from './user-search.service';
describe('UserSearchService', () => {
function createService(users: Record<string, unknown>[] = []) {
const exec = jest.fn().mockResolvedValue(users);
const limit = jest.fn().mockReturnValue({ exec });
const find = jest.fn().mockReturnValue({ limit });
const UserModel = { find };
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'user') return UserModel;
return {};
}),
};
return {
service: new UserSearchService(connectionService as never),
UserModel,
limit,
};
}
it('returns no results for short queries', async () => {
const communityId = new mongoose.Types.ObjectId();
const { service, UserModel } = createService();
const results = await service.search({ communityId, query: 'a' });
expect(results).toEqual([]);
expect(UserModel.find).not.toHaveBeenCalled();
});
it('searches by kakao nickname and Riot ID parts', async () => {
const communityId = new mongoose.Types.ObjectId();
const { service, UserModel, limit } = createService();
await service.search({ communityId, query: 'Hide on bush#KR1', limit: 50 });
expect(UserModel.find).toHaveBeenCalledWith({
communityId,
$or: expect.arrayContaining([
{ kakaoTalkNickname: expect.any(RegExp) },
{
riotAccounts: {
$elemMatch: {
gameName: expect.any(RegExp),
tagLine: expect.any(RegExp),
},
},
},
]),
});
expect(limit).toHaveBeenCalledWith(20);
});
it('serializes limited candidate fields', async () => {
const communityId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const { service } = createService([
{
_id: userId,
kakaoTalkNickname: '다혜',
isActivated: true,
preferredPositions: [{ position: 'MID', priority: 1 }],
riotAccounts: [
{
puuid: 'puuid-1',
gameName: 'Dahyeon',
tagLine: 'KR1',
profileIconId: 7,
isPrimary: true,
tiers: [{ queueType: 'RANKED_SOLO_5x5', tier: 'GOLD' }],
matchIds: ['private-extra-field'],
},
],
},
]);
const results = await service.search({ communityId, query: '다혜' });
expect(results).toEqual([
{
userId: userId.toString(),
kakaoTalkNickname: '다혜',
isActivated: true,
preferredPositions: [{ position: 'MID', priority: 1 }],
matchedRiotPuuid: undefined,
riotAccounts: [
{
puuid: 'puuid-1',
gameName: 'Dahyeon',
tagLine: 'KR1',
profileIconId: 7,
isPrimary: true,
tiers: [{ queueType: 'RANKED_SOLO_5x5', tier: 'GOLD' }],
},
],
},
]);
});
it('returns the matching secondary Riot account as a selection hint', async () => {
const communityId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const { service } = createService([
{
_id: userId,
kakaoTalkNickname: '다혜',
isActivated: true,
preferredPositions: [],
riotAccounts: [
{
puuid: 'main-puuid',
gameName: 'MainDahyeon',
tagLine: 'KR1',
profileIconId: 7,
isPrimary: true,
tiers: [],
},
{
puuid: 'smurf-puuid',
gameName: 'PracticeDahyeon',
tagLine: 'KR2',
profileIconId: 8,
isPrimary: false,
tiers: [],
},
],
},
]);
const results = await service.search({
communityId,
query: 'Practice#KR2',
});
expect(results[0]).toMatchObject({
userId: userId.toString(),
matchedRiotPuuid: 'smurf-puuid',
});
});
});
@@ -0,0 +1,164 @@
import { Injectable } from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type {
PositionPreference,
RiotAccount,
TierInfo,
UserDocument,
} from '../global/database/schema';
const DEFAULT_SEARCH_LIMIT = 10;
const MAX_SEARCH_LIMIT = 20;
const MIN_QUERY_LENGTH = 2;
export interface UserSearchRiotAccountResult {
puuid: string;
gameName: string;
tagLine: string;
profileIconId: number;
isPrimary: boolean;
tiers: TierInfo[];
}
export interface UserSearchResult {
userId: string;
kakaoTalkNickname?: string;
isActivated: boolean;
preferredPositions: PositionPreference[];
matchedRiotPuuid?: string;
riotAccounts: UserSearchRiotAccountResult[];
}
export interface SearchCommunityUsersParams {
communityId: mongoose.Types.ObjectId;
query: string;
limit?: number;
}
@Injectable()
export class UserSearchService {
constructor(private readonly connectionService: ConnectionService) {}
public async search(
params: SearchCommunityUsersParams,
): Promise<UserSearchResult[]> {
const query = params.query.trim();
if (query.length < MIN_QUERY_LENGTH) return [];
const UserModel = await this.connectionService.getModel('user');
const users = await UserModel.find(
this.buildFilter(params.communityId, query),
)
.limit(this.resolveLimit(params.limit))
.exec();
return users.map((user) => this.serializeUser(user, query));
}
private buildFilter(communityId: mongoose.Types.ObjectId, query: string) {
const [gameName, tagLine] = this.splitRiotId(query);
const generalRegex = this.toContainsRegex(query);
const filters: Record<string, unknown>[] = [
{ kakaoTalkNickname: generalRegex },
{ 'riotAccounts.gameName': generalRegex },
{ 'riotAccounts.tagLine': generalRegex },
];
if (gameName && tagLine) {
filters.push({
riotAccounts: {
$elemMatch: {
gameName: this.toContainsRegex(gameName),
tagLine: this.toContainsRegex(tagLine),
},
},
});
}
return { communityId, $or: filters };
}
private splitRiotId(query: string): [string | null, string | null] {
const hashIndex = query.lastIndexOf('#');
if (hashIndex <= 0 || hashIndex === query.length - 1) {
return [null, null];
}
return [
query.slice(0, hashIndex).trim(),
query.slice(hashIndex + 1).trim(),
];
}
private toContainsRegex(value: string): RegExp {
return new RegExp(escapeRegex(value.trim()), 'i');
}
private resolveLimit(limit: number | undefined): number {
if (typeof limit !== 'number' || !Number.isFinite(limit)) {
return DEFAULT_SEARCH_LIMIT;
}
return Math.min(MAX_SEARCH_LIMIT, Math.max(1, Math.trunc(limit)));
}
private serializeUser(user: UserDocument, query: string): UserSearchResult {
return {
userId: user._id.toString(),
kakaoTalkNickname: user.kakaoTalkNickname,
isActivated: user.isActivated,
preferredPositions: user.preferredPositions ?? [],
matchedRiotPuuid: this.findMatchingRiotAccount(
user.riotAccounts ?? [],
query,
)?.puuid,
riotAccounts: (user.riotAccounts ?? []).map((account) =>
this.serializeRiotAccount(account),
),
};
}
private serializeRiotAccount(
account: RiotAccount,
): UserSearchRiotAccountResult {
return {
puuid: account.puuid,
gameName: account.gameName,
tagLine: account.tagLine,
profileIconId: account.profileIconId,
isPrimary: account.isPrimary,
tiers: account.tiers ?? [],
};
}
private findMatchingRiotAccount(
accounts: RiotAccount[],
query: string,
): RiotAccount | undefined {
const [gameName, tagLine] = this.splitRiotId(query);
if (gameName && tagLine) {
return accounts.find(
(account) =>
includesNormalized(account.gameName, gameName) &&
includesNormalized(account.tagLine, tagLine),
);
}
return accounts.find(
(account) =>
includesNormalized(account.gameName, query) ||
includesNormalized(account.tagLine, query),
);
}
}
function escapeRegex(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function includesNormalized(value: string | undefined, query: string): boolean {
return normalizeForSearch(value).includes(normalizeForSearch(query));
}
function normalizeForSearch(value: string | undefined): string {
return (value ?? '').trim().toLowerCase();
}
+4 -1
View File
@@ -1,9 +1,12 @@
import { Module } from '@nestjs/common';
import { RiotModule } from '../riot/riot.module';
import { CommunityUserController } from './community-user.controller';
import { UserController } from './user.controller';
import { UserSearchService } from './user-search.service';
@Module({
imports: [RiotModule],
controllers: [UserController],
controllers: [UserController, CommunityUserController],
providers: [UserSearchService],
})
export class UserModule {}
+31
View File
@@ -13,6 +13,7 @@ import type {
ApiAuctionHistoryEntry,
ApiChampionStatsResponse,
ApiCommunity,
ApiCommunityUserSearchCandidate,
ApiEnqueueRefreshResult,
ApiInternalMatchDetailResponse,
ApiInternalMatchListResponse,
@@ -40,6 +41,7 @@ import type {
RebuildLegacyMatchesResponse,
TournamentCodeBulkUploadResponse,
TournamentCodeListResponse,
TournamentCodeSlotView,
TournamentCodeState,
TournamentCodeStatsResponse,
TournamentCodeUploadItem,
@@ -162,6 +164,25 @@ export function useMatch(matchId: string | undefined, communityId = DEFAULT_COMM
});
}
export function useCommunityUserSearch(
query: string,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: ['community-user-search', communityId, query],
queryFn: () => {
const searchParams = new URLSearchParams();
searchParams.set('query', query);
searchParams.set('limit', '10');
return apiFetch<ApiCommunityUserSearchCandidate[]>(
`/communities/${communityId}/users/search?${searchParams.toString()}`,
);
},
enabled: Boolean(communityId && enabled && query.trim().length >= 2),
});
}
export function useAuction(
matchId: string | undefined,
communityId = DEFAULT_COMMUNITY_ID,
@@ -612,6 +633,16 @@ export function useDeleteTournamentCode(communityId = DEFAULT_COMMUNITY_ID) {
});
}
export function useReplaceTournamentCode(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (params: { matchId: string; gameNumber: number }) =>
apiFetch<TournamentCodeSlotView>(
`/communities/${communityId}/tournament-codes/matches/${params.matchId}/games/${params.gameNumber}/replace`,
{ method: 'POST' },
),
});
}
export function usePollTournamentResult(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (matchId: string) =>
+22
View File
@@ -103,6 +103,24 @@ export interface ApiUser {
updatedAt: string;
}
export interface ApiCommunityUserSearchRiotAccount {
puuid: string;
gameName: string;
tagLine: string;
profileIconId: number;
isPrimary: boolean;
tiers: ApiTierInfo[];
}
export interface ApiCommunityUserSearchCandidate {
userId: string;
kakaoTalkNickname?: string;
isActivated: boolean;
preferredPositions: ApiPositionPreference[];
matchedRiotPuuid?: string;
riotAccounts: ApiCommunityUserSearchRiotAccount[];
}
export interface ApiCommunity {
_id: string;
name: string;
@@ -124,6 +142,7 @@ export type TournamentCodeSlotState = TournamentCodeState | 'pending';
export interface TournamentCodeSlotView {
gameNumber: number;
roundNumber?: number;
teamAIndex: number;
teamBIndex: number;
code: string | null;
@@ -201,6 +220,7 @@ export interface ApiMatchScheduleItem {
export interface ApiMatchGameAssignment {
gameNumber: number;
roundNumber?: number;
teamAIndex: number;
teamBIndex: number;
}
@@ -225,6 +245,7 @@ export interface ApiMatch {
maxParticipants: number;
gameCount: number;
gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
gameSchedule?: ApiMatchGameAssignment[];
tournamentCodes?: TournamentCodeSlotView[];
hostUserId?: string;
@@ -353,6 +374,7 @@ export interface MatchMutationRequest {
maxParticipants?: number;
gameCount?: number;
gameMode?: MatchGameMode;
roundRobinMaxRounds?: number;
prizes?: string[];
notices?: string[];
schedule?: ApiMatchScheduleItem[];
+156 -61
View File
@@ -11,15 +11,33 @@ const HISTORY_MATCH_PAGE_SIZE = 10;
const EMPTY_SCHEDULE_TEXT = '예정된 매치가 없습니다.';
const HISTORY_TABLE_ROW_CLASS =
'h-10 border-b border-base-content/5 last:border-b-0';
function SkeletonBlock({ className }: { className: string }) {
return (
<div
aria-hidden="true"
className={`animate-pulse bg-base-content/10 ${className}`}
/>
);
}
const SECTION_HEADING_CLASS =
'text-xs font-bold text-base-content/40 uppercase tracking-widest';
const ADMIN_LINK_CLASS =
'text-xs font-bold text-base-content/35 hover:text-primary';
const STATS_LINK_CLASS = 'text-xs font-bold text-primary hover:underline';
const STATUS_BADGE_CLASS =
'inline-flex items-center whitespace-nowrap text-xs font-semibold px-1.5 py-0.5 border';
const MAP_BADGE_CLASS =
'inline-flex items-center whitespace-nowrap text-xs px-1.5 py-0.5 border';
const NEXT_MATCH_TITLE_CLASS =
'text-xl sm:text-2xl font-bold text-base-content leading-tight';
const NEXT_MATCH_DESCRIPTION_CLASS =
'text-sm text-base-content/50 max-w-xl leading-relaxed';
const NEXT_MATCH_META_CLASS =
'flex items-center gap-3 text-xs text-base-content/40 flex-wrap';
const NEXT_MATCH_PARTICIPANT_BADGE_CLASS =
'inline-flex items-center whitespace-nowrap bg-accent text-accent-content px-1.5 py-0.5 font-semibold';
const DETAIL_BUTTON_CLASS = 'btn btn-secondary btn-sm px-6 text-xs font-semibold';
const UPCOMING_CARD_FRAME_CLASS = 'bg-base-100 h-full p-4 min-h-[135px]';
const UPCOMING_CARD_TITLE_CLASS =
'text-sm font-bold text-base-content truncate mr-2';
const UPCOMING_CARD_META_CLASS = 'space-y-1 text-xs text-base-content/40';
const HISTORY_MOBILE_DATE_CLASS = 'text-xs font-medium text-base-content/40';
const HISTORY_MOBILE_TITLE_CLASS =
'mt-1 text-sm font-semibold leading-snug text-base-content break-words';
const HISTORY_MOBILE_META_CLASS =
'flex flex-wrap items-center gap-x-1.5 gap-y-1 text-xs text-base-content/45';
function SkeletonText({
children,
@@ -87,7 +105,11 @@ function HistoryTableHeader() {
);
}
function HistoryRecordsSkeleton({ rows = 5 }: { rows?: number }) {
function HistoryRecordsSkeleton({
rows = HISTORY_MATCH_PAGE_SIZE,
}: {
rows?: number;
}) {
const historySkeletons = Array.from({ length: rows });
return (
@@ -118,12 +140,12 @@ function HistoryRecordsSkeleton({ rows = 5 }: { rows?: number }) {
</SkeletonText>
</td>
<td className="py-2.5 px-4">
<SkeletonBadge className="inline-flex items-center whitespace-nowrap text-xs font-semibold px-1.5 py-0.5 border border-transparent">
<SkeletonBadge className={`${STATUS_BADGE_CLASS} border-transparent`}>
팀빌딩
</SkeletonBadge>
</td>
<td className="py-2.5 px-4">
<SkeletonBadge className="inline-flex items-center whitespace-nowrap text-xs px-1.5 py-0.5 border border-transparent">
<SkeletonBadge className={`${MAP_BADGE_CLASS} border-transparent`}>
소환사의 협곡
</SkeletonBadge>
</td>
@@ -154,13 +176,41 @@ function HistoryRecordsSkeleton({ rows = 5 }: { rows?: number }) {
className="border-b border-base-content/5 last:border-b-0 p-3"
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1 space-y-2">
<SkeletonBlock className="h-3 w-28" />
<SkeletonBlock className="h-4 w-32" />
<div className="min-w-0 flex-1">
<SkeletonText
className={HISTORY_MOBILE_DATE_CLASS}
skeletonClassName="h-[1em] w-28"
>
6/8 (월) 21:00
</SkeletonText>
<SkeletonText
className={HISTORY_MOBILE_TITLE_CLASS}
skeletonClassName="h-[1em] w-32 max-w-full"
>
정기 내전
</SkeletonText>
</div>
<div className="shrink-0">
<SkeletonBadge className={`${STATUS_BADGE_CLASS} border-transparent`}>
팀빌딩
</SkeletonBadge>
</div>
</div>
<div className="mt-2">
<div className={HISTORY_MOBILE_META_CLASS}>
<SkeletonText skeletonClassName="h-[1em] w-20">
소환사의 협곡
</SkeletonText>
<span className="invisible text-base-content/20">·</span>
<SkeletonText skeletonClassName="h-[1em] w-8">
10명
</SkeletonText>
<span className="invisible text-base-content/20">·</span>
<SkeletonText skeletonClassName="h-[1em] w-14">
1팀 승리
</SkeletonText>
</div>
<SkeletonBlock className="h-5 w-12 shrink-0" />
</div>
<SkeletonBlock className="mt-2 h-3 w-40" />
</div>
))}
</div>
@@ -181,58 +231,103 @@ function HomePageSkeleton() {
<section className="pt-8 pb-6">
<div className="flex items-center justify-between gap-3 mb-3">
<SkeletonBlock className="h-3 w-20" />
<h2 className={SECTION_HEADING_CLASS}>
다음 내전
</h2>
<div className="flex items-center gap-3">
<SkeletonBlock className="h-3 w-16" />
<SkeletonBlock className="h-3 w-20" />
<Link
to={`/communities/${DEFAULT_COMMUNITY_ID}/internal-stats`}
className={STATS_LINK_CLASS}
>
내전 전적 보기
</Link>
</div>
</div>
<div className="border border-base-content/10 bg-base-200/50">
<div className="p-5 sm:p-6">
<div className="p-5 sm:p-6 min-h-[150px]">
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
<div className="space-y-3 flex-1">
<div className="space-y-2.5 flex-1">
<div className="flex items-center gap-2.5 flex-wrap">
<SkeletonBlock className="h-7 w-52 sm:w-64" />
<SkeletonBlock className="h-5 w-12" />
<SkeletonText
className={NEXT_MATCH_TITLE_CLASS}
skeletonClassName="h-[1em] w-52 sm:w-64 max-w-full"
>
롤림푸스 경매 테스트 매치
</SkeletonText>
<SkeletonBadge className={`${STATUS_BADGE_CLASS} border-transparent`}>
모집중
</SkeletonBadge>
</div>
<div className="space-y-2">
<SkeletonBlock className="h-4 w-full max-w-xl" />
<SkeletonBlock className="h-4 w-4/5 max-w-lg" />
<div className={NEXT_MATCH_DESCRIPTION_CLASS}>
<SkeletonText skeletonClassName="h-[1em] w-full max-w-xl">
Socket.IO 경매 페이지 검증용으로 생성된 매치입니다.
</SkeletonText>
</div>
<div className="flex items-center gap-3 flex-wrap pt-1">
<SkeletonBlock className="h-3 w-24" />
<SkeletonBlock className="h-3 w-12" />
<SkeletonBlock className="h-5 w-16" />
<div className={NEXT_MATCH_META_CLASS}>
<SkeletonText skeletonClassName="h-[1em] w-24">
6월 11일 21:00
</SkeletonText>
<span className="invisible text-base-content/15">|</span>
<SkeletonBadge className={NEXT_MATCH_PARTICIPANT_BADGE_CLASS}>
10/10명
</SkeletonBadge>
<span className="invisible text-base-content/15">|</span>
<SkeletonBadge className={`${MAP_BADGE_CLASS} border-transparent`}>
소환사의 협곡
</SkeletonBadge>
</div>
</div>
<SkeletonBlock className="h-8 w-24 sm:shrink-0" />
<div className="sm:shrink-0">
<SkeletonBadge className={DETAIL_BUTTON_CLASS}>
상세 보기
</SkeletonBadge>
</div>
</div>
</div>
</div>
</section>
<section className="pb-6">
<SkeletonBlock className="h-3 w-24 mb-3" />
<h2 className={`${SECTION_HEADING_CLASS} mb-3`}>
예정된 내전
</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-px bg-base-content/10 border border-base-content/10">
{upcomingSkeletons.map((_, index) => (
<div key={index} className="bg-base-100 h-full p-4 min-h-[122px]">
<div className="flex items-center justify-between mb-3 gap-3">
<SkeletonBlock className="h-4 w-28" />
<SkeletonBlock className="h-5 w-12 shrink-0" />
<div key={index} className={UPCOMING_CARD_FRAME_CLASS}>
<div className="flex items-center justify-between mb-2.5 gap-3">
<SkeletonText
className={UPCOMING_CARD_TITLE_CLASS}
skeletonClassName="h-[1em] w-28 max-w-full"
>
정기 내전
</SkeletonText>
<SkeletonBadge className={`${STATUS_BADGE_CLASS} border-transparent shrink-0`}>
모집중
</SkeletonBadge>
</div>
<div className="space-y-2">
<SkeletonBlock className="h-3 w-24" />
<SkeletonBlock className="h-3 w-12" />
<div className={UPCOMING_CARD_META_CLASS}>
<SkeletonText skeletonClassName="h-[1em] w-24">
6월 11일 21:00
</SkeletonText>
<SkeletonText skeletonClassName="h-[1em] w-12">
10/10명
</SkeletonText>
</div>
<div className="mt-2.5">
<SkeletonBadge className={`${MAP_BADGE_CLASS} border-transparent`}>
소환사의 협곡
</SkeletonBadge>
</div>
<SkeletonBlock className="h-5 w-16 mt-3" />
</div>
))}
</div>
</section>
<section className="pb-12">
<SkeletonBlock className="h-3 w-24 mb-3" />
<h2 className={`${SECTION_HEADING_CLASS} mb-3`}>
지난 내전 기록
</h2>
<HistoryRecordsSkeleton />
</section>
</main>
@@ -249,7 +344,7 @@ function StatusBadge({ status }: { status: string }) {
return (
<span
className={`inline-flex items-center whitespace-nowrap text-xs font-semibold px-1.5 py-0.5 border ${styles[status] ?? 'bg-base-content/10 text-base-content/50 border-base-content/10'}`}
className={`${STATUS_BADGE_CLASS} ${styles[status] ?? 'bg-base-content/10 text-base-content/50 border-base-content/10'}`}
>
{status}
</span>
@@ -258,7 +353,7 @@ function StatusBadge({ status }: { status: string }) {
function MapBadge({ map }: { map: string }) {
return (
<span className="inline-flex items-center whitespace-nowrap text-xs px-1.5 py-0.5 border border-base-content/10 text-base-content/50">
<span className={`${MAP_BADGE_CLASS} border-base-content/10 text-base-content/50`}>
{map}
</span>
);
@@ -302,7 +397,7 @@ function HistoryMetaText({
result?: string;
}) {
return (
<div className="flex flex-wrap items-center gap-x-1.5 gap-y-1 text-xs text-base-content/45">
<div className={HISTORY_MOBILE_META_CLASS}>
<span>{map}</span>
<span className="text-base-content/20">·</span>
<span>{participants}명</span>
@@ -448,21 +543,21 @@ export default function HomePage() {
<main className="max-w-5xl mx-auto px-4 sm:px-6">
<section className="pt-8 pb-6">
<div className="flex items-center justify-between gap-3 mb-3">
<h2 className="text-xs font-bold text-base-content/40 uppercase tracking-widest">
<h2 className={SECTION_HEADING_CLASS}>
다음 내전
</h2>
<div className="flex items-center gap-3">
{canManage && (
<Link
to={`/admin/communities/${DEFAULT_COMMUNITY_ID}/matches`}
className="text-xs font-bold text-base-content/35 hover:text-primary"
className={ADMIN_LINK_CLASS}
>
내전 관리
</Link>
)}
<Link
to={`/communities/${DEFAULT_COMMUNITY_ID}/internal-stats`}
className="text-xs font-bold text-primary hover:underline"
className={STATS_LINK_CLASS}
>
내전 전적 보기
</Link>
@@ -476,18 +571,18 @@ export default function HomePage() {
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
<div className="space-y-2.5">
<div className="flex items-center gap-2.5 flex-wrap">
<h3 className="text-xl sm:text-2xl font-bold text-base-content leading-tight">
<h3 className={NEXT_MATCH_TITLE_CLASS}>
{nextMatch.title}
</h3>
<StatusBadge status={getStatusLabel(nextMatch.status)} />
</div>
<p className="text-sm text-base-content/50 max-w-xl leading-relaxed">
<p className={NEXT_MATCH_DESCRIPTION_CLASS}>
{nextMatch.description}
</p>
<div className="flex items-center gap-3 text-xs text-base-content/40 flex-wrap">
<div className={NEXT_MATCH_META_CLASS}>
<span>{nextMatch.date} {nextMatch.time}</span>
<span className="text-base-content/15">|</span>
<span className="bg-accent text-accent-content px-1.5 py-0.5 font-semibold">
<span className={NEXT_MATCH_PARTICIPANT_BADGE_CLASS}>
{nextMatch.participants.length}/{nextMatch.maxParticipants}명
</span>
<span className="text-base-content/15">|</span>
@@ -495,7 +590,7 @@ export default function HomePage() {
</div>
</div>
<div className="sm:shrink-0">
<span className="btn btn-secondary btn-sm px-6 text-xs font-semibold">
<span className={DETAIL_BUTTON_CLASS}>
상세 보기
</span>
</div>
@@ -513,21 +608,21 @@ export default function HomePage() {
</section>
<section className="pb-6">
<h2 className="text-xs font-bold text-base-content/40 uppercase tracking-widest mb-3">
<h2 className={`${SECTION_HEADING_CLASS} mb-3`}>
예정된 내전
</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-px bg-base-content/10 border border-base-content/10">
{upcomingCards.length > 0 ? (
upcomingCards.map((match) => (
<Link key={match.id} to={`/match/${match.id}`}>
<div className="bg-base-100 hover:bg-base-200/50 transition-colors cursor-pointer h-full p-4 min-h-[122px]">
<div className={`${UPCOMING_CARD_FRAME_CLASS} hover:bg-base-200/50 transition-colors cursor-pointer`}>
<div className="flex items-center justify-between mb-2.5">
<h3 className="text-sm font-bold text-base-content truncate mr-2">
<h3 className={UPCOMING_CARD_TITLE_CLASS}>
{match.title}
</h3>
<StatusBadge status={getStatusLabel(match.status)} />
</div>
<div className="space-y-1 text-xs text-base-content/40">
<div className={UPCOMING_CARD_META_CLASS}>
<div>{match.date} {match.time}</div>
<div>
{match.participants.length}/{match.maxParticipants}명
@@ -540,7 +635,7 @@ export default function HomePage() {
</Link>
))
) : (
<div className="bg-base-100 h-full p-4 min-h-[122px] flex items-center justify-center text-center text-sm text-base-content/35">
<div className={`${UPCOMING_CARD_FRAME_CLASS} sm:col-span-2 lg:col-span-3 flex items-center justify-center text-center text-sm text-base-content/35`}>
{EMPTY_SCHEDULE_TEXT}
</div>
)}
@@ -552,7 +647,7 @@ export default function HomePage() {
aria-busy={isHistoryPageLoading}
aria-live="polite"
>
<h2 className="text-xs font-bold text-base-content/40 uppercase tracking-widest mb-3">
<h2 className={`${SECTION_HEADING_CLASS} mb-3`}>
지난 내전 기록
</h2>
{isHistoryPageLoading ? (
@@ -634,11 +729,11 @@ export default function HomePage() {
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="text-xs font-medium text-base-content/40">
<div className={HISTORY_MOBILE_DATE_CLASS}>
{match.compactDateTime ||
`${match.date} ${match.time}`}
</div>
<div className="mt-1 text-sm font-semibold leading-snug text-base-content break-words">
<div className={HISTORY_MOBILE_TITLE_CLASS}>
{match.title}
</div>
</div>
+726 -64
View File
@@ -1,14 +1,17 @@
import { useEffect, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { AlertTriangle, Search, X } from "lucide-react";
import { Link, useLocation, useNavigate, useParams } from "react-router";
import {
useAuction,
useCollectTournamentResultByRiotMatch,
useCollectTournamentResultByWindow,
useCommunityUserSearch,
useDdragonManifest,
useMatch,
useMe,
usePollTournamentResult,
useReplaceTournamentCode,
useTournamentCodeStats,
useUserHistoryProfile,
} from "../api/hooks";
@@ -32,11 +35,14 @@ import {
} from "../lib/league";
import type {
AuctionTopTierThreshold,
ApiCommunityUserSearchCandidate,
ApiCommunityUserSearchRiotAccount,
ApiMatch,
ApiMatchParticipant,
ApiPositionPreference,
ApiTierInfo,
ManualTournamentResultCollectResponse,
MatchGameMode,
Position,
TeamSide,
TournamentCodeSlotView,
@@ -155,6 +161,62 @@ function buildCaptainSlots(
}));
}
function getDefaultSearchAccount(candidate: ApiCommunityUserSearchCandidate) {
return (
candidate.riotAccounts.find(
(account) => account.puuid === candidate.matchedRiotPuuid,
) ??
candidate.riotAccounts.find((account) => account.isPrimary) ??
candidate.riotAccounts[0]
);
}
function getSelectedSearchAccount(
candidate: ApiCommunityUserSearchCandidate,
selectedPuuid: string | undefined,
) {
return (
candidate.riotAccounts.find((account) => account.puuid === selectedPuuid) ??
getDefaultSearchAccount(candidate)
);
}
function getCandidateTier(account?: ApiCommunityUserSearchRiotAccount) {
return (
account?.tiers.find((tier) => tier.queueType === "RANKED_SOLO_5x5") ??
account?.tiers[0]
);
}
function resolveCandidateMainSub(
candidate: ApiCommunityUserSearchCandidate,
): [Position, Position] {
const ordered = [...candidate.preferredPositions].sort(
(left, right) => left.priority - right.priority,
);
const main = ordered[0]?.position ?? POSITION_ORDER[0];
const sub =
ordered.find((preference) => preference.position !== main)?.position ??
POSITION_ORDER.find((position) => position !== main) ??
POSITION_ORDER[1];
return [main, sub];
}
function buildPreferredPositionsFromMainSub(
mainPosition: Position,
subPosition: Position,
) {
const ordered: Position[] = [mainPosition];
if (subPosition !== mainPosition) ordered.push(subPosition);
for (const position of POSITION_ORDER) {
if (!ordered.includes(position)) ordered.push(position);
}
return ordered.map((position, index) => ({
position,
priority: index + 1,
}));
}
function tierByQueue(tiers: ApiTierInfo[], queueType: string) {
return tiers.find((tier) => tier.queueType === queueType);
}
@@ -168,9 +230,7 @@ function QueueRankCell({
}) {
return (
<span className="grid grid-cols-[27px_auto] items-center gap-1.5">
<span className="text-xs font-medium text-base-content/50">
{label}
</span>
<span className="text-xs font-medium text-base-content/50">{label}</span>
<RankBadge tier={tier} size="sm" tooltipPlacement="left" />
</span>
);
@@ -617,6 +677,327 @@ function ParticipantMobileRow({
);
}
function AdminAddParticipantModal({
open,
participants,
maxParticipants,
onClose,
onAddParticipant,
addingUserId,
error,
}: {
open: boolean;
participants: ParticipantView[];
maxParticipants: number;
onClose: () => void;
onAddParticipant: (params: {
userId: string;
riotPuuid?: string;
preferredPositions: ApiPositionPreference[];
}) => void;
addingUserId: string | null;
error?: Error | null;
}) {
const { data: ddragon } = useDdragonManifest();
const [searchText, setSearchText] = useState("");
const [debouncedSearchText, setDebouncedSearchText] = useState("");
const [selectedRiotPuuidByUserId, setSelectedRiotPuuidByUserId] = useState<
Record<string, string>
>({});
const [positionOverrides, setPositionOverrides] = useState<
Record<string, { mainPosition: Position; subPosition: Position }>
>({});
const participantUserIds = new Set(
participants.map((participant) => participant.userId),
);
const isFull = participants.length >= maxParticipants;
useEffect(() => {
const timer = window.setTimeout(() => {
setDebouncedSearchText(searchText.trim());
}, 250);
return () => window.clearTimeout(timer);
}, [searchText]);
useEffect(() => {
if (!open) {
setSearchText("");
setDebouncedSearchText("");
setSelectedRiotPuuidByUserId({});
setPositionOverrides({});
}
}, [open]);
useEffect(() => {
setSelectedRiotPuuidByUserId({});
}, [debouncedSearchText]);
const searchQuery = useCommunityUserSearch(
debouncedSearchText,
DEFAULT_COMMUNITY_ID,
open && debouncedSearchText.length >= 2,
);
if (!open) return null;
function positionsFor(candidate: ApiCommunityUserSearchCandidate) {
const override = positionOverrides[candidate.userId];
if (override) return override;
const [mainPosition, subPosition] = resolveCandidateMainSub(candidate);
return { mainPosition, subPosition };
}
function setCandidatePosition(
candidate: ApiCommunityUserSearchCandidate,
key: "mainPosition" | "subPosition",
position: Position,
) {
const current = positionsFor(candidate);
setPositionOverrides((previous) => ({
...previous,
[candidate.userId]: {
...current,
[key]: position,
},
}));
}
return (
<div
className="fixed inset-0 z-50 flex items-start justify-center bg-black/55 px-3 py-6 sm:items-center"
role="dialog"
aria-modal="true"
aria-labelledby="admin-add-participant-title"
>
<div className="w-full max-w-3xl border border-base-content/12 bg-base-100 shadow-xl">
<div className="flex items-start justify-between gap-4 border-b border-base-content/10 px-4 py-3">
<div>
<h3
id="admin-add-participant-title"
className="text-sm font-black text-base-content"
>
참여자 추가
</h3>
<p className="mt-1 text-xs text-base-content/45">
카카오 닉네임 또는 Riot ID로 커뮤니티 유저를 찾습니다.
</p>
</div>
<button
type="button"
className="btn btn-ghost btn-xs h-8 min-h-8 w-8 p-0"
aria-label="참여자 추가 닫기"
onClick={onClose}
>
<X size={15} aria-hidden="true" />
</button>
</div>
<div className="space-y-3 px-4 py-4">
<label className="block">
<span className="mb-1.5 block text-xs font-bold text-base-content/45">
검색
</span>
<span className="flex h-10 items-center gap-2 border border-base-content/10 bg-base-200/30 px-3 focus-within:border-primary/40">
<Search
size={15}
className="text-base-content/35"
aria-hidden="true"
/>
<input
type="search"
value={searchText}
onChange={(event) => setSearchText(event.target.value)}
aria-label="참여자 검색"
placeholder="카카오 닉네임 또는 Riot ID (GameName#TagLine)"
className="min-w-0 flex-1 bg-transparent text-sm text-base-content outline-none placeholder:text-base-content/25"
/>
</span>
</label>
{error && (
<div className="border border-red-500/20 bg-red-500/10 px-3 py-2 text-xs text-red-500">
{error.message}
</div>
)}
<div className="max-h-[56vh] overflow-y-auto border border-base-content/10">
{debouncedSearchText.length < 2 ? (
<div className="px-4 py-8 text-center text-sm text-base-content/35">
두 글자 이상 입력하면 검색합니다.
</div>
) : searchQuery.isLoading ? (
<div className="px-4 py-8 text-center text-sm text-base-content/35">
검색 중...
</div>
) : searchQuery.error instanceof Error ? (
<div className="px-4 py-8 text-center text-sm text-red-500">
{searchQuery.error.message}
</div>
) : searchQuery.data && searchQuery.data.length > 0 ? (
<div className="divide-y divide-base-content/8">
{searchQuery.data.map((candidate) => {
const selectedRiotPuuid =
selectedRiotPuuidByUserId[candidate.userId];
const account = getSelectedSearchAccount(
candidate,
selectedRiotPuuid,
);
const tier = getCandidateTier(account);
const positions = positionsFor(candidate);
const disabledReason = participantUserIds.has(
candidate.userId,
)
? "이미 참가중"
: !candidate.isActivated
? "비활성"
: !account
? "Riot 계정 없음"
: isFull
? "정원 초과"
: null;
const isAdding = addingUserId === candidate.userId;
return (
<div
key={candidate.userId}
className="grid gap-3 px-3 py-3 sm:grid-cols-[minmax(0,1fr)_190px_82px] sm:items-center"
>
<div className="flex min-w-0 items-center gap-3">
<img
src={profileIconUrl(
ddragon,
account?.profileIconId ?? 0,
)}
alt=""
className="h-9 w-9 shrink-0 border border-base-content/10 bg-base-200 object-cover"
/>
<div className="min-w-0">
<div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
<span className="truncate text-sm font-bold text-base-content">
{candidate.kakaoTalkNickname ?? "닉네임 없음"}
</span>
<span
className={`shrink-0 border px-1.5 py-0.5 text-[11px] font-bold ${
disabledReason
? "border-base-content/10 text-base-content/35"
: "border-primary/25 bg-primary/5 text-primary"
}`}
>
{disabledReason ?? "추가 가능"}
</span>
</div>
<div className="mt-1 flex min-w-0 items-center gap-2 text-xs text-base-content/40">
{candidate.riotAccounts.length > 1 ? (
<select
value={account?.puuid ?? ""}
aria-label={`${candidate.kakaoTalkNickname ?? "유저"} Riot ID 선택`}
onChange={(event) =>
setSelectedRiotPuuidByUserId((previous) => ({
...previous,
[candidate.userId]: event.target.value,
}))
}
className="h-8 min-w-0 flex-1 border border-base-content/10 bg-base-100 px-2 text-xs text-base-content focus:border-primary/30 focus:outline-none"
>
{candidate.riotAccounts.map((riotAccount) => (
<option
key={riotAccount.puuid}
value={riotAccount.puuid}
>
{riotAccount.gameName}#{riotAccount.tagLine}
{riotAccount.isPrimary ? " · 대표" : ""}
</option>
))}
</select>
) : (
<span className="truncate">
{account
? `${account.gameName}#${account.tagLine}`
: "Riot 계정 없음"}
</span>
)}
<RankBadge tier={tier} size="sm" />
</div>
</div>
</div>
<div className="grid grid-cols-2 gap-2">
<label className="text-[11px] font-bold text-base-content/35">
주
<select
value={positions.mainPosition}
onChange={(event) =>
setCandidatePosition(
candidate,
"mainPosition",
event.target.value as Position,
)
}
className="mt-1 h-8 w-full border border-base-content/10 bg-base-100 px-2 text-xs text-base-content focus:border-primary/30 focus:outline-none"
>
{POSITION_ORDER.map((position) => (
<option key={position} value={position}>
{positionLabel[position]}
</option>
))}
</select>
</label>
<label className="text-[11px] font-bold text-base-content/35">
부
<select
value={positions.subPosition}
onChange={(event) =>
setCandidatePosition(
candidate,
"subPosition",
event.target.value as Position,
)
}
className="mt-1 h-8 w-full border border-base-content/10 bg-base-100 px-2 text-xs text-base-content focus:border-primary/30 focus:outline-none"
>
{POSITION_ORDER.map((position) => (
<option key={position} value={position}>
{positionLabel[position]}
</option>
))}
</select>
</label>
</div>
<button
type="button"
disabled={Boolean(disabledReason) || isAdding}
onClick={() =>
onAddParticipant({
userId: candidate.userId,
riotPuuid: account?.puuid,
preferredPositions:
buildPreferredPositionsFromMainSub(
positions.mainPosition,
positions.subPosition,
),
})
}
className="btn btn-primary btn-sm h-9 min-h-9 w-full text-xs disabled:opacity-40"
>
{isAdding ? "추가 중..." : "추가"}
</button>
</div>
);
})}
</div>
) : (
<div className="px-4 py-8 text-center text-sm text-base-content/35">
검색 결과가 없습니다.
</div>
)}
</div>
</div>
</div>
</div>
);
}
function ParticipantTable({
participants,
maxParticipants,
@@ -625,6 +1006,7 @@ function ParticipantTable({
onJoin,
isJoining,
canManage,
onOpenAddParticipant,
onRemoveParticipant,
onUpdatePositions,
removingUserId,
@@ -637,6 +1019,7 @@ function ParticipantTable({
onJoin: () => void;
isJoining: boolean;
canManage: boolean;
onOpenAddParticipant: () => void;
onRemoveParticipant: (userId: string) => void;
onUpdatePositions: (
userId: string,
@@ -697,18 +1080,30 @@ function ParticipantTable({
return (
<div className="border border-base-content/10 bg-base-100 overflow-hidden">
<div className="px-4 py-2.5 border-b border-base-content/10 bg-base-200/40 flex items-center justify-between gap-3">
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-base-content/10 bg-base-200/40 px-4 py-2.5">
<h3 className="text-xs font-bold uppercase tracking-wider text-base-content/40">
참가자 ({participants.length}/{maxParticipants})
</h3>
<button
type="button"
onClick={onJoin}
disabled={!canJoin || joined || isJoining}
className="btn btn-primary btn-xs px-4 text-xs font-semibold disabled:opacity-40"
>
{joined ? "참가 완료" : isJoining ? "신청 중..." : "참가 신청"}
</button>
<div className="flex flex-wrap items-center justify-end gap-2">
<button
type="button"
onClick={onJoin}
disabled={!canJoin || joined || isJoining}
className="btn btn-primary btn-xs px-4 text-xs font-semibold disabled:opacity-40"
>
{joined ? "참가 완료" : isJoining ? "신청 중..." : "참가 신청"}
</button>
{canManage && (
<button
type="button"
onClick={onOpenAddParticipant}
disabled={participants.length >= maxParticipants}
className="btn btn-outline btn-xs px-3 text-xs font-semibold disabled:opacity-40"
>
참여자 추가
</button>
)}
</div>
</div>
<div className="border-b border-base-content/10 bg-base-100 px-4 py-2.5">
<div className="flex flex-wrap items-center gap-x-2 gap-y-2">
@@ -999,12 +1394,11 @@ function SideCard({
function formatTournamentCodeExpiry(value: string | null) {
if (!value) return null;
return new Intl.DateTimeFormat("ko-KR", {
month: "long",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
}).format(new Date(value));
const date = new Date(value);
if (Number.isNaN(date.getTime())) return null;
return `${date.getMonth() + 1}/${date.getDate()} ${String(
date.getHours(),
).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
}
function isExpiringSoon(value: string | null) {
@@ -1013,11 +1407,23 @@ function isExpiringSoon(value: string | null) {
return expiresAt - Date.now() <= 24 * 60 * 60 * 1000;
}
function TournamentCodeDisplay({ slot }: { slot: TournamentCodeSlotView }) {
function TournamentCodeDisplay({
slot,
canReplace,
replacing,
onReplace,
}: {
slot: TournamentCodeSlotView;
canReplace?: boolean;
replacing?: boolean;
onReplace?: (slot: TournamentCodeSlotView) => void;
}) {
const [copied, setCopied] = useState(false);
const expired = slot.state === "expired";
const used = slot.state === "used";
const expiringSoon = isExpiringSoon(slot.expiresAt);
const replaceable = Boolean(canReplace && slot.code && !used);
const expiryText = formatTournamentCodeExpiry(slot.expiresAt);
async function copyCode() {
if (!slot.code) return;
@@ -1027,9 +1433,9 @@ function TournamentCodeDisplay({ slot }: { slot: TournamentCodeSlotView }) {
}
return (
<div className="flex-1 min-w-0">
<div className="min-w-0 space-y-1.5">
<div
className={`flex items-center gap-2 border px-2 py-1.5 ${
className={`border px-2 py-2 ${
expired
? "border-red-500/20 bg-red-500/8 text-red-400"
: used
@@ -1037,35 +1443,63 @@ function TournamentCodeDisplay({ slot }: { slot: TournamentCodeSlotView }) {
: "border-primary/20 bg-primary/5 text-base-content"
}`}
>
<code className="font-mono text-xs font-bold truncate">
<code className="block min-w-0 truncate font-mono text-[11px] font-bold leading-4">
{expired ? "코드 만료" : slot.code}
</code>
{slot.code && !expired && (
<button
type="button"
className="ml-auto text-xs px-1.5 py-0.5 border border-base-content/10 text-base-content/45 hover:text-primary"
onClick={copyCode}
>
{copied ? "복사됨" : "복사"}
</button>
)}
</div>
<div
className={`mt-1 text-xs ${
expired || expiringSoon ? "text-amber-500" : "text-base-content/30"
}`}
>
{used
? "사용됨"
: expired
? "운영자에게 새 코드를 요청해주세요."
: `만료: ${formatTournamentCodeExpiry(slot.expiresAt)}`}
<div className="flex items-center justify-between gap-2">
<div
className={`min-w-0 truncate text-xs ${
expired || expiringSoon ? "text-amber-500" : "text-base-content/30"
}`}
>
{used
? "사용됨"
: expired
? "운영자에게 새 코드를 요청해주세요."
: expiryText
? `만료 ${expiryText}`
: "만료 정보 없음"}
</div>
<div className="flex shrink-0 items-center gap-1">
{slot.code && !expired && (
<button
type="button"
className="whitespace-nowrap border border-base-content/10 px-1.5 py-0.5 text-xs text-base-content/45 hover:text-primary"
onClick={copyCode}
>
{copied ? "복사됨" : "복사"}
</button>
)}
{replaceable && (
<button
type="button"
className="whitespace-nowrap border border-base-content/10 px-1.5 py-0.5 text-xs text-base-content/45 hover:text-primary disabled:cursor-not-allowed disabled:opacity-45"
disabled={replacing}
onClick={() => onReplace?.(slot)}
>
{replacing ? "교체 중" : "교체"}
</button>
)}
</div>
</div>
</div>
);
}
function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) {
function TournamentCodeList({
slots,
gameMode,
canReplace,
replacingGameNumber,
onReplace,
}: {
slots: TournamentCodeSlotView[];
gameMode: MatchGameMode;
canReplace?: boolean;
replacingGameNumber?: number | null;
onReplace?: (slot: TournamentCodeSlotView) => void;
}) {
if (slots.length === 0) {
return (
<div className="border border-dashed border-base-content/10 px-3 py-3 text-xs text-base-content/30">
@@ -1074,28 +1508,76 @@ function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) {
);
}
return (
<div className="space-y-2">
{slots.map((slot) => (
<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">
function renderSlot(slot: TournamentCodeSlotView) {
const shouldShowTeamLabel =
gameMode === "round-robin" || slot.teamAIndex > 1 || slot.teamBIndex > 2;
return (
<div
key={slot.gameNumber}
className="border-b border-base-content/8 pb-2 last:border-b-0 last:pb-0"
>
<div className="mb-1.5 flex items-center justify-between gap-2">
<span className="shrink-0 text-xs font-bold text-base-content/45">
{slot.gameNumber}경기
{(slot.teamAIndex > 1 || slot.teamBIndex > 2) && (
<span className="block text-xs font-normal text-base-content/25">
{teamIndexLabel(slot.teamAIndex)} vs{" "}
{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">
발급 대기 중... 운영자가 코드를 채우면 자동으로 붙습니다.
{shouldShowTeamLabel && (
<span className="min-w-0 truncate text-xs text-base-content/30">
{teamIndexLabel(slot.teamAIndex)} vs{" "}
{teamIndexLabel(slot.teamBIndex)}
</span>
)}
</div>
))}
{slot.code ? (
<TournamentCodeDisplay
slot={slot}
canReplace={canReplace}
replacing={replacingGameNumber === slot.gameNumber}
onReplace={onReplace}
/>
) : (
<span className="block border border-dashed border-base-content/10 px-2 py-2 text-xs text-base-content/30">
발급 대기 중... 운영자가 코드를 채우면 자동으로 붙습니다.
</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>
);
}
@@ -1547,8 +2029,14 @@ export default function MatchDetailPage() {
const [manualResultStartTime, setManualResultStartTime] = useState("");
const [manualResultEndTime, setManualResultEndTime] = useState("");
const [manualRiotMatchId, setManualRiotMatchId] = useState("");
const [addParticipantOpen, setAddParticipantOpen] = useState(false);
const [replaceCodeSlot, setReplaceCodeSlot] =
useState<TournamentCodeSlotView | null>(null);
const [replaceCodeConfirmText, setReplaceCodeConfirmText] = useState("");
const pollTournamentResultMutation =
usePollTournamentResult(DEFAULT_COMMUNITY_ID);
const replaceTournamentCodeMutation =
useReplaceTournamentCode(DEFAULT_COMMUNITY_ID);
const collectResultByWindowMutation =
useCollectTournamentResultByWindow(DEFAULT_COMMUNITY_ID);
const collectResultByRiotMatchMutation =
@@ -1581,6 +2069,33 @@ export default function MatchDetailPage() {
const matchQueryKey = ["match", DEFAULT_COMMUNITY_ID, id ?? null];
const addParticipantMutation = useMutation({
mutationFn: ({
userId,
preferredPositions,
riotPuuid,
}: {
userId: string;
preferredPositions: ApiPositionPreference[];
riotPuuid?: string;
}) =>
apiFetch<ApiMatch>(
`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants/${userId}`,
{
method: "POST",
body: JSON.stringify({ preferredPositions, riotPuuid }),
},
),
onSuccess: async () => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: matchQueryKey }),
queryClient.invalidateQueries({
queryKey: ["matches", DEFAULT_COMMUNITY_ID],
}),
]);
},
});
const removeParticipantMutation = useMutation({
mutationFn: (userId: string) =>
apiFetch(
@@ -1711,6 +2226,36 @@ export default function MatchDetailPage() {
});
}
function handleReplaceTournamentCode(slot: TournamentCodeSlotView) {
if (!slot.code) return;
setReplaceCodeConfirmText("");
setReplaceCodeSlot(slot);
}
function handleConfirmReplaceTournamentCode() {
if (!id || !replaceCodeSlot || replaceCodeConfirmText.trim() !== "예") {
return;
}
replaceTournamentCodeMutation.mutate(
{ matchId: id, gameNumber: replaceCodeSlot.gameNumber },
{
onSuccess: async () => {
await Promise.all([
invalidateCurrentMatch(),
queryClient.invalidateQueries({
queryKey: ["tournament-code-stats", DEFAULT_COMMUNITY_ID],
}),
queryClient.invalidateQueries({
queryKey: ["tournament-codes", DEFAULT_COMMUNITY_ID],
}),
]);
setReplaceCodeSlot(null);
setReplaceCodeConfirmText("");
},
},
);
}
async function invalidateCurrentMatch() {
await queryClient.invalidateQueries({
queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null],
@@ -1976,6 +2521,7 @@ export default function MatchDetailPage() {
onJoin={() => joinMatchMutation.mutate()}
isJoining={joinMatchMutation.isPending}
canManage={canManageAuction}
onOpenAddParticipant={() => setAddParticipantOpen(true)}
onRemoveParticipant={(userId) =>
removeParticipantMutation.mutate(userId)
}
@@ -1998,6 +2544,26 @@ export default function MatchDetailPage() {
}
/>
<AdminAddParticipantModal
open={addParticipantOpen}
participants={match.participants}
maxParticipants={match.maxParticipants}
onClose={() => setAddParticipantOpen(false)}
onAddParticipant={(params) =>
addParticipantMutation.mutate(params)
}
addingUserId={
addParticipantMutation.isPending
? (addParticipantMutation.variables?.userId ?? null)
: null
}
error={
addParticipantMutation.error instanceof Error
? addParticipantMutation.error
: null
}
/>
{isCheckingPermissions ? (
<div className="border border-base-content/10 bg-base-100 p-4">
<h3 className="text-xs font-bold uppercase tracking-wider text-base-content/40">
@@ -2335,10 +2901,7 @@ export default function MatchDetailPage() {
<SideCard title="일정">
<ul className="space-y-2">
{match.schedule.map((item, index) => (
<li
key={index}
className="flex items-start gap-2.5 text-sm"
>
<li key={index} className="flex items-start gap-2.5 text-sm">
<span className="font-mono text-xs text-base-content/30 w-11 shrink-0 pt-px">
{item.time}
</span>
@@ -2352,7 +2915,22 @@ export default function MatchDetailPage() {
{(match.status === "team-built" ||
match.status === "in-progress") && (
<SideCard title="토너먼트 코드">
<TournamentCodeList slots={match.tournamentCodes} />
<TournamentCodeList
slots={match.tournamentCodes}
gameMode={match.gameMode}
canReplace
replacingGameNumber={
replaceTournamentCodeMutation.isPending
? replaceTournamentCodeMutation.variables?.gameNumber ?? null
: null
}
onReplace={handleReplaceTournamentCode}
/>
{replaceTournamentCodeMutation.error instanceof Error && (
<div className="mt-3 border border-red-500/20 bg-red-500/8 px-3 py-2 text-xs text-red-300">
{replaceTournamentCodeMutation.error.message}
</div>
)}
<PoolStatsHint enabled={canManageAuction} />
</SideCard>
)}
@@ -2508,6 +3086,90 @@ export default function MatchDetailPage() {
)}
</div>
</div>
{replaceCodeSlot && (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/55 px-4"
role="dialog"
aria-modal="true"
aria-labelledby="tournament-code-replace-title"
>
<div className="w-full max-w-md border border-amber-500/25 bg-base-100 p-5 shadow-2xl">
<div className="flex items-start gap-3">
<span className="inline-flex h-9 w-9 shrink-0 items-center justify-center border border-amber-500/25 bg-amber-500/10 text-amber-400">
<AlertTriangle className="h-4 w-4" />
</span>
<div className="min-w-0">
<h2
id="tournament-code-replace-title"
className="text-base font-bold text-base-content"
>
토너먼트 코드 교체
</h2>
<p className="mt-2 text-sm leading-6 text-base-content/60">
정상적인 경기 진행이 불가한 경우 우리팀과 상대팀에
상황을 알린 뒤 {replaceCodeSlot.gameNumber}경기 코드를
교체하세요.
</p>
</div>
</div>
<label
htmlFor="tournament-code-replace-confirm"
className="mt-5 block text-xs font-bold uppercase tracking-wider text-base-content/40"
>
계속하려면 예 입력
</label>
<input
id="tournament-code-replace-confirm"
value={replaceCodeConfirmText}
onChange={(event) => setReplaceCodeConfirmText(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Escape") {
setReplaceCodeSlot(null);
setReplaceCodeConfirmText("");
}
if (
event.key === "Enter" &&
replaceCodeConfirmText.trim() === "예" &&
!replaceTournamentCodeMutation.isPending
) {
handleConfirmReplaceTournamentCode();
}
}}
className="mt-2 h-10 w-full border border-base-content/15 bg-base-100 px-3 text-sm text-base-content outline-none transition-colors focus:border-amber-400/60"
placeholder="예"
/>
<div className="mt-5 flex flex-wrap justify-end gap-2">
<button
type="button"
className="btn btn-ghost btn-sm px-4 text-xs"
onClick={() => {
setReplaceCodeSlot(null);
setReplaceCodeConfirmText("");
}}
disabled={replaceTournamentCodeMutation.isPending}
>
닫기
</button>
<button
type="button"
className="btn btn-warning btn-sm px-4 text-xs"
onClick={handleConfirmReplaceTournamentCode}
disabled={
replaceCodeConfirmText.trim() !== "예" ||
replaceTournamentCodeMutation.isPending
}
>
{replaceTournamentCodeMutation.isPending
? "교체 중..."
: "코드 교체 진행"}
</button>
</div>
</div>
</div>
)}
</main>
);
}
+157 -2
View File
@@ -1,9 +1,11 @@
import { useState } from "react";
import { ChevronDown, ChevronUp } from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
import { AlertTriangle, ChevronDown, ChevronUp } from "lucide-react";
import { Link, useLocation, useParams } from "react-router";
import {
useDdragonManifest,
useMatch,
useReplaceTournamentCode,
useUserHistoryProfile,
} from "../api/hooks";
import { formatKoreanDate } from "../api/mappers";
@@ -167,8 +169,10 @@ function UpcomingGameCard({
game,
isNext,
onToggle,
onReplaceCode,
participantByUserId,
parsedTeamIndex,
replacingCode,
slot,
teamByIndex,
}: {
@@ -176,8 +180,10 @@ function UpcomingGameCard({
game?: ApiMatchGameResult;
isNext?: boolean;
onToggle: () => void;
onReplaceCode?: (slot: TournamentCodeSlotView) => void;
participantByUserId: Map<string, ApiMatchParticipant>;
parsedTeamIndex: number;
replacingCode?: boolean;
slot: TournamentCodeSlotView;
teamByIndex: Map<number, ApiMatch["teams"][number]>;
}) {
@@ -195,6 +201,7 @@ function UpcomingGameCard({
const won = finished && game?.winnerTeamIndex === parsedTeamIndex;
const ourSide: TeamSide =
slot.teamAIndex === parsedTeamIndex ? "blue" : "red";
const replaceable = Boolean(slot.code && !finished && slot.state !== "used");
async function handleCopy() {
if (!slot.code) return;
@@ -306,11 +313,21 @@ function UpcomingGameCard({
</code>
<button
type="button"
className="border border-base-content/10 px-2 py-1 text-xs font-bold text-base-content/45 hover:text-primary"
className="whitespace-nowrap border border-base-content/10 px-2 py-1 text-xs font-bold text-base-content/45 hover:text-primary"
onClick={handleCopy}
>
{copied ? "복사됨" : "복사"}
</button>
{replaceable && (
<button
type="button"
className="whitespace-nowrap border border-base-content/10 px-2 py-1 text-xs font-bold text-base-content/45 hover:text-primary disabled:cursor-not-allowed disabled:opacity-45"
disabled={replacingCode}
onClick={() => onReplaceCode?.(slot)}
>
{replacingCode ? "교체 중" : "교체"}
</button>
)}
</>
) : (
<span className="text-xs font-semibold text-base-content/30">
@@ -371,9 +388,12 @@ function TeamGameCardsSection({
match,
participantByUserId,
parsedTeamIndex,
replaceError,
replacingGameNumber,
teamByIndex,
slots,
title,
onReplaceCode,
}: {
defaultExpandedGameNumber?: number | null;
emptyMessage: string;
@@ -382,9 +402,12 @@ function TeamGameCardsSection({
match: ApiMatch;
participantByUserId: Map<string, ApiMatchParticipant>;
parsedTeamIndex: number;
replaceError?: string | null;
replacingGameNumber?: number | null;
teamByIndex: Map<number, ApiMatch["teams"][number]>;
slots: TournamentCodeSlotView[];
title: string;
onReplaceCode?: (slot: TournamentCodeSlotView) => void;
}) {
const formatted = formatKoreanDate(match.scheduledAt);
const [expandedGameNumber, setExpandedGameNumber] = useState<number | null>(
@@ -409,6 +432,11 @@ function TeamGameCardsSection({
</div>
<div className="p-4">
{replaceError && (
<div className="mb-3 border border-red-500/20 bg-red-500/8 px-3 py-2 text-xs text-red-300">
{replaceError}
</div>
)}
{isPreTeamBuilt ? (
<div className="border border-dashed border-base-content/10 px-4 py-8 text-center text-xs text-base-content/35">
팀 빌딩이 끝나면 일정이 표시됩니다.
@@ -430,8 +458,10 @@ function TeamGameCardsSection({
current === slot.gameNumber ? null : slot.gameNumber,
)
}
onReplaceCode={onReplaceCode}
participantByUserId={participantByUserId}
parsedTeamIndex={parsedTeamIndex}
replacingCode={replacingGameNumber === slot.gameNumber}
slot={slot}
teamByIndex={teamByIndex}
/>
@@ -463,7 +493,41 @@ function buildFinishedSlot(
export default function MatchTeamProgressPage() {
const { id, teamIndex } = useParams();
const parsedTeamIndex = Number(teamIndex);
const queryClient = useQueryClient();
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
const replaceTournamentCodeMutation =
useReplaceTournamentCode(DEFAULT_COMMUNITY_ID);
const [replaceCodeSlot, setReplaceCodeSlot] =
useState<TournamentCodeSlotView | null>(null);
const [replaceCodeConfirmText, setReplaceCodeConfirmText] = useState("");
function handleReplaceTournamentCode(slot: TournamentCodeSlotView) {
if (!slot.code) return;
setReplaceCodeConfirmText("");
setReplaceCodeSlot(slot);
}
function closeReplaceTournamentCodeDialog() {
setReplaceCodeSlot(null);
setReplaceCodeConfirmText("");
}
function handleConfirmReplaceTournamentCode() {
if (!id || !replaceCodeSlot || replaceCodeConfirmText.trim() !== "예") {
return;
}
replaceTournamentCodeMutation.mutate(
{ matchId: id, gameNumber: replaceCodeSlot.gameNumber },
{
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null],
});
closeReplaceTournamentCodeDialog();
},
},
);
}
if (!DEFAULT_COMMUNITY_ID) {
return (
@@ -577,8 +641,19 @@ export default function MatchTeamProgressPage() {
gameByNumber={gameByNumber}
isPreTeamBuilt={isPreTeamBuilt}
match={match}
onReplaceCode={handleReplaceTournamentCode}
participantByUserId={participantByUserId}
parsedTeamIndex={parsedTeamIndex}
replaceError={
replaceTournamentCodeMutation.error instanceof Error
? replaceTournamentCodeMutation.error.message
: null
}
replacingGameNumber={
replaceTournamentCodeMutation.isPending
? replaceTournamentCodeMutation.variables?.gameNumber ?? null
: null
}
teamByIndex={teamByIndex}
slots={activeSlots}
title="다가오는 경기"
@@ -618,6 +693,86 @@ export default function MatchTeamProgressPage() {
/>
))}
</section>
{replaceCodeSlot && (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/55 px-4"
role="dialog"
aria-modal="true"
aria-labelledby="team-tournament-code-replace-title"
>
<div className="w-full max-w-md border border-amber-500/25 bg-base-100 p-5 shadow-2xl">
<div className="flex items-start gap-3">
<span className="inline-flex h-9 w-9 shrink-0 items-center justify-center border border-amber-500/25 bg-amber-500/10 text-amber-400">
<AlertTriangle className="h-4 w-4" />
</span>
<div className="min-w-0">
<h2
id="team-tournament-code-replace-title"
className="text-base font-bold text-base-content"
>
토너먼트 코드 교체
</h2>
<p className="mt-2 text-sm leading-6 text-base-content/60">
정상적인 경기 진행이 불가한 경우 우리팀과 상대팀에
상황을 알린 뒤 {replaceCodeSlot.gameNumber}경기 코드를
교체하세요.
</p>
</div>
</div>
<label
htmlFor="team-tournament-code-replace-confirm"
className="mt-5 block text-xs font-bold uppercase tracking-wider text-base-content/40"
>
계속하려면 예 입력
</label>
<input
id="team-tournament-code-replace-confirm"
value={replaceCodeConfirmText}
onChange={(event) => setReplaceCodeConfirmText(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Escape") {
closeReplaceTournamentCodeDialog();
}
if (
event.key === "Enter" &&
replaceCodeConfirmText.trim() === "예" &&
!replaceTournamentCodeMutation.isPending
) {
handleConfirmReplaceTournamentCode();
}
}}
className="mt-2 h-10 w-full border border-base-content/15 bg-base-100 px-3 text-sm text-base-content outline-none transition-colors focus:border-amber-400/60"
placeholder="예"
/>
<div className="mt-5 flex flex-wrap justify-end gap-2">
<button
type="button"
className="btn btn-ghost btn-sm px-4 text-xs"
onClick={closeReplaceTournamentCodeDialog}
disabled={replaceTournamentCodeMutation.isPending}
>
닫기
</button>
<button
type="button"
className="btn btn-warning btn-sm px-4 text-xs"
onClick={handleConfirmReplaceTournamentCode}
disabled={
replaceCodeConfirmText.trim() !== "예" ||
replaceTournamentCodeMutation.isPending
}
>
{replaceTournamentCodeMutation.isPending
? "교체 중..."
: "코드 교체 진행"}
</button>
</div>
</div>
</div>
)}
</main>
);
}
+69 -1
View File
@@ -35,6 +35,21 @@ const GAME_MODE_LABEL: Record<MatchGameMode, string> = {
'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() {
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">
@@ -106,6 +121,7 @@ function makeForm(match?: ApiMatch): MatchMutationRequest & {
maxParticipants: match.maxParticipants,
gameCount: match.gameCount,
gameMode: match.gameMode ?? 'pair',
roundRobinMaxRounds: match.roundRobinMaxRounds,
prizes: match.prizes,
notices: match.notices,
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],
);
const roundRobinFullRoundCount = resolveRoundRobinFullRoundCount(
form.maxParticipants,
);
async function invalidate() {
await Promise.all([
@@ -169,6 +188,13 @@ export default function MatchAdminPage() {
maxParticipants: Number(form.maxParticipants ?? 10),
gameCount: Number(form.gameCount ?? 3),
gameMode: form.gameMode,
roundRobinMaxRounds:
form.gameMode === 'round-robin'
? normalizeRoundRobinMaxRounds(
form.roundRobinMaxRounds,
form.maxParticipants,
)
: undefined,
prizes: parseLines(form.prizesText),
notices: parseLines(form.noticesText),
schedule: parseSchedule(form.scheduleText),
@@ -290,7 +316,17 @@ export default function MatchAdminPage() {
정원
<select
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"
>
{[10, 20, 30, 40, 50, 60].map((value) => (
@@ -323,6 +359,32 @@ export default function MatchAdminPage() {
현재 경매/코드 연결은 페어 방식 기준으로 동작합니다.
</span>
</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">
상품 (줄바꿈 구분)
<textarea
@@ -406,6 +468,12 @@ export default function MatchAdminPage() {
</td>
<td className="px-3 py-2 text-xs">
{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 className="px-3 py-2 text-right">
<div className="inline-flex gap-2">