Compare commits

...
18 Commits
Author SHA1 Message Date
dahyeon 737702d78c chore: point dev web api to shared host 2026-06-22 12:16:28 -07:00
dahyeon 98c2323ff2 fix: sync auction timer with server time 2026-06-22 12:16:18 -07:00
dahyeon d2fe4604dd fix: show solo queue tier graph in auction 2026-06-22 05:07:28 -07:00
dahyeon b0dc857463 fix: reserve auction points for remaining slots 2026-06-22 04:37:06 -07:00
dahyeon bac29ac933 feat: auto provision tournament codes 2026-06-20 02:29:30 -07:00
dahyeon 65bc214fb2 feat: add finished match detail tabs 2026-06-20 01:19:39 -07:00
dahyeon 0434a5db66 feat: refine match game detail ux 2026-06-20 01:04:03 -07:00
dahyeon 747adfcb11 feat: improve match game detail ux 2026-06-19 16:57:28 -07:00
dahyeon 7b5604873e feat: add match game detail analytics 2026-06-20 07:26:20 +09:00
dahyeon c6da2013bd feat: add team page tournament code replacement 2026-06-19 04:01:22 -07:00
dahyeon b9881fcb6f fix: allow public tournament code replacement 2026-06-19 03:56:44 -07:00
dahyeon 303886ed53 feat: allow tournament code replacement 2026-06-19 03:43:53 -07:00
dahyeon 1272c81fa9 chore: add round-robin match repair script 2026-06-19 02:33:18 -07:00
dahyeon ade5735dc2 refactor: remove legacy round-robin repair 2026-06-19 01:36:34 -07:00
dahyeon 7399968fe8 fix: repair legacy round-robin schedules 2026-06-19 01:31:27 -07:00
dahyeon 658592973e feat: add limited round-robin scheduling 2026-06-19 01:13:50 -07:00
dahyeon 24983aeb09 feat: allow admins to add match participants 2026-06-16 06:39:50 -07:00
dahyeon 8aff1be225 fix: align home page loading states 2026-06-09 19:13:34 -07:00
53 changed files with 8340 additions and 299 deletions

No files matched your search

@@ -459,6 +459,91 @@ describe('AuctionService', () => {
expect(auction.save).not.toHaveBeenCalled(); expect(auction.save).not.toHaveBeenCalled();
}); });
it('rejects bids that do not reserve minimum points for remaining team slots', async () => {
const matchId = new mongoose.Types.ObjectId();
const auction = {
_id: new mongoose.Types.ObjectId(),
matchId,
phase: 'bidding',
teams: [
{
teamIndex: 1,
captainUserId: new mongoose.Types.ObjectId(),
points: 1000,
members: [],
},
],
currentBid: 100,
currentDeadline: new Date(),
maxTimerSeconds: 30,
bidExtensionSeconds: 5,
bids: [],
save: jest.fn().mockResolvedValue(undefined),
toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }),
};
const { service } = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
await expect(
service.placeBid({
matchId,
teamIndex: 1,
amount: 980,
}),
).rejects.toThrow('Bid must reserve minimum points for remaining slots.');
expect(auction.save).not.toHaveBeenCalled();
});
it('allows bids up to the maximum after reserving minimum points', async () => {
const matchId = new mongoose.Types.ObjectId();
const captainUserId = new mongoose.Types.ObjectId();
const auction = {
_id: new mongoose.Types.ObjectId(),
matchId,
phase: 'bidding',
teams: [
{
teamIndex: 1,
captainUserId,
points: 1000,
members: [],
},
],
currentBid: 100,
currentDeadline: new Date(),
maxTimerSeconds: 30,
bidExtensionSeconds: 5,
bids: [],
save: jest.fn().mockResolvedValue(undefined),
toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }),
};
const { service } = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
await service.placeBid({
matchId,
teamIndex: 1,
amount: 970,
});
expect(auction.currentBid).toBe(970);
expect(auction.currentBidderTeamIndex).toBe(1);
expect(auction.bids).toEqual([
expect.objectContaining({
teamIndex: 1,
amount: 970,
bidderUserId: captainUserId,
}),
]);
expect(auction.save).toHaveBeenCalledTimes(1);
});
it('extends a short bid deadline using the configured bid extension seconds', async () => { it('extends a short bid deadline using the configured bid extension seconds', async () => {
const now = new Date('2026-05-02T00:00:00.000Z'); const now = new Date('2026-05-02T00:00:00.000Z');
jest.useFakeTimers().setSystemTime(now); jest.useFakeTimers().setSystemTime(now);
@@ -26,6 +26,7 @@ import { TournamentCodeService } from '../tournament-code/tournament-code.servic
import { TournamentResultService } from '../tournament-result/tournament-result.service'; import { TournamentResultService } from '../tournament-result/tournament-result.service';
const AUCTION_MAX_TEAM_SIZE = 5; const AUCTION_MAX_TEAM_SIZE = 5;
const AUCTION_MIN_BID_POINTS = 10;
const AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY = 1; const AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY = 1;
const AUCTION_ENRICHMENT_COOLDOWN_MS = 3 * 60 * 60 * 1000; const AUCTION_ENRICHMENT_COOLDOWN_MS = 3 * 60 * 60 * 1000;
const AUCTION_CHAT_MAX_MESSAGES = 200; const AUCTION_CHAT_MAX_MESSAGES = 200;
@@ -318,6 +319,11 @@ export class AuctionService {
throw new BadRequestException('Bid exceeds team points.'); throw new BadRequestException('Bid exceeds team points.');
} }
this.assertTeamHasSlot(team); this.assertTeamHasSlot(team);
if (params.amount > this.calculateMaxBidForTeam(team)) {
throw new BadRequestException(
'Bid must reserve minimum points for remaining slots.',
);
}
// 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다. // 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다.
await this.recordSnapshot(auction, 'bid', params.bidderUserId); await this.recordSnapshot(auction, 'bid', params.bidderUserId);
@@ -809,6 +815,16 @@ export class AuctionService {
} }
} }
private calculateMaxBidForTeam(team: AuctionTeam): number {
const remainingSlotsAfterCurrentBid = Math.max(
0,
AUCTION_MAX_TEAM_SIZE - this.countTeamMembersIncludingCaptain(team) - 1,
);
const reservedPoints =
remainingSlotsAfterCurrentBid * AUCTION_MIN_BID_POINTS;
return Math.max(0, team.points - reservedPoints);
}
private countTeamMembersIncludingCaptain(team: AuctionTeam): number { private countTeamMembersIncludingCaptain(team: AuctionTeam): number {
const userIds = new Set<string>([team.captainUserId.toString()]); const userIds = new Set<string>([team.captainUserId.toString()]);
for (const member of team.members) { for (const member of team.members) {
@@ -1,4 +1,5 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { RiotModule } from '../riot/riot.module';
import { CommunityStatsCacheService } from './community-stats-cache.service'; import { CommunityStatsCacheService } from './community-stats-cache.service';
import { CommunityStatsController } from './community-stats.controller'; import { CommunityStatsController } from './community-stats.controller';
import { CommunityStatsService } from './community-stats.service'; import { CommunityStatsService } from './community-stats.service';
@@ -7,6 +8,7 @@ import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service'; import { MatchStatsService } from './match-stats.service';
@Module({ @Module({
imports: [RiotModule],
controllers: [CommunityStatsController], controllers: [CommunityStatsController],
providers: [ providers: [
CommunityStatsService, 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_LIST_LIMIT = 50;
const MAX_MATCH_SCAN = 300; const MAX_MATCH_SCAN = 300;
const MIN_HIGHLIGHT_GAMES = 5; const MIN_HIGHLIGHT_GAMES = 5;
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 3;
interface CommunityStatsContext { interface CommunityStatsContext {
community: CommunityDocument; community: CommunityDocument;
@@ -205,10 +206,10 @@ export class CommunityStatsService {
communityId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
}): Promise<InternalMatchDetailResponse> { }): 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 = const cached =
await this.cacheService.get<InternalMatchDetailResponse>(key); await this.cacheService.get<InternalMatchDetailResponse>(key);
if (cached) return cached; if (cached && isCompleteMatchDetailResponse(cached)) return cached;
const dataset = await this.buildBaseDataset(params.communityId, { const dataset = await this.buildBaseDataset(params.communityId, {
seasonId: 'all', seasonId: 'all',
@@ -217,26 +218,42 @@ export class CommunityStatsService {
(item) => item.matchId === params.matchId.toString(), (item) => item.matchId === params.matchId.toString(),
); );
if (!match) throw new NotFoundException('Internal match not found.'); 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 = { const response: InternalMatchDetailResponse = {
match, match,
games: (dataset.detailsByMatchId.get(match.matchId) ?? []).map( games: gameDetails.map(
(game) => ({ (game) => ({
gameNumber: game.gameNumber, gameNumber: game.gameNumber,
riotMatchId: game.riotMatchId, riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation, gameCreation: game.gameCreation,
gameDuration: game.gameDuration, gameDuration: game.gameDuration,
gameVersion: game.gameVersion,
timeline: game.timeline ?? [],
objectiveEvents: game.objectiveEvents ?? [],
teams: game.teams.map((team) => ({ teams: game.teams.map((team) => ({
teamIndex: team.teamIndex, teamIndex: team.teamIndex,
side: team.side, side: team.side,
win: team.win, win: team.win,
objectives: team.objectives, objectives: team.objectives,
bans: team.bans ?? [],
participants: team.participants.map((record) => ({ participants: team.participants.map((record) => ({
userId: record.userId, userId: record.userId,
summonerName: record.summonerName, summonerName: record.summonerName,
tagLine: record.tagLine,
teamIndex: record.teamIndex, teamIndex: record.teamIndex,
side: record.side, side: record.side,
teamPosition: record.teamPosition, teamPosition: record.teamPosition,
championId: record.championId, championId: record.championId,
championLevel: record.championLevel,
kills: record.kills, kills: record.kills,
deaths: record.deaths, deaths: record.deaths,
assists: record.assists, assists: record.assists,
@@ -245,13 +262,21 @@ export class CommunityStatsService {
gold: record.gold, gold: record.gold,
gpm: record.gpm, gpm: record.gpm,
damageDealtToChampions: record.damageDealtToChampions, damageDealtToChampions: record.damageDealtToChampions,
damageTaken: record.damageTaken,
damageShare: record.damageShare, damageShare: record.damageShare,
killParticipation: record.killParticipation, killParticipation: record.killParticipation,
visionScore: record.visionScore, visionScore: record.visionScore,
wardsPlaced: record.wardsPlaced,
wardsKilled: record.wardsKilled,
controlWardsBought: record.controlWardsBought,
firstBloodKill: record.firstBloodKill ?? false,
firstBloodAssist: record.firstBloodAssist ?? false,
items: record.items, items: record.items,
trinket: record.trinket, trinket: record.trinket,
summonerSpells: record.summonerSpells, summonerSpells: record.summonerSpells,
perks: record.perks, perks: record.perks,
itemBuild: record.itemBuild ?? [],
skillBuild: record.skillBuild ?? [],
win: record.win, win: record.win,
})), })),
})), })),
@@ -990,3 +1015,23 @@ export class CommunityStatsService {
return Math.round(value * 10) / 10; 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'; import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types';
export interface CommunityStatsFilters { export interface CommunityStatsFilters {
@@ -108,18 +114,43 @@ export interface InternalMatchDetailResponse {
riotMatchId: string; riotMatchId: string;
gameCreation: number; gameCreation: number;
gameDuration: 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<{ teams: Array<{
teamIndex: number; teamIndex: number;
side: TeamSide; side: TeamSide;
win: boolean; 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<{ participants: Array<{
userId: string | null; userId: string | null;
summonerName: string; summonerName: string;
tagLine: string;
teamIndex: number; teamIndex: number;
side: TeamSide; side: TeamSide;
teamPosition: string; teamPosition: string;
championId: number; championId: number;
championLevel: number;
kills: number; kills: number;
deaths: number; deaths: number;
assists: number; assists: number;
@@ -128,13 +159,21 @@ export interface InternalMatchDetailResponse {
gold: number; gold: number;
gpm: number; gpm: number;
damageDealtToChampions: number; damageDealtToChampions: number;
damageTaken: number;
damageShare: number; damageShare: number;
killParticipation: number; killParticipation: number;
visionScore: number; visionScore: number;
wardsPlaced: number;
wardsKilled: number;
controlWardsBought: number;
firstBloodKill: boolean;
firstBloodAssist: boolean;
items: number[]; items: number[];
trinket: number; trinket: number;
summonerSpells: [number, number]; summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; perks: MatchStatsRunePerks;
itemBuild: MatchStatsItemBuildEvent[];
skillBuild: MatchStatsSkillBuildEvent[];
win: boolean; win: boolean;
}>; }>;
}>; }>;
@@ -1,5 +1,6 @@
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema'; import type { MatchDocument } from '../global/database/schema';
import type { RiotMatchDto, RiotMatchTimelineDto } from '../riot/riot.types';
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder'; import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
function makeMatch(): MatchDocument { function makeMatch(): MatchDocument {
@@ -95,4 +96,301 @@ describe('MatchStatsFragmentBuilder', () => {
}); });
expect(fragment.gameDetails[0].teams[0].participants).toHaveLength(1); 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 { import type {
MatchDocument, MatchDocument,
MatchGameResultParticipant, MatchGameResultParticipant,
MatchStatsItemBuildEvent,
MatchStatsObjectiveEvent,
MatchStatsObjectiveSummary,
MatchStatsSkillBuildEvent,
MatchStatsTimelinePoint,
TeamSide, TeamSide,
} from '../global/database/schema'; } 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 { InternalMatchCardView } from './community-stats.types';
import type { import type {
InternalGameDetail, InternalGameDetail,
@@ -13,11 +22,18 @@ import type {
MatchStatsFragment, MatchStatsFragment,
} from './match-stats.types'; } from './match-stats.types';
interface ParticipantBuildEvents {
items: MatchStatsItemBuildEvent[];
skills: MatchStatsSkillBuildEvent[];
}
@Injectable() @Injectable()
export class MatchStatsFragmentBuilder { export class MatchStatsFragmentBuilder {
public buildFragment(params: { public buildFragment(params: {
match: MatchDocument; match: MatchDocument;
rawByRiotMatchId: Map<string, RiotMatchDto>; rawByRiotMatchId: Map<string, RiotMatchDto>;
timelineByRiotMatchId?: Map<string, RiotMatchTimelineDto>;
timelineLoadAttempted?: boolean;
}): MatchStatsFragment { }): MatchStatsFragment {
const games = [...(params.match.result?.games ?? [])].sort( const games = [...(params.match.result?.games ?? [])].sort(
(left, right) => left.gameNumber - right.gameNumber, (left, right) => left.gameNumber - right.gameNumber,
@@ -25,8 +41,15 @@ export class MatchStatsFragmentBuilder {
const matchCard = this.toMatchCard(params.match, games); const matchCard = this.toMatchCard(params.match, games);
const gameDetails = games.map((game) => { const gameDetails = games.map((game) => {
const raw = params.rawByRiotMatchId.get(game.riotMatchId); const raw = params.rawByRiotMatchId.get(game.riotMatchId);
const timeline = params.timelineByRiotMatchId?.get(game.riotMatchId);
return raw return raw
? this.toGameDetail(params.match, game, raw) ? this.toGameDetail(
params.match,
game,
raw,
timeline,
params.timelineLoadAttempted === true,
)
: this.toFallbackGameDetail(params.match, game); : this.toFallbackGameDetail(params.match, game);
}); });
const records = gameDetails.flatMap((detail) => const records = gameDetails.flatMap((detail) =>
@@ -106,6 +129,8 @@ export class MatchStatsFragmentBuilder {
match: MatchDocument, match: MatchDocument,
game: NonNullable<MatchDocument['result']>['games'][number], game: NonNullable<MatchDocument['result']>['games'][number],
raw: RiotMatchDto, raw: RiotMatchDto,
timeline?: RiotMatchTimelineDto,
timelineLoadAttempted = false,
): InternalGameDetail { ): InternalGameDetail {
const puuidByUserId = new Map( const puuidByUserId = new Map(
match.participants match.participants
@@ -129,13 +154,29 @@ export class MatchStatsFragmentBuilder {
rawTeamIdBySide.set(participant.side, rawParticipant.teamId); 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 { return {
gameNumber: game.gameNumber, gameNumber: game.gameNumber,
riotMatchId: game.riotMatchId, riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation, gameCreation: game.gameCreation,
gameDuration: game.gameDuration, gameDuration: game.gameDuration,
gameVersion: raw.info.gameVersion,
winnerSide: game.winnerSide, winnerSide: game.winnerSide,
timeline: this.toTimeline(raw, rawTeamIdBySide, timeline),
timelineLoaded: timelineLoadAttempted || Boolean(timeline),
objectiveEvents,
teams: (['blue', 'red'] as TeamSide[]).map((side) => { teams: (['blue', 'red'] as TeamSide[]).map((side) => {
const teamIndex = const teamIndex =
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex; side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
@@ -158,25 +199,35 @@ export class MatchStatsFragmentBuilder {
teamIndex, teamIndex,
side, side,
win: game.winnerSide === side, win: game.winnerSide === side,
objectives: { objectives: this.toObjectiveSummary(
baron: rawTeam?.objectives?.baron?.kills ?? 0, rawTeam,
dragon: rawTeam?.objectives?.dragon?.kills ?? 0, timelineObjectives.get(side),
tower: rawTeam?.objectives?.tower?.kills ?? 0, Boolean(timeline),
}, ),
bans: (rawTeam?.bans ?? []).map((ban) => ({
championId: ban.championId,
pickTurn: ban.pickTurn,
})),
participants: game.participants participants: game.participants
.filter((participant) => participant.side === side) .filter((participant) => participant.side === side)
.map((participant) => .map((participant) => {
this.toRecord({ const rawParticipant = rawByPuuid.get(
puuidByUserId.get(participant.userId.toString()) ?? '',
);
return this.toRecord({
match, match,
game, game,
participant, participant,
rawParticipant: rawByPuuid.get( rawParticipant,
puuidByUserId.get(participant.userId.toString()) ?? '', buildEvents: rawParticipant
), ? buildEventsByParticipantId.get(
rawParticipant.participantId,
)
: undefined,
teamKills, teamKills,
teamDamage, teamDamage,
});
}), }),
),
}; };
}), }),
}; };
@@ -192,11 +243,15 @@ export class MatchStatsFragmentBuilder {
gameCreation: game.gameCreation, gameCreation: game.gameCreation,
gameDuration: game.gameDuration, gameDuration: game.gameDuration,
winnerSide: game.winnerSide, winnerSide: game.winnerSide,
timeline: [],
timelineLoaded: false,
objectiveEvents: [],
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({ teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex, teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
side, side,
win: game.winnerSide === side, win: game.winnerSide === side,
objectives: { baron: 0, dragon: 0, tower: 0 }, objectives: emptyObjectives(),
bans: [],
participants: game.participants participants: game.participants
.filter((participant) => participant.side === side) .filter((participant) => participant.side === side)
.map((participant) => .map((participant) =>
@@ -217,11 +272,19 @@ export class MatchStatsFragmentBuilder {
game: NonNullable<MatchDocument['result']>['games'][number]; game: NonNullable<MatchDocument['result']>['games'][number];
participant: MatchGameResultParticipant; participant: MatchGameResultParticipant;
rawParticipant?: RiotMatchParticipantDto; rawParticipant?: RiotMatchParticipantDto;
buildEvents?: ParticipantBuildEvents;
teamKills: number; teamKills: number;
teamDamage: number; teamDamage: number;
}): InternalRecord { }): InternalRecord {
const { match, game, participant, rawParticipant, teamKills, teamDamage } = const {
params; match,
game,
participant,
rawParticipant,
buildEvents,
teamKills,
teamDamage,
} = params;
const snapshot = match.participants.find((item) => const snapshot = match.participants.find((item) =>
item.userId.equals(participant.userId), item.userId.equals(participant.userId),
); );
@@ -262,6 +325,7 @@ export class MatchStatsFragmentBuilder {
rawParticipant?.riotIdGameName ?? rawParticipant?.riotIdGameName ??
rawParticipant?.summonerName ?? rawParticipant?.summonerName ??
'Unknown', 'Unknown',
tagLine: snapshot?.tagLine ?? rawParticipant?.riotIdTagLine ?? '',
profileIconId: snapshot?.profileIconId ?? 0, profileIconId: snapshot?.profileIconId ?? 0,
teamIndex: participant.teamIndex, teamIndex: participant.teamIndex,
side: participant.side, side: participant.side,
@@ -290,6 +354,8 @@ export class MatchStatsFragmentBuilder {
), ),
wardsPlaced: rawParticipant?.wardsPlaced ?? 0, wardsPlaced: rawParticipant?.wardsPlaced ?? 0,
wardsKilled: rawParticipant?.wardsKilled ?? 0, wardsKilled: rawParticipant?.wardsKilled ?? 0,
firstBloodKill: booleanField(rawParticipant, 'firstBloodKill'),
firstBloodAssist: booleanField(rawParticipant, 'firstBloodAssist'),
items: [ items: [
rawParticipant?.item0 ?? 0, rawParticipant?.item0 ?? 0,
rawParticipant?.item1 ?? 0, rawParticipant?.item1 ?? 0,
@@ -304,6 +370,8 @@ export class MatchStatsFragmentBuilder {
rawParticipant?.summoner2Id ?? 0, rawParticipant?.summoner2Id ?? 0,
], ],
perks: rawParticipant ? this.resolvePerks(rawParticipant) : {}, perks: rawParticipant ? this.resolvePerks(rawParticipant) : {},
itemBuild: buildEvents?.items ?? [],
skillBuild: buildEvents?.skills ?? [],
rating, rating,
}; };
} }
@@ -319,6 +387,250 @@ export class MatchStatsFragmentBuilder {
primaryStyle: primary?.style, primaryStyle: primary?.style,
subStyle: sub?.style, subStyle: sub?.style,
keystone: primary?.selections[0]?.perk, 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; 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 { function round(value: number): number {
return Math.round(value * 10) / 10; return Math.round(value * 10) / 10;
} }
@@ -365,3 +698,22 @@ function numberField(
const value = participant?.[key]; const value = participant?.[key];
return typeof value === 'number' && Number.isFinite(value) ? value : 0; 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, connectionService,
repository, repository,
{} as MatchStatsFragmentBuilder, {} as MatchStatsFragmentBuilder,
{ getMatchTimeline: jest.fn() } as never,
); );
await service.buildAndUpsert(matchId); await service.buildAndUpsert(matchId);
@@ -53,7 +54,20 @@ describe('MatchStatsService', () => {
}); });
const riotFind = jest.fn().mockReturnValue({ const riotFind = jest.fn().mockReturnValue({
lean: () => ({ 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 = { const connectionService = {
@@ -82,6 +96,7 @@ describe('MatchStatsService', () => {
connectionService, connectionService,
repository, repository,
builder, builder,
{ getMatchTimeline: jest.fn() } as never,
); );
await service.buildAndUpsert(matchId); await service.buildAndUpsert(matchId);
@@ -89,6 +104,8 @@ describe('MatchStatsService', () => {
expect(builder.buildFragment).toHaveBeenCalledWith({ expect(builder.buildFragment).toHaveBeenCalledWith({
match, match,
rawByRiotMatchId: expect.any(Map), rawByRiotMatchId: expect.any(Map),
timelineByRiotMatchId: expect.any(Map),
timelineLoadAttempted: false,
}); });
expect(repository.upsert).toHaveBeenCalledWith( expect(repository.upsert).toHaveBeenCalledWith(
expect.objectContaining({ expect.objectContaining({
@@ -97,7 +114,7 @@ describe('MatchStatsService', () => {
scheduledAt, scheduledAt,
gameCreationMin: 1_000, gameCreationMin: 1_000,
gameCreationMax: 2_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 mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import type { MatchDocument } from '../global/database/schema'; 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 { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
import { MatchStatsRepository } from './match-stats.repository'; import { MatchStatsRepository } from './match-stats.repository';
import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types'; import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types';
@Injectable() @Injectable()
export class MatchStatsService { export class MatchStatsService {
private readonly logger = new Logger(MatchStatsService.name);
constructor( constructor(
private readonly connectionService: ConnectionService, private readonly connectionService: ConnectionService,
private readonly repository: MatchStatsRepository, private readonly repository: MatchStatsRepository,
private readonly builder: MatchStatsFragmentBuilder, 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 MatchModel = await this.connectionService.getModel('match');
const RiotMatchModel = await this.connectionService.getModel('riotMatch'); const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const match = await MatchModel.findById(matchId).exec(); const match = await MatchModel.findById(matchId).exec();
@@ -41,7 +53,51 @@ export class MatchStatsService {
const rawByRiotMatchId = new Map( const rawByRiotMatchId = new Map(
riotDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]), 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({ await this.repository.upsert({
matchId: match._id, matchId: match._id,
@@ -101,4 +157,29 @@ export class MatchStatsService {
Boolean(match.result?.games?.length) 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'; } from '../global/database/schema';
import type { InternalMatchCardView } from './community-stats.types'; 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 InternalRecord = MatchStatsRecord;
export type InternalGameDetail = MatchStatsGameDetail; 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 -3
View File
@@ -398,6 +398,8 @@ export interface RiotMatch extends MongooseTimestamps {
queueId?: number; queueId?: number;
participantPuuids: string[]; participantPuuids: string[];
raw: Record<string, unknown>; // Riot API Match-V5 원본 응답 전체 raw: Record<string, unknown>; // Riot API Match-V5 원본 응답 전체
timeline?: Record<string, unknown>; // Riot API Match-V5 timeline 원본 응답 전체
timelineFetchedAt?: Date;
fetchedAt: Date; fetchedAt: Date;
} }
@@ -487,6 +489,7 @@ export interface MatchSeriesResult {
export interface MatchGameAssignment { export interface MatchGameAssignment {
gameNumber: number; gameNumber: number;
roundNumber?: number;
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
} }
@@ -524,6 +527,7 @@ export interface Match extends MongooseTimestamps {
maxParticipants: number; maxParticipants: number;
gameCount: number; gameCount: number;
gameMode: MatchGameMode; gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
tournamentCodeIds: mongoose.Types.ObjectId[]; tournamentCodeIds: mongoose.Types.ObjectId[];
gameSchedule: MatchGameAssignment[]; gameSchedule: MatchGameAssignment[];
teamBuiltAt?: Date; teamBuiltAt?: Date;
@@ -664,6 +668,39 @@ export interface AuctionHistoryEntry extends MongooseTimestamps {
export type AuctionHistoryEntryDocument = HydratedDocument<AuctionHistoryEntry>; export type AuctionHistoryEntryDocument = HydratedDocument<AuctionHistoryEntry>;
// ===== MatchStats (precomputed internal stats fragment) ===== // ===== 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 { export interface MatchStatsRecord {
matchId: string; matchId: string;
title: string; title: string;
@@ -674,6 +711,7 @@ export interface MatchStatsRecord {
gameDuration: number; gameDuration: number;
userId: string; userId: string;
summonerName: string; summonerName: string;
tagLine: string;
profileIconId: number; profileIconId: number;
teamIndex: number; teamIndex: number;
side: TeamSide; side: TeamSide;
@@ -696,10 +734,14 @@ export interface MatchStatsRecord {
controlWardsBought: number; controlWardsBought: number;
wardsPlaced: number; wardsPlaced: number;
wardsKilled: number; wardsKilled: number;
firstBloodKill: boolean;
firstBloodAssist: boolean;
items: number[]; items: number[];
trinket: number; trinket: number;
summonerSpells: [number, number]; summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; perks: MatchStatsRunePerks;
itemBuild: MatchStatsItemBuildEvent[];
skillBuild: MatchStatsSkillBuildEvent[];
rating: number; rating: number;
} }
@@ -708,16 +750,46 @@ export interface MatchStatsGameDetail {
riotMatchId: string; riotMatchId: string;
gameCreation: number; gameCreation: number;
gameDuration: number; gameDuration: number;
gameVersion?: string;
winnerSide: TeamSide; winnerSide: TeamSide;
timeline: MatchStatsTimelinePoint[];
timelineLoaded?: boolean;
objectiveEvents: MatchStatsObjectiveEvent[];
teams: Array<{ teams: Array<{
teamIndex: number; teamIndex: number;
side: TeamSide; side: TeamSide;
win: boolean; win: boolean;
objectives: { baron: number; dragon: number; tower: number }; objectives: MatchStatsObjectiveSummary;
bans: Array<{ championId: number; pickTurn: number }>;
participants: MatchStatsRecord[]; 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 { export interface MatchStats extends MongooseTimestamps {
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId;
@@ -1133,6 +1205,8 @@ export const RiotMatchSchema = new Schema<RiotMatch>(
queueId: { type: Number }, queueId: { type: Number },
participantPuuids: { type: [String], required: true, default: [] }, participantPuuids: { type: [String], required: true, default: [] },
raw: { type: Schema.Types.Mixed, 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 }, fetchedAt: { type: Date, required: true, default: Date.now },
}, },
{ {
@@ -1151,7 +1225,6 @@ export const TournamentCodeSchema = new Schema<TournamentCode>(
type: String, type: String,
required: true, required: true,
trim: true, trim: true,
uppercase: true,
}, },
region: { type: String, required: true, default: 'kr' }, region: { type: String, required: true, default: 'kr' },
mapType: { mapType: {
@@ -1284,6 +1357,7 @@ const MatchSeriesResultSubSchema = new Schema<MatchSeriesResult>(
const MatchGameAssignmentSubSchema = new Schema<MatchGameAssignment>( const MatchGameAssignmentSubSchema = new Schema<MatchGameAssignment>(
{ {
gameNumber: { type: Number, required: true, min: 1 }, gameNumber: { type: Number, required: true, min: 1 },
roundNumber: { type: Number, required: false, min: 1 },
teamAIndex: { type: Number, required: true, min: 1 }, teamAIndex: { type: Number, required: true, min: 1 },
teamBIndex: { type: Number, required: true, min: 1 }, teamBIndex: { type: Number, required: true, min: 1 },
}, },
@@ -1389,6 +1463,7 @@ export const MatchSchema = new Schema<Match>(
required: true, required: true,
default: 'pair', default: 'pair',
}, },
roundRobinMaxRounds: { type: Number, required: false, min: 1 },
tournamentCodeIds: { tournamentCodeIds: {
type: [{ type: Schema.Types.ObjectId, ref: 'tournamentCode' }], type: [{ type: Schema.Types.ObjectId, ref: 'tournamentCode' }],
required: true, required: true,
@@ -1,4 +1,4 @@
import type { RiotLane } from '../global/database/schema'; import type { MatchStatsRunePerks, RiotLane } from '../global/database/schema';
import type { import type {
RiotQueueGroup, RiotQueueGroup,
RiotRankFilter, RiotRankFilter,
@@ -121,7 +121,7 @@ export interface RecentMatchTeamParticipantView {
items: number[]; items: number[];
trinket: number; trinket: number;
summonerSpells: [number, number]; summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; perks: MatchStatsRunePerks;
totalCs: number; totalCs: number;
csPerMin: number; csPerMin: number;
goldEarned: number; goldEarned: number;
@@ -162,7 +162,7 @@ export interface RecentMatchView {
items: number[]; items: number[];
trinket: number; trinket: number;
summonerSpells: [number, number]; summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; perks: MatchStatsRunePerks;
teams: Array<{ teams: Array<{
side: 100 | 200; side: 100 | 200;
win: boolean; win: boolean;
@@ -101,6 +101,11 @@ export class CreateMatchDto {
@IsEnum(MATCH_GAME_MODES) @IsEnum(MATCH_GAME_MODES)
gameMode?: MatchGameMode; gameMode?: MatchGameMode;
@IsOptional()
@IsInt()
@Min(1)
roundRobinMaxRounds?: number;
@IsOptional() @IsOptional()
@IsArray() @IsArray()
@IsString({ each: true }) @IsString({ each: true })
@@ -156,6 +161,11 @@ export class UpdateMatchDto {
@IsEnum(MATCH_GAME_MODES) @IsEnum(MATCH_GAME_MODES)
gameMode?: MatchGameMode; gameMode?: MatchGameMode;
@IsOptional()
@IsInt()
@Min(1)
roundRobinMaxRounds?: number;
@IsOptional() @IsOptional()
@IsArray() @IsArray()
@IsString({ each: true }) @IsString({ each: true })
@@ -193,3 +203,17 @@ export class JoinMatchDto {
@IsString() @IsString()
userId?: string; 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, UserDocument,
} from '../global/database/schema'; } from '../global/database/schema';
import { import {
AddParticipantDto,
CreateMatchDto, CreateMatchDto,
JoinMatchDto, JoinMatchDto,
UpdateMatchDto, UpdateMatchDto,
@@ -56,6 +57,7 @@ export class MatchController {
maxParticipants: body.maxParticipants ?? 10, maxParticipants: body.maxParticipants ?? 10,
gameCount: body.gameCount, gameCount: body.gameCount,
gameMode: body.gameMode ?? 'pair', gameMode: body.gameMode ?? 'pair',
roundRobinMaxRounds: body.roundRobinMaxRounds,
prizes: body.prizes ?? [], prizes: body.prizes ?? [],
notices: body.notices ?? [], notices: body.notices ?? [],
schedule: body.schedule ?? [], schedule: body.schedule ?? [],
@@ -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') @Patch(':matchId/participants/:userId')
@Roles('admin', 'owner') @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 () => { it('returns a paginated match list with total count', async () => {
const communityId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId();
const { service, MatchModel, sort, skip, limit } = const { service, MatchModel, sort, skip, limit } =
@@ -165,6 +206,54 @@ describe('MatchService', () => {
expect(sort).toHaveBeenCalledWith({ scheduledAt: -1 }); 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 () => { it('clears game schedule when a built match returns to recruiting', async () => {
const communityId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId();
const match = { const match = {
@@ -203,6 +292,29 @@ describe('MatchService', () => {
expect(matchStatsService.removeByMatch).toHaveBeenCalledWith(match._id); expect(matchStatsService.removeByMatch).toHaveBeenCalledWith(match._id);
}); });
it('rejects round-robin max round changes after recruiting', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
communityId,
status: 'team-built',
tournamentCodeIds: [],
set: jest.fn(),
save: jest.fn().mockResolvedValue(undefined),
};
const { service } = createService(match);
await expect(
service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { roundRobinMaxRounds: 3 },
}),
).rejects.toThrow(
'maxParticipants, gameMode, and roundRobinMaxRounds can only be changed while recruiting.',
);
expect(match.set).not.toHaveBeenCalled();
});
it('releases reserved codes when returning a built match to recruiting', async () => { it('releases reserved codes when returning a built match to recruiting', async () => {
const communityId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId();
const codeId = new mongoose.Types.ObjectId(); const codeId = new mongoose.Types.ObjectId();
+32 -4
View File
@@ -13,6 +13,7 @@ import {
MatchDocument, MatchDocument,
MatchSeriesResult, MatchSeriesResult,
MatchStatus, MatchStatus,
POSITIONS,
Position, Position,
PositionPreference, PositionPreference,
TierInfo, TierInfo,
@@ -64,7 +65,7 @@ interface MatchListFilter {
interface JoinMatchParams { interface JoinMatchParams {
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId;
preferredPositions: PositionPreference[]; preferredPositions?: PositionPreference[];
// 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용. // 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용.
riotPuuid?: string; riotPuuid?: string;
} }
@@ -213,10 +214,12 @@ export class MatchService {
const previousStatus = match.status; const previousStatus = match.status;
if ( if (
previousStatus !== 'recruiting' && previousStatus !== 'recruiting' &&
('maxParticipants' in params.patch || 'gameMode' in params.patch) ('maxParticipants' in params.patch ||
'gameMode' in params.patch ||
'roundRobinMaxRounds' in params.patch)
) { ) {
throw new BadRequestException( throw new BadRequestException(
'maxParticipants and gameMode can only be changed while recruiting.', 'maxParticipants, gameMode, and roundRobinMaxRounds can only be changed while recruiting.',
); );
} }
match.set(params.patch); match.set(params.patch);
@@ -293,7 +296,10 @@ export class MatchService {
tagLine: selectedRiot?.tagLine, tagLine: selectedRiot?.tagLine,
profileIconId: selectedRiot?.profileIconId, profileIconId: selectedRiot?.profileIconId,
tier: selectedTier, tier: selectedTier,
preferredPositions: params.preferredPositions, preferredPositions: this.resolveJoinPreferredPositions(
params.preferredPositions,
user.preferredPositions,
),
joinedAt: new Date(), joinedAt: new Date(),
excluded: false, 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 { private buildListFilter(query: ListMatchesQuery): MatchListFilter {
const filter: MatchListFilter = { const filter: MatchListFilter = {
communityId: query.communityId, communityId: query.communityId,
@@ -106,4 +106,112 @@ describe('RiotMatchService', () => {
expect(match.info.participants[0].teamPosition).toBe(''); expect(match.info.participants[0].teamPosition).toBe('');
expect(match.info.participants[0].individualPosition).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, RiotMatchPerkStyleSelectionDto,
RiotMatchStatPerksDto, RiotMatchStatPerksDto,
RiotMatchTeamDto, RiotMatchTeamDto,
RiotMatchTimelineDto,
RiotMatchTimelineEventDto,
RiotMatchTimelineFrameDto,
RiotMatchTimelineInfoDto,
RiotMatchTimelineParticipantDto,
RiotMatchTimelineParticipantFrameDto,
RiotMatchType, RiotMatchType,
} from './riot.types'; } from './riot.types';
@@ -66,6 +72,20 @@ export class RiotMatchService {
parseMatchResponse, 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( 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 { function parseMatchMetadata(value: unknown): RiotMatchMetadataDto {
if (!isRecord(value)) { if (!isRecord(value)) {
throw new TypeError('Riot match metadata must be an object.'); 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( function parseParticipant(
value: unknown, value: unknown,
index: number, index: number,
@@ -504,12 +755,22 @@ function parseObjectives(
baron: parseObjective(value.baron, teamIndex, 'baron'), baron: parseObjective(value.baron, teamIndex, 'baron'),
champion: parseObjective(value.champion, teamIndex, 'champion'), champion: parseObjective(value.champion, teamIndex, 'champion'),
dragon: parseObjective(value.dragon, teamIndex, 'dragon'), dragon: parseObjective(value.dragon, teamIndex, 'dragon'),
horde: optionalObjective(value.horde, teamIndex, 'horde'),
inhibitor: parseObjective(value.inhibitor, teamIndex, 'inhibitor'), inhibitor: parseObjective(value.inhibitor, teamIndex, 'inhibitor'),
riftHerald: parseObjective(value.riftHerald, teamIndex, 'riftHerald'), riftHerald: parseObjective(value.riftHerald, teamIndex, 'riftHerald'),
tower: parseObjective(value.tower, teamIndex, 'tower'), 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( function parseObjective(
value: unknown, value: unknown,
teamIndex: number, teamIndex: number,
+54
View File
@@ -134,6 +134,11 @@ export interface RiotMatchDto {
info: RiotMatchInfoDto; info: RiotMatchInfoDto;
} }
export interface RiotMatchTimelineDto {
metadata: RiotMatchMetadataDto;
info: RiotMatchTimelineInfoDto;
}
export interface RiotMatchMetadataDto { export interface RiotMatchMetadataDto {
dataVersion: string; dataVersion: string;
matchId: string; matchId: string;
@@ -240,6 +245,7 @@ export interface RiotMatchObjectivesDto {
baron: RiotMatchObjectiveDto; baron: RiotMatchObjectiveDto;
champion: RiotMatchObjectiveDto; champion: RiotMatchObjectiveDto;
dragon: RiotMatchObjectiveDto; dragon: RiotMatchObjectiveDto;
horde?: RiotMatchObjectiveDto;
inhibitor: RiotMatchObjectiveDto; inhibitor: RiotMatchObjectiveDto;
riftHerald: RiotMatchObjectiveDto; riftHerald: RiotMatchObjectiveDto;
tower: RiotMatchObjectiveDto; tower: RiotMatchObjectiveDto;
@@ -249,3 +255,51 @@ export interface RiotMatchObjectiveDto {
first: boolean; first: boolean;
kills: number; 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 { import {
resolveRoundRobinTeamCount, resolveRoundRobinTeamCount,
roundRobinGameSchedule,
roundRobinPairCount, roundRobinPairCount,
roundRobinPairs, roundRobinPairs,
shuffleInPlace, shuffleInPlace,
@@ -25,6 +26,30 @@ describe('round-robin util', () => {
expect(roundRobinPairCount(6)).toBe(15); expect(roundRobinPairCount(6)).toBe(15);
}); });
it('builds round-robin games grouped into simultaneously playable rounds', () => {
const schedule = roundRobinGameSchedule(6, { gamesPerPair: 1 });
expect(schedule).toHaveLength(15);
for (const roundNumber of [1, 2, 3, 4, 5]) {
const round = schedule.filter((game) => game.roundNumber === roundNumber);
expect(round).toHaveLength(3);
expect(new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex])))
.toHaveProperty('size', 6);
}
});
it('limits round-robin games by max rounds', () => {
const schedule = roundRobinGameSchedule(8, {
gamesPerPair: 1,
maxRounds: 3,
});
expect(schedule).toHaveLength(12);
expect(new Set(schedule.map((game) => game.roundNumber))).toEqual(
new Set([1, 2, 3]),
);
});
it('resolves team count from teams first, then active participants', () => { it('resolves team count from teams first, then active participants', () => {
expect( expect(
resolveRoundRobinTeamCount({ resolveRoundRobinTeamCount({
@@ -3,11 +3,23 @@ export interface RoundRobinPair {
teamBIndex: number; teamBIndex: number;
} }
export interface RoundRobinGameAssignment extends RoundRobinPair {
gameNumber: number;
roundNumber: number;
}
export interface RoundRobinTeamCountInput { export interface RoundRobinTeamCountInput {
teams?: Array<{ teamIndex: number }>; teams?: Array<{ teamIndex: number }>;
participants: Array<{ excluded?: boolean }>; participants: Array<{ excluded?: boolean }>;
} }
export interface RoundRobinGameScheduleOptions {
gamesPerPair?: number;
maxRounds?: number;
rng?: () => number;
shuffleTeams?: boolean;
}
export function roundRobinPairs(teamCount: number): RoundRobinPair[] { export function roundRobinPairs(teamCount: number): RoundRobinPair[] {
const pairs: RoundRobinPair[] = []; const pairs: RoundRobinPair[] = [];
for (let teamAIndex = 1; teamAIndex <= teamCount; teamAIndex += 1) { for (let teamAIndex = 1; teamAIndex <= teamCount; teamAIndex += 1) {
@@ -27,6 +39,70 @@ export function roundRobinPairCount(teamCount: number): number {
return (teamCount * (teamCount - 1)) / 2; return (teamCount * (teamCount - 1)) / 2;
} }
export function roundRobinRoundCount(teamCount: number): number {
if (teamCount < 2) return 0;
return teamCount % 2 === 0 ? teamCount - 1 : teamCount;
}
export function roundRobinGameSchedule(
teamCount: number,
options: RoundRobinGameScheduleOptions = {},
): RoundRobinGameAssignment[] {
if (teamCount < 2) return [];
const rawGamesPerPair = options.gamesPerPair ?? 1;
const gamesPerPair = Number.isFinite(rawGamesPerPair)
? Math.max(1, Math.floor(rawGamesPerPair))
: 1;
const fullRoundCount = roundRobinRoundCount(teamCount);
const requestedRoundCount =
typeof options.maxRounds === 'number' && Number.isFinite(options.maxRounds)
? Math.floor(options.maxRounds)
: fullRoundCount;
const roundLimit = Math.max(
0,
Math.min(fullRoundCount, requestedRoundCount),
);
if (roundLimit === 0) return [];
const bye = 0;
const teams = Array.from({ length: teamCount }, (_, index) => index + 1);
if (options.shuffleTeams) shuffleInPlace(teams, options.rng);
if (teams.length % 2 === 1) teams.push(bye);
const rotating = [...teams];
const schedule: RoundRobinGameAssignment[] = [];
let gameNumber = 1;
for (let roundIndex = 0; roundIndex < roundLimit; roundIndex += 1) {
const roundNumber = roundIndex + 1;
for (let index = 0; index < rotating.length / 2; index += 1) {
const left = rotating[index];
const right = rotating[rotating.length - 1 - index];
if (left === bye || right === bye) continue;
const teamAIndex = Math.min(left, right);
const teamBIndex = Math.max(left, right);
for (let gameIndex = 0; gameIndex < gamesPerPair; gameIndex += 1) {
schedule.push({
gameNumber,
roundNumber,
teamAIndex,
teamBIndex,
});
gameNumber += 1;
}
}
const fixed = rotating[0];
const tail = rotating.slice(1);
tail.unshift(tail.pop() as number);
rotating.splice(0, rotating.length, fixed, ...tail);
}
return schedule;
}
export function resolveRoundRobinTeamCount( export function resolveRoundRobinTeamCount(
match: RoundRobinTeamCountInput, match: RoundRobinTeamCountInput,
): number { ): number {
@@ -0,0 +1,111 @@
import {
SYSTEM_TOURNAMENT_CODE_UPLOADED_BY,
TournamentCodeAutoProvisionService,
} from './tournament-code-auto-provision.service';
import { TournamentCodeService } from './tournament-code.service';
import { TournamentCodeVendorService } from './tournament-code-vendor.service';
describe('TournamentCodeAutoProvisionService', () => {
function createFixture(params?: {
availableCounts?: number[];
vendorCodes?: string[];
}) {
const availableCounts = [...(params?.availableCounts ?? [30])];
const vendorCodes = [...(params?.vendorCodes ?? [])];
const tournamentCodeService = {
countUsableAvailable: jest.fn().mockImplementation(async () => {
return availableCounts.shift() ?? 30;
}),
bulkUpload: jest.fn().mockResolvedValue({
inserted: 1,
duplicates: [],
invalid: [],
}),
} as unknown as jest.Mocked<TournamentCodeService>;
const vendorService = {
fetchTournamentCode: jest.fn().mockImplementation(async () => {
const code = vendorCodes.shift();
if (!code) throw new Error('No vendor code');
return code;
}),
} as unknown as jest.Mocked<TournamentCodeVendorService>;
const service = new TournamentCodeAutoProvisionService(
tournamentCodeService,
vendorService,
);
jest
.spyOn(
service as unknown as { sleepBeforeVendorRequest(): Promise<void> },
'sleepBeforeVendorRequest',
)
.mockResolvedValue(undefined);
return { service, tournamentCodeService, vendorService };
}
it('does nothing when the usable pool already meets the target', async () => {
const { service, tournamentCodeService, vendorService } = createFixture({
availableCounts: [30],
});
await expect(service.ensurePool()).resolves.toMatchObject({
target: 30,
before: 30,
after: 30,
requested: 0,
inserted: 0,
});
expect(vendorService.fetchTournamentCode).not.toHaveBeenCalled();
expect(tournamentCodeService.bulkUpload).not.toHaveBeenCalled();
});
it('requests vendor codes until the pool reaches 30', async () => {
const { service, tournamentCodeService, vendorService } = createFixture({
availableCounts: [28, 29, 30],
vendorCodes: ['KR05090-aBc', 'KR05090-dEf'],
});
const result = await service.ensurePool();
expect(result).toMatchObject({
target: 30,
before: 28,
after: 30,
requested: 2,
inserted: 2,
});
expect(vendorService.fetchTournamentCode).toHaveBeenCalledTimes(2);
expect(
(
service as unknown as {
sleepBeforeVendorRequest: jest.Mock;
}
).sleepBeforeVendorRequest,
).toHaveBeenCalledTimes(2);
expect(tournamentCodeService.bulkUpload).toHaveBeenCalledWith({
uploadedBy: SYSTEM_TOURNAMENT_CODE_UPLOADED_BY,
codes: [
expect.objectContaining({
code: 'KR05090-aBc',
source: 'deeplol-vendor',
spectatorType: 'ALL',
}),
],
});
});
it('shares an in-flight refill instead of starting overlapping vendor loops', async () => {
const { service, vendorService } = createFixture({
availableCounts: [29, 30],
vendorCodes: ['KR05090-aBc'],
});
const [left, right] = await Promise.all([
service.ensurePool(),
service.ensurePool(),
]);
expect(left).toBe(right);
expect(vendorService.fetchTournamentCode).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,128 @@
import { Injectable, Logger } from '@nestjs/common';
import mongoose from 'mongoose';
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from './tournament-code.constants';
import { TournamentCodeService } from './tournament-code.service';
import {
resolveVendorRequestDelayMs,
TournamentCodeVendorService,
} from './tournament-code-vendor.service';
const DEFAULT_POOL_TARGET = 30;
const DEFAULT_VENDOR_CODE_EXPIRES_IN_MS = 14 * 24 * 60 * 60 * 1000;
const MAX_REFILL_ATTEMPTS_MULTIPLIER = 2;
export const SYSTEM_TOURNAMENT_CODE_UPLOADED_BY = new mongoose.Types.ObjectId(
'000000000000000000000000',
);
export interface TournamentCodeAutoProvisionResult {
target: number;
before: number;
after: number;
requested: number;
inserted: number;
duplicates: number;
invalid: number;
}
@Injectable()
export class TournamentCodeAutoProvisionService {
private readonly logger = new Logger(TournamentCodeAutoProvisionService.name);
private inFlight?: Promise<TournamentCodeAutoProvisionResult>;
constructor(
private readonly tournamentCodeService: TournamentCodeService,
private readonly vendorService: TournamentCodeVendorService,
) {}
public async ensurePool(): Promise<TournamentCodeAutoProvisionResult> {
if (this.inFlight) return this.inFlight;
this.inFlight = this.refillPool().finally(() => {
this.inFlight = undefined;
});
return this.inFlight;
}
public async sleepBeforeVendorRequest(): Promise<void> {
await sleep(resolveVendorRequestDelayMs());
}
private async refillPool(): Promise<TournamentCodeAutoProvisionResult> {
const target = resolvePoolTarget();
const before = await this.tournamentCodeService.countUsableAvailable();
let after = before;
let requested = 0;
let inserted = 0;
let duplicates = 0;
let invalid = 0;
const maxAttempts = Math.max(
1,
(target - before) * MAX_REFILL_ATTEMPTS_MULTIPLIER,
);
while (after < target && requested < maxAttempts) {
await this.sleepBeforeVendorRequest();
const code = await this.vendorService.fetchTournamentCode();
requested += 1;
const uploadResult = await this.tournamentCodeService.bulkUpload({
uploadedBy: SYSTEM_TOURNAMENT_CODE_UPLOADED_BY,
codes: [
{
code,
expiresAt: resolveVendorCodeExpiresAt().toISOString(),
spectatorType: 'ALL',
source: 'deeplol-vendor',
notes: 'auto-provisioned from Deeplol vendor',
},
],
});
inserted += uploadResult.inserted;
duplicates += uploadResult.duplicates.length;
invalid += uploadResult.invalid.length;
after = await this.tournamentCodeService.countUsableAvailable();
}
if (inserted > 0 || before < target) {
this.logger.log(
`Tournament code pool refill: before=${before} after=${after} target=${target} requested=${requested} inserted=${inserted} duplicates=${duplicates} invalid=${invalid}`,
);
}
return {
target,
before,
after,
requested,
inserted,
duplicates,
invalid,
};
}
}
function resolvePoolTarget(): number {
const configured = Number(process.env.TOURNAMENT_CODE_POOL_TARGET);
return Number.isInteger(configured) && configured > 0
? configured
: DEFAULT_POOL_TARGET;
}
function resolveVendorCodeExpiresAt(): Date {
const configuredHours = Number(
process.env.TOURNAMENT_CODE_VENDOR_EXPIRES_IN_HOURS,
);
const expiresInMs =
Number.isFinite(configuredHours) && configuredHours > 0
? configuredHours * 60 * 60 * 1000
: DEFAULT_VENDOR_CODE_EXPIRES_IN_MS;
return new Date(
Date.now() + Math.max(expiresInMs, TOURNAMENT_CODE_EXPIRY_MARGIN_MS),
);
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
@@ -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,
});
}
}
@@ -0,0 +1,95 @@
import {
buildDeeplolTournamentCodeRequest,
resolveVendorRequestDelayMs,
TournamentCodeVendorService,
} from './tournament-code-vendor.service';
describe('TournamentCodeVendorService', () => {
const originalFetch = global.fetch;
afterEach(() => {
global.fetch = originalFetch;
jest.restoreAllMocks();
});
it('builds the Deeplol request URL and browser-like headers', () => {
const request = buildDeeplolTournamentCodeRequest();
expect(request.url.toString()).toBe(
'https://b2c-api.deeplol.gg/tournament/tournament_code?server_id=212&server_name=%EB%A1%A4%EB%A6%BC%ED%91%B8%EC%8A%A4&server_comment=LPS_%EB%82%B4%EC%A0%84&spectator_type=ALL&pick_type=TOURNAMENT_DRAFT&map_name=SUMMONERS_RIFT&platform_id=KR',
);
expect(request.headers).toMatchObject({
accept: '*/*',
'accept-encoding': 'gzip, deflate, br, zstd',
'accept-language': 'ko,en;q=0.9,en-US;q=0.8',
'cache-control': 'no-cache',
host: 'b2c-api.deeplol.gg',
origin: 'https://clash.deeplol.gg',
pragma: 'no-cache',
priority: 'u=1, i',
referer: 'https://clash.deeplol.gg/',
'sec-ch-ua':
'"Microsoft Edge";v="149", "Chromium";v="149", "Not)A;Brand";v="24"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-site',
'user-agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36 Edg/149.0.0.0',
});
expect(Object.keys(request.headers)).not.toContain(':authority');
});
it('fetches the first tournament code from the vendor response', async () => {
global.fetch = jest.fn().mockResolvedValue({
ok: true,
status: 200,
json: jest.fn().mockResolvedValue({
tournament_code_list: [
'KR05090-85d64e26-0a7d-438b-9ada-11784e46add3',
],
}),
});
const service = new TournamentCodeVendorService();
await expect(service.fetchTournamentCode()).resolves.toBe(
'KR05090-85d64e26-0a7d-438b-9ada-11784e46add3',
);
expect(global.fetch).toHaveBeenCalledWith(
expect.stringContaining(
'https://b2c-api.deeplol.gg/tournament/tournament_code?',
),
expect.objectContaining({
method: 'GET',
headers: expect.objectContaining({
origin: 'https://clash.deeplol.gg',
referer: 'https://clash.deeplol.gg/',
}),
signal: expect.any(AbortSignal),
}),
);
});
it('rejects malformed vendor responses', async () => {
global.fetch = jest.fn().mockResolvedValue({
ok: true,
status: 200,
json: jest.fn().mockResolvedValue({
tournament_code_list: [null],
}),
});
const service = new TournamentCodeVendorService();
await expect(service.fetchTournamentCode()).rejects.toThrow(
'Vendor tournament code response is malformed.',
);
});
it('generates mostly near-5-second delays with occasional extra delay', () => {
expect(resolveVendorRequestDelayMs(() => 0.1)).toBe(5_050);
expect(resolveVendorRequestDelayMs(() => 0.84)).toBe(5_420);
expect(resolveVendorRequestDelayMs(() => 0.9)).toBe(8_700);
expect(resolveVendorRequestDelayMs(() => 0)).toBeGreaterThanOrEqual(5_000);
});
});
@@ -0,0 +1,152 @@
import { Injectable } from '@nestjs/common';
const DEFAULT_VENDOR_URL =
'https://b2c-api.deeplol.gg/tournament/tournament_code';
const DEFAULT_FETCH_TIMEOUT_MS = 10_000;
const MIN_REQUEST_DELAY_MS = 5_000;
const DEFAULT_QUERY_PARAMS = {
server_id: '212',
server_name: '롤림푸스',
server_comment: 'LPS_내전',
spectator_type: 'ALL',
pick_type: 'TOURNAMENT_DRAFT',
map_name: 'SUMMONERS_RIFT',
platform_id: 'KR',
} as const;
const BROWSER_LIKE_HEADERS = {
accept: '*/*',
'accept-encoding': 'gzip, deflate, br, zstd',
'accept-language': 'ko,en;q=0.9,en-US;q=0.8',
'cache-control': 'no-cache',
host: 'b2c-api.deeplol.gg',
origin: 'https://clash.deeplol.gg',
pragma: 'no-cache',
priority: 'u=1, i',
referer: 'https://clash.deeplol.gg/',
'sec-ch-ua':
'"Microsoft Edge";v="149", "Chromium";v="149", "Not)A;Brand";v="24"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-site',
'user-agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36 Edg/149.0.0.0',
} as const;
interface DeeplolTournamentCodeResponse {
tournament_code_list?: unknown;
}
export interface DeeplolTournamentCodeRequest {
url: URL;
headers: Record<string, string>;
}
@Injectable()
export class TournamentCodeVendorService {
public async fetchTournamentCode(): Promise<string> {
const request = buildDeeplolTournamentCodeRequest();
const controller = new AbortController();
const timeout = setTimeout(() => {
controller.abort();
}, resolveFetchTimeoutMs());
try {
const response = await fetch(request.url.toString(), {
method: 'GET',
headers: request.headers,
signal: controller.signal,
});
if (!response.ok) {
throw new Error(
`Vendor tournament code request failed (${response.status}).`,
);
}
const payload = (await response.json()) as DeeplolTournamentCodeResponse;
return parseVendorTournamentCode(payload);
} finally {
clearTimeout(timeout);
}
}
}
export function buildDeeplolTournamentCodeRequest(
env: NodeJS.ProcessEnv = process.env,
): DeeplolTournamentCodeRequest {
const url = new URL(
env.TOURNAMENT_CODE_VENDOR_URL?.trim() || DEFAULT_VENDOR_URL,
);
const params = {
server_id:
env.TOURNAMENT_CODE_VENDOR_SERVER_ID ?? DEFAULT_QUERY_PARAMS.server_id,
server_name:
env.TOURNAMENT_CODE_VENDOR_SERVER_NAME ??
DEFAULT_QUERY_PARAMS.server_name,
server_comment:
env.TOURNAMENT_CODE_VENDOR_SERVER_COMMENT ??
DEFAULT_QUERY_PARAMS.server_comment,
spectator_type:
env.TOURNAMENT_CODE_VENDOR_SPECTATOR_TYPE ??
DEFAULT_QUERY_PARAMS.spectator_type,
pick_type:
env.TOURNAMENT_CODE_VENDOR_PICK_TYPE ?? DEFAULT_QUERY_PARAMS.pick_type,
map_name:
env.TOURNAMENT_CODE_VENDOR_MAP_NAME ?? DEFAULT_QUERY_PARAMS.map_name,
platform_id:
env.TOURNAMENT_CODE_VENDOR_PLATFORM_ID ??
DEFAULT_QUERY_PARAMS.platform_id,
};
for (const [key, value] of Object.entries(params)) {
url.searchParams.set(key, value);
}
return {
url,
headers: {
...BROWSER_LIKE_HEADERS,
host: url.host,
},
};
}
export function resolveVendorRequestDelayMs(
random: () => number = Math.random,
): number {
const roll = clampRandom(random());
if (roll < 0.85) {
return MIN_REQUEST_DELAY_MS + Math.round(roll * 500);
}
return MIN_REQUEST_DELAY_MS + 100 + Math.round(roll * 4_000);
}
function parseVendorTournamentCode(
payload: DeeplolTournamentCodeResponse,
): string {
const codes = payload.tournament_code_list;
if (
!Array.isArray(codes) ||
typeof codes[0] !== 'string' ||
!codes[0].trim()
) {
throw new Error('Vendor tournament code response is malformed.');
}
return codes[0].trim();
}
function resolveFetchTimeoutMs(): number {
const configured = Number(process.env.TOURNAMENT_CODE_VENDOR_TIMEOUT_MS);
return Number.isFinite(configured) && configured > 0
? configured
: DEFAULT_FETCH_TIMEOUT_MS;
}
function clampRandom(value: number): number {
if (!Number.isFinite(value)) return 0;
return Math.min(1, Math.max(0, value));
}
@@ -1,11 +1,19 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { TournamentCodeController } from './tournament-code.controller'; import { TournamentCodeController } from './tournament-code.controller';
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
import { TournamentCodeReplacementController } from './tournament-code-replacement.controller';
import { TournamentCodeScheduler } from './tournament-code.scheduler'; import { TournamentCodeScheduler } from './tournament-code.scheduler';
import { TournamentCodeService } from './tournament-code.service'; import { TournamentCodeService } from './tournament-code.service';
import { TournamentCodeVendorService } from './tournament-code-vendor.service';
@Module({ @Module({
controllers: [TournamentCodeController], controllers: [TournamentCodeController, TournamentCodeReplacementController],
providers: [TournamentCodeService, TournamentCodeScheduler], providers: [
TournamentCodeService,
TournamentCodeVendorService,
TournamentCodeAutoProvisionService,
TournamentCodeScheduler,
],
exports: [TournamentCodeService], exports: [TournamentCodeService],
}) })
export class TournamentCodeModule {} export class TournamentCodeModule {}
@@ -1,4 +1,5 @@
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
import { TournamentCodeService } from './tournament-code.service'; import { TournamentCodeService } from './tournament-code.service';
@Injectable() @Injectable()
@@ -6,8 +7,12 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(TournamentCodeScheduler.name); private readonly logger = new Logger(TournamentCodeScheduler.name);
private attachTimer?: NodeJS.Timeout; private attachTimer?: NodeJS.Timeout;
private expireTimer?: NodeJS.Timeout; private expireTimer?: NodeJS.Timeout;
private refillTimer?: NodeJS.Timeout;
constructor(private readonly tournamentCodeService: TournamentCodeService) {} constructor(
private readonly tournamentCodeService: TournamentCodeService,
private readonly autoProvisionService: TournamentCodeAutoProvisionService,
) {}
public onModuleInit() { public onModuleInit() {
this.attachTimer = setInterval(() => { this.attachTimer = setInterval(() => {
@@ -16,16 +21,26 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
this.expireTimer = setInterval(() => { this.expireTimer = setInterval(() => {
void this.markExpired(); void this.markExpired();
}, 60 * 60 * 1000); }, 60 * 60 * 1000);
if (isAutoProvisionEnabled()) {
this.refillTimer = setInterval(() => {
void this.ensureVendorPool();
}, 5 * 60 * 1000);
}
this.attachTimer.unref?.(); this.attachTimer.unref?.();
this.expireTimer.unref?.(); this.expireTimer.unref?.();
this.refillTimer?.unref?.();
void this.attachPending(); void this.attachPending();
void this.markExpired(); void this.markExpired();
if (isAutoProvisionEnabled()) {
void this.ensureVendorPool();
}
} }
public onModuleDestroy() { public onModuleDestroy() {
if (this.attachTimer) clearInterval(this.attachTimer); if (this.attachTimer) clearInterval(this.attachTimer);
if (this.expireTimer) clearInterval(this.expireTimer); if (this.expireTimer) clearInterval(this.expireTimer);
if (this.refillTimer) clearInterval(this.refillTimer);
} }
private async attachPending() { private async attachPending() {
@@ -54,4 +69,23 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
); );
} }
} }
private async ensureVendorPool() {
try {
await this.autoProvisionService.ensurePool();
} catch (error) {
this.logger.warn(
`Failed to auto-provision tournament codes: ${
error instanceof Error ? error.message : error
}`,
);
}
}
}
function isAutoProvisionEnabled(): boolean {
const raw = process.env.TOURNAMENT_CODE_AUTO_PROVISION_ENABLED
?.trim()
.toLowerCase();
return raw !== 'false' && raw !== '0' && raw !== 'off';
} }
@@ -1,4 +1,8 @@
import type { MatchDocument } from '../global/database/schema'; import {
TournamentCodeSchema,
type MatchDocument,
} from '../global/database/schema';
import mongoose from 'mongoose';
import { TournamentCodeService } from './tournament-code.service'; import { TournamentCodeService } from './tournament-code.service';
type TournamentCodeServiceInternals = TournamentCodeService & { type TournamentCodeServiceInternals = TournamentCodeService & {
@@ -8,6 +12,12 @@ type TournamentCodeServiceInternals = TournamentCodeService & {
gameNumber: number, gameNumber: number,
): { teamAIndex: number; teamBIndex: number }; ): { teamAIndex: number; teamBIndex: number };
ensureGameSchedule(match: MatchDocument): void; ensureGameSchedule(match: MatchDocument): void;
replaceForMatchGame(params: {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
gameNumber: number;
}): Promise<unknown>;
attachPendingMatches(communityId?: mongoose.Types.ObjectId): Promise<number>;
}; };
function createService() { function createService() {
@@ -19,10 +29,12 @@ function createService() {
interface MatchOverrides { interface MatchOverrides {
gameCount?: number; gameCount?: number;
gameMode?: 'pair' | 'bracket' | 'round-robin'; gameMode?: 'pair' | 'bracket' | 'round-robin';
roundRobinMaxRounds?: number;
participants?: Array<{ excluded?: boolean }>; participants?: Array<{ excluded?: boolean }>;
teams?: Array<{ teamIndex: number }>; teams?: Array<{ teamIndex: number }>;
gameSchedule?: Array<{ gameSchedule?: Array<{
gameNumber: number; gameNumber: number;
roundNumber?: number;
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
}>; }>;
@@ -30,11 +42,15 @@ interface MatchOverrides {
function createMatch(overrides: MatchOverrides): MatchDocument { function createMatch(overrides: MatchOverrides): MatchDocument {
return { return {
_id: new mongoose.Types.ObjectId(),
status: 'in-progress',
gameCount: 1, gameCount: 1,
gameMode: 'pair', gameMode: 'pair',
participants: [], participants: [],
teams: [], teams: [],
tournamentCodeIds: [],
gameSchedule: [], gameSchedule: [],
save: jest.fn().mockResolvedValue(undefined),
...overrides, ...overrides,
} as unknown as MatchDocument; } as unknown as MatchDocument;
} }
@@ -102,15 +118,32 @@ describe('TournamentCodeService round-robin scheduling', () => {
).toBe(15); ).toBe(15);
}); });
it('calculates limited round-robin slots from max rounds', () => {
const service = createService();
expect(
service.resolveRequiredSlots(
createMatch({
gameMode: 'round-robin',
gameCount: 1,
roundRobinMaxRounds: 3,
teams: Array.from({ length: 8 }, (_, index) => ({
teamIndex: index + 1,
})),
}),
),
).toBe(12);
});
it('uses persisted round-robin game schedule for game refs', () => { it('uses persisted round-robin game schedule for game refs', () => {
const service = createService(); const service = createService();
const match = createMatch({ const match = createMatch({
gameMode: 'round-robin', gameMode: 'round-robin',
gameCount: 2, gameCount: 2,
gameSchedule: [ gameSchedule: [
{ gameNumber: 1, teamAIndex: 2, teamBIndex: 5 }, { gameNumber: 1, roundNumber: 1, teamAIndex: 2, teamBIndex: 5 },
{ gameNumber: 2, teamAIndex: 2, teamBIndex: 5 }, { gameNumber: 2, roundNumber: 1, teamAIndex: 2, teamBIndex: 5 },
{ gameNumber: 3, teamAIndex: 1, teamBIndex: 4 }, { gameNumber: 3, roundNumber: 2, teamAIndex: 1, teamBIndex: 4 },
], ],
}); });
@@ -124,7 +157,7 @@ describe('TournamentCodeService round-robin scheduling', () => {
}); });
}); });
it('falls back to lexicographic round-robin pairs before schedule is persisted', () => { it('falls back to round-based pairs before schedule is persisted', () => {
const service = createService(); const service = createService();
const match = createMatch({ const match = createMatch({
gameMode: 'round-robin', gameMode: 'round-robin',
@@ -137,10 +170,10 @@ describe('TournamentCodeService round-robin scheduling', () => {
expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({ expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({
teamAIndex: 1, teamAIndex: 1,
teamBIndex: 2, teamBIndex: 4,
}); });
expect(service.resolveSeriesRefForGameNumber(match, 2)).toEqual({ expect(service.resolveSeriesRefForGameNumber(match, 2)).toEqual({
teamAIndex: 1, teamAIndex: 2,
teamBIndex: 3, teamBIndex: 3,
}); });
}); });
@@ -173,6 +206,105 @@ describe('TournamentCodeService round-robin scheduling', () => {
expect(pair.gameSchedule).toEqual([]); expect(pair.gameSchedule).toEqual([]);
}); });
it('creates a limited round-robin schedule grouped by playable rounds', () => {
const service = createService();
const roundRobin = createMatch({
gameMode: 'round-robin',
gameCount: 1,
roundRobinMaxRounds: 3,
teams: Array.from({ length: 8 }, (_, index) => ({
teamIndex: index + 1,
})),
gameSchedule: [],
});
service.ensureGameSchedule(roundRobin);
expect(roundRobin.gameSchedule).toHaveLength(12);
for (const roundNumber of [1, 2, 3]) {
const round = roundRobin.gameSchedule.filter(
(game) => game.roundNumber === roundNumber,
);
expect(round).toHaveLength(4);
expect(new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex])).size)
.toBe(8);
}
});
it('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 () => { it('does not expose fallback round-robin slots before the schedule is persisted', async () => {
const service = createService(); const service = createService();
const slots = await service.buildSlots( const slots = await service.buildSlots(
@@ -189,3 +321,282 @@ describe('TournamentCodeService round-robin scheduling', () => {
expect(slots).toEqual([]); expect(slots).toEqual([]);
}); });
}); });
describe('TournamentCodeService bulk upload', () => {
it('preserves tournament code casing at the schema layer', async () => {
const connection = mongoose.createConnection();
try {
const TournamentCodeModel = connection.model(
'TournamentCodeCasingSpec',
TournamentCodeSchema,
);
const code = new TournamentCodeModel({
code: ' AbC-12345 ',
expiresAt: new Date(Date.now() + 60 * 60 * 1000),
uploadedBy: new mongoose.Types.ObjectId(),
});
expect(code.code).toBe('AbC-12345');
} finally {
await connection.close();
}
});
it('stores tournament codes with the exact casing from input', async () => {
const insertMany = jest.fn().mockResolvedValue(undefined);
const TournamentCodeModel = {
find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue([]),
}),
}),
}),
insertMany,
};
const connectionService = {
getModel: jest.fn().mockResolvedValue(TournamentCodeModel),
};
const service = new TournamentCodeService(
connectionService as never,
) as unknown as TournamentCodeServiceInternals;
service.attachPendingMatches = jest.fn().mockResolvedValue(0);
await service.bulkUpload({
communityId: new mongoose.Types.ObjectId(),
uploadedBy: new mongoose.Types.ObjectId(),
codes: [
{
code: ' AbC-12345 ',
expiresAt: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
},
],
});
expect(insertMany).toHaveBeenCalledWith(
[
expect.objectContaining({
code: 'AbC-12345',
}),
],
{ ordered: false },
);
});
});
describe('TournamentCodeService pool stats', () => {
it('counts only available codes that are usable beyond the expiry margin', async () => {
const countDocuments = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(12),
});
const connectionService = {
getModel: jest.fn().mockResolvedValue({ countDocuments }),
};
const service = new TournamentCodeService(connectionService as never);
await expect(service.countUsableAvailable()).resolves.toBe(12);
expect(countDocuments).toHaveBeenCalledWith({
state: 'available',
expiresAt: {
$gt: expect.any(Date),
},
});
});
});
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, TournamentCodeUploadItem,
} from './tournament-code.types'; } from './tournament-code.types';
import { import {
roundRobinGameSchedule,
resolveRoundRobinTeamCount, resolveRoundRobinTeamCount,
roundRobinPairCount,
roundRobinPairs,
shuffleInPlace,
} from './round-robin.util'; } from './round-robin.util';
const DEFAULT_REGION = 'kr'; const DEFAULT_REGION = 'kr';
@@ -39,7 +37,7 @@ export class TournamentCodeService {
constructor(private readonly connectionService: ConnectionService) {} constructor(private readonly connectionService: ConnectionService) {}
public async bulkUpload(params: { public async bulkUpload(params: {
communityId: mongoose.Types.ObjectId; communityId?: mongoose.Types.ObjectId;
uploadedBy: mongoose.Types.ObjectId; uploadedBy: mongoose.Types.ObjectId;
codes: TournamentCodeUploadItem[]; codes: TournamentCodeUploadItem[];
}): Promise<BulkUploadTournamentCodesResponse> { }): Promise<BulkUploadTournamentCodesResponse> {
@@ -123,6 +121,17 @@ export class TournamentCodeService {
}; };
} }
public async countUsableAvailable(): Promise<number> {
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
return TournamentCodeModel.countDocuments({
state: 'available',
expiresAt: {
$gt: new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS),
},
}).exec();
}
public async list(params: { public async list(params: {
state?: TournamentCodeState; state?: TournamentCodeState;
limit?: number; limit?: number;
@@ -275,6 +284,111 @@ export class TournamentCodeService {
return match; 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( public async releaseFromMatch(
matchOrId: MatchDocument | mongoose.Types.ObjectId, matchOrId: MatchDocument | mongoose.Types.ObjectId,
): Promise<void> { ): Promise<void> {
@@ -368,6 +482,7 @@ export class TournamentCodeService {
const seriesRef = this.resolveSeriesRefForGameNumber(match, gameNumber); const seriesRef = this.resolveSeriesRefForGameNumber(match, gameNumber);
return { return {
gameNumber, gameNumber,
roundNumber: this.resolveRoundNumberForGameNumber(match, gameNumber),
...seriesRef, ...seriesRef,
code: null, code: null,
expiresAt: null, expiresAt: null,
@@ -377,6 +492,7 @@ export class TournamentCodeService {
} }
return { return {
gameNumber, gameNumber,
roundNumber: this.resolveRoundNumberForGameNumber(match, gameNumber),
...this.resolveSeriesRefForGameNumber(match, gameNumber), ...this.resolveSeriesRefForGameNumber(match, gameNumber),
code: code.code, code: code.code,
expiresAt: code.expiresAt.toISOString(), expiresAt: code.expiresAt.toISOString(),
@@ -387,7 +503,22 @@ export class TournamentCodeService {
} }
private normalizeCode(code: string | undefined): string { private normalizeCode(code: string | undefined): string {
return (code ?? '').trim().toUpperCase(); return (code ?? '').trim();
}
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 { private resolveRequiredSlots(match: MatchDocument): number {
@@ -395,8 +526,10 @@ export class TournamentCodeService {
const gameMode = match.gameMode ?? 'pair'; const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'round-robin') { if (gameMode === 'round-robin') {
const teamCount = resolveRoundRobinTeamCount(match); if ((match.gameSchedule?.length ?? 0) > 0) {
return roundRobinPairCount(teamCount) * gameCount; return match.gameSchedule.length;
}
return this.buildRoundRobinGameSchedule(match).length;
} }
const teamCount = (match.teams ?? []).length; const teamCount = (match.teams ?? []).length;
@@ -426,10 +559,15 @@ export class TournamentCodeService {
}; };
} }
const teamCount = resolveRoundRobinTeamCount(match); const fallback = this.buildRoundRobinGameSchedule(match).find(
const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; (entry) => entry.gameNumber === gameNumber,
const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1); );
return roundRobinPairs(teamCount)[pairIndex] ?? { return fallback
? {
teamAIndex: fallback.teamAIndex,
teamBIndex: fallback.teamBIndex,
}
: {
teamAIndex: 1, teamAIndex: 1,
teamBIndex: 2, teamBIndex: 2,
}; };
@@ -450,21 +588,33 @@ export class TournamentCodeService {
const teamCount = resolveRoundRobinTeamCount(match); const teamCount = resolveRoundRobinTeamCount(match);
if (teamCount < 2) return; if (teamCount < 2) return;
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; match.gameSchedule = this.buildRoundRobinGameSchedule(match);
const pairs = shuffleInPlace([...roundRobinPairs(teamCount)]); }
const schedule: MatchGameAssignment[] = [];
for (let pairIndex = 0; pairIndex < pairs.length; pairIndex += 1) { private resolveRoundNumberForGameNumber(
const pair = pairs[pairIndex]; match: MatchDocument,
for (let gameIndex = 0; gameIndex < gameCount; gameIndex += 1) { gameNumber: number,
schedule.push({ ): number | undefined {
gameNumber: pairIndex * gameCount + gameIndex + 1, if ((match.gameMode ?? 'pair') !== 'round-robin') return undefined;
teamAIndex: pair.teamAIndex,
teamBIndex: pair.teamBIndex, 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 { export interface TournamentCodeSlotView {
gameNumber: number; gameNumber: number;
roundNumber?: number;
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
code: string | null; code: string | null;
@@ -24,10 +24,12 @@ function createService() {
interface MatchOverrides { interface MatchOverrides {
gameCount?: number; gameCount?: number;
gameMode?: 'pair' | 'bracket' | 'round-robin'; gameMode?: 'pair' | 'bracket' | 'round-robin';
roundRobinMaxRounds?: number;
participants?: Array<{ excluded?: boolean }>; participants?: Array<{ excluded?: boolean }>;
teams?: Array<{ teamIndex: number }>; teams?: Array<{ teamIndex: number }>;
gameSchedule?: Array<{ gameSchedule?: Array<{
gameNumber: number; gameNumber: number;
roundNumber?: number;
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
}>; }>;
@@ -58,6 +60,20 @@ describe('TournamentResultService round-robin scheduling', () => {
expect(service.resolveRequiredGameSlots(match)).toBe(15); expect(service.resolveRequiredGameSlots(match)).toBe(15);
}); });
it('calculates limited round-robin slots for polling', () => {
const service = createService();
const match = createMatch({
gameMode: 'round-robin',
gameCount: 1,
roundRobinMaxRounds: 3,
teams: Array.from({ length: 8 }, (_, index) => ({
teamIndex: index + 1,
})),
});
expect(service.resolveRequiredGameSlots(match)).toBe(12);
});
it('uses persisted round-robin schedule when mapping a game number', () => { it('uses persisted round-robin schedule when mapping a game number', () => {
const service = createService(); const service = createService();
const match = createMatch({ const match = createMatch({
@@ -85,6 +101,180 @@ describe('TournamentResultService round-robin scheduling', () => {
}); });
}); });
describe('TournamentResultService tournament code polling', () => {
function queryResult<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) };
}
function sortedQueryResult<T>(value: T) {
return {
sort: jest.fn().mockReturnValue(queryResult(value)),
};
}
function createPollFixture(params: {
storedCode: string;
riotTournamentCode: string;
}) {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const codeId = new mongoose.Types.ObjectId();
const users = Array.from({ length: 10 }, (_, index) => ({
userId: new mongoose.Types.ObjectId(),
puuid: `poll-puuid-${index + 1}`,
}));
const match = {
_id: matchId,
communityId,
status: 'team-built',
teamBuiltAt: new Date('2026-05-03T10:00:00.000Z'),
gameCount: 1,
gameMode: 'pair',
tournamentCodeIds: [codeId],
gameSchedule: [],
resultPollState: {
startedAt: new Date(),
matchedCount: 0,
expandedToAllPuuids: true,
state: 'polling',
},
participants: users.map((user) => ({
userId: user.userId,
puuid: user.puuid,
excluded: false,
})),
teams: [
{
teamIndex: 1,
members: users.slice(0, 5).map((user) => ({ userId: user.userId })),
},
{
teamIndex: 2,
members: users.slice(5).map((user) => ({ userId: user.userId })),
},
],
save: jest.fn().mockResolvedValue(undefined),
} as unknown as MatchDocument & {
save: jest.Mock;
result?: MatchDocument['result'];
};
const code = {
_id: codeId,
code: params.storedCode,
state: 'reserved',
gameNumber: 1,
riotMatchId: undefined,
save: jest.fn().mockResolvedValue(undefined),
};
const detail = {
metadata: {
matchId: 'KR_9876543210',
participants: users.map((user) => user.puuid),
},
info: {
tournamentCode: params.riotTournamentCode,
gameCreation: Date.parse('2026-05-03T10:30:00.000Z'),
gameEndTimestamp: Date.parse('2026-05-03T11:00:00.000Z'),
gameDuration: 1800,
participants: users.map((user, index) => ({
puuid: user.puuid,
teamId: index < 5 ? 100 : 200,
championId: 1,
kills: 1,
deaths: 1,
assists: 1,
win: index < 5,
})),
teams: [
{ teamId: 100, win: true },
{ teamId: 200, win: false },
],
},
} as unknown as RiotMatchDto;
const TournamentCodeModel = {
find: jest
.fn()
.mockReturnValueOnce(sortedQueryResult([code]))
.mockReturnValueOnce(sortedQueryResult([code])),
exists: jest.fn().mockResolvedValue(null),
};
const RiotMatchModel = {
findOne: jest.fn().mockReturnValue(queryResult(null)),
updateOne: jest.fn().mockReturnValue(queryResult(undefined)),
};
const CommunityModel = {
findById: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue(queryResult({ riotRegion: 'asia' })),
}),
}),
};
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') {
return { findById: jest.fn().mockResolvedValue(match) };
}
if (name === 'tournamentCode') return TournamentCodeModel;
if (name === 'community') return CommunityModel;
if (name === 'riotMatch') return RiotMatchModel;
throw new Error(`Unexpected model: ${name}`);
}),
};
const riotMatchService = {
getMatchIdsByPuuid: jest.fn().mockResolvedValue(['KR_9876543210']),
getMatch: jest.fn().mockResolvedValue(detail),
};
const riotJobQueueService = {
enqueueTournamentResultPoll: jest.fn().mockResolvedValue(undefined),
};
const service = new TournamentResultService(
connectionService as never,
riotMatchService as never,
riotJobQueueService as never,
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
{ buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never,
);
return { service, match, code };
}
it('matches Riot tournament codes using exact casing', async () => {
const { service, match, code } = createPollFixture({
storedCode: 'AbC-12345',
riotTournamentCode: 'AbC-12345',
});
await service.processPollJob({
matchId: match._id.toString(),
attempt: 1,
expandedToAllPuuids: true,
});
expect(code.state).toBe('used');
expect(code.riotMatchId).toBe('KR_9876543210');
expect(code.save).toHaveBeenCalled();
expect(match.result?.games).toHaveLength(1);
});
it('does not match tournament codes when casing differs', async () => {
const { service, match, code } = createPollFixture({
storedCode: 'ABC-12345',
riotTournamentCode: 'abc-12345',
});
await service.processPollJob({
matchId: match._id.toString(),
attempt: 1,
expandedToAllPuuids: true,
});
expect(code.state).toBe('reserved');
expect(code.riotMatchId).toBeUndefined();
expect(code.save).not.toHaveBeenCalled();
expect(match.result?.games).toBeUndefined();
});
});
describe('TournamentResultService manual result collection', () => { describe('TournamentResultService manual result collection', () => {
function createManualFixture() { function createManualFixture() {
const communityId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId();
@@ -19,9 +19,8 @@ import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types';
import { RiotMatchService } from '../riot/riot-match.service'; import { RiotMatchService } from '../riot/riot-match.service';
import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types'; import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types';
import { import {
roundRobinGameSchedule,
resolveRoundRobinTeamCount, resolveRoundRobinTeamCount,
roundRobinPairCount,
roundRobinPairs,
} from '../tournament-code/round-robin.util'; } from '../tournament-code/round-robin.util';
import { import {
collectCaptainUserIds, collectCaptainUserIds,
@@ -263,7 +262,7 @@ export class TournamentResultService {
); );
continue; continue;
} }
const tournamentCode = detail.info.tournamentCode?.trim().toUpperCase(); const tournamentCode = detail.info.tournamentCode?.trim();
if (!tournamentCode) continue; if (!tournamentCode) continue;
const code = unmatchedByCode.get(tournamentCode); const code = unmatchedByCode.get(tournamentCode);
@@ -785,14 +784,18 @@ export class TournamentResultService {
}; };
} }
const perSeries = match.gameCount || 1; const fallback = this.buildRoundRobinGameSchedule(match).find(
const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1); (entry) => entry.gameNumber === gameNumber,
return ( );
roundRobinPairs(resolveRoundRobinTeamCount(match))[pairIndex] ?? { return fallback
? {
teamAIndex: fallback.teamAIndex,
teamBIndex: fallback.teamBIndex,
}
: {
teamAIndex: 1, teamAIndex: 1,
teamBIndex: 2, teamBIndex: 2,
} };
);
} }
const perSeries = match.gameCount || 1; const perSeries = match.gameCount || 1;
@@ -806,8 +809,10 @@ export class TournamentResultService {
private resolveRequiredGameSlots(match: MatchDocument): number { private resolveRequiredGameSlots(match: MatchDocument): number {
const gameMode = match.gameMode ?? 'pair'; const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'round-robin') { if (gameMode === 'round-robin') {
const teamCount = resolveRoundRobinTeamCount(match); if ((match.gameSchedule?.length ?? 0) > 0) {
return roundRobinPairCount(teamCount) * (match.gameCount || 1); return match.gameSchedule.length;
}
return this.buildRoundRobinGameSchedule(match).length;
} }
const activeParticipantCount = match.participants.filter( const activeParticipantCount = match.participants.filter(
@@ -819,6 +824,13 @@ export class TournamentResultService {
return seriesCount * (match.gameCount || 1); return seriesCount * (match.gameCount || 1);
} }
private buildRoundRobinGameSchedule(match: MatchDocument) {
return roundRobinGameSchedule(resolveRoundRobinTeamCount(match), {
gamesPerPair: match.gameCount || 1,
maxRounds: match.roundRobinMaxRounds,
});
}
private resolveMatchWinnerTeamIndex( private resolveMatchWinnerTeamIndex(
seriesResults: NonNullable<MatchDocument['result']>['seriesResults'], seriesResults: NonNullable<MatchDocument['result']>['seriesResults'],
): number | undefined { ): number | undefined {
@@ -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 { Module } from '@nestjs/common';
import { RiotModule } from '../riot/riot.module'; import { RiotModule } from '../riot/riot.module';
import { CommunityUserController } from './community-user.controller';
import { UserController } from './user.controller'; import { UserController } from './user.controller';
import { UserSearchService } from './user-search.service';
@Module({ @Module({
imports: [RiotModule], imports: [RiotModule],
controllers: [UserController], controllers: [UserController, CommunityUserController],
providers: [UserSearchService],
}) })
export class UserModule {} export class UserModule {}
+1 -1
View File
@@ -1,4 +1,4 @@
VITE_API_BASE_URL=http://localhost:3000 VITE_API_BASE_URL=http://126.dahyeon.us:3000
VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1 VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1
VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3 VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863 VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863
+5
View File
@@ -10,6 +10,7 @@ import AuthCallbackPage from "./pages/AuthCallback";
import HomePage from "./pages/HomePage"; import HomePage from "./pages/HomePage";
import LoginPage from "./pages/Login"; import LoginPage from "./pages/Login";
import MatchDetailPage from "./pages/MatchDetailPage"; import MatchDetailPage from "./pages/MatchDetailPage";
import MatchGameDetailPage from "./pages/MatchGameDetailPage";
import MatchTeamProgressPage from "./pages/MatchTeamProgressPage"; import MatchTeamProgressPage from "./pages/MatchTeamProgressPage";
import AuctionPage from "./pages/AuctionPage"; import AuctionPage from "./pages/AuctionPage";
import UserHistoryPage from "./pages/UserHistoryPage"; import UserHistoryPage from "./pages/UserHistoryPage";
@@ -151,6 +152,10 @@ function App() {
<Route path="/login" element={<LoginPage />} /> <Route path="/login" element={<LoginPage />} />
<Route path="/auth/callback" element={<AuthCallbackPage />} /> <Route path="/auth/callback" element={<AuthCallbackPage />} />
<Route path="/match/:id" element={<MatchDetailPage />} /> <Route path="/match/:id" element={<MatchDetailPage />} />
<Route
path="/match/:id/game/:gameNumber"
element={<MatchGameDetailPage />}
/>
<Route <Route
path="/match/:id/team/:teamIndex" path="/match/:id/team/:teamIndex"
element={<MatchTeamProgressPage />} element={<MatchTeamProgressPage />}
+31
View File
@@ -13,6 +13,7 @@ import type {
ApiAuctionHistoryEntry, ApiAuctionHistoryEntry,
ApiChampionStatsResponse, ApiChampionStatsResponse,
ApiCommunity, ApiCommunity,
ApiCommunityUserSearchCandidate,
ApiEnqueueRefreshResult, ApiEnqueueRefreshResult,
ApiInternalMatchDetailResponse, ApiInternalMatchDetailResponse,
ApiInternalMatchListResponse, ApiInternalMatchListResponse,
@@ -40,6 +41,7 @@ import type {
RebuildLegacyMatchesResponse, RebuildLegacyMatchesResponse,
TournamentCodeBulkUploadResponse, TournamentCodeBulkUploadResponse,
TournamentCodeListResponse, TournamentCodeListResponse,
TournamentCodeSlotView,
TournamentCodeState, TournamentCodeState,
TournamentCodeStatsResponse, TournamentCodeStatsResponse,
TournamentCodeUploadItem, 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( export function useAuction(
matchId: string | undefined, matchId: string | undefined,
communityId = DEFAULT_COMMUNITY_ID, 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) { export function usePollTournamentResult(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({ return useMutation({
mutationFn: (matchId: string) => mutationFn: (matchId: string) =>
+16 -2
View File
@@ -36,6 +36,9 @@ export interface TeamParticipantView extends ParticipantView {
export interface TeamView { export interface TeamView {
teamIndex: number; teamIndex: number;
name: string; name: string;
captainUserId?: string;
captainName?: string;
captainTag?: string;
participants: TeamParticipantView[]; participants: TeamParticipantView[];
} }
@@ -413,9 +416,19 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
participants.map((participant) => [participant.userId, participant]), participants.map((participant) => [participant.userId, participant]),
); );
const teams = match.teams.map((team) => ({ const teams = match.teams.map((team) => {
const captain = team.captainUserId
? participantLookup.get(team.captainUserId)
: undefined;
return {
teamIndex: team.teamIndex, teamIndex: team.teamIndex,
name: teamIndexLabel(team.teamIndex, team.name), name: teamIndexLabel(team.teamIndex, team.name),
captainUserId: team.captainUserId,
captainName:
captain?.summonerName ??
(team.captainUserId ? `User ${team.captainUserId.slice(-4)}` : undefined),
captainTag: captain?.tag,
participants: team.members.map((member) => { participants: team.members.map((member) => {
const participant = const participant =
participantLookup.get(member.userId) ?? participantLookup.get(member.userId) ??
@@ -427,7 +440,8 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
cost: member.cost, cost: member.cost,
}; };
}), }),
})); };
});
const winnerTeam = match.result?.winnerTeamIndex const winnerTeam = match.result?.winnerTeamIndex
? teams.find((team) => team.teamIndex === match.result?.winnerTeamIndex) ? teams.find((team) => team.teamIndex === match.result?.winnerTeamIndex)
+92 -4
View File
@@ -103,6 +103,24 @@ export interface ApiUser {
updatedAt: string; 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 { export interface ApiCommunity {
_id: string; _id: string;
name: string; name: string;
@@ -124,6 +142,7 @@ export type TournamentCodeSlotState = TournamentCodeState | 'pending';
export interface TournamentCodeSlotView { export interface TournamentCodeSlotView {
gameNumber: number; gameNumber: number;
roundNumber?: number;
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
code: string | null; code: string | null;
@@ -201,6 +220,7 @@ export interface ApiMatchScheduleItem {
export interface ApiMatchGameAssignment { export interface ApiMatchGameAssignment {
gameNumber: number; gameNumber: number;
roundNumber?: number;
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
} }
@@ -225,6 +245,7 @@ export interface ApiMatch {
maxParticipants: number; maxParticipants: number;
gameCount: number; gameCount: number;
gameMode: MatchGameMode; gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
gameSchedule?: ApiMatchGameAssignment[]; gameSchedule?: ApiMatchGameAssignment[];
tournamentCodes?: TournamentCodeSlotView[]; tournamentCodes?: TournamentCodeSlotView[];
hostUserId?: string; hostUserId?: string;
@@ -353,6 +374,7 @@ export interface MatchMutationRequest {
maxParticipants?: number; maxParticipants?: number;
gameCount?: number; gameCount?: number;
gameMode?: MatchGameMode; gameMode?: MatchGameMode;
roundRobinMaxRounds?: number;
prizes?: string[]; prizes?: string[];
notices?: string[]; notices?: string[];
schedule?: ApiMatchScheduleItem[]; schedule?: ApiMatchScheduleItem[];
@@ -540,6 +562,39 @@ export interface ApiRecentSummaryResponse {
lastFetchedAt: string | null; 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 { export interface ApiRecentMatchTeamParticipant {
puuid: string; puuid: string;
gameName: string; gameName: string;
@@ -553,7 +608,7 @@ export interface ApiRecentMatchTeamParticipant {
items: number[]; items: number[];
trinket: number; trinket: number;
summonerSpells: [number, number]; summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; perks: ApiRunePerks;
totalCs: number; totalCs: number;
csPerMin: number; csPerMin: number;
goldEarned: number; goldEarned: number;
@@ -601,7 +656,7 @@ export interface ApiRecentMatchView {
items: number[]; items: number[];
trinket: number; trinket: number;
summonerSpells: [number, number]; summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; perks: ApiRunePerks;
teams: ApiRecentMatchTeam[]; teams: ApiRecentMatchTeam[];
} }
@@ -710,18 +765,43 @@ export interface ApiInternalMatchDetailResponse {
riotMatchId: string; riotMatchId: string;
gameCreation: number; gameCreation: number;
gameDuration: 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<{ teams: Array<{
teamIndex: number; teamIndex: number;
side: TeamSide; side: TeamSide;
win: boolean; 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<{ participants: Array<{
userId: string | null; userId: string | null;
summonerName: string; summonerName: string;
tagLine: string;
teamIndex: number; teamIndex: number;
side: TeamSide; side: TeamSide;
teamPosition: string; teamPosition: string;
championId: number; championId: number;
championLevel: number;
kills: number; kills: number;
deaths: number; deaths: number;
assists: number; assists: number;
@@ -730,13 +810,21 @@ export interface ApiInternalMatchDetailResponse {
gold: number; gold: number;
gpm: number; gpm: number;
damageDealtToChampions: number; damageDealtToChampions: number;
damageTaken: number;
damageShare: number; damageShare: number;
killParticipation: number; killParticipation: number;
visionScore: number; visionScore: number;
wardsPlaced: number;
wardsKilled: number;
controlWardsBought: number;
firstBloodKill: boolean;
firstBloodAssist: boolean;
items: number[]; items: number[];
trinket: number; trinket: number;
summonerSpells: [number, number]; summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; perks: ApiRunePerks;
itemBuild: ApiItemBuildEvent[];
skillBuild: ApiSkillBuildEvent[];
win: boolean; win: boolean;
}>; }>;
}>; }>;
+18
View File
@@ -30,6 +30,11 @@ interface ResetPayload {
matchId?: string; matchId?: string;
} }
interface TickPayload {
deadline?: string;
serverTime?: string;
}
const MAX_CHAT_MESSAGES = 200; const MAX_CHAT_MESSAGES = 200;
function mergeChatMessages( function mergeChatMessages(
@@ -55,6 +60,7 @@ export function useAuctionSocket(matchId: string | undefined) {
const [connectionStatus, setConnectionStatus] = const [connectionStatus, setConnectionStatus] =
useState<ConnectionStatus>('idle'); useState<ConnectionStatus>('idle');
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [serverTimeOffsetMs, setServerTimeOffsetMs] = useState(0);
useEffect(() => { useEffect(() => {
if (!matchId) { if (!matchId) {
@@ -100,6 +106,16 @@ export function useAuctionSocket(matchId: string | undefined) {
setError(null); setError(null);
}); });
socket.on('tick', (payload: TickPayload) => {
const serverTime =
typeof payload?.serverTime === 'string'
? Date.parse(payload.serverTime)
: NaN;
if (Number.isFinite(serverTime)) {
setServerTimeOffsetMs(serverTime - Date.now());
}
});
socket.on('chat-history', (payload: ChatHistoryPayload) => { socket.on('chat-history', (payload: ChatHistoryPayload) => {
setChatMessages(mergeChatMessages([], payload.messages ?? [])); setChatMessages(mergeChatMessages([], payload.messages ?? []));
}); });
@@ -129,6 +145,7 @@ export function useAuctionSocket(matchId: string | undefined) {
socket?.disconnect(); socket?.disconnect();
socketRef.current = null; socketRef.current = null;
setConnectionStatus('idle'); setConnectionStatus('idle');
setServerTimeOffsetMs(0);
}; };
}, [authUserId, matchId]); }, [authUserId, matchId]);
@@ -160,6 +177,7 @@ export function useAuctionSocket(matchId: string | undefined) {
resetAt, resetAt,
connectionStatus: visibleConnectionStatus, connectionStatus: visibleConnectionStatus,
error, error,
serverTimeOffsetMs: matchId ? serverTimeOffsetMs : 0,
placeBid(payload: BidPayload) { placeBid(payload: BidPayload) {
emit('bid', payload); emit('bid', payload);
}, },
+7
View File
@@ -69,3 +69,10 @@ export function runeKeystoneIconUrl(
return rune ? `${cdn(manifest)}/img/${rune.icon}` : null; return rune ? `${cdn(manifest)}/img/${rune.icon}` : null;
} }
export function runeIconUrl(
manifest: DdragonManifest | null | undefined,
runeId: number | undefined,
) {
return runeKeystoneIconUrl(manifest, runeId);
}
+93 -25
View File
@@ -48,6 +48,7 @@ import { RankBadge, ResponsiveTierLabel } from '../components/RankBadge';
import type { import type {
ApiAuction, ApiAuction,
ApiAuctionChatMessage, ApiAuctionChatMessage,
ApiTierHistoryEntry,
ApiRiotLaneStats, ApiRiotLaneStats,
ApiUser, ApiUser,
Position, Position,
@@ -125,6 +126,7 @@ function pickLatestAuction(
} }
const AUCTION_MAX_TEAM_SIZE = 5; const AUCTION_MAX_TEAM_SIZE = 5;
const AUCTION_MIN_BID_POINTS = 10;
const LANE_ROWS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP']; const LANE_ROWS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
const POSITION_TO_RIOT_LANE = { const POSITION_TO_RIOT_LANE = {
TOP: 'TOP', TOP: 'TOP',
@@ -134,6 +136,28 @@ const POSITION_TO_RIOT_LANE = {
SUP: 'UTILITY', SUP: 'UTILITY',
} as const; } as const;
function getAuctionTeamSize(team: AuctionStateView['teams'][number]) {
return team.members.length + 1;
}
function getReservedPointsAfterCurrentBid(
team: AuctionStateView['teams'][number],
) {
const remainingSlotsAfterCurrentBid = Math.max(
0,
AUCTION_MAX_TEAM_SIZE - getAuctionTeamSize(team) - 1,
);
return remainingSlotsAfterCurrentBid * AUCTION_MIN_BID_POINTS;
}
function getMaxBidForTeam(team: AuctionStateView['teams'][number]) {
return Math.max(0, team.points - getReservedPointsAfterCurrentBid(team));
}
function getSoloTierHistory(entries: ApiTierHistoryEntry[]) {
return entries.filter((entry) => entry.queueType === 'RANKED_SOLO_5x5');
}
function PosBadge({ pos }: { pos: Position }) { function PosBadge({ pos }: { pos: Position }) {
return ( return (
<span className="inline-flex items-center gap-1.5 text-xs font-medium px-1.5 py-0.5 border border-primary/20 text-primary bg-primary/5"> <span className="inline-flex items-center gap-1.5 text-xs font-medium px-1.5 py-0.5 border border-primary/20 text-primary bg-primary/5">
@@ -291,7 +315,7 @@ function TeamPanel({
}) { }) {
const { data: ddragon } = useDdragonManifest(); const { data: ddragon } = useDdragonManifest();
const tone = teamIndexColorClasses(team.teamIndex); const tone = teamIndexColorClasses(team.teamIndex);
const teamSize = team.members.length + 1; const teamSize = getAuctionTeamSize(team);
const isFull = teamSize >= AUCTION_MAX_TEAM_SIZE; const isFull = teamSize >= AUCTION_MAX_TEAM_SIZE;
return ( return (
@@ -389,16 +413,19 @@ function PlayerSpotlight({
}) { }) {
const { data: ddragon } = useDdragonManifest(); const { data: ddragon } = useDdragonManifest();
const player = state.currentPlayer; const player = state.currentPlayer;
const snapshotSoloTierHistory = player
? getSoloTierHistory(player.tierHistory)
: [];
const historyProfileQuery = useUserHistoryProfile( const historyProfileQuery = useUserHistoryProfile(
player?.userId, player?.userId,
DEFAULT_COMMUNITY_ID, DEFAULT_COMMUNITY_ID,
Boolean(player && player.tierHistory.length === 0), Boolean(player && snapshotSoloTierHistory.length === 0),
); );
if (!player) return null; if (!player) return null;
const tierHistory = const tierHistory =
player.tierHistory.length > 0 snapshotSoloTierHistory.length > 0
? player.tierHistory ? snapshotSoloTierHistory
: (historyProfileQuery.data?.tierHistory ?? []); : getSoloTierHistory(historyProfileQuery.data?.tierHistory ?? []);
return ( return (
<div className="border border-base-content/10 bg-base-100"> <div className="border border-base-content/10 bg-base-100">
@@ -453,6 +480,7 @@ function PlayerSpotlight({
} }
> >
<TierHistoryChart <TierHistoryChart
key={`${player.userId}-solo-tier-history`}
entries={tierHistory} entries={tierHistory}
className="border-b border-base-content/8 bg-base-100 overflow-hidden" className="border-b border-base-content/8 bg-base-100 overflow-hidden"
summaryVariant="inline" summaryVariant="inline"
@@ -553,16 +581,22 @@ function BidControls({
onBid: (teamIndex: number, amount: number) => void; onBid: (teamIndex: number, amount: number) => void;
}) { }) {
const [bidAmount, setBidAmount] = useState(100); const [bidAmount, setBidAmount] = useState(100);
const minBid = state.currentBid + 10; const minBid = state.currentBid + AUCTION_MIN_BID_POINTS;
const activeTeam = captainRole const activeTeam = captainRole
? state.teams.find((team) => team.teamIndex === captainRole.teamIndex) ? state.teams.find((team) => team.teamIndex === captainRole.teamIndex)
: null; : null;
const activeTeamSize = activeTeam ? activeTeam.members.length + 1 : 0; const activeTeamSize = activeTeam ? getAuctionTeamSize(activeTeam) : 0;
const isActiveTeamFull = activeTeamSize >= AUCTION_MAX_TEAM_SIZE; const isActiveTeamFull = activeTeamSize >= AUCTION_MAX_TEAM_SIZE;
const reservedPoints = activeTeam
? getReservedPointsAfterCurrentBid(activeTeam)
: 0;
const maxBid = activeTeam ? getMaxBidForTeam(activeTeam) : 0;
const canAffordNextBid = !isActiveTeamFull && maxBid >= minBid;
useEffect(() => { useEffect(() => {
setBidAmount(Math.max(minBid, Math.ceil(minBid / 10) * 10)); const nextBid = Math.max(minBid, Math.ceil(minBid / 10) * 10);
}, [state.currentBid, minBid]); setBidAmount(activeTeam ? Math.min(maxBid, nextBid) : nextBid);
}, [activeTeam, maxBid, minBid]);
if (state.phase !== 'bidding') return null; if (state.phase !== 'bidding') return null;
@@ -578,16 +612,40 @@ function BidControls({
return ( return (
<div className="border border-base-content/10 bg-base-100 p-4"> <div className="border border-base-content/10 bg-base-100 p-4">
<div className="mb-3 grid grid-cols-2 gap-2 text-xs sm:grid-cols-3">
<div className="border border-base-content/10 px-2.5 py-2">
<div className="text-base-content/30">보유</div>
<div className="mt-0.5 font-bold tabular-nums text-base-content">
{formatPoints(activeTeam.points)}P
</div>
</div>
<div className="border border-primary/20 bg-primary/5 px-2.5 py-2">
<div className="text-primary/70">이번 최대</div>
<div className="mt-0.5 font-black tabular-nums text-primary">
{formatPoints(maxBid)}P
</div>
</div>
<div
className="border border-base-content/10 px-2.5 py-2 text-base-content/45"
title={`현재 선수를 낙찰받은 뒤 남은 자리를 채우도록 자리당 ${AUCTION_MIN_BID_POINTS}P씩 보존합니다.`}
aria-label={`보존 ${reservedPoints}P. 현재 선수를 낙찰받은 뒤 남은 자리를 채우도록 자리당 ${AUCTION_MIN_BID_POINTS}P씩 보존합니다.`}
>
<div>보존</div>
<div className="mt-0.5 font-bold tabular-nums">
{formatPoints(reservedPoints)}P
</div>
</div>
</div>
<div className="flex items-center gap-2 mb-3 flex-wrap"> <div className="flex items-center gap-2 mb-3 flex-wrap">
{presets.map((preset) => ( {presets.map((preset) => (
<button <button
key={preset} key={preset}
onClick={() => setBidAmount(Math.max(minBid, preset))} onClick={() => setBidAmount(Math.min(maxBid, Math.max(minBid, preset)))}
disabled={isActiveTeamFull} disabled={!canAffordNextBid || Math.max(minBid, preset) > maxBid}
className={`text-xs px-2.5 py-1 border transition-colors ${ className={`text-xs px-2.5 py-1 border transition-colors ${
bidAmount === preset bidAmount === preset
? 'border-primary/40 bg-primary/10 text-primary' ? 'border-primary/40 bg-primary/10 text-primary'
: 'border-base-content/10 text-base-content/40 hover:border-base-content/20' : 'border-base-content/10 text-base-content/40 hover:border-base-content/20 disabled:opacity-30 disabled:cursor-not-allowed'
}`} }`}
> >
{preset}P {preset}P
@@ -597,18 +655,19 @@ function BidControls({
type="number" type="number"
value={bidAmount} value={bidAmount}
onChange={(event) => onChange={(event) =>
setBidAmount(Math.max(minBid, Number(event.target.value))) setBidAmount(Math.min(maxBid, Math.max(minBid, Number(event.target.value))))
} }
min={minBid} min={minBid}
disabled={isActiveTeamFull} max={maxBid}
disabled={!canAffordNextBid}
className="w-24 text-xs px-2 py-1 border border-base-content/10 bg-transparent text-base-content tabular-nums text-right focus:outline-none focus:border-primary/30" className="w-24 text-xs px-2 py-1 border border-base-content/10 bg-transparent text-base-content tabular-nums text-right focus:outline-none focus:border-primary/30"
/> />
</div> </div>
<button <button
onClick={() => onBid(activeTeam.teamIndex, bidAmount)} onClick={() => onBid(activeTeam.teamIndex, bidAmount)}
disabled={ disabled={
isActiveTeamFull || !canAffordNextBid ||
bidAmount > activeTeam.points || bidAmount > maxBid ||
bidAmount <= state.currentBid bidAmount <= state.currentBid
} }
className={`w-full py-2 text-xs font-bold uppercase tracking-wide border transition-colors disabled:opacity-30 disabled:cursor-not-allowed ${ className={`w-full py-2 text-xs font-bold uppercase tracking-wide border transition-colors disabled:opacity-30 disabled:cursor-not-allowed ${
@@ -617,6 +676,8 @@ function BidControls({
> >
{isActiveTeamFull {isActiveTeamFull
? `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 정원 완료 (${activeTeamSize}/${AUCTION_MAX_TEAM_SIZE})` ? `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 정원 완료 (${activeTeamSize}/${AUCTION_MAX_TEAM_SIZE})`
: !canAffordNextBid
? `입찰 불가 (다음 ${formatPoints(minBid)}P · 최대 ${formatPoints(maxBid)}P)`
: `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 입찰 (${formatPoints(bidAmount)}P)`} : `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 입찰 (${formatPoints(bidAmount)}P)`}
</button> </button>
</div> </div>
@@ -624,10 +685,12 @@ function BidControls({
} }
function BidLog({ bids }: { bids: AuctionStateView['bids'] }) { function BidLog({ bids }: { bids: AuctionStateView['bids'] }) {
const endRef = useRef<HTMLDivElement>(null); const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => { useEffect(() => {
endRef.current?.scrollIntoView({ behavior: 'smooth' }); const scrollContainer = scrollRef.current;
if (!scrollContainer) return;
scrollContainer.scrollTop = scrollContainer.scrollHeight;
}, [bids.length]); }, [bids.length]);
if (bids.length === 0) return null; if (bids.length === 0) return null;
@@ -639,7 +702,7 @@ function BidLog({ bids }: { bids: AuctionStateView['bids'] }) {
입찰 기록 입찰 기록
</span> </span>
</div> </div>
<div className="max-h-28 overflow-y-auto p-2 space-y-0.5"> <div ref={scrollRef} className="max-h-28 overflow-y-auto p-2 space-y-0.5">
{bids.map((bid, index) => ( {bids.map((bid, index) => (
<div key={`${bid.teamIndex}-${bid.timestamp}-${index}`} className="flex items-center gap-2 text-xs"> <div key={`${bid.teamIndex}-${bid.timestamp}-${index}`} className="flex items-center gap-2 text-xs">
<span <span
@@ -653,7 +716,6 @@ function BidLog({ bids }: { bids: AuctionStateView['bids'] }) {
</span> </span>
</div> </div>
))} ))}
<div ref={endRef} />
</div> </div>
</div> </div>
); );
@@ -719,9 +781,14 @@ export default function AuctionPage() {
}, [showCancelModal]); }, [showCancelModal]);
const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data); const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data);
const syncedNow = now + socket.serverTimeOffsetMs;
const auctionState = const auctionState =
liveAuction && matchQuery.data liveAuction && matchQuery.data
? mapApiAuctionToAuctionState(liveAuction, matchQuery.data, new Date(now)) ? mapApiAuctionToAuctionState(
liveAuction,
matchQuery.data,
new Date(syncedNow),
)
: null; : null;
const availableTeamIndexes = useMemo(() => { const availableTeamIndexes = useMemo(() => {
const indexes = new Set((auctionState?.teams ?? []).map((team) => team.teamIndex)); const indexes = new Set((auctionState?.teams ?? []).map((team) => team.teamIndex));
@@ -1391,13 +1458,15 @@ function ChatPanel({
className?: string; className?: string;
}) { }) {
const [draft, setDraft] = useState(''); const [draft, setDraft] = useState('');
const messagesEndRef = useRef<HTMLDivElement | null>(null); const messagesScrollRef = useRef<HTMLDivElement | null>(null);
const trimmedDraft = draft.trim(); const trimmedDraft = draft.trim();
const isConnected = connectionStatus === 'connected'; const isConnected = connectionStatus === 'connected';
const canSend = isConnected && trimmedDraft.length > 0; const canSend = isConnected && trimmedDraft.length > 0;
useEffect(() => { useEffect(() => {
messagesEndRef.current?.scrollIntoView({ block: 'end' }); const scrollContainer = messagesScrollRef.current;
if (!scrollContainer) return;
scrollContainer.scrollTop = scrollContainer.scrollHeight;
}, [messages.length]); }, [messages.length]);
function handleSubmit(event: FormEvent<HTMLFormElement>) { function handleSubmit(event: FormEvent<HTMLFormElement>) {
@@ -1439,7 +1508,7 @@ function ChatPanel({
</span> </span>
</div> </div>
<div className="flex-1 min-h-0 overflow-y-auto px-3 py-3"> <div ref={messagesScrollRef} className="flex-1 min-h-0 overflow-y-auto px-3 py-3">
{messages.length === 0 ? ( {messages.length === 0 ? (
<div className="flex h-full items-center justify-center text-center text-xs text-base-content/25"> <div className="flex h-full items-center justify-center text-center text-xs text-base-content/25">
아직 메시지가 없습니다 아직 메시지가 없습니다
@@ -1463,7 +1532,6 @@ function ChatPanel({
))} ))}
</ol> </ol>
)} )}
<div ref={messagesEndRef} />
</div> </div>
<form onSubmit={handleSubmit} className="border-t border-base-content/10 p-2 space-y-2"> <form onSubmit={handleSubmit} className="border-t border-base-content/10 p-2 space-y-2">
+156 -61
View File
@@ -11,15 +11,33 @@ const HISTORY_MATCH_PAGE_SIZE = 10;
const EMPTY_SCHEDULE_TEXT = '예정된 매치가 없습니다.'; const EMPTY_SCHEDULE_TEXT = '예정된 매치가 없습니다.';
const HISTORY_TABLE_ROW_CLASS = const HISTORY_TABLE_ROW_CLASS =
'h-10 border-b border-base-content/5 last:border-b-0'; 'h-10 border-b border-base-content/5 last:border-b-0';
const SECTION_HEADING_CLASS =
function SkeletonBlock({ className }: { className: string }) { 'text-xs font-bold text-base-content/40 uppercase tracking-widest';
return ( const ADMIN_LINK_CLASS =
<div 'text-xs font-bold text-base-content/35 hover:text-primary';
aria-hidden="true" const STATS_LINK_CLASS = 'text-xs font-bold text-primary hover:underline';
className={`animate-pulse bg-base-content/10 ${className}`} 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({ function SkeletonText({
children, 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 }); const historySkeletons = Array.from({ length: rows });
return ( return (
@@ -118,12 +140,12 @@ function HistoryRecordsSkeleton({ rows = 5 }: { rows?: number }) {
</SkeletonText> </SkeletonText>
</td> </td>
<td className="py-2.5 px-4"> <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> </SkeletonBadge>
</td> </td>
<td className="py-2.5 px-4"> <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> </SkeletonBadge>
</td> </td>
@@ -154,13 +176,41 @@ function HistoryRecordsSkeleton({ rows = 5 }: { rows?: number }) {
className="border-b border-base-content/5 last:border-b-0 p-3" className="border-b border-base-content/5 last:border-b-0 p-3"
> >
<div className="flex items-start justify-between gap-3"> <div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1 space-y-2"> <div className="min-w-0 flex-1">
<SkeletonBlock className="h-3 w-28" /> <SkeletonText
<SkeletonBlock className="h-4 w-32" /> 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> </div>
<SkeletonBlock className="h-5 w-12 shrink-0" />
</div> </div>
<SkeletonBlock className="mt-2 h-3 w-40" />
</div> </div>
))} ))}
</div> </div>
@@ -181,58 +231,103 @@ function HomePageSkeleton() {
<section className="pt-8 pb-6"> <section className="pt-8 pb-6">
<div className="flex items-center justify-between gap-3 mb-3"> <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"> <div className="flex items-center gap-3">
<SkeletonBlock className="h-3 w-16" /> <Link
<SkeletonBlock className="h-3 w-20" /> to={`/communities/${DEFAULT_COMMUNITY_ID}/internal-stats`}
className={STATS_LINK_CLASS}
>
내전 전적 보기
</Link>
</div> </div>
</div> </div>
<div className="border border-base-content/10 bg-base-200/50"> <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="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"> <div className="flex items-center gap-2.5 flex-wrap">
<SkeletonBlock className="h-7 w-52 sm:w-64" /> <SkeletonText
<SkeletonBlock className="h-5 w-12" /> 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>
<div className="space-y-2"> <div className={NEXT_MATCH_DESCRIPTION_CLASS}>
<SkeletonBlock className="h-4 w-full max-w-xl" /> <SkeletonText skeletonClassName="h-[1em] w-full max-w-xl">
<SkeletonBlock className="h-4 w-4/5 max-w-lg" /> Socket.IO 경매 페이지 검증용으로 생성된 매치입니다.
</SkeletonText>
</div> </div>
<div className="flex items-center gap-3 flex-wrap pt-1"> <div className={NEXT_MATCH_META_CLASS}>
<SkeletonBlock className="h-3 w-24" /> <SkeletonText skeletonClassName="h-[1em] w-24">
<SkeletonBlock className="h-3 w-12" /> 6월 11일 21:00
<SkeletonBlock className="h-5 w-16" /> </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>
</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> </div>
</div> </div>
</section> </section>
<section className="pb-6"> <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"> <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) => ( {upcomingSkeletons.map((_, index) => (
<div key={index} className="bg-base-100 h-full p-4 min-h-[122px]"> <div key={index} className={UPCOMING_CARD_FRAME_CLASS}>
<div className="flex items-center justify-between mb-3 gap-3"> <div className="flex items-center justify-between mb-2.5 gap-3">
<SkeletonBlock className="h-4 w-28" /> <SkeletonText
<SkeletonBlock className="h-5 w-12 shrink-0" /> 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>
<div className="space-y-2"> <div className={UPCOMING_CARD_META_CLASS}>
<SkeletonBlock className="h-3 w-24" /> <SkeletonText skeletonClassName="h-[1em] w-24">
<SkeletonBlock className="h-3 w-12" /> 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> </div>
<SkeletonBlock className="h-5 w-16 mt-3" />
</div> </div>
))} ))}
</div> </div>
</section> </section>
<section className="pb-12"> <section className="pb-12">
<SkeletonBlock className="h-3 w-24 mb-3" /> <h2 className={`${SECTION_HEADING_CLASS} mb-3`}>
지난 내전 기록
</h2>
<HistoryRecordsSkeleton /> <HistoryRecordsSkeleton />
</section> </section>
</main> </main>
@@ -249,7 +344,7 @@ function StatusBadge({ status }: { status: string }) {
return ( return (
<span <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} {status}
</span> </span>
@@ -258,7 +353,7 @@ function StatusBadge({ status }: { status: string }) {
function MapBadge({ map }: { map: string }) { function MapBadge({ map }: { map: string }) {
return ( 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} {map}
</span> </span>
); );
@@ -302,7 +397,7 @@ function HistoryMetaText({
result?: string; result?: string;
}) { }) {
return ( 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>{map}</span>
<span className="text-base-content/20">·</span> <span className="text-base-content/20">·</span>
<span>{participants}명</span> <span>{participants}명</span>
@@ -448,21 +543,21 @@ export default function HomePage() {
<main className="max-w-5xl mx-auto px-4 sm:px-6"> <main className="max-w-5xl mx-auto px-4 sm:px-6">
<section className="pt-8 pb-6"> <section className="pt-8 pb-6">
<div className="flex items-center justify-between gap-3 mb-3"> <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> </h2>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
{canManage && ( {canManage && (
<Link <Link
to={`/admin/communities/${DEFAULT_COMMUNITY_ID}/matches`} 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>
)} )}
<Link <Link
to={`/communities/${DEFAULT_COMMUNITY_ID}/internal-stats`} to={`/communities/${DEFAULT_COMMUNITY_ID}/internal-stats`}
className="text-xs font-bold text-primary hover:underline" className={STATS_LINK_CLASS}
> >
내전 전적 보기 내전 전적 보기
</Link> </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="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
<div className="space-y-2.5"> <div className="space-y-2.5">
<div className="flex items-center gap-2.5 flex-wrap"> <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} {nextMatch.title}
</h3> </h3>
<StatusBadge status={getStatusLabel(nextMatch.status)} /> <StatusBadge status={getStatusLabel(nextMatch.status)} />
</div> </div>
<p className="text-sm text-base-content/50 max-w-xl leading-relaxed"> <p className={NEXT_MATCH_DESCRIPTION_CLASS}>
{nextMatch.description} {nextMatch.description}
</p> </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>{nextMatch.date} {nextMatch.time}</span>
<span className="text-base-content/15">|</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}명 {nextMatch.participants.length}/{nextMatch.maxParticipants}명
</span> </span>
<span className="text-base-content/15">|</span> <span className="text-base-content/15">|</span>
@@ -495,7 +590,7 @@ export default function HomePage() {
</div> </div>
</div> </div>
<div className="sm:shrink-0"> <div className="sm:shrink-0">
<span className="btn btn-secondary btn-sm px-6 text-xs font-semibold"> <span className={DETAIL_BUTTON_CLASS}>
상세 보기 상세 보기
</span> </span>
</div> </div>
@@ -513,21 +608,21 @@ export default function HomePage() {
</section> </section>
<section className="pb-6"> <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> </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"> <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.length > 0 ? (
upcomingCards.map((match) => ( upcomingCards.map((match) => (
<Link key={match.id} to={`/match/${match.id}`}> <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"> <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} {match.title}
</h3> </h3>
<StatusBadge status={getStatusLabel(match.status)} /> <StatusBadge status={getStatusLabel(match.status)} />
</div> </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.date} {match.time}</div>
<div> <div>
{match.participants.length}/{match.maxParticipants}명 {match.participants.length}/{match.maxParticipants}명
@@ -540,7 +635,7 @@ export default function HomePage() {
</Link> </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} {EMPTY_SCHEDULE_TEXT}
</div> </div>
)} )}
@@ -552,7 +647,7 @@ export default function HomePage() {
aria-busy={isHistoryPageLoading} aria-busy={isHistoryPageLoading}
aria-live="polite" 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> </h2>
{isHistoryPageLoading ? ( {isHistoryPageLoading ? (
@@ -634,11 +729,11 @@ export default function HomePage() {
> >
<div className="flex items-start justify-between gap-3"> <div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1"> <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.compactDateTime ||
`${match.date} ${match.time}`} `${match.date} ${match.time}`}
</div> </div>
<div className="mt-1 text-sm font-semibold leading-snug text-base-content break-words"> <div className={HISTORY_MOBILE_TITLE_CLASS}>
{match.title} {match.title}
</div> </div>
</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 { 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 { Link, useLocation, useParams } from "react-router";
import { import {
useDdragonManifest, useDdragonManifest,
useMatch, useMatch,
useReplaceTournamentCode,
useUserHistoryProfile, useUserHistoryProfile,
} from "../api/hooks"; } from "../api/hooks";
import { formatKoreanDate } from "../api/mappers"; import { formatKoreanDate } from "../api/mappers";
@@ -167,8 +169,10 @@ function UpcomingGameCard({
game, game,
isNext, isNext,
onToggle, onToggle,
onReplaceCode,
participantByUserId, participantByUserId,
parsedTeamIndex, parsedTeamIndex,
replacingCode,
slot, slot,
teamByIndex, teamByIndex,
}: { }: {
@@ -176,8 +180,10 @@ function UpcomingGameCard({
game?: ApiMatchGameResult; game?: ApiMatchGameResult;
isNext?: boolean; isNext?: boolean;
onToggle: () => void; onToggle: () => void;
onReplaceCode?: (slot: TournamentCodeSlotView) => void;
participantByUserId: Map<string, ApiMatchParticipant>; participantByUserId: Map<string, ApiMatchParticipant>;
parsedTeamIndex: number; parsedTeamIndex: number;
replacingCode?: boolean;
slot: TournamentCodeSlotView; slot: TournamentCodeSlotView;
teamByIndex: Map<number, ApiMatch["teams"][number]>; teamByIndex: Map<number, ApiMatch["teams"][number]>;
}) { }) {
@@ -195,6 +201,7 @@ function UpcomingGameCard({
const won = finished && game?.winnerTeamIndex === parsedTeamIndex; const won = finished && game?.winnerTeamIndex === parsedTeamIndex;
const ourSide: TeamSide = const ourSide: TeamSide =
slot.teamAIndex === parsedTeamIndex ? "blue" : "red"; slot.teamAIndex === parsedTeamIndex ? "blue" : "red";
const replaceable = Boolean(slot.code && !finished && slot.state !== "used");
async function handleCopy() { async function handleCopy() {
if (!slot.code) return; if (!slot.code) return;
@@ -306,11 +313,21 @@ function UpcomingGameCard({
</code> </code>
<button <button
type="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} onClick={handleCopy}
> >
{copied ? "복사됨" : "복사"} {copied ? "복사됨" : "복사"}
</button> </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"> <span className="text-xs font-semibold text-base-content/30">
@@ -371,9 +388,12 @@ function TeamGameCardsSection({
match, match,
participantByUserId, participantByUserId,
parsedTeamIndex, parsedTeamIndex,
replaceError,
replacingGameNumber,
teamByIndex, teamByIndex,
slots, slots,
title, title,
onReplaceCode,
}: { }: {
defaultExpandedGameNumber?: number | null; defaultExpandedGameNumber?: number | null;
emptyMessage: string; emptyMessage: string;
@@ -382,9 +402,12 @@ function TeamGameCardsSection({
match: ApiMatch; match: ApiMatch;
participantByUserId: Map<string, ApiMatchParticipant>; participantByUserId: Map<string, ApiMatchParticipant>;
parsedTeamIndex: number; parsedTeamIndex: number;
replaceError?: string | null;
replacingGameNumber?: number | null;
teamByIndex: Map<number, ApiMatch["teams"][number]>; teamByIndex: Map<number, ApiMatch["teams"][number]>;
slots: TournamentCodeSlotView[]; slots: TournamentCodeSlotView[];
title: string; title: string;
onReplaceCode?: (slot: TournamentCodeSlotView) => void;
}) { }) {
const formatted = formatKoreanDate(match.scheduledAt); const formatted = formatKoreanDate(match.scheduledAt);
const [expandedGameNumber, setExpandedGameNumber] = useState<number | null>( const [expandedGameNumber, setExpandedGameNumber] = useState<number | null>(
@@ -409,6 +432,11 @@ function TeamGameCardsSection({
</div> </div>
<div className="p-4"> <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 ? ( {isPreTeamBuilt ? (
<div className="border border-dashed border-base-content/10 px-4 py-8 text-center text-xs text-base-content/35"> <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, current === slot.gameNumber ? null : slot.gameNumber,
) )
} }
onReplaceCode={onReplaceCode}
participantByUserId={participantByUserId} participantByUserId={participantByUserId}
parsedTeamIndex={parsedTeamIndex} parsedTeamIndex={parsedTeamIndex}
replacingCode={replacingGameNumber === slot.gameNumber}
slot={slot} slot={slot}
teamByIndex={teamByIndex} teamByIndex={teamByIndex}
/> />
@@ -463,7 +493,41 @@ function buildFinishedSlot(
export default function MatchTeamProgressPage() { export default function MatchTeamProgressPage() {
const { id, teamIndex } = useParams(); const { id, teamIndex } = useParams();
const parsedTeamIndex = Number(teamIndex); const parsedTeamIndex = Number(teamIndex);
const queryClient = useQueryClient();
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); 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) { if (!DEFAULT_COMMUNITY_ID) {
return ( return (
@@ -577,8 +641,19 @@ export default function MatchTeamProgressPage() {
gameByNumber={gameByNumber} gameByNumber={gameByNumber}
isPreTeamBuilt={isPreTeamBuilt} isPreTeamBuilt={isPreTeamBuilt}
match={match} match={match}
onReplaceCode={handleReplaceTournamentCode}
participantByUserId={participantByUserId} participantByUserId={participantByUserId}
parsedTeamIndex={parsedTeamIndex} parsedTeamIndex={parsedTeamIndex}
replaceError={
replaceTournamentCodeMutation.error instanceof Error
? replaceTournamentCodeMutation.error.message
: null
}
replacingGameNumber={
replaceTournamentCodeMutation.isPending
? replaceTournamentCodeMutation.variables?.gameNumber ?? null
: null
}
teamByIndex={teamByIndex} teamByIndex={teamByIndex}
slots={activeSlots} slots={activeSlots}
title="다가오는 경기" title="다가오는 경기"
@@ -618,6 +693,86 @@ export default function MatchTeamProgressPage() {
/> />
))} ))}
</section> </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> </main>
); );
} }
+69 -1
View File
@@ -35,6 +35,21 @@ const GAME_MODE_LABEL: Record<MatchGameMode, string> = {
'round-robin': '라운드 로빈', 'round-robin': '라운드 로빈',
}; };
function resolveRoundRobinFullRoundCount(maxParticipants?: number) {
const teamCount = Math.floor(Number(maxParticipants ?? 10) / 5);
if (teamCount < 2) return 0;
return teamCount % 2 === 0 ? teamCount - 1 : teamCount;
}
function normalizeRoundRobinMaxRounds(
value: number | undefined,
maxParticipants?: number,
) {
if (!value || !Number.isFinite(value)) return undefined;
const fullRoundCount = resolveRoundRobinFullRoundCount(maxParticipants);
return Math.max(1, Math.min(fullRoundCount, Math.floor(value)));
}
function RequiredBadge() { function RequiredBadge() {
return ( return (
<span className="ml-1 inline-flex items-center border border-primary/20 bg-primary/5 px-1.5 py-0.5 text-xs font-bold text-primary"> <span className="ml-1 inline-flex items-center border border-primary/20 bg-primary/5 px-1.5 py-0.5 text-xs font-bold text-primary">
@@ -106,6 +121,7 @@ function makeForm(match?: ApiMatch): MatchMutationRequest & {
maxParticipants: match.maxParticipants, maxParticipants: match.maxParticipants,
gameCount: match.gameCount, gameCount: match.gameCount,
gameMode: match.gameMode ?? 'pair', gameMode: match.gameMode ?? 'pair',
roundRobinMaxRounds: match.roundRobinMaxRounds,
prizes: match.prizes, prizes: match.prizes,
notices: match.notices, notices: match.notices,
schedule: match.schedule, schedule: match.schedule,
@@ -138,6 +154,9 @@ export default function MatchAdminPage() {
() => [...(matchesQuery.data ?? [])].sort((a, b) => new Date(b.scheduledAt).getTime() - new Date(a.scheduledAt).getTime()), () => [...(matchesQuery.data ?? [])].sort((a, b) => new Date(b.scheduledAt).getTime() - new Date(a.scheduledAt).getTime()),
[matchesQuery.data], [matchesQuery.data],
); );
const roundRobinFullRoundCount = resolveRoundRobinFullRoundCount(
form.maxParticipants,
);
async function invalidate() { async function invalidate() {
await Promise.all([ await Promise.all([
@@ -169,6 +188,13 @@ export default function MatchAdminPage() {
maxParticipants: Number(form.maxParticipants ?? 10), maxParticipants: Number(form.maxParticipants ?? 10),
gameCount: Number(form.gameCount ?? 3), gameCount: Number(form.gameCount ?? 3),
gameMode: form.gameMode, gameMode: form.gameMode,
roundRobinMaxRounds:
form.gameMode === 'round-robin'
? normalizeRoundRobinMaxRounds(
form.roundRobinMaxRounds,
form.maxParticipants,
)
: undefined,
prizes: parseLines(form.prizesText), prizes: parseLines(form.prizesText),
notices: parseLines(form.noticesText), notices: parseLines(form.noticesText),
schedule: parseSchedule(form.scheduleText), schedule: parseSchedule(form.scheduleText),
@@ -290,7 +316,17 @@ export default function MatchAdminPage() {
정원 정원
<select <select
value={form.maxParticipants} value={form.maxParticipants}
onChange={(event) => setForm((current) => ({ ...current, maxParticipants: Number(event.target.value) }))} onChange={(event) => {
const maxParticipants = Number(event.target.value);
setForm((current) => ({
...current,
maxParticipants,
roundRobinMaxRounds: normalizeRoundRobinMaxRounds(
current.roundRobinMaxRounds,
maxParticipants,
),
}));
}}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm" className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
> >
{[10, 20, 30, 40, 50, 60].map((value) => ( {[10, 20, 30, 40, 50, 60].map((value) => (
@@ -323,6 +359,32 @@ export default function MatchAdminPage() {
현재 경매/코드 연결은 페어 방식 기준으로 동작합니다. 현재 경매/코드 연결은 페어 방식 기준으로 동작합니다.
</span> </span>
</label> </label>
{form.gameMode === 'round-robin' && (
<label className="text-xs text-base-content/45">
최대 라운드 수
<span className="ml-1 text-xs text-base-content/25">선택</span>
<input
type="number"
min={1}
max={roundRobinFullRoundCount || undefined}
placeholder="예: 3"
value={form.roundRobinMaxRounds ?? ''}
onChange={(event) =>
setForm((current) => ({
...current,
roundRobinMaxRounds:
event.target.value === ''
? undefined
: Number(event.target.value),
}))
}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
/>
<span className="mt-1 block text-xs text-base-content/30">
비워두면 전체 {roundRobinFullRoundCount}라운드로 생성됩니다.
</span>
</label>
)}
<label className="text-xs text-base-content/45"> <label className="text-xs text-base-content/45">
상품 (줄바꿈 구분) 상품 (줄바꿈 구분)
<textarea <textarea
@@ -406,6 +468,12 @@ export default function MatchAdminPage() {
</td> </td>
<td className="px-3 py-2 text-xs"> <td className="px-3 py-2 text-xs">
{GAME_MODE_LABEL[match.gameMode ?? 'pair']} {GAME_MODE_LABEL[match.gameMode ?? 'pair']}
{match.gameMode === 'round-robin' &&
match.roundRobinMaxRounds && (
<span className="block text-xs text-base-content/30">
최대 {match.roundRobinMaxRounds}R
</span>
)}
</td> </td>
<td className="px-3 py-2 text-right"> <td className="px-3 py-2 text-right">
<div className="inline-flex gap-2"> <div className="inline-flex gap-2">