Compare commits

...
7 Commits
33 changed files with 5309 additions and 238 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;
+74 -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;
} }
@@ -666,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;
@@ -676,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;
@@ -698,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;
} }
@@ -710,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;
@@ -1135,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 },
}, },
{ {
@@ -1153,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: {
@@ -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;
@@ -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;
}
@@ -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,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,12 +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 { 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, TournamentCodeReplacementController], 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,7 @@
import type { MatchDocument } from '../global/database/schema'; import {
TournamentCodeSchema,
type MatchDocument,
} from '../global/database/schema';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { TournamentCodeService } from './tournament-code.service'; import { TournamentCodeService } from './tournament-code.service';
@@ -14,6 +17,7 @@ type TournamentCodeServiceInternals = TournamentCodeService & {
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
gameNumber: number; gameNumber: number;
}): Promise<unknown>; }): Promise<unknown>;
attachPendingMatches(communityId?: mongoose.Types.ObjectId): Promise<number>;
}; };
function createService() { function createService() {
@@ -318,6 +322,89 @@ describe('TournamentCodeService round-robin scheduling', () => {
}); });
}); });
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', () => { describe('TournamentCodeService code replacement', () => {
function queryResult<T>(value: T) { function queryResult<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) }; return { exec: jest.fn().mockResolvedValue(value) };
@@ -37,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> {
@@ -121,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;
@@ -492,7 +503,7 @@ export class TournamentCodeService {
} }
private normalizeCode(code: string | undefined): string { private normalizeCode(code: string | undefined): string {
return (code ?? '').trim().toUpperCase(); return (code ?? '').trim();
} }
private replaceTournamentCodeId( private replaceTournamentCodeId(
@@ -101,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();
@@ -262,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);
+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 />}
+28 -14
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,21 +416,32 @@ 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) => {
teamIndex: team.teamIndex, const captain = team.captainUserId
name: teamIndexLabel(team.teamIndex, team.name), ? participantLookup.get(team.captainUserId)
participants: team.members.map((member) => { : undefined;
const participant =
participantLookup.get(member.userId) ??
createFallbackParticipant(member.userId);
return { return {
...participant, teamIndex: team.teamIndex,
assignedPosition: member.assignedPosition, name: teamIndexLabel(team.teamIndex, team.name),
cost: member.cost, captainUserId: team.captainUserId,
}; captainName:
}), captain?.summonerName ??
})); (team.captainUserId ? `User ${team.captainUserId.slice(-4)}` : undefined),
captainTag: captain?.tag,
participants: team.members.map((member) => {
const participant =
participantLookup.get(member.userId) ??
createFallbackParticipant(member.userId);
return {
...participant,
assignedPosition: member.assignedPosition,
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)
+70 -4
View File
@@ -562,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;
@@ -575,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;
@@ -623,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[];
} }
@@ -732,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;
@@ -752,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;
}>; }>;
}>; }>;
+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);
}
+87 -24
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>
); );
@@ -1391,13 +1453,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 +1503,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 +1527,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">
+532 -154
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQueryClient } from "@tanstack/react-query";
import { AlertTriangle, Search, X } from "lucide-react"; import { AlertTriangle, ChevronRight, Search, X } from "lucide-react";
import { Link, useLocation, useNavigate, useParams } from "react-router"; import { Link, useLocation, useNavigate, useParams } from "react-router";
import { import {
useAuction, useAuction,
@@ -29,7 +29,6 @@ import { profileIconUrl } from "../lib/ddragon";
import { import {
POSITION_ORDER, POSITION_ORDER,
positionLabel, positionLabel,
sideShortLabel,
teamIndexColorClasses, teamIndexColorClasses,
teamIndexLabel, teamIndexLabel,
} from "../lib/league"; } from "../lib/league";
@@ -44,7 +43,6 @@ import type {
ManualTournamentResultCollectResponse, ManualTournamentResultCollectResponse,
MatchGameMode, MatchGameMode,
Position, Position,
TeamSide,
TournamentCodeSlotView, TournamentCodeSlotView,
} from "../api/types"; } from "../api/types";
@@ -1311,21 +1309,33 @@ function TeamCard({
<div <div
className={`${tone.bg} px-4 py-2 flex items-center justify-between border-b ${tone.border}`} className={`${tone.bg} px-4 py-2 flex items-center justify-between border-b ${tone.border}`}
> >
<div className="flex items-center gap-2"> <div className="min-w-0">
<span <div className="flex items-center gap-2">
className={`text-xs font-bold uppercase tracking-wide ${tone.text}`} <span
> className={`text-xs font-bold uppercase tracking-wide ${tone.text}`}
{team.name} >
</span> {team.name}
{isWinner && (
<span className="inline-flex items-center text-xs font-bold px-1.5 py-0.5 bg-accent/15 text-amber-400 border border-accent/20">
WIN
</span> </span>
{isWinner && (
<span className="inline-flex items-center text-xs font-bold px-1.5 py-0.5 bg-accent/15 text-amber-400 border border-accent/20">
WIN
</span>
)}
</div>
{team.captainName && (
<div className="mt-0.5 truncate text-xs text-base-content/35">
팀장 {team.captainName}
{team.captainTag ? (
<span className="ml-1 text-base-content/20">
#{team.captainTag}
</span>
) : null}
</div>
)} )}
</div> </div>
<Link <Link
to={`/match/${matchId}/team/${team.teamIndex}`} to={`/match/${matchId}/team/${team.teamIndex}`}
className="text-xs font-bold text-base-content/35 hover:text-primary" className="shrink-0 text-xs font-bold text-base-content/35 hover:text-primary"
> >
진행 페이지 진행 페이지
</Link> </Link>
@@ -1621,28 +1631,64 @@ function PoolStatsHint({ enabled }: { enabled: boolean }) {
); );
} }
function formatGameDuration(seconds: number) { const KST_GAME_START_FORMATTER = new Intl.DateTimeFormat("ko-KR", {
const minutes = Math.floor(seconds / 60); timeZone: "Asia/Seoul",
const rest = seconds % 60; month: "numeric",
return `${minutes}:${String(rest).padStart(2, "0")}`; day: "numeric",
hour: "numeric",
minute: "2-digit",
hour12: true,
});
function formatGameStartKst(timestamp: number) {
const date = new Date(timestamp);
if (Number.isNaN(date.getTime())) return "-";
const parts = KST_GAME_START_FORMATTER.formatToParts(date);
const value = (type: Intl.DateTimeFormatPartTypes) =>
parts.find((part) => part.type === type)?.value ?? "";
const month = value("month");
const day = value("day");
const dayPeriod = value("dayPeriod");
const hour = value("hour");
const minute = value("minute");
return `${month}/${day} ${dayPeriod} ${hour}:${minute}`.trim();
} }
function resultSideClass(side: "blue" | "red") { function resolveMatchTeam(match: MatchDetailView, teamIndex: number) {
return side === "blue" ? "text-blue-400" : "text-red-400"; return match.teams.find((item) => item.teamIndex === teamIndex);
}
function resultSideLabel(side: TeamSide) {
return sideShortLabel(side);
} }
function resolveMatchTeamName(match: MatchDetailView, teamIndex: number) { function resolveMatchTeamName(match: MatchDetailView, teamIndex: number) {
const team = match.teams.find((item) => item.teamIndex === teamIndex); const team = resolveMatchTeam(match, teamIndex);
return teamIndexLabel(teamIndex, team?.name); return teamIndexLabel(teamIndex, team?.name);
} }
function resolveMatchCaptainName(match: MatchDetailView, teamIndex: number) {
return resolveMatchTeam(match, teamIndex)?.captainName ?? "팀장 미지정";
}
function getMatchResultGameCapacity(match: MatchDetailView) {
return Math.max(
match.gameCount,
match.tournamentCodes.length,
...(match.result?.games.map((game) => game.gameNumber) ?? []),
);
}
type RoundRobinStandingResult = {
gameNumber: number;
opponentTeamIndex: number;
opponentName: string;
won: boolean;
};
type RoundRobinStanding = { type RoundRobinStanding = {
teamIndex: number; teamIndex: number;
name: string; name: string;
captainName?: string;
captainTag?: string;
seriesWins: number; seriesWins: number;
seriesLosses: number; seriesLosses: number;
gameWins: number; gameWins: number;
@@ -1653,6 +1699,7 @@ type RoundRobinStanding = {
assists: number; assists: number;
kdaScore: number; kdaScore: number;
winRate: number; winRate: number;
matchResults: RoundRobinStandingResult[];
}; };
function formatRecordRate(value: number) { function formatRecordRate(value: number) {
@@ -1661,7 +1708,12 @@ function formatRecordRate(value: number) {
} }
function formatSignedNumber(value: number) { function formatSignedNumber(value: number) {
return String(value); return value > 0 ? `+${value}` : String(value);
}
function formatWinRate(value: number) {
if (!Number.isFinite(value)) return "-";
return `${Math.round(value * 100)}%`;
} }
function formatKda(standing: RoundRobinStanding) { function formatKda(standing: RoundRobinStanding) {
@@ -1679,10 +1731,13 @@ function buildRoundRobinStandings(
const getStanding = (teamIndex: number) => { const getStanding = (teamIndex: number) => {
const existing = standings.get(teamIndex); const existing = standings.get(teamIndex);
if (existing) return existing; if (existing) return existing;
const team = resolveMatchTeam(match, teamIndex);
const standing: RoundRobinStanding = { const standing: RoundRobinStanding = {
teamIndex, teamIndex,
name: resolveMatchTeamName(match, teamIndex), name: resolveMatchTeamName(match, teamIndex),
captainName: team?.captainName,
captainTag: team?.captainTag,
seriesWins: 0, seriesWins: 0,
seriesLosses: 0, seriesLosses: 0,
gameWins: 0, gameWins: 0,
@@ -1693,6 +1748,7 @@ function buildRoundRobinStandings(
assists: 0, assists: 0,
kdaScore: 0, kdaScore: 0,
winRate: 0, winRate: 0,
matchResults: [],
}; };
standings.set(teamIndex, standing); standings.set(teamIndex, standing);
return standing; return standing;
@@ -1730,6 +1786,21 @@ function buildRoundRobinStandings(
}); });
match.result?.games.forEach((game) => { match.result?.games.forEach((game) => {
const blueTeam = getStanding(game.blueTeamIndex);
const redTeam = getStanding(game.redTeamIndex);
blueTeam.matchResults.push({
gameNumber: game.gameNumber,
opponentTeamIndex: game.redTeamIndex,
opponentName: redTeam.name,
won: game.winnerTeamIndex === game.blueTeamIndex,
});
redTeam.matchResults.push({
gameNumber: game.gameNumber,
opponentTeamIndex: game.blueTeamIndex,
opponentName: blueTeam.name,
won: game.winnerTeamIndex === game.redTeamIndex,
});
game.participants.forEach((participant) => { game.participants.forEach((participant) => {
const standing = getStanding(participant.teamIndex); const standing = getStanding(participant.teamIndex);
standing.kills += participant.kills; standing.kills += participant.kills;
@@ -1746,6 +1817,9 @@ function buildRoundRobinStandings(
standing.deaths > 0 standing.deaths > 0
? (standing.kills + standing.assists) / standing.deaths ? (standing.kills + standing.assists) / standing.deaths
: standing.kills + standing.assists; : standing.kills + standing.assists;
standing.matchResults.sort(
(left, right) => left.gameNumber - right.gameNumber,
);
}); });
return [...standings.values()].sort((left, right) => { return [...standings.values()].sort((left, right) => {
@@ -1771,6 +1845,45 @@ function buildRoundRobinStandings(
}); });
} }
function StandingResultChips({
results,
limit = 4,
}: {
results: RoundRobinStandingResult[];
limit?: number;
}) {
if (results.length === 0) {
return <span className="text-xs text-base-content/25">경기 없음</span>;
}
const visibleResults = results.slice(0, limit);
const hiddenCount = Math.max(0, results.length - visibleResults.length);
return (
<div className="flex min-w-0 flex-wrap gap-1.5">
{visibleResults.map((result) => (
<span
key={`${result.gameNumber}-${result.opponentTeamIndex}`}
className={`inline-flex items-center gap-1 border px-1.5 py-0.5 text-[11px] font-semibold ${
result.won
? "border-primary/20 bg-primary/5 text-primary"
: "border-base-content/10 bg-base-200/35 text-base-content/45"
}`}
>
<span className="font-black">{result.won ? "W" : "L"}</span>
<span className="text-base-content/35">vs</span>
<span className="max-w-16 truncate">{result.opponentName}</span>
</span>
))}
{hiddenCount > 0 && (
<span className="inline-flex items-center border border-base-content/8 px-1.5 py-0.5 text-[11px] font-semibold text-base-content/35">
+{hiddenCount}
</span>
)}
</div>
);
}
function RoundRobinStandingsTable({ match }: { match: MatchDetailView }) { function RoundRobinStandingsTable({ match }: { match: MatchDetailView }) {
const standings = buildRoundRobinStandings(match); const standings = buildRoundRobinStandings(match);
@@ -1796,21 +1909,108 @@ function RoundRobinStandingsTable({ match }: { match: MatchDetailView }) {
</div> </div>
)} )}
</div> </div>
<div className="mt-4 overflow-x-auto border border-base-content/8"> <div className="mt-4 space-y-3 md:hidden">
<table className="min-w-[760px] w-full text-xs"> {standings.map((standing, index) => {
const tone = teamIndexColorClasses(standing.teamIndex);
const isWinner = match.result?.winnerTeamIndex === standing.teamIndex;
return (
<div
key={standing.teamIndex}
className={`relative border bg-base-100 p-3 ${
isWinner ? "border-primary/25" : "border-base-content/8"
}`}
>
<span
className={`absolute left-0 top-0 h-full w-0.5 ${tone.bar}`}
aria-hidden="true"
/>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="flex items-center gap-2">
<span className="inline-flex h-7 w-7 items-center justify-center bg-base-200 text-sm font-black text-base-content">
{index + 1}
</span>
<div className="min-w-0">
<div className="truncate text-sm font-black text-base-content">
{standing.name}
</div>
<div className="truncate text-xs text-base-content/35">
팀장 {standing.captainName ?? "미지정"}
{standing.captainTag ? (
<span className="ml-1 text-base-content/20">
#{standing.captainTag}
</span>
) : null}
</div>
</div>
</div>
</div>
{isWinner && (
<span className="shrink-0 border border-primary/20 bg-primary/5 px-1.5 py-0.5 text-[11px] font-bold text-primary">
1위
</span>
)}
</div>
<div className="mt-3 grid grid-cols-4 gap-2 text-center text-xs">
<div className="bg-base-200/35 px-2 py-2">
<div className="text-base-content/30">전적</div>
<div className="mt-0.5 font-black text-base-content">
{standing.seriesWins}승 {standing.seriesLosses}패
</div>
</div>
<div className="bg-base-200/35 px-2 py-2">
<div className="text-base-content/30">세트</div>
<div className="mt-0.5 font-bold tabular-nums text-base-content/75">
{standing.gameWins}-{standing.gameLosses}
</div>
</div>
<div className="bg-base-200/35 px-2 py-2">
<div className="text-base-content/30">득실</div>
<div className="mt-0.5 font-bold tabular-nums text-base-content/75">
{formatSignedNumber(standing.gameDiff)}
</div>
</div>
<div className="bg-base-200/35 px-2 py-2">
<div className="text-base-content/30">승률</div>
<div className="mt-0.5 font-bold tabular-nums text-base-content/75">
{formatWinRate(standing.winRate)}
</div>
</div>
</div>
<div className="mt-3">
<div className="mb-1 text-xs font-bold text-base-content/35">
경기 흐름
</div>
<StandingResultChips results={standing.matchResults} limit={5} />
</div>
<div className="mt-3 flex items-center justify-between border-t border-base-content/8 pt-2 text-xs">
<span className="text-base-content/35">K/D/A</span>
<span className="font-mono text-base-content/70">
{standing.kills} / {standing.deaths} / {standing.assists}
</span>
<span className="font-mono font-bold text-base-content/70">
KDA {formatKda(standing)}
</span>
</div>
</div>
);
})}
</div>
<div className="mt-4 hidden overflow-x-auto border border-base-content/8 md:block">
<table className="min-w-[920px] w-full text-xs">
<thead className="bg-base-100 text-xs text-base-content/45"> <thead className="bg-base-100 text-xs text-base-content/45">
<tr className="border-b border-base-content/8"> <tr className="border-b border-base-content/8">
<th className="h-9 px-3 text-left font-semibold">팀 순위</th> <th className="h-9 px-3 text-left font-semibold">팀 / 팀장</th>
<th className="h-9 px-3 text-center font-semibold bg-primary/5 text-primary"> <th className="h-9 px-3 text-center font-semibold bg-primary/5 text-primary">
승 전적
</th> </th>
<th className="h-9 px-3 text-center font-semibold">패</th> <th className="h-9 px-3 text-center font-semibold">세트</th>
<th className="h-9 px-3 text-center font-semibold">득실차</th> <th className="h-9 px-3 text-center font-semibold">득실</th>
<th className="h-9 px-3 text-center font-semibold">승률</th> <th className="h-9 px-3 text-center font-semibold">승률</th>
<th className="h-9 px-3 text-left font-semibold">경기 흐름</th>
<th className="h-9 px-3 text-center font-semibold">K/D/A</th>
<th className="h-9 px-3 text-center font-semibold">KDA</th> <th className="h-9 px-3 text-center font-semibold">KDA</th>
<th className="h-9 px-3 text-center font-semibold">킬</th>
<th className="h-9 px-3 text-center font-semibold">데스</th>
<th className="h-9 px-3 text-center font-semibold">어시스트</th>
</tr> </tr>
</thead> </thead>
<tbody className="divide-y divide-base-content/8 bg-base-100/60"> <tbody className="divide-y divide-base-content/8 bg-base-100/60">
@@ -1833,35 +2033,49 @@ function RoundRobinStandingsTable({ match }: { match: MatchDetailView }) {
className={`h-6 w-1 shrink-0 ${tone.bar}`} className={`h-6 w-1 shrink-0 ${tone.bar}`}
aria-hidden="true" aria-hidden="true"
/> />
<span className="min-w-0 truncate font-semibold text-base-content/85"> <div className="min-w-0">
{standing.name} <div className="flex min-w-0 items-center gap-2">
</span> <span className="min-w-0 truncate font-semibold text-base-content/85">
{standing.name}
</span>
{isWinner && (
<span className="shrink-0 border border-primary/20 bg-primary/5 px-1 py-0.5 text-[10px] font-bold text-primary">
1위
</span>
)}
</div>
<div className="mt-0.5 truncate text-xs text-base-content/35">
팀장 {standing.captainName ?? "미지정"}
{standing.captainTag ? (
<span className="ml-1 text-base-content/20">
#{standing.captainTag}
</span>
) : null}
</div>
</div>
</div> </div>
</td> </td>
<td className="h-14 px-3 text-center font-black tabular-nums bg-primary/5 text-primary"> <td className="h-14 px-3 text-center font-black tabular-nums bg-primary/5 text-primary">
{standing.seriesWins} {standing.seriesWins}승 {standing.seriesLosses}패
</td> </td>
<td className="h-14 px-3 text-center tabular-nums text-base-content/70"> <td className="h-14 px-3 text-center tabular-nums text-base-content/70">
{standing.seriesLosses} {standing.gameWins}-{standing.gameLosses}
</td> </td>
<td className="h-14 px-3 text-center tabular-nums text-base-content/70"> <td className="h-14 px-3 text-center tabular-nums text-base-content/70">
{formatSignedNumber(standing.gameDiff)} {formatSignedNumber(standing.gameDiff)}
</td> </td>
<td className="h-14 px-3 text-center tabular-nums text-base-content/70"> <td className="h-14 px-3 text-center tabular-nums text-base-content/70">
{formatRecordRate(standing.winRate)} {formatWinRate(standing.winRate)}
</td>
<td className="h-14 px-3 text-left">
<StandingResultChips results={standing.matchResults} />
</td>
<td className="h-14 px-3 text-center tabular-nums text-base-content/70">
{standing.kills} / {standing.deaths} / {standing.assists}
</td> </td>
<td className="h-14 px-3 text-center tabular-nums text-base-content/70"> <td className="h-14 px-3 text-center tabular-nums text-base-content/70">
{formatKda(standing)} {formatKda(standing)}
</td> </td>
<td className="h-14 px-3 text-center tabular-nums text-base-content/70">
{standing.kills}
</td>
<td className="h-14 px-3 text-center tabular-nums text-base-content/70">
{standing.deaths}
</td>
<td className="h-14 px-3 text-center tabular-nums text-base-content/70">
{standing.assists}
</td>
</tr> </tr>
); );
})} })}
@@ -1872,133 +2086,291 @@ function RoundRobinStandingsTable({ match }: { match: MatchDetailView }) {
); );
} }
function MatchResultPanel({ match }: { match: MatchDetailView }) { function MatchStandingsSection({ match }: { match: MatchDetailView }) {
if (!match.result) return null; if (!match.result) return null;
const gamesByNumber = new Map( const maxGameNumber = getMatchResultGameCapacity(match);
match.result.games.map((game) => [game.gameNumber, game]),
);
const maxGameNumber = Math.max(
match.gameCount,
match.tournamentCodes.length,
...match.result.games.map((game) => game.gameNumber),
);
const gameNumbers = Array.from(
{ length: maxGameNumber },
(_, index) => index + 1,
);
const seriesResults = match.result.seriesResults ?? []; const seriesResults = match.result.seriesResults ?? [];
const primarySeries = seriesResults[0]; const primarySeries = seriesResults[0];
const showRoundRobinStandings = const showRoundRobinStandings =
match.gameMode === "round-robin" && match.teams.length > 2; match.gameMode === "round-robin" && match.teams.length > 2;
if (showRoundRobinStandings) {
return <RoundRobinStandingsTable match={match} />;
}
return ( return (
<div className="mb-6 border border-base-content/10 bg-base-content/[0.02] p-5"> <>
{showRoundRobinStandings ? ( {primarySeries && (
<RoundRobinStandingsTable match={match} /> <div className="flex items-center justify-center gap-8">
) : ( <div
<> className={`text-center ${primarySeries.winnerTeamIndex === primarySeries.teamAIndex ? teamIndexColorClasses(primarySeries.teamAIndex).text : "text-base-content/30"}`}
{primarySeries && ( >
<div className="flex items-center justify-center gap-8"> <div className="text-3xl font-black tabular-nums">
<div {primarySeries.teamAWins}
className={`text-center ${primarySeries.winnerTeamIndex === primarySeries.teamAIndex ? teamIndexColorClasses(primarySeries.teamAIndex).text : "text-base-content/30"}`} </div>
> <div className="text-xs uppercase tracking-wider mt-0.5 font-semibold">
<div className="text-3xl font-black tabular-nums"> {resolveMatchTeamName(match, primarySeries.teamAIndex)}
{primarySeries.teamAWins}
</div>
<div className="text-xs uppercase tracking-wider mt-0.5 font-semibold">
{resolveMatchTeamName(match, primarySeries.teamAIndex)}
</div>
</div>
<div className="text-base-content/20 text-xs font-bold uppercase tracking-widest">
VS
</div>
<div
className={`text-center ${primarySeries.winnerTeamIndex === primarySeries.teamBIndex ? teamIndexColorClasses(primarySeries.teamBIndex).text : "text-base-content/30"}`}
>
<div className="text-3xl font-black tabular-nums">
{primarySeries.teamBWins}
</div>
<div className="text-xs uppercase tracking-wider mt-0.5 font-semibold">
{resolveMatchTeamName(match, primarySeries.teamBIndex)}
</div>
</div>
</div> </div>
)}
<div className="text-center mt-3 text-xs font-bold text-amber-400 uppercase tracking-wide">
{match.result.winner
? `${match.result.winner} 승리`
: `결과 수집 중 · ${match.result.games.length}/${maxGameNumber}경기`}
</div> </div>
{seriesResults.length > 1 && ( <div className="text-base-content/20 text-xs font-bold uppercase tracking-widest">
<div className="mt-4 grid sm:grid-cols-2 gap-2"> VS
{seriesResults.map((series) => ( </div>
<div <div
key={`${series.teamAIndex}-${series.teamBIndex}`} className={`text-center ${primarySeries.winnerTeamIndex === primarySeries.teamBIndex ? teamIndexColorClasses(primarySeries.teamBIndex).text : "text-base-content/30"}`}
className="border border-base-content/8 bg-base-100 px-3 py-2 text-xs" >
> <div className="text-3xl font-black tabular-nums">
<div className="font-bold text-base-content/55"> {primarySeries.teamBWins}
{resolveMatchTeamName(match, series.teamAIndex)} vs{" "}
{resolveMatchTeamName(match, series.teamBIndex)}
</div>
<div className="mt-1 flex items-center justify-between">
<span
className={teamIndexColorClasses(series.teamAIndex).text}
>
{series.teamAWins}
</span>
<span className="text-base-content/20">:</span>
<span
className={teamIndexColorClasses(series.teamBIndex).text}
>
{series.teamBWins}
</span>
</div>
</div>
))}
</div> </div>
)} <div className="text-xs uppercase tracking-wider mt-0.5 font-semibold">
</> {resolveMatchTeamName(match, primarySeries.teamBIndex)}
</div>
</div>
</div>
)} )}
<div className="mt-5 border border-base-content/8 divide-y divide-base-content/8"> <div className="text-center mt-3 text-xs font-bold text-amber-400 uppercase tracking-wide">
{gameNumbers.map((gameNumber) => { {match.result.winner
const game = gamesByNumber.get(gameNumber); ? `${match.result.winner} 승리`
return ( : `결과 수집 중 · ${match.result.games.length}/${maxGameNumber}경기`}
</div>
{seriesResults.length > 1 && (
<div className="mt-4 grid sm:grid-cols-2 gap-2">
{seriesResults.map((series) => (
<div <div
key={gameNumber} key={`${series.teamAIndex}-${series.teamBIndex}`}
className="grid grid-cols-[56px_1fr_auto] gap-3 items-center px-3 py-2.5 text-xs" className="border border-base-content/8 bg-base-100 px-3 py-2 text-xs"
> >
<span className="text-base-content/35 font-bold"> <div className="font-bold text-base-content/55">
{gameNumber}경기 {resolveMatchTeamName(match, series.teamAIndex)} vs{" "}
</span> {resolveMatchTeamName(match, series.teamBIndex)}
{game ? ( </div>
<div> <div className="mt-1 flex items-center justify-between">
<span <span className={teamIndexColorClasses(series.teamAIndex).text}>
className={`font-black ${resultSideClass(game.winnerSide)}`} {series.teamAWins}
> </span>
<span className="text-base-content/20">:</span>
<span className={teamIndexColorClasses(series.teamBIndex).text}>
{series.teamBWins}
</span>
</div>
</div>
))}
</div>
)}
</>
);
}
function MatchGameListSection({ match }: { match: MatchDetailView }) {
if (!match.result) return null;
const gamesByNumber = new Map(
match.result.games.map((game) => [game.gameNumber, game]),
);
const maxGameNumber = getMatchResultGameCapacity(match);
const gameNumbers = Array.from(
{ length: maxGameNumber },
(_, index) => index + 1,
);
return (
<div className="border border-base-content/8 divide-y divide-base-content/8 bg-base-100">
{gameNumbers.map((gameNumber) => {
const game = gamesByNumber.get(gameNumber);
const rowClass =
"grid grid-cols-[52px_minmax(0,1fr)_auto] gap-3 px-3 py-3 text-sm";
const content = (
<>
<span className="pt-0.5 text-xs font-bold text-base-content/35">
{gameNumber}경기
</span>
{game ? (
<div className="min-w-0 space-y-1">
<div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
<TeamNameChip match={match} teamIndex={game.blueTeamIndex} />
<span className="text-[10px] font-black text-base-content/25">
VS
</span>
<TeamNameChip match={match} teamIndex={game.redTeamIndex} />
<span className="inline-flex items-center border border-amber-500/20 bg-amber-500/8 px-1.5 py-0.5 text-[11px] font-bold text-amber-500">
{resolveMatchTeamName(match, game.winnerTeamIndex)} 승 {resolveMatchTeamName(match, game.winnerTeamIndex)} 승
</span> </span>
<span className="ml-1 text-base-content/35"> </div>
({resultSideLabel(game.winnerSide)} 진영) <div className="flex min-w-0 flex-wrap gap-x-3 gap-y-1 text-xs text-base-content/35">
<span className="min-w-0 truncate">
팀장 {resolveMatchCaptainName(match, game.blueTeamIndex)} vs{" "}
{resolveMatchCaptainName(match, game.redTeamIndex)}
</span> </span>
<span className="ml-2 text-base-content/35 font-mono"> <span className="font-mono text-[11px] text-base-content/25">
{game.riotMatchId} {game.riotMatchId}
</span> </span>
</div> </div>
) : ( </div>
<span className="text-base-content/25">대기 중</span> ) : (
)} <div className="min-w-0 text-base-content/30">대기 중</div>
<span className="text-base-content/35 font-mono"> )}
{game ? formatGameDuration(game.gameDuration) : "-"} {game ? (
<span className="flex shrink-0 items-center justify-end gap-3 pt-0.5">
<span className="whitespace-nowrap text-right text-xs font-medium text-base-content/45">
{formatGameStartKst(game.gameCreation)}
</span>
<span className="inline-flex h-7 w-7 items-center justify-center text-primary/70 transition-colors group-hover:text-primary">
<ChevronRight className="h-4 w-4 transition-transform group-hover:translate-x-0.5" />
</span>
</span> </span>
</div> ) : (
<span className="shrink-0 pt-0.5 text-right text-xs text-base-content/25">
-
</span>
)}
</>
);
if (game) {
return (
<Link
key={gameNumber}
to={`/match/${match.id}/game/${gameNumber}`}
className={`${rowClass} group transition-colors hover:bg-primary/5 focus-visible:bg-primary/8 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary`}
aria-label={`${gameNumber}경기 ${resolveMatchTeamName(match, game.blueTeamIndex)} 대 ${resolveMatchTeamName(match, game.redTeamIndex)} 상세 보기`}
>
{content}
</Link>
); );
})} }
return (
<div key={gameNumber} className={rowClass}>
{content}
</div>
);
})}
</div>
);
}
function TeamNameChip({
match,
teamIndex,
}: {
match: MatchDetailView;
teamIndex: number;
}) {
const tone = teamIndexColorClasses(teamIndex);
return (
<span className="inline-flex min-w-0 items-center gap-1.5 font-semibold text-base-content/75">
<span className={`h-1.5 w-1.5 shrink-0 rounded-full ${tone.bar}`} />
<span className="truncate">{resolveMatchTeamName(match, teamIndex)}</span>
</span>
);
}
function MatchResultPanel({ match }: { match: MatchDetailView }) {
if (!match.result) return null;
return (
<div className="mb-6 space-y-4">
<div className="border border-base-content/10 bg-base-content/[0.02] p-5">
<MatchStandingsSection match={match} />
<div className="mt-5">
<MatchGameListSection match={match} />
</div>
</div> </div>
</div> </div>
); );
} }
type FinishedResultTab = "standings" | "games" | "teams" | "info";
function FinishedMatchTabs({ match }: { match: MatchDetailView }) {
const [resultTab, setResultTab] = useState<FinishedResultTab>("standings");
const hasInfo = match.prizes.length > 0 || match.notices.length > 0;
const tabs: Array<{ id: FinishedResultTab; label: string }> = [
{ id: "standings", label: "순위표" },
{ id: "games", label: "경기결과" },
{ id: "teams", label: "팀 빌딩" },
...(hasInfo
? [{ id: "info" as FinishedResultTab, label: "대회 정보" }]
: []),
];
const activeTab =
resultTab === "info" && !hasInfo ? "standings" : resultTab;
return (
<div className="mb-6 space-y-4">
<div className="flex overflow-x-auto border border-base-content/10 bg-base-100">
{tabs.map((item) => (
<button
key={item.id}
type="button"
onClick={() => setResultTab(item.id)}
className={`min-w-[7.5rem] border-r border-b-2 border-base-content/8 px-4 py-3 text-xs font-bold transition-colors last:border-r-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary ${
activeTab === item.id
? "border-b-primary bg-base-200/50 text-base-content"
: "border-b-transparent text-base-content/45 hover:bg-base-content/[0.03] hover:text-base-content"
}`}
>
{item.label}
</button>
))}
</div>
{activeTab === "standings" && (
<div className="border border-base-content/10 bg-base-content/[0.02] p-5">
<MatchStandingsSection match={match} />
</div>
)}
{activeTab === "games" && <MatchGameListSection match={match} />}
{activeTab === "teams" && (
<div className="space-y-4">
{match.teams.map((team) => (
<TeamCard
key={team.teamIndex}
team={team}
matchId={match.id}
isWinner={match.result?.winnerTeamIndex === team.teamIndex}
/>
))}
</div>
)}
{activeTab === "info" && (
<div className="grid gap-4 sm:grid-cols-2">
{match.prizes.length > 0 && (
<SideCard title="상품">
<ul className="space-y-1.5">
{match.prizes.map((prize, index) => (
<li
key={index}
className="flex items-start gap-2 text-sm text-base-content/60"
>
<span className="text-accent shrink-0 text-xs">▸</span>
<span>{prize}</span>
</li>
))}
</ul>
</SideCard>
)}
{match.notices.length > 0 && (
<SideCard title="안내사항">
<ul className="space-y-1.5">
{match.notices.map((notice, index) => (
<li
key={index}
className="flex items-start gap-2 text-sm text-base-content/60"
>
<span className="text-info shrink-0 font-bold">•</span>
<span>{notice}</span>
</li>
))}
</ul>
</SideCard>
)}
</div>
)}
</div>
);
}
export default function MatchDetailPage() { export default function MatchDetailPage() {
const { id } = useParams(); const { id } = useParams();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -2507,10 +2879,14 @@ export default function MatchDetailPage() {
</div> </div>
)} )}
<MatchResultPanel match={match} /> {match.status === "finished" ? (
<FinishedMatchTabs match={match} />
) : (
<>
<MatchResultPanel match={match} />
<div className="flex flex-col lg:flex-row gap-5"> <div className="flex flex-col lg:flex-row gap-5">
<div className="flex-1 min-w-0 space-y-4"> <div className="flex-1 min-w-0 space-y-4">
{match.status === "recruiting" ? ( {match.status === "recruiting" ? (
<> <>
<ParticipantTable <ParticipantTable
@@ -3084,8 +3460,10 @@ export default function MatchDetailPage() {
</ul> </ul>
</SideCard> </SideCard>
)} )}
</div> </div>
</div> </div>
</>
)}
{replaceCodeSlot && ( {replaceCodeSlot && (
<div <div
File diff suppressed because it is too large. Load diff