Compare commits

...
13 Commits
42 changed files with 7022 additions and 215 deletions

No files matched your search

@@ -1,4 +1,5 @@
import { Module } from '@nestjs/common';
import { RiotModule } from '../riot/riot.module';
import { CommunityStatsCacheService } from './community-stats-cache.service';
import { CommunityStatsController } from './community-stats.controller';
import { CommunityStatsService } from './community-stats.service';
@@ -7,6 +8,7 @@ import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
@Module({
imports: [RiotModule],
controllers: [CommunityStatsController],
providers: [
CommunityStatsService,
@@ -0,0 +1,194 @@
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { CommunityStatsCacheService } from './community-stats-cache.service';
import { CommunityStatsService } from './community-stats.service';
import type {
InternalMatchCardView,
InternalMatchDetailResponse,
} from './community-stats.types';
import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
import type { InternalGameDetail, InternalRecord } from './match-stats.types';
function objectives() {
return {
tower: 1,
dragon: 0,
inhibitor: 0,
baron: 0,
riftHerald: 0,
voidGrub: 0,
elderDragon: 0,
};
}
function record(matchId: mongoose.Types.ObjectId): InternalRecord {
return {
matchId: matchId.toString(),
title: '내전',
scheduledAt: new Date('2026-06-18T12:00:00.000Z'),
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
userId: new mongoose.Types.ObjectId().toString(),
summonerName: 'Player',
tagLine: 'KR1',
profileIconId: 1,
teamIndex: 1,
side: 'blue',
championId: 266,
championLevel: 15,
teamPosition: 'TOP',
kills: 5,
deaths: 1,
assists: 7,
win: true,
cs: 200,
csPerMin: 6.7,
gold: 12_000,
gpm: 400,
damageDealtToChampions: 18_000,
damageTaken: 20_000,
damageShare: 30,
killParticipation: 60,
visionScore: 18,
controlWardsBought: 1,
wardsPlaced: 8,
wardsKilled: 2,
firstBloodKill: false,
firstBloodAssist: false,
items: [1054, 3071, 0, 0, 0, 0],
trinket: 3340,
summonerSpells: [4, 12],
perks: {
primaryStyle: 8000,
subStyle: 8400,
keystone: 8010,
selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451],
styles: [
{ styleId: 8000, perkIds: [8010, 9111, 9105, 8299] },
{ styleId: 8400, perkIds: [8444, 8451] },
],
statPerks: { defense: 5001, flex: 5008, offense: 5005 },
},
itemBuild: [{ timestamp: 10, itemId: 1054, type: 'purchased' }],
skillBuild: [{ timestamp: 11, skillSlot: 1, level: 1 }],
rating: 8.5,
};
}
describe('CommunityStatsService', () => {
it('ignores stale detail cache entries missing timeline build fields', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match: InternalMatchCardView = {
matchId: matchId.toString(),
title: '내전',
scheduledAt: '2026-06-18T12:00:00.000Z',
status: 'finished',
gameCount: 1,
games: [],
teams: [],
seriesResults: [],
};
const participant = record(matchId);
const gameDetail: InternalGameDetail = {
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
winnerSide: 'blue',
timelineLoaded: true,
timeline: [
{
timestamp: 0,
blue: { gold: 500, xp: 0 },
red: { gold: 500, xp: 0 },
goldDiff: 0,
xpDiff: 0,
},
],
objectiveEvents: [],
teams: [
{
teamIndex: 1,
side: 'blue',
win: true,
objectives: objectives(),
bans: [],
participants: [participant],
},
],
};
const staleCache = {
match,
games: [
{
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
teams: [
{
teamIndex: 1,
side: 'blue',
win: true,
objectives: { tower: 1, dragon: 0, baron: 0 },
participants: [
{
summonerName: 'Player',
perks: {
primaryStyle: 8000,
subStyle: 8400,
keystone: 8010,
},
},
],
},
],
},
],
} as unknown as InternalMatchDetailResponse;
const cacheService = {
get: jest.fn().mockResolvedValue(staleCache),
setDetail: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<MatchStatsService>;
const service = new CommunityStatsService(
{} as ConnectionService,
cacheService,
{} as MatchStatsRepository,
matchStatsService,
);
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
jest.fn().mockResolvedValue({
season: {
id: 'all',
label: '전체',
startTime: null,
endTime: null,
},
matches: [match],
records: [participant],
detailsByMatchId: new Map([[matchId.toString(), [gameDetail]]]),
});
const response = await service.getMatchDetail({ communityId, matchId });
expect(response.games[0].timeline).toHaveLength(1);
expect(response.games[0].teams[0].participants[0].itemBuild).toHaveLength(
1,
);
expect(response.games[0].teams[0].participants[0].perks).toMatchObject({
selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451],
});
expect(matchStatsService.buildAndUpsert).not.toHaveBeenCalled();
expect(cacheService.setDetail).toHaveBeenCalledWith(
expect.stringContaining(':r3:'),
response,
);
});
});
@@ -36,6 +36,7 @@ const DEFAULT_LIST_LIMIT = 20;
const MAX_LIST_LIMIT = 50;
const MAX_MATCH_SCAN = 300;
const MIN_HIGHLIGHT_GAMES = 5;
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 3;
interface CommunityStatsContext {
community: CommunityDocument;
@@ -205,10 +206,10 @@ export class CommunityStatsService {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
}): Promise<InternalMatchDetailResponse> {
const key = `riot:communitystats:matchDetail:${params.communityId.toString()}:${params.matchId.toString()}`;
const key = `riot:communitystats:matchDetail:v${MATCH_STATS_BUILDER_VERSION}:r${MATCH_DETAIL_RESPONSE_CACHE_VERSION}:${params.communityId.toString()}:${params.matchId.toString()}`;
const cached =
await this.cacheService.get<InternalMatchDetailResponse>(key);
if (cached) return cached;
if (cached && isCompleteMatchDetailResponse(cached)) return cached;
const dataset = await this.buildBaseDataset(params.communityId, {
seasonId: 'all',
@@ -217,26 +218,42 @@ export class CommunityStatsService {
(item) => item.matchId === params.matchId.toString(),
);
if (!match) throw new NotFoundException('Internal match not found.');
let gameDetails = dataset.detailsByMatchId.get(match.matchId) ?? [];
if (gameDetails.some((game) => game.timelineLoaded !== true)) {
await this.matchStatsService.buildAndUpsert(params.matchId, {
includeTimeline: true,
});
const refreshedDataset = await this.buildBaseDataset(params.communityId, {
seasonId: 'all',
});
gameDetails = refreshedDataset.detailsByMatchId.get(match.matchId) ?? [];
}
const response: InternalMatchDetailResponse = {
match,
games: (dataset.detailsByMatchId.get(match.matchId) ?? []).map(
games: gameDetails.map(
(game) => ({
gameNumber: game.gameNumber,
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
gameVersion: game.gameVersion,
timeline: game.timeline ?? [],
objectiveEvents: game.objectiveEvents ?? [],
teams: game.teams.map((team) => ({
teamIndex: team.teamIndex,
side: team.side,
win: team.win,
objectives: team.objectives,
bans: team.bans ?? [],
participants: team.participants.map((record) => ({
userId: record.userId,
summonerName: record.summonerName,
tagLine: record.tagLine,
teamIndex: record.teamIndex,
side: record.side,
teamPosition: record.teamPosition,
championId: record.championId,
championLevel: record.championLevel,
kills: record.kills,
deaths: record.deaths,
assists: record.assists,
@@ -245,13 +262,21 @@ export class CommunityStatsService {
gold: record.gold,
gpm: record.gpm,
damageDealtToChampions: record.damageDealtToChampions,
damageTaken: record.damageTaken,
damageShare: record.damageShare,
killParticipation: record.killParticipation,
visionScore: record.visionScore,
wardsPlaced: record.wardsPlaced,
wardsKilled: record.wardsKilled,
controlWardsBought: record.controlWardsBought,
firstBloodKill: record.firstBloodKill ?? false,
firstBloodAssist: record.firstBloodAssist ?? false,
items: record.items,
trinket: record.trinket,
summonerSpells: record.summonerSpells,
perks: record.perks,
itemBuild: record.itemBuild ?? [],
skillBuild: record.skillBuild ?? [],
win: record.win,
})),
})),
@@ -990,3 +1015,23 @@ export class CommunityStatsService {
return Math.round(value * 10) / 10;
}
}
function isCompleteMatchDetailResponse(
response: InternalMatchDetailResponse,
): boolean {
return response.games.every(
(game) =>
Array.isArray(game.timeline) &&
Array.isArray(game.objectiveEvents) &&
game.teams.every(
(team) =>
Array.isArray(team.bans) &&
team.participants.every(
(participant) =>
typeof participant.tagLine === 'string' &&
Array.isArray(participant.itemBuild) &&
Array.isArray(participant.skillBuild),
),
),
);
}
@@ -1,4 +1,10 @@
import type { RiotLane, TeamSide } from '../global/database/schema';
import type {
MatchStatsItemBuildEvent,
MatchStatsRunePerks,
MatchStatsSkillBuildEvent,
RiotLane,
TeamSide,
} from '../global/database/schema';
import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types';
export interface CommunityStatsFilters {
@@ -108,18 +114,43 @@ export interface InternalMatchDetailResponse {
riotMatchId: string;
gameCreation: number;
gameDuration: number;
gameVersion?: string;
timeline: Array<{
timestamp: number;
blue: { gold: number; xp: number };
red: { gold: number; xp: number };
goldDiff: number;
xpDiff: number;
}>;
objectiveEvents: Array<{
timestamp: number;
side: TeamSide;
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
monsterSubType?: string;
}>;
teams: Array<{
teamIndex: number;
side: TeamSide;
win: boolean;
objectives: { baron: number; dragon: number; tower: number };
objectives: {
tower: number;
dragon: number;
inhibitor: number;
baron: number;
riftHerald: number;
voidGrub: number;
elderDragon: number;
};
bans: Array<{ championId: number; pickTurn: number }>;
participants: Array<{
userId: string | null;
summonerName: string;
tagLine: string;
teamIndex: number;
side: TeamSide;
teamPosition: string;
championId: number;
championLevel: number;
kills: number;
deaths: number;
assists: number;
@@ -128,13 +159,21 @@ export interface InternalMatchDetailResponse {
gold: number;
gpm: number;
damageDealtToChampions: number;
damageTaken: number;
damageShare: number;
killParticipation: number;
visionScore: number;
wardsPlaced: number;
wardsKilled: number;
controlWardsBought: number;
firstBloodKill: boolean;
firstBloodAssist: boolean;
items: number[];
trinket: number;
summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
perks: MatchStatsRunePerks;
itemBuild: MatchStatsItemBuildEvent[];
skillBuild: MatchStatsSkillBuildEvent[];
win: boolean;
}>;
}>;
@@ -1,5 +1,6 @@
import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema';
import type { RiotMatchDto, RiotMatchTimelineDto } from '../riot/riot.types';
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
function makeMatch(): MatchDocument {
@@ -95,4 +96,301 @@ describe('MatchStatsFragmentBuilder', () => {
});
expect(fragment.gameDetails[0].teams[0].participants).toHaveLength(1);
});
it('builds rich set detail from raw Riot match data', () => {
const builder = new MatchStatsFragmentBuilder();
const match = makeMatch();
const raw = {
metadata: {
dataVersion: '2',
matchId: 'KR_1',
participants: ['puuid-1'],
},
info: {
gameCreation: 1_000,
gameDuration: 1_800,
gameId: 1,
gameMode: 'CLASSIC',
gameName: 'teambuilder-match-1',
gameStartTimestamp: 1_000,
gameType: 'CUSTOM_GAME',
gameVersion: '16.11.1.1234',
mapId: 11,
participants: [
{
assists: 7,
champExperience: 15_000,
champLevel: 15,
championId: 266,
championName: 'Aatrox',
deaths: 1,
firstBloodAssist: false,
firstBloodKill: true,
goldEarned: 12_345,
goldSpent: 11_000,
individualPosition: 'TOP',
item0: 1054,
item1: 3071,
item2: 0,
item3: 0,
item4: 0,
item5: 0,
item6: 3340,
kills: 5,
neutralMinionsKilled: 8,
participantId: 1,
perks: {
statPerks: { defense: 5001, flex: 5008, offense: 5005 },
styles: [
{
description: 'primaryStyle',
style: 8000,
selections: [
{ perk: 8010, var1: 0, var2: 0, var3: 0 },
{ perk: 9111, var1: 0, var2: 0, var3: 0 },
{ perk: 9105, var1: 0, var2: 0, var3: 0 },
{ perk: 8299, var1: 0, var2: 0, var3: 0 },
],
},
{
description: 'subStyle',
style: 8400,
selections: [
{ perk: 8444, var1: 0, var2: 0, var3: 0 },
{ perk: 8451, var1: 0, var2: 0, var3: 0 },
],
},
],
},
puuid: 'puuid-1',
riotIdGameName: 'Player',
riotIdTagLine: 'KR1',
summoner1Id: 4,
summoner2Id: 12,
summonerId: 'summoner-1',
summonerLevel: 100,
summonerName: 'Player',
teamId: 100,
teamPosition: 'TOP',
timePlayed: 1_800,
totalDamageDealtToChampions: 18_765,
totalDamageTaken: 24_321,
totalMinionsKilled: 220,
visionScore: 18,
visionWardsBoughtInGame: 2,
wardsKilled: 3,
wardsPlaced: 11,
win: true,
},
],
platformId: 'KR',
queueId: 0,
teams: [
{
bans: [
{ championId: 14, pickTurn: 1 },
{ championId: 43, pickTurn: 2 },
],
objectives: {
baron: { first: true, kills: 1 },
champion: { first: true, kills: 5 },
dragon: { first: true, kills: 2 },
horde: { first: false, kills: 3 },
inhibitor: { first: false, kills: 0 },
riftHerald: { first: false, kills: 0 },
tower: { first: true, kills: 7 },
},
teamId: 100,
win: true,
},
],
},
};
const timeline = {
metadata: {
dataVersion: '2',
matchId: 'KR_1',
participants: ['puuid-1'],
},
info: {
frameInterval: 60_000,
frames: [
{
timestamp: 0,
participantFrames: {
'1': { participantId: 1, totalGold: 500, xp: 0 },
},
},
{
timestamp: 60_000,
events: [
{
type: 'ITEM_PURCHASED',
timestamp: 10_000,
participantId: 1,
itemId: 1054,
},
{
type: 'SKILL_LEVEL_UP',
timestamp: 11_000,
participantId: 1,
skillSlot: 1,
levelUpType: 'NORMAL',
},
{
type: 'ITEM_DESTROYED',
timestamp: 12_000,
participantId: 1,
itemId: 2003,
},
{
type: 'ITEM_UNDO',
timestamp: 13_000,
participantId: 1,
beforeId: 1054,
afterId: 3071,
},
{
type: 'ELITE_MONSTER_KILL',
timestamp: 20_000,
killerTeamId: 100,
monsterType: 'DRAGON',
monsterSubType: 'FIRE_DRAGON',
},
{
type: 'ELITE_MONSTER_KILL',
timestamp: 30_000,
killerTeamId: 100,
monsterType: 'DRAGON',
monsterSubType: 'ELDER_DRAGON',
},
{
type: 'ELITE_MONSTER_KILL',
timestamp: 40_000,
killerId: 1,
monsterType: 'HORDE',
},
{
type: 'SKILL_LEVEL_UP',
timestamp: 45_000,
participantId: 1,
skillSlot: 3,
levelUpType: 'NORMAL',
},
{
type: 'ELITE_MONSTER_KILL',
timestamp: 50_000,
killerTeamId: 100,
monsterType: 'BARON_NASHOR',
},
{
type: 'ELITE_MONSTER_KILL',
timestamp: 55_000,
killerTeamId: 100,
monsterType: 'RIFTHERALD',
},
],
participantFrames: {
'1': { participantId: 1, totalGold: 1_150, xp: 550 },
},
},
],
},
};
const fragment = builder.buildFragment({
match,
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
timelineByRiotMatchId: new Map([
['KR_1', timeline as RiotMatchTimelineDto],
]),
});
expect(fragment.gameDetails[0]).toMatchObject({
gameVersion: '16.11.1.1234',
objectiveEvents: [
{
timestamp: 20,
side: 'blue',
type: 'dragon',
monsterSubType: 'FIRE_DRAGON',
},
{
timestamp: 30,
side: 'blue',
type: 'elderDragon',
monsterSubType: 'ELDER_DRAGON',
},
{ timestamp: 40, side: 'blue', type: 'voidGrub' },
{ timestamp: 50, side: 'blue', type: 'baron' },
{ timestamp: 55, side: 'blue', type: 'riftHerald' },
],
timeline: [
{
timestamp: 0,
blue: { gold: 500, xp: 0 },
red: { gold: 0, xp: 0 },
goldDiff: 500,
xpDiff: 0,
},
{
timestamp: 60,
blue: { gold: 1_150, xp: 550 },
red: { gold: 0, xp: 0 },
goldDiff: 1_150,
xpDiff: 550,
},
],
});
expect(fragment.gameDetails[0].teams[0].bans).toEqual([
{ championId: 14, pickTurn: 1 },
{ championId: 43, pickTurn: 2 },
]);
expect(fragment.gameDetails[0].teams[0].objectives).toMatchObject({
baron: 1,
dragon: 1,
elderDragon: 1,
inhibitor: 0,
riftHerald: 1,
tower: 7,
voidGrub: 1,
});
expect(fragment.records[0]).toMatchObject({
championLevel: 15,
cs: 228,
damageDealtToChampions: 18_765,
damageTaken: 24_321,
firstBloodKill: true,
firstBloodAssist: false,
controlWardsBought: 2,
wardsKilled: 3,
wardsPlaced: 11,
perks: {
primaryStyle: 8000,
subStyle: 8400,
keystone: 8010,
selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451],
styles: [
{ styleId: 8000, perkIds: [8010, 9111, 9105, 8299] },
{ styleId: 8400, perkIds: [8444, 8451] },
],
statPerks: { defense: 5001, flex: 5008, offense: 5005 },
},
itemBuild: [
{ timestamp: 10, itemId: 1054, type: 'purchased' },
{ timestamp: 12, itemId: 2003, type: 'destroyed' },
{
timestamp: 13,
itemId: 3071,
type: 'undo',
beforeId: 1054,
afterId: 3071,
},
],
skillBuild: [
{ timestamp: 11, skillSlot: 1, level: 1, levelUpType: 'NORMAL' },
{ timestamp: 45, skillSlot: 3, level: 2, levelUpType: 'NORMAL' },
],
});
});
});
@@ -3,9 +3,18 @@ import mongoose from 'mongoose';
import type {
MatchDocument,
MatchGameResultParticipant,
MatchStatsItemBuildEvent,
MatchStatsObjectiveEvent,
MatchStatsObjectiveSummary,
MatchStatsSkillBuildEvent,
MatchStatsTimelinePoint,
TeamSide,
} from '../global/database/schema';
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
import type {
RiotMatchDto,
RiotMatchParticipantDto,
RiotMatchTimelineDto,
} from '../riot/riot.types';
import type { InternalMatchCardView } from './community-stats.types';
import type {
InternalGameDetail,
@@ -13,11 +22,18 @@ import type {
MatchStatsFragment,
} from './match-stats.types';
interface ParticipantBuildEvents {
items: MatchStatsItemBuildEvent[];
skills: MatchStatsSkillBuildEvent[];
}
@Injectable()
export class MatchStatsFragmentBuilder {
public buildFragment(params: {
match: MatchDocument;
rawByRiotMatchId: Map<string, RiotMatchDto>;
timelineByRiotMatchId?: Map<string, RiotMatchTimelineDto>;
timelineLoadAttempted?: boolean;
}): MatchStatsFragment {
const games = [...(params.match.result?.games ?? [])].sort(
(left, right) => left.gameNumber - right.gameNumber,
@@ -25,8 +41,15 @@ export class MatchStatsFragmentBuilder {
const matchCard = this.toMatchCard(params.match, games);
const gameDetails = games.map((game) => {
const raw = params.rawByRiotMatchId.get(game.riotMatchId);
const timeline = params.timelineByRiotMatchId?.get(game.riotMatchId);
return raw
? this.toGameDetail(params.match, game, raw)
? this.toGameDetail(
params.match,
game,
raw,
timeline,
params.timelineLoadAttempted === true,
)
: this.toFallbackGameDetail(params.match, game);
});
const records = gameDetails.flatMap((detail) =>
@@ -106,6 +129,8 @@ export class MatchStatsFragmentBuilder {
match: MatchDocument,
game: NonNullable<MatchDocument['result']>['games'][number],
raw: RiotMatchDto,
timeline?: RiotMatchTimelineDto,
timelineLoadAttempted = false,
): InternalGameDetail {
const puuidByUserId = new Map(
match.participants
@@ -129,13 +154,29 @@ export class MatchStatsFragmentBuilder {
rawTeamIdBySide.set(participant.side, rawParticipant.teamId);
}
}
const sideByParticipantId = this.toSideByParticipantId(
raw,
rawTeamIdBySide,
);
const objectiveEvents = this.toObjectiveEvents(
timeline,
rawTeamIdBySide,
sideByParticipantId,
);
const timelineObjectives = this.toTimelineObjectives(objectiveEvents);
const buildEventsByParticipantId =
this.toBuildEventsByParticipantId(timeline);
return {
gameNumber: game.gameNumber,
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
gameVersion: raw.info.gameVersion,
winnerSide: game.winnerSide,
timeline: this.toTimeline(raw, rawTeamIdBySide, timeline),
timelineLoaded: timelineLoadAttempted || Boolean(timeline),
objectiveEvents,
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
const teamIndex =
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
@@ -158,25 +199,35 @@ export class MatchStatsFragmentBuilder {
teamIndex,
side,
win: game.winnerSide === side,
objectives: {
baron: rawTeam?.objectives?.baron?.kills ?? 0,
dragon: rawTeam?.objectives?.dragon?.kills ?? 0,
tower: rawTeam?.objectives?.tower?.kills ?? 0,
},
objectives: this.toObjectiveSummary(
rawTeam,
timelineObjectives.get(side),
Boolean(timeline),
),
bans: (rawTeam?.bans ?? []).map((ban) => ({
championId: ban.championId,
pickTurn: ban.pickTurn,
})),
participants: game.participants
.filter((participant) => participant.side === side)
.map((participant) =>
this.toRecord({
.map((participant) => {
const rawParticipant = rawByPuuid.get(
puuidByUserId.get(participant.userId.toString()) ?? '',
);
return this.toRecord({
match,
game,
participant,
rawParticipant: rawByPuuid.get(
puuidByUserId.get(participant.userId.toString()) ?? '',
),
rawParticipant,
buildEvents: rawParticipant
? buildEventsByParticipantId.get(
rawParticipant.participantId,
)
: undefined,
teamKills,
teamDamage,
});
}),
),
};
}),
};
@@ -192,11 +243,15 @@ export class MatchStatsFragmentBuilder {
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
winnerSide: game.winnerSide,
timeline: [],
timelineLoaded: false,
objectiveEvents: [],
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
side,
win: game.winnerSide === side,
objectives: { baron: 0, dragon: 0, tower: 0 },
objectives: emptyObjectives(),
bans: [],
participants: game.participants
.filter((participant) => participant.side === side)
.map((participant) =>
@@ -217,11 +272,19 @@ export class MatchStatsFragmentBuilder {
game: NonNullable<MatchDocument['result']>['games'][number];
participant: MatchGameResultParticipant;
rawParticipant?: RiotMatchParticipantDto;
buildEvents?: ParticipantBuildEvents;
teamKills: number;
teamDamage: number;
}): InternalRecord {
const { match, game, participant, rawParticipant, teamKills, teamDamage } =
params;
const {
match,
game,
participant,
rawParticipant,
buildEvents,
teamKills,
teamDamage,
} = params;
const snapshot = match.participants.find((item) =>
item.userId.equals(participant.userId),
);
@@ -262,6 +325,7 @@ export class MatchStatsFragmentBuilder {
rawParticipant?.riotIdGameName ??
rawParticipant?.summonerName ??
'Unknown',
tagLine: snapshot?.tagLine ?? rawParticipant?.riotIdTagLine ?? '',
profileIconId: snapshot?.profileIconId ?? 0,
teamIndex: participant.teamIndex,
side: participant.side,
@@ -290,6 +354,8 @@ export class MatchStatsFragmentBuilder {
),
wardsPlaced: rawParticipant?.wardsPlaced ?? 0,
wardsKilled: rawParticipant?.wardsKilled ?? 0,
firstBloodKill: booleanField(rawParticipant, 'firstBloodKill'),
firstBloodAssist: booleanField(rawParticipant, 'firstBloodAssist'),
items: [
rawParticipant?.item0 ?? 0,
rawParticipant?.item1 ?? 0,
@@ -304,6 +370,8 @@ export class MatchStatsFragmentBuilder {
rawParticipant?.summoner2Id ?? 0,
],
perks: rawParticipant ? this.resolvePerks(rawParticipant) : {},
itemBuild: buildEvents?.items ?? [],
skillBuild: buildEvents?.skills ?? [],
rating,
};
}
@@ -319,6 +387,250 @@ export class MatchStatsFragmentBuilder {
primaryStyle: primary?.style,
subStyle: sub?.style,
keystone: primary?.selections[0]?.perk,
selectedPerkIds: participant.perks.styles.flatMap((style) =>
style.selections.map((selection) => selection.perk),
),
styles: participant.perks.styles.map((style) => ({
styleId: style.style,
perkIds: style.selections.map((selection) => selection.perk),
})),
statPerks: {
offense: participant.perks.statPerks.offense,
flex: participant.perks.statPerks.flex,
defense: participant.perks.statPerks.defense,
},
};
}
private toBuildEventsByParticipantId(
timeline?: RiotMatchTimelineDto,
): Map<number, ParticipantBuildEvents> {
const buildEventsByParticipantId = new Map<number, ParticipantBuildEvents>();
if (!timeline?.info.frames.length) return buildEventsByParticipantId;
const getEvents = (participantId: number): ParticipantBuildEvents => {
const current = buildEventsByParticipantId.get(participantId);
if (current) return current;
const created: ParticipantBuildEvents = { items: [], skills: [] };
buildEventsByParticipantId.set(participantId, created);
return created;
};
for (const frame of timeline.info.frames) {
for (const event of frame.events ?? []) {
const participantId = event.participantId;
if (!participantId) continue;
const timestamp = Math.max(0, Math.round(event.timestamp / 1000));
if (event.type === 'SKILL_LEVEL_UP' && isSkillSlot(event.skillSlot)) {
const skills = getEvents(participantId).skills;
skills.push({
timestamp,
skillSlot: event.skillSlot,
level: skills.length + 1,
levelUpType: event.levelUpType,
});
continue;
}
const itemType = toItemBuildType(event.type);
if (!itemType) continue;
const itemId = event.itemId ?? event.afterId ?? event.beforeId ?? 0;
if (itemId <= 0) continue;
getEvents(participantId).items.push({
timestamp,
itemId,
type: itemType,
beforeId: event.beforeId,
afterId: event.afterId,
});
}
}
for (const events of buildEventsByParticipantId.values()) {
events.items.sort((left, right) => left.timestamp - right.timestamp);
events.skills.sort((left, right) => left.timestamp - right.timestamp);
}
return buildEventsByParticipantId;
}
private toTimeline(
raw: RiotMatchDto,
rawTeamIdBySide: Map<TeamSide, number>,
timeline?: RiotMatchTimelineDto,
): MatchStatsTimelinePoint[] {
if (!timeline?.info.frames.length) return [];
const sideByParticipantId = this.toSideByParticipantId(
raw,
rawTeamIdBySide,
);
const points = timeline.info.frames.map((frame) => {
const point: MatchStatsTimelinePoint = {
timestamp: Math.max(0, Math.round(frame.timestamp / 1000)),
blue: { gold: 0, xp: 0 },
red: { gold: 0, xp: 0 },
goldDiff: 0,
xpDiff: 0,
};
for (const participantFrame of Object.values(frame.participantFrames)) {
const side = sideByParticipantId.get(participantFrame.participantId);
if (!side) continue;
point[side].gold += participantFrame.totalGold;
point[side].xp += participantFrame.xp;
}
point.goldDiff = point.blue.gold - point.red.gold;
point.xpDiff = point.blue.xp - point.red.xp;
return point;
});
return points.filter(
(point, index) =>
index === 0 || point.timestamp !== points[index - 1].timestamp,
);
}
private toSideByParticipantId(
raw: RiotMatchDto,
rawTeamIdBySide: Map<TeamSide, number>,
): Map<number, TeamSide> {
const blueTeamId = rawTeamIdBySide.get('blue') ?? 100;
const redTeamId = rawTeamIdBySide.get('red') ?? 200;
const sideByParticipantId = new Map<number, TeamSide>();
for (const participant of raw.info.participants) {
if (participant.teamId === blueTeamId) {
sideByParticipantId.set(participant.participantId, 'blue');
}
if (participant.teamId === redTeamId) {
sideByParticipantId.set(participant.participantId, 'red');
}
}
return sideByParticipantId;
}
private toObjectiveEvents(
timeline: RiotMatchTimelineDto | undefined,
rawTeamIdBySide: Map<TeamSide, number>,
sideByParticipantId: Map<number, TeamSide>,
): MatchStatsObjectiveEvent[] {
if (!timeline?.info.frames.length) return [];
const sideByTeamId = new Map<number, TeamSide>();
for (const [side, teamId] of rawTeamIdBySide.entries()) {
sideByTeamId.set(teamId, side);
}
const objectiveEvents: MatchStatsObjectiveEvent[] = [];
for (const frame of timeline.info.frames) {
for (const event of frame.events ?? []) {
if (event.type !== 'ELITE_MONSTER_KILL') continue;
const side =
(typeof event.killerTeamId === 'number'
? sideByTeamId.get(event.killerTeamId)
: undefined) ??
(typeof event.killerId === 'number'
? sideByParticipantId.get(event.killerId)
: undefined);
if (!side) continue;
const timestamp = Math.max(0, Math.round(event.timestamp / 1000));
switch (event.monsterType) {
case 'BARON_NASHOR':
objectiveEvents.push({ timestamp, side, type: 'baron' });
break;
case 'RIFTHERALD':
objectiveEvents.push({ timestamp, side, type: 'riftHerald' });
break;
case 'HORDE':
objectiveEvents.push({ timestamp, side, type: 'voidGrub' });
break;
case 'DRAGON':
if (event.monsterSubType === 'ELDER_DRAGON') {
objectiveEvents.push({
timestamp,
side,
type: 'elderDragon',
monsterSubType: event.monsterSubType,
});
} else {
objectiveEvents.push({
timestamp,
side,
type: 'dragon',
monsterSubType: event.monsterSubType,
});
}
break;
default:
break;
}
}
}
return objectiveEvents.sort((left, right) => left.timestamp - right.timestamp);
}
private toTimelineObjectives(
objectiveEvents: MatchStatsObjectiveEvent[],
): Map<TeamSide, MatchStatsObjectiveSummary> {
const objectives = new Map<TeamSide, MatchStatsObjectiveSummary>([
['blue', emptyObjectives()],
['red', emptyObjectives()],
]);
for (const event of objectiveEvents) {
const current = objectives.get(event.side) ?? emptyObjectives();
switch (event.type) {
case 'baron':
current.baron += 1;
break;
case 'riftHerald':
current.riftHerald += 1;
break;
case 'voidGrub':
current.voidGrub += 1;
break;
case 'dragon':
current.dragon += 1;
break;
case 'elderDragon':
current.elderDragon += 1;
break;
default:
break;
}
objectives.set(event.side, current);
}
return objectives;
}
private toObjectiveSummary(
rawTeam:
| RiotMatchDto['info']['teams'][number]
| undefined,
timelineObjectives: MatchStatsObjectiveSummary | undefined,
hasTimeline: boolean,
): MatchStatsObjectiveSummary {
const rawObjectives = rawTeam?.objectives;
return {
tower: rawObjectives?.tower?.kills ?? 0,
dragon: hasTimeline
? (timelineObjectives?.dragon ?? 0)
: (rawObjectives?.dragon?.kills ?? 0),
inhibitor: rawObjectives?.inhibitor?.kills ?? 0,
baron: hasTimeline
? (timelineObjectives?.baron ?? 0)
: (rawObjectives?.baron?.kills ?? 0),
riftHerald: hasTimeline
? (timelineObjectives?.riftHerald ?? 0)
: (rawObjectives?.riftHerald?.kills ?? 0),
voidGrub: hasTimeline
? (timelineObjectives?.voidGrub ?? 0)
: (rawObjectives?.horde?.kills ?? 0),
elderDragon: timelineObjectives?.elderDragon ?? 0,
};
}
@@ -354,6 +666,27 @@ function average(value: number, total: number): number {
return total > 0 ? round(value / total) : 0;
}
function isSkillSlot(value: number | undefined): value is 1 | 2 | 3 | 4 {
return value === 1 || value === 2 || value === 3 || value === 4;
}
function toItemBuildType(
value: string,
): MatchStatsItemBuildEvent['type'] | null {
switch (value) {
case 'ITEM_PURCHASED':
return 'purchased';
case 'ITEM_SOLD':
return 'sold';
case 'ITEM_DESTROYED':
return 'destroyed';
case 'ITEM_UNDO':
return 'undo';
default:
return null;
}
}
function round(value: number): number {
return Math.round(value * 10) / 10;
}
@@ -365,3 +698,22 @@ function numberField(
const value = participant?.[key];
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
}
function booleanField(
participant: RiotMatchParticipantDto | undefined,
key: string,
): boolean {
return participant?.[key] === true;
}
function emptyObjectives(): MatchStatsObjectiveSummary {
return {
tower: 0,
dragon: 0,
inhibitor: 0,
baron: 0,
riftHerald: 0,
voidGrub: 0,
elderDragon: 0,
};
}
@@ -29,6 +29,7 @@ describe('MatchStatsService', () => {
connectionService,
repository,
{} as MatchStatsFragmentBuilder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId);
@@ -53,7 +54,20 @@ describe('MatchStatsService', () => {
});
const riotFind = jest.fn().mockReturnValue({
lean: () => ({
exec: jest.fn().mockResolvedValue([{ matchId: 'KR_1', raw: {} }]),
exec: jest.fn().mockResolvedValue([
{
matchId: 'KR_1',
raw: {},
timeline: {
metadata: {
dataVersion: '2',
matchId: 'KR_1',
participants: [],
},
info: { frameInterval: 60_000, frames: [] },
},
},
]),
}),
});
const connectionService = {
@@ -82,6 +96,7 @@ describe('MatchStatsService', () => {
connectionService,
repository,
builder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId);
@@ -89,6 +104,8 @@ describe('MatchStatsService', () => {
expect(builder.buildFragment).toHaveBeenCalledWith({
match,
rawByRiotMatchId: expect.any(Map),
timelineByRiotMatchId: expect.any(Map),
timelineLoadAttempted: false,
});
expect(repository.upsert).toHaveBeenCalledWith(
expect.objectContaining({
@@ -97,7 +114,7 @@ describe('MatchStatsService', () => {
scheduledAt,
gameCreationMin: 1_000,
gameCreationMax: 2_000,
builderVersion: 1,
builderVersion: 9,
}),
);
});
@@ -1,21 +1,33 @@
import { Injectable } from '@nestjs/common';
import { Injectable, Logger } from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type { MatchDocument } from '../global/database/schema';
import type { RiotMatchDto } from '../riot/riot.types';
import { RiotMatchService } from '../riot/riot-match.service';
import {
RIOT_REGIONAL_ROUTES,
type RiotMatchDto,
type RiotMatchTimelineDto,
type RiotRegionalRoute,
} from '../riot/riot.types';
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
import { MatchStatsRepository } from './match-stats.repository';
import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types';
@Injectable()
export class MatchStatsService {
private readonly logger = new Logger(MatchStatsService.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly repository: MatchStatsRepository,
private readonly builder: MatchStatsFragmentBuilder,
private readonly riotMatchService: RiotMatchService,
) {}
public async buildAndUpsert(matchId: mongoose.Types.ObjectId): Promise<void> {
public async buildAndUpsert(
matchId: mongoose.Types.ObjectId,
options: { includeTimeline?: boolean } = {},
): Promise<void> {
const MatchModel = await this.connectionService.getModel('match');
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const match = await MatchModel.findById(matchId).exec();
@@ -41,7 +53,51 @@ export class MatchStatsService {
const rawByRiotMatchId = new Map(
riotDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]),
);
const fragment = this.builder.buildFragment({ match, rawByRiotMatchId });
const timelineByRiotMatchId = new Map<string, RiotMatchTimelineDto>();
for (const doc of riotDocs) {
if (isRiotMatchTimelineDto(doc.timeline)) {
timelineByRiotMatchId.set(doc.matchId, doc.timeline);
}
}
if (
options.includeTimeline &&
riotDocs.length > 0 &&
timelineByRiotMatchId.size < riotDocs.length
) {
const region = await this.resolveRiotRegion(match.communityId);
for (const doc of riotDocs) {
if (timelineByRiotMatchId.has(doc.matchId)) continue;
try {
const timeline = await this.riotMatchService.getMatchTimeline(
doc.matchId,
{ region },
);
await RiotMatchModel.updateOne(
{ matchId: doc.matchId },
{
$set: {
timeline: timeline as unknown as Record<string, unknown>,
timelineFetchedAt: new Date(),
},
},
).exec();
timelineByRiotMatchId.set(doc.matchId, timeline);
} catch (error) {
this.logger.warn(
`Failed to fetch match timeline for ${doc.matchId}: ${
error instanceof Error ? error.message : error
}`,
);
}
}
}
const fragment = this.builder.buildFragment({
match,
rawByRiotMatchId,
timelineByRiotMatchId,
timelineLoadAttempted: options.includeTimeline === true,
});
await this.repository.upsert({
matchId: match._id,
@@ -101,4 +157,29 @@ export class MatchStatsService {
Boolean(match.result?.games?.length)
);
}
private async resolveRiotRegion(
communityId: mongoose.Types.ObjectId,
): Promise<RiotRegionalRoute> {
const CommunityModel = await this.connectionService.getModel('community');
const community = await CommunityModel.findById(communityId)
.select({ riotRegion: 1 })
.lean()
.exec();
const region = community?.riotRegion;
return RIOT_REGIONAL_ROUTES.includes(region as RiotRegionalRoute)
? (region as RiotRegionalRoute)
: 'asia';
}
}
function isRiotMatchTimelineDto(
value: unknown,
): value is RiotMatchTimelineDto {
if (!isRecord(value) || !isRecord(value.info)) return false;
return Array.isArray(value.info.frames);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
@@ -4,7 +4,7 @@ import type {
} from '../global/database/schema';
import type { InternalMatchCardView } from './community-stats.types';
export const MATCH_STATS_BUILDER_VERSION = 1;
export const MATCH_STATS_BUILDER_VERSION = 9;
export type InternalRecord = MatchStatsRecord;
export type InternalGameDetail = MatchStatsGameDetail;
@@ -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);
});
+78 -2
View File
@@ -398,6 +398,8 @@ export interface RiotMatch extends MongooseTimestamps {
queueId?: number;
participantPuuids: string[];
raw: Record<string, unknown>; // Riot API Match-V5 원본 응답 전체
timeline?: Record<string, unknown>; // Riot API Match-V5 timeline 원본 응답 전체
timelineFetchedAt?: Date;
fetchedAt: Date;
}
@@ -487,6 +489,7 @@ export interface MatchSeriesResult {
export interface MatchGameAssignment {
gameNumber: number;
roundNumber?: number;
teamAIndex: number;
teamBIndex: number;
}
@@ -524,6 +527,7 @@ export interface Match extends MongooseTimestamps {
maxParticipants: number;
gameCount: number;
gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
tournamentCodeIds: mongoose.Types.ObjectId[];
gameSchedule: MatchGameAssignment[];
teamBuiltAt?: Date;
@@ -664,6 +668,39 @@ export interface AuctionHistoryEntry extends MongooseTimestamps {
export type AuctionHistoryEntryDocument = HydratedDocument<AuctionHistoryEntry>;
// ===== MatchStats (precomputed internal stats fragment) =====
export interface MatchStatsRuneStyleSelection {
styleId: number;
perkIds: number[];
}
export interface MatchStatsRunePerks {
primaryStyle?: number;
subStyle?: number;
keystone?: number;
selectedPerkIds?: number[];
styles?: MatchStatsRuneStyleSelection[];
statPerks?: {
offense?: number;
flex?: number;
defense?: number;
};
}
export interface MatchStatsItemBuildEvent {
timestamp: number;
itemId: number;
type: 'purchased' | 'sold' | 'destroyed' | 'undo';
beforeId?: number;
afterId?: number;
}
export interface MatchStatsSkillBuildEvent {
timestamp: number;
skillSlot: 1 | 2 | 3 | 4;
level: number;
levelUpType?: string;
}
export interface MatchStatsRecord {
matchId: string;
title: string;
@@ -674,6 +711,7 @@ export interface MatchStatsRecord {
gameDuration: number;
userId: string;
summonerName: string;
tagLine: string;
profileIconId: number;
teamIndex: number;
side: TeamSide;
@@ -696,10 +734,14 @@ export interface MatchStatsRecord {
controlWardsBought: number;
wardsPlaced: number;
wardsKilled: number;
firstBloodKill: boolean;
firstBloodAssist: boolean;
items: number[];
trinket: number;
summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
perks: MatchStatsRunePerks;
itemBuild: MatchStatsItemBuildEvent[];
skillBuild: MatchStatsSkillBuildEvent[];
rating: number;
}
@@ -708,16 +750,46 @@ export interface MatchStatsGameDetail {
riotMatchId: string;
gameCreation: number;
gameDuration: number;
gameVersion?: string;
winnerSide: TeamSide;
timeline: MatchStatsTimelinePoint[];
timelineLoaded?: boolean;
objectiveEvents: MatchStatsObjectiveEvent[];
teams: Array<{
teamIndex: number;
side: TeamSide;
win: boolean;
objectives: { baron: number; dragon: number; tower: number };
objectives: MatchStatsObjectiveSummary;
bans: Array<{ championId: number; pickTurn: number }>;
participants: MatchStatsRecord[];
}>;
}
export interface MatchStatsObjectiveSummary {
tower: number;
dragon: number;
inhibitor: number;
baron: number;
riftHerald: number;
voidGrub: number;
elderDragon: number;
}
export interface MatchStatsObjectiveEvent {
timestamp: number;
side: TeamSide;
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
monsterSubType?: string;
}
export interface MatchStatsTimelinePoint {
timestamp: number;
blue: { gold: number; xp: number };
red: { gold: number; xp: number };
goldDiff: number;
xpDiff: number;
}
export interface MatchStats extends MongooseTimestamps {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
@@ -1133,6 +1205,8 @@ export const RiotMatchSchema = new Schema<RiotMatch>(
queueId: { type: Number },
participantPuuids: { type: [String], required: true, default: [] },
raw: { type: Schema.Types.Mixed, required: true, default: () => ({}) },
timeline: { type: Schema.Types.Mixed },
timelineFetchedAt: { type: Date },
fetchedAt: { type: Date, required: true, default: Date.now },
},
{
@@ -1284,6 +1358,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 +1464,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,
@@ -1,4 +1,4 @@
import type { RiotLane } from '../global/database/schema';
import type { MatchStatsRunePerks, RiotLane } from '../global/database/schema';
import type {
RiotQueueGroup,
RiotRankFilter,
@@ -121,7 +121,7 @@ export interface RecentMatchTeamParticipantView {
items: number[];
trinket: number;
summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
perks: MatchStatsRunePerks;
totalCs: number;
csPerMin: number;
goldEarned: number;
@@ -162,7 +162,7 @@ export interface RecentMatchView {
items: number[];
trinket: number;
summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
perks: MatchStatsRunePerks;
teams: Array<{
side: 100 | 200;
win: boolean;
@@ -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,
@@ -106,4 +106,112 @@ describe('RiotMatchService', () => {
expect(match.info.participants[0].teamPosition).toBe('');
expect(match.info.participants[0].individualPosition).toBe('');
});
it('fetches and parses match timeline frames', async () => {
const payload = {
metadata: {
dataVersion: '2',
matchId: 'KR_8188913502',
participants: ['puuid-1'],
},
info: {
frameInterval: 60_000,
gameId: 8188913502,
participants: [{ participantId: 1, puuid: 'puuid-1' }],
frames: [
{
timestamp: 60_000,
events: [
{
type: 'ELITE_MONSTER_KILL',
timestamp: 30_000,
killerTeamId: 100,
monsterType: 'DRAGON',
monsterSubType: 'ELDER_DRAGON',
},
{
type: 'ITEM_PURCHASED',
timestamp: 40_000,
participantId: 1,
itemId: 1054,
},
{
type: 'ITEM_UNDO',
timestamp: 45_000,
participantId: 1,
beforeId: 1054,
afterId: 3071,
},
{
type: 'SKILL_LEVEL_UP',
timestamp: 50_000,
participantId: 1,
skillSlot: 3,
levelUpType: 'NORMAL',
},
],
participantFrames: {
'1': {
currentGold: 650,
jungleMinionsKilled: 0,
level: 2,
minionsKilled: 6,
participantId: 1,
totalGold: 1_150,
xp: 550,
},
},
},
],
},
};
const riotClientService = {
get: jest.fn(
async <T>(
_path: string,
_options: unknown,
parser?: RiotResponseParser<T>,
) => (parser ? parser(payload) : (payload as T)),
),
} as unknown as RiotClientService;
const service = new RiotMatchService(riotClientService);
const timeline = await service.getMatchTimeline('KR_8188913502', {
region: 'asia',
});
expect(riotClientService.get).toHaveBeenCalledWith(
'/lol/match/v5/matches/KR_8188913502/timeline',
expect.objectContaining({ region: 'asia' }),
expect.any(Function),
);
expect(timeline.info.frames[0].participantFrames['1']).toMatchObject({
participantId: 1,
totalGold: 1_150,
xp: 550,
});
expect(timeline.info.frames[0].events[0]).toMatchObject({
type: 'ELITE_MONSTER_KILL',
killerTeamId: 100,
monsterType: 'DRAGON',
monsterSubType: 'ELDER_DRAGON',
});
expect(timeline.info.frames[0].events[1]).toMatchObject({
type: 'ITEM_PURCHASED',
participantId: 1,
itemId: 1054,
});
expect(timeline.info.frames[0].events[2]).toMatchObject({
type: 'ITEM_UNDO',
participantId: 1,
beforeId: 1054,
afterId: 3071,
});
expect(timeline.info.frames[0].events[3]).toMatchObject({
type: 'SKILL_LEVEL_UP',
participantId: 1,
skillSlot: 3,
levelUpType: 'NORMAL',
});
});
});
@@ -15,6 +15,12 @@ import {
RiotMatchPerkStyleSelectionDto,
RiotMatchStatPerksDto,
RiotMatchTeamDto,
RiotMatchTimelineDto,
RiotMatchTimelineEventDto,
RiotMatchTimelineFrameDto,
RiotMatchTimelineInfoDto,
RiotMatchTimelineParticipantDto,
RiotMatchTimelineParticipantFrameDto,
RiotMatchType,
} from './riot.types';
@@ -66,6 +72,20 @@ export class RiotMatchService {
parseMatchResponse,
);
}
public async getMatchTimeline(
matchId: string,
options: RiotMatchLookupOptions = {},
): Promise<RiotMatchTimelineDto> {
return this.riotClientService.get<RiotMatchTimelineDto>(
`/lol/match/v5/matches/${encodeURIComponent(matchId)}/timeline`,
{
region: options.region,
signal: options.signal,
},
parseMatchTimelineResponse,
);
}
}
function validateMatchIdsLookupOptions(
@@ -115,6 +135,48 @@ function parseMatchResponse(value: unknown): RiotMatchDto {
};
}
function parseMatchTimelineResponse(value: unknown): RiotMatchTimelineDto {
if (!isRecord(value)) {
throw new TypeError('Riot match timeline response must be an object.');
}
return {
metadata: parseMatchMetadata(value.metadata),
info: parseMatchTimelineInfo(value.info),
};
}
function parseMatchTimelineInfo(value: unknown): RiotMatchTimelineInfoDto {
if (!isRecord(value)) {
throw new TypeError('Riot match timeline info must be an object.');
}
const frames = value.frames;
if (!Array.isArray(frames)) {
throw new TypeError('Riot match timeline info.frames must be an array.');
}
const participants = value.participants;
if (participants !== undefined && !Array.isArray(participants)) {
throw new TypeError(
'Riot match timeline info.participants must be an array when present.',
);
}
return {
...value,
frameInterval: requireNumber(
value.frameInterval,
'timeline.info.frameInterval',
),
frames: frames.map((frame, index) => parseTimelineFrame(frame, index)),
gameId: optionalNumber(value.gameId, 'timeline.info.gameId'),
participants: participants?.map((participant, index) =>
parseTimelineParticipant(participant, index),
),
};
}
function parseMatchMetadata(value: unknown): RiotMatchMetadataDto {
if (!isRecord(value)) {
throw new TypeError('Riot match metadata must be an object.');
@@ -211,6 +273,195 @@ function parseMatchInfo(value: unknown): RiotMatchInfoDto {
};
}
function parseTimelineParticipant(
value: unknown,
index: number,
): RiotMatchTimelineParticipantDto {
if (!isRecord(value)) {
throw new TypeError(`timeline.info.participants[${index}] must be an object.`);
}
return {
...value,
participantId: requireNumber(
value.participantId,
`timeline.info.participants[${index}].participantId`,
),
puuid: requireString(value.puuid, `timeline.info.participants[${index}].puuid`),
};
}
function parseTimelineFrame(
value: unknown,
index: number,
): RiotMatchTimelineFrameDto {
if (!isRecord(value)) {
throw new TypeError(`timeline.info.frames[${index}] must be an object.`);
}
const participantFrames = value.participantFrames;
if (!isRecord(participantFrames)) {
throw new TypeError(
`timeline.info.frames[${index}].participantFrames must be an object.`,
);
}
const events = value.events;
if (events !== undefined && !Array.isArray(events)) {
throw new TypeError(
`timeline.info.frames[${index}].events must be an array when present.`,
);
}
return {
...value,
events: (events ?? []).map((event, eventIndex) =>
parseTimelineEvent(event, index, eventIndex),
),
timestamp: requireNumber(
value.timestamp,
`timeline.info.frames[${index}].timestamp`,
),
participantFrames: Object.fromEntries(
Object.entries(participantFrames).map(([key, participantFrame]) => [
key,
parseTimelineParticipantFrame(participantFrame, index, key),
]),
),
};
}
function parseTimelineEvent(
value: unknown,
frameIndex: number,
eventIndex: number,
): RiotMatchTimelineEventDto {
if (!isRecord(value)) {
throw new TypeError(
`timeline.info.frames[${frameIndex}].events[${eventIndex}] must be an object.`,
);
}
const assistingParticipantIds = value.assistingParticipantIds;
if (
assistingParticipantIds !== undefined &&
(!Array.isArray(assistingParticipantIds) ||
!assistingParticipantIds.every(isFiniteNumber))
) {
throw new TypeError(
`timeline.info.frames[${frameIndex}].events[${eventIndex}].assistingParticipantIds must be an array of numbers when present.`,
);
}
return {
...value,
afterId: optionalNumber(
value.afterId,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].afterId`,
),
assistingParticipantIds,
beforeId: optionalNumber(
value.beforeId,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].beforeId`,
),
buildingType: optionalString(
value.buildingType,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].buildingType`,
),
itemId: optionalNumber(
value.itemId,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].itemId`,
),
killerId: optionalNumber(
value.killerId,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].killerId`,
),
killerTeamId: optionalNumber(
value.killerTeamId,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].killerTeamId`,
),
levelUpType: optionalString(
value.levelUpType,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].levelUpType`,
),
monsterSubType: optionalString(
value.monsterSubType,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].monsterSubType`,
),
monsterType: optionalString(
value.monsterType,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].monsterType`,
),
participantId: optionalNumber(
value.participantId,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].participantId`,
),
skillSlot: optionalNumber(
value.skillSlot,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].skillSlot`,
),
teamId: optionalNumber(
value.teamId,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].teamId`,
),
timestamp: requireNumber(
value.timestamp,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].timestamp`,
),
towerType: optionalString(
value.towerType,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].towerType`,
),
type: requireString(
value.type,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].type`,
),
};
}
function parseTimelineParticipantFrame(
value: unknown,
frameIndex: number,
key: string,
): RiotMatchTimelineParticipantFrameDto {
if (!isRecord(value)) {
throw new TypeError(
`timeline.info.frames[${frameIndex}].participantFrames.${key} must be an object.`,
);
}
return {
...value,
currentGold: optionalNumber(
value.currentGold,
`timeline.info.frames[${frameIndex}].participantFrames.${key}.currentGold`,
),
jungleMinionsKilled: optionalNumber(
value.jungleMinionsKilled,
`timeline.info.frames[${frameIndex}].participantFrames.${key}.jungleMinionsKilled`,
),
level: optionalNumber(
value.level,
`timeline.info.frames[${frameIndex}].participantFrames.${key}.level`,
),
minionsKilled: optionalNumber(
value.minionsKilled,
`timeline.info.frames[${frameIndex}].participantFrames.${key}.minionsKilled`,
),
participantId: requireNumber(
value.participantId,
`timeline.info.frames[${frameIndex}].participantFrames.${key}.participantId`,
),
totalGold: requireNumber(
value.totalGold,
`timeline.info.frames[${frameIndex}].participantFrames.${key}.totalGold`,
),
xp: requireNumber(
value.xp,
`timeline.info.frames[${frameIndex}].participantFrames.${key}.xp`,
),
};
}
function parseParticipant(
value: unknown,
index: number,
@@ -504,12 +755,22 @@ function parseObjectives(
baron: parseObjective(value.baron, teamIndex, 'baron'),
champion: parseObjective(value.champion, teamIndex, 'champion'),
dragon: parseObjective(value.dragon, teamIndex, 'dragon'),
horde: optionalObjective(value.horde, teamIndex, 'horde'),
inhibitor: parseObjective(value.inhibitor, teamIndex, 'inhibitor'),
riftHerald: parseObjective(value.riftHerald, teamIndex, 'riftHerald'),
tower: parseObjective(value.tower, teamIndex, 'tower'),
};
}
function optionalObjective(
value: unknown,
teamIndex: number,
key: keyof RiotMatchObjectivesDto,
): RiotMatchObjectiveDto | undefined {
if (value === undefined || value === null) return undefined;
return parseObjective(value, teamIndex, key);
}
function parseObjective(
value: unknown,
teamIndex: number,
+54
View File
@@ -134,6 +134,11 @@ export interface RiotMatchDto {
info: RiotMatchInfoDto;
}
export interface RiotMatchTimelineDto {
metadata: RiotMatchMetadataDto;
info: RiotMatchTimelineInfoDto;
}
export interface RiotMatchMetadataDto {
dataVersion: string;
matchId: string;
@@ -240,6 +245,7 @@ export interface RiotMatchObjectivesDto {
baron: RiotMatchObjectiveDto;
champion: RiotMatchObjectiveDto;
dragon: RiotMatchObjectiveDto;
horde?: RiotMatchObjectiveDto;
inhibitor: RiotMatchObjectiveDto;
riftHerald: RiotMatchObjectiveDto;
tower: RiotMatchObjectiveDto;
@@ -249,3 +255,51 @@ export interface RiotMatchObjectiveDto {
first: boolean;
kills: number;
}
export interface RiotMatchTimelineInfoDto extends Record<string, unknown> {
frameInterval: number;
frames: RiotMatchTimelineFrameDto[];
gameId?: number;
participants?: RiotMatchTimelineParticipantDto[];
}
export interface RiotMatchTimelineParticipantDto extends Record<string, unknown> {
participantId: number;
puuid: string;
}
export interface RiotMatchTimelineFrameDto extends Record<string, unknown> {
timestamp: number;
events: RiotMatchTimelineEventDto[];
participantFrames: Record<string, RiotMatchTimelineParticipantFrameDto>;
}
export interface RiotMatchTimelineEventDto extends Record<string, unknown> {
type: string;
timestamp: number;
afterId?: number;
assistingParticipantIds?: number[];
beforeId?: number;
buildingType?: string;
itemId?: number;
killerId?: number;
killerTeamId?: number;
levelUpType?: string;
monsterSubType?: string;
monsterType?: string;
participantId?: number;
skillSlot?: number;
teamId?: number;
towerType?: string;
}
export interface RiotMatchTimelineParticipantFrameDto
extends Record<string, unknown> {
participantId: number;
totalGold: number;
xp: number;
currentGold?: number;
jungleMinionsKilled?: number;
level?: number;
minionsKilled?: number;
}
@@ -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,10 +548,15 @@ 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] ?? {
const fallback = this.buildRoundRobinGameSchedule(match).find(
(entry) => entry.gameNumber === gameNumber,
);
return fallback
? {
teamAIndex: fallback.teamAIndex,
teamBIndex: fallback.teamBIndex,
}
: {
teamAIndex: 1,
teamBIndex: 2,
};
@@ -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;
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,
});
}
}
match.gameSchedule = schedule;
}
}
@@ -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] ?? {
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 {}
+5
View File
@@ -10,6 +10,7 @@ import AuthCallbackPage from "./pages/AuthCallback";
import HomePage from "./pages/HomePage";
import LoginPage from "./pages/Login";
import MatchDetailPage from "./pages/MatchDetailPage";
import MatchGameDetailPage from "./pages/MatchGameDetailPage";
import MatchTeamProgressPage from "./pages/MatchTeamProgressPage";
import AuctionPage from "./pages/AuctionPage";
import UserHistoryPage from "./pages/UserHistoryPage";
@@ -151,6 +152,10 @@ function App() {
<Route path="/login" element={<LoginPage />} />
<Route path="/auth/callback" element={<AuthCallbackPage />} />
<Route path="/match/:id" element={<MatchDetailPage />} />
<Route
path="/match/:id/game/:gameNumber"
element={<MatchGameDetailPage />}
/>
<Route
path="/match/:id/team/:teamIndex"
element={<MatchTeamProgressPage />}
+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) =>
+92 -4
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[];
@@ -540,6 +562,39 @@ export interface ApiRecentSummaryResponse {
lastFetchedAt: string | null;
}
export interface ApiRuneStyleSelection {
styleId: number;
perkIds: number[];
}
export interface ApiRunePerks {
primaryStyle?: number;
subStyle?: number;
keystone?: number;
selectedPerkIds?: number[];
styles?: ApiRuneStyleSelection[];
statPerks?: {
offense?: number;
flex?: number;
defense?: number;
};
}
export interface ApiItemBuildEvent {
timestamp: number;
itemId: number;
type: 'purchased' | 'sold' | 'destroyed' | 'undo';
beforeId?: number;
afterId?: number;
}
export interface ApiSkillBuildEvent {
timestamp: number;
skillSlot: 1 | 2 | 3 | 4;
level: number;
levelUpType?: string;
}
export interface ApiRecentMatchTeamParticipant {
puuid: string;
gameName: string;
@@ -553,7 +608,7 @@ export interface ApiRecentMatchTeamParticipant {
items: number[];
trinket: number;
summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
perks: ApiRunePerks;
totalCs: number;
csPerMin: number;
goldEarned: number;
@@ -601,7 +656,7 @@ export interface ApiRecentMatchView {
items: number[];
trinket: number;
summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
perks: ApiRunePerks;
teams: ApiRecentMatchTeam[];
}
@@ -710,18 +765,43 @@ export interface ApiInternalMatchDetailResponse {
riotMatchId: string;
gameCreation: number;
gameDuration: number;
gameVersion?: string;
timeline: Array<{
timestamp: number;
blue: { gold: number; xp: number };
red: { gold: number; xp: number };
goldDiff: number;
xpDiff: number;
}>;
objectiveEvents: Array<{
timestamp: number;
side: TeamSide;
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
monsterSubType?: string;
}>;
teams: Array<{
teamIndex: number;
side: TeamSide;
win: boolean;
objectives: { baron: number; dragon: number; tower: number };
objectives: {
tower: number;
dragon: number;
inhibitor: number;
baron: number;
riftHerald: number;
voidGrub: number;
elderDragon: number;
};
bans: Array<{ championId: number; pickTurn: number }>;
participants: Array<{
userId: string | null;
summonerName: string;
tagLine: string;
teamIndex: number;
side: TeamSide;
teamPosition: string;
championId: number;
championLevel: number;
kills: number;
deaths: number;
assists: number;
@@ -730,13 +810,21 @@ export interface ApiInternalMatchDetailResponse {
gold: number;
gpm: number;
damageDealtToChampions: number;
damageTaken: number;
damageShare: number;
killParticipation: number;
visionScore: number;
wardsPlaced: number;
wardsKilled: number;
controlWardsBought: number;
firstBloodKill: boolean;
firstBloodAssist: boolean;
items: number[];
trinket: number;
summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
perks: ApiRunePerks;
itemBuild: ApiItemBuildEvent[];
skillBuild: ApiSkillBuildEvent[];
win: boolean;
}>;
}>;
+7
View File
@@ -69,3 +69,10 @@ export function runeKeystoneIconUrl(
return rune ? `${cdn(manifest)}/img/${rune.icon}` : null;
}
export function runeIconUrl(
manifest: DdragonManifest | null | undefined,
runeId: number | undefined,
) {
return runeKeystoneIconUrl(manifest, runeId);
}
+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>
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+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">