From 7b5604873e0e5ae89d02d4351714c1ce0af8e551 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=EB=8B=A4=ED=98=84=20=28Dahyeon=20Park=29?= Date: Sat, 20 Jun 2026 07:26:20 +0900 Subject: [PATCH] feat: add match game detail analytics --- .../community-stats/community-stats.module.ts | 2 + .../community-stats.service.ts | 27 +- .../community-stats/community-stats.types.ts | 44 +- .../match-stats-fragment.builder.spec.ts | 298 +++ .../match-stats-fragment.builder.ts | 385 +++- .../match-stats.service.spec.ts | 21 +- .../community-stats/match-stats.service.ts | 89 +- .../community-stats/match-stats.types.ts | 2 +- .../api/src/modules/global/database/schema.ts | 75 +- .../match-history/match-history.types.ts | 6 +- .../modules/riot/riot-match.service.spec.ts | 108 + .../src/modules/riot/riot-match.service.ts | 261 +++ apps/api/src/modules/riot/riot.types.ts | 54 + apps/web/src/App.tsx | 5 + apps/web/src/api/types.ts | 73 +- apps/web/src/lib/ddragon.ts | 7 + apps/web/src/pages/MatchDetailPage.tsx | 46 +- apps/web/src/pages/MatchGameDetailPage.tsx | 1995 +++++++++++++++++ 18 files changed, 3452 insertions(+), 46 deletions(-) create mode 100644 apps/web/src/pages/MatchGameDetailPage.tsx diff --git a/apps/api/src/modules/community-stats/community-stats.module.ts b/apps/api/src/modules/community-stats/community-stats.module.ts index 4be3ae42..9b19a740 100644 --- a/apps/api/src/modules/community-stats/community-stats.module.ts +++ b/apps/api/src/modules/community-stats/community-stats.module.ts @@ -1,4 +1,5 @@ import { Module } from '@nestjs/common'; +import { RiotModule } from '../riot/riot.module'; import { CommunityStatsCacheService } from './community-stats-cache.service'; import { CommunityStatsController } from './community-stats.controller'; import { CommunityStatsService } from './community-stats.service'; @@ -7,6 +8,7 @@ import { MatchStatsRepository } from './match-stats.repository'; import { MatchStatsService } from './match-stats.service'; @Module({ + imports: [RiotModule], controllers: [CommunityStatsController], providers: [ CommunityStatsService, diff --git a/apps/api/src/modules/community-stats/community-stats.service.ts b/apps/api/src/modules/community-stats/community-stats.service.ts index df89ea56..bd42cbed 100644 --- a/apps/api/src/modules/community-stats/community-stats.service.ts +++ b/apps/api/src/modules/community-stats/community-stats.service.ts @@ -205,7 +205,7 @@ export class CommunityStatsService { communityId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId; }): Promise { - const key = `riot:communitystats:matchDetail:${params.communityId.toString()}:${params.matchId.toString()}`; + const key = `riot:communitystats:matchDetail:v${MATCH_STATS_BUILDER_VERSION}:${params.communityId.toString()}:${params.matchId.toString()}`; const cached = await this.cacheService.get(key); if (cached) return cached; @@ -217,19 +217,33 @@ export class CommunityStatsService { (item) => item.matchId === params.matchId.toString(), ); if (!match) throw new NotFoundException('Internal match not found.'); + let gameDetails = dataset.detailsByMatchId.get(match.matchId) ?? []; + if (gameDetails.some((game) => game.timelineLoaded !== true)) { + await this.matchStatsService.buildAndUpsert(params.matchId, { + includeTimeline: true, + }); + const refreshedDataset = await this.buildBaseDataset(params.communityId, { + seasonId: 'all', + }); + gameDetails = refreshedDataset.detailsByMatchId.get(match.matchId) ?? []; + } const response: InternalMatchDetailResponse = { match, - games: (dataset.detailsByMatchId.get(match.matchId) ?? []).map( + games: gameDetails.map( (game) => ({ gameNumber: game.gameNumber, riotMatchId: game.riotMatchId, gameCreation: game.gameCreation, gameDuration: game.gameDuration, + gameVersion: game.gameVersion, + timeline: game.timeline ?? [], + objectiveEvents: game.objectiveEvents ?? [], teams: game.teams.map((team) => ({ teamIndex: team.teamIndex, side: team.side, win: team.win, objectives: team.objectives, + bans: team.bans ?? [], participants: team.participants.map((record) => ({ userId: record.userId, summonerName: record.summonerName, @@ -237,6 +251,7 @@ export class CommunityStatsService { side: record.side, teamPosition: record.teamPosition, championId: record.championId, + championLevel: record.championLevel, kills: record.kills, deaths: record.deaths, assists: record.assists, @@ -245,13 +260,21 @@ export class CommunityStatsService { gold: record.gold, gpm: record.gpm, damageDealtToChampions: record.damageDealtToChampions, + damageTaken: record.damageTaken, damageShare: record.damageShare, killParticipation: record.killParticipation, visionScore: record.visionScore, + wardsPlaced: record.wardsPlaced, + wardsKilled: record.wardsKilled, + controlWardsBought: record.controlWardsBought, + firstBloodKill: record.firstBloodKill ?? false, + firstBloodAssist: record.firstBloodAssist ?? false, items: record.items, trinket: record.trinket, summonerSpells: record.summonerSpells, perks: record.perks, + itemBuild: record.itemBuild ?? [], + skillBuild: record.skillBuild ?? [], win: record.win, })), })), diff --git a/apps/api/src/modules/community-stats/community-stats.types.ts b/apps/api/src/modules/community-stats/community-stats.types.ts index ec381dea..5fcbf5fe 100644 --- a/apps/api/src/modules/community-stats/community-stats.types.ts +++ b/apps/api/src/modules/community-stats/community-stats.types.ts @@ -1,4 +1,10 @@ -import type { RiotLane, TeamSide } from '../global/database/schema'; +import type { + MatchStatsItemBuildEvent, + MatchStatsRunePerks, + MatchStatsSkillBuildEvent, + RiotLane, + TeamSide, +} from '../global/database/schema'; import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types'; export interface CommunityStatsFilters { @@ -108,11 +114,34 @@ export interface InternalMatchDetailResponse { riotMatchId: string; gameCreation: number; gameDuration: number; + gameVersion?: string; + timeline: Array<{ + timestamp: number; + blue: { gold: number; xp: number }; + red: { gold: number; xp: number }; + goldDiff: number; + xpDiff: number; + }>; + objectiveEvents: Array<{ + timestamp: number; + side: TeamSide; + type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub'; + monsterSubType?: string; + }>; teams: Array<{ teamIndex: number; side: TeamSide; win: boolean; - objectives: { baron: number; dragon: number; tower: number }; + objectives: { + tower: number; + dragon: number; + inhibitor: number; + baron: number; + riftHerald: number; + voidGrub: number; + elderDragon: number; + }; + bans: Array<{ championId: number; pickTurn: number }>; participants: Array<{ userId: string | null; summonerName: string; @@ -120,6 +149,7 @@ export interface InternalMatchDetailResponse { side: TeamSide; teamPosition: string; championId: number; + championLevel: number; kills: number; deaths: number; assists: number; @@ -128,13 +158,21 @@ export interface InternalMatchDetailResponse { gold: number; gpm: number; damageDealtToChampions: number; + damageTaken: number; damageShare: number; killParticipation: number; visionScore: number; + wardsPlaced: number; + wardsKilled: number; + controlWardsBought: number; + firstBloodKill: boolean; + firstBloodAssist: boolean; items: number[]; trinket: number; summonerSpells: [number, number]; - perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + perks: MatchStatsRunePerks; + itemBuild: MatchStatsItemBuildEvent[]; + skillBuild: MatchStatsSkillBuildEvent[]; win: boolean; }>; }>; diff --git a/apps/api/src/modules/community-stats/match-stats-fragment.builder.spec.ts b/apps/api/src/modules/community-stats/match-stats-fragment.builder.spec.ts index 3f5c9b1f..c7fde734 100644 --- a/apps/api/src/modules/community-stats/match-stats-fragment.builder.spec.ts +++ b/apps/api/src/modules/community-stats/match-stats-fragment.builder.spec.ts @@ -1,5 +1,6 @@ import mongoose from 'mongoose'; import type { MatchDocument } from '../global/database/schema'; +import type { RiotMatchDto, RiotMatchTimelineDto } from '../riot/riot.types'; import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder'; function makeMatch(): MatchDocument { @@ -95,4 +96,301 @@ describe('MatchStatsFragmentBuilder', () => { }); expect(fragment.gameDetails[0].teams[0].participants).toHaveLength(1); }); + + it('builds rich set detail from raw Riot match data', () => { + const builder = new MatchStatsFragmentBuilder(); + const match = makeMatch(); + const raw = { + metadata: { + dataVersion: '2', + matchId: 'KR_1', + participants: ['puuid-1'], + }, + info: { + gameCreation: 1_000, + gameDuration: 1_800, + gameId: 1, + gameMode: 'CLASSIC', + gameName: 'teambuilder-match-1', + gameStartTimestamp: 1_000, + gameType: 'CUSTOM_GAME', + gameVersion: '16.11.1.1234', + mapId: 11, + participants: [ + { + assists: 7, + champExperience: 15_000, + champLevel: 15, + championId: 266, + championName: 'Aatrox', + deaths: 1, + firstBloodAssist: false, + firstBloodKill: true, + goldEarned: 12_345, + goldSpent: 11_000, + individualPosition: 'TOP', + item0: 1054, + item1: 3071, + item2: 0, + item3: 0, + item4: 0, + item5: 0, + item6: 3340, + kills: 5, + neutralMinionsKilled: 8, + participantId: 1, + perks: { + statPerks: { defense: 5001, flex: 5008, offense: 5005 }, + styles: [ + { + description: 'primaryStyle', + style: 8000, + selections: [ + { perk: 8010, var1: 0, var2: 0, var3: 0 }, + { perk: 9111, var1: 0, var2: 0, var3: 0 }, + { perk: 9105, var1: 0, var2: 0, var3: 0 }, + { perk: 8299, var1: 0, var2: 0, var3: 0 }, + ], + }, + { + description: 'subStyle', + style: 8400, + selections: [ + { perk: 8444, var1: 0, var2: 0, var3: 0 }, + { perk: 8451, var1: 0, var2: 0, var3: 0 }, + ], + }, + ], + }, + puuid: 'puuid-1', + riotIdGameName: 'Player', + riotIdTagLine: 'KR1', + summoner1Id: 4, + summoner2Id: 12, + summonerId: 'summoner-1', + summonerLevel: 100, + summonerName: 'Player', + teamId: 100, + teamPosition: 'TOP', + timePlayed: 1_800, + totalDamageDealtToChampions: 18_765, + totalDamageTaken: 24_321, + totalMinionsKilled: 220, + visionScore: 18, + visionWardsBoughtInGame: 2, + wardsKilled: 3, + wardsPlaced: 11, + win: true, + }, + ], + platformId: 'KR', + queueId: 0, + teams: [ + { + bans: [ + { championId: 14, pickTurn: 1 }, + { championId: 43, pickTurn: 2 }, + ], + objectives: { + baron: { first: true, kills: 1 }, + champion: { first: true, kills: 5 }, + dragon: { first: true, kills: 2 }, + horde: { first: false, kills: 3 }, + inhibitor: { first: false, kills: 0 }, + riftHerald: { first: false, kills: 0 }, + tower: { first: true, kills: 7 }, + }, + teamId: 100, + win: true, + }, + ], + }, + }; + const timeline = { + metadata: { + dataVersion: '2', + matchId: 'KR_1', + participants: ['puuid-1'], + }, + info: { + frameInterval: 60_000, + frames: [ + { + timestamp: 0, + participantFrames: { + '1': { participantId: 1, totalGold: 500, xp: 0 }, + }, + }, + { + timestamp: 60_000, + events: [ + { + type: 'ITEM_PURCHASED', + timestamp: 10_000, + participantId: 1, + itemId: 1054, + }, + { + type: 'SKILL_LEVEL_UP', + timestamp: 11_000, + participantId: 1, + skillSlot: 1, + levelUpType: 'NORMAL', + }, + { + type: 'ITEM_DESTROYED', + timestamp: 12_000, + participantId: 1, + itemId: 2003, + }, + { + type: 'ITEM_UNDO', + timestamp: 13_000, + participantId: 1, + beforeId: 1054, + afterId: 3071, + }, + { + type: 'ELITE_MONSTER_KILL', + timestamp: 20_000, + killerTeamId: 100, + monsterType: 'DRAGON', + monsterSubType: 'FIRE_DRAGON', + }, + { + type: 'ELITE_MONSTER_KILL', + timestamp: 30_000, + killerTeamId: 100, + monsterType: 'DRAGON', + monsterSubType: 'ELDER_DRAGON', + }, + { + type: 'ELITE_MONSTER_KILL', + timestamp: 40_000, + killerId: 1, + monsterType: 'HORDE', + }, + { + type: 'SKILL_LEVEL_UP', + timestamp: 45_000, + participantId: 1, + skillSlot: 3, + levelUpType: 'NORMAL', + }, + { + type: 'ELITE_MONSTER_KILL', + timestamp: 50_000, + killerTeamId: 100, + monsterType: 'BARON_NASHOR', + }, + { + type: 'ELITE_MONSTER_KILL', + timestamp: 55_000, + killerTeamId: 100, + monsterType: 'RIFTHERALD', + }, + ], + participantFrames: { + '1': { participantId: 1, totalGold: 1_150, xp: 550 }, + }, + }, + ], + }, + }; + + const fragment = builder.buildFragment({ + match, + rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]), + timelineByRiotMatchId: new Map([ + ['KR_1', timeline as RiotMatchTimelineDto], + ]), + }); + + expect(fragment.gameDetails[0]).toMatchObject({ + gameVersion: '16.11.1.1234', + objectiveEvents: [ + { + timestamp: 20, + side: 'blue', + type: 'dragon', + monsterSubType: 'FIRE_DRAGON', + }, + { + timestamp: 30, + side: 'blue', + type: 'elderDragon', + monsterSubType: 'ELDER_DRAGON', + }, + { timestamp: 40, side: 'blue', type: 'voidGrub' }, + { timestamp: 50, side: 'blue', type: 'baron' }, + { timestamp: 55, side: 'blue', type: 'riftHerald' }, + ], + timeline: [ + { + timestamp: 0, + blue: { gold: 500, xp: 0 }, + red: { gold: 0, xp: 0 }, + goldDiff: 500, + xpDiff: 0, + }, + { + timestamp: 60, + blue: { gold: 1_150, xp: 550 }, + red: { gold: 0, xp: 0 }, + goldDiff: 1_150, + xpDiff: 550, + }, + ], + }); + expect(fragment.gameDetails[0].teams[0].bans).toEqual([ + { championId: 14, pickTurn: 1 }, + { championId: 43, pickTurn: 2 }, + ]); + expect(fragment.gameDetails[0].teams[0].objectives).toMatchObject({ + baron: 1, + dragon: 1, + elderDragon: 1, + inhibitor: 0, + riftHerald: 1, + tower: 7, + voidGrub: 1, + }); + expect(fragment.records[0]).toMatchObject({ + championLevel: 15, + cs: 228, + damageDealtToChampions: 18_765, + damageTaken: 24_321, + firstBloodKill: true, + firstBloodAssist: false, + controlWardsBought: 2, + wardsKilled: 3, + wardsPlaced: 11, + perks: { + primaryStyle: 8000, + subStyle: 8400, + keystone: 8010, + selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451], + styles: [ + { styleId: 8000, perkIds: [8010, 9111, 9105, 8299] }, + { styleId: 8400, perkIds: [8444, 8451] }, + ], + statPerks: { defense: 5001, flex: 5008, offense: 5005 }, + }, + itemBuild: [ + { timestamp: 10, itemId: 1054, type: 'purchased' }, + { timestamp: 12, itemId: 2003, type: 'destroyed' }, + { + timestamp: 13, + itemId: 3071, + type: 'undo', + beforeId: 1054, + afterId: 3071, + }, + ], + skillBuild: [ + { timestamp: 11, skillSlot: 1, level: 1, levelUpType: 'NORMAL' }, + { timestamp: 45, skillSlot: 3, level: 2, levelUpType: 'NORMAL' }, + ], + }); + }); }); diff --git a/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts b/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts index b4a10c0d..2f49ea7b 100644 --- a/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts +++ b/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts @@ -3,9 +3,18 @@ import mongoose from 'mongoose'; import type { MatchDocument, MatchGameResultParticipant, + MatchStatsItemBuildEvent, + MatchStatsObjectiveEvent, + MatchStatsObjectiveSummary, + MatchStatsSkillBuildEvent, + MatchStatsTimelinePoint, TeamSide, } from '../global/database/schema'; -import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types'; +import type { + RiotMatchDto, + RiotMatchParticipantDto, + RiotMatchTimelineDto, +} from '../riot/riot.types'; import type { InternalMatchCardView } from './community-stats.types'; import type { InternalGameDetail, @@ -13,11 +22,18 @@ import type { MatchStatsFragment, } from './match-stats.types'; +interface ParticipantBuildEvents { + items: MatchStatsItemBuildEvent[]; + skills: MatchStatsSkillBuildEvent[]; +} + @Injectable() export class MatchStatsFragmentBuilder { public buildFragment(params: { match: MatchDocument; rawByRiotMatchId: Map; + timelineByRiotMatchId?: Map; + timelineLoadAttempted?: boolean; }): MatchStatsFragment { const games = [...(params.match.result?.games ?? [])].sort( (left, right) => left.gameNumber - right.gameNumber, @@ -25,8 +41,15 @@ export class MatchStatsFragmentBuilder { const matchCard = this.toMatchCard(params.match, games); const gameDetails = games.map((game) => { const raw = params.rawByRiotMatchId.get(game.riotMatchId); + const timeline = params.timelineByRiotMatchId?.get(game.riotMatchId); return raw - ? this.toGameDetail(params.match, game, raw) + ? this.toGameDetail( + params.match, + game, + raw, + timeline, + params.timelineLoadAttempted === true, + ) : this.toFallbackGameDetail(params.match, game); }); const records = gameDetails.flatMap((detail) => @@ -106,6 +129,8 @@ export class MatchStatsFragmentBuilder { match: MatchDocument, game: NonNullable['games'][number], raw: RiotMatchDto, + timeline?: RiotMatchTimelineDto, + timelineLoadAttempted = false, ): InternalGameDetail { const puuidByUserId = new Map( match.participants @@ -129,13 +154,29 @@ export class MatchStatsFragmentBuilder { rawTeamIdBySide.set(participant.side, rawParticipant.teamId); } } + const sideByParticipantId = this.toSideByParticipantId( + raw, + rawTeamIdBySide, + ); + const objectiveEvents = this.toObjectiveEvents( + timeline, + rawTeamIdBySide, + sideByParticipantId, + ); + const timelineObjectives = this.toTimelineObjectives(objectiveEvents); + const buildEventsByParticipantId = + this.toBuildEventsByParticipantId(timeline); return { gameNumber: game.gameNumber, riotMatchId: game.riotMatchId, gameCreation: game.gameCreation, gameDuration: game.gameDuration, + gameVersion: raw.info.gameVersion, winnerSide: game.winnerSide, + timeline: this.toTimeline(raw, rawTeamIdBySide, timeline), + timelineLoaded: timelineLoadAttempted || Boolean(timeline), + objectiveEvents, teams: (['blue', 'red'] as TeamSide[]).map((side) => { const teamIndex = side === 'blue' ? game.blueTeamIndex : game.redTeamIndex; @@ -158,25 +199,35 @@ export class MatchStatsFragmentBuilder { teamIndex, side, win: game.winnerSide === side, - objectives: { - baron: rawTeam?.objectives?.baron?.kills ?? 0, - dragon: rawTeam?.objectives?.dragon?.kills ?? 0, - tower: rawTeam?.objectives?.tower?.kills ?? 0, - }, + objectives: this.toObjectiveSummary( + rawTeam, + timelineObjectives.get(side), + Boolean(timeline), + ), + bans: (rawTeam?.bans ?? []).map((ban) => ({ + championId: ban.championId, + pickTurn: ban.pickTurn, + })), participants: game.participants .filter((participant) => participant.side === side) - .map((participant) => - this.toRecord({ + .map((participant) => { + const rawParticipant = rawByPuuid.get( + puuidByUserId.get(participant.userId.toString()) ?? '', + ); + return this.toRecord({ match, game, participant, - rawParticipant: rawByPuuid.get( - puuidByUserId.get(participant.userId.toString()) ?? '', - ), + rawParticipant, + buildEvents: rawParticipant + ? buildEventsByParticipantId.get( + rawParticipant.participantId, + ) + : undefined, teamKills, teamDamage, - }), - ), + }); + }), }; }), }; @@ -192,11 +243,15 @@ export class MatchStatsFragmentBuilder { gameCreation: game.gameCreation, gameDuration: game.gameDuration, winnerSide: game.winnerSide, + timeline: [], + timelineLoaded: false, + objectiveEvents: [], teams: (['blue', 'red'] as TeamSide[]).map((side) => ({ teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex, side, win: game.winnerSide === side, - objectives: { baron: 0, dragon: 0, tower: 0 }, + objectives: emptyObjectives(), + bans: [], participants: game.participants .filter((participant) => participant.side === side) .map((participant) => @@ -217,11 +272,19 @@ export class MatchStatsFragmentBuilder { game: NonNullable['games'][number]; participant: MatchGameResultParticipant; rawParticipant?: RiotMatchParticipantDto; + buildEvents?: ParticipantBuildEvents; teamKills: number; teamDamage: number; }): InternalRecord { - const { match, game, participant, rawParticipant, teamKills, teamDamage } = - params; + const { + match, + game, + participant, + rawParticipant, + buildEvents, + teamKills, + teamDamage, + } = params; const snapshot = match.participants.find((item) => item.userId.equals(participant.userId), ); @@ -290,6 +353,8 @@ export class MatchStatsFragmentBuilder { ), wardsPlaced: rawParticipant?.wardsPlaced ?? 0, wardsKilled: rawParticipant?.wardsKilled ?? 0, + firstBloodKill: booleanField(rawParticipant, 'firstBloodKill'), + firstBloodAssist: booleanField(rawParticipant, 'firstBloodAssist'), items: [ rawParticipant?.item0 ?? 0, rawParticipant?.item1 ?? 0, @@ -304,6 +369,8 @@ export class MatchStatsFragmentBuilder { rawParticipant?.summoner2Id ?? 0, ], perks: rawParticipant ? this.resolvePerks(rawParticipant) : {}, + itemBuild: buildEvents?.items ?? [], + skillBuild: buildEvents?.skills ?? [], rating, }; } @@ -319,6 +386,250 @@ export class MatchStatsFragmentBuilder { primaryStyle: primary?.style, subStyle: sub?.style, keystone: primary?.selections[0]?.perk, + selectedPerkIds: participant.perks.styles.flatMap((style) => + style.selections.map((selection) => selection.perk), + ), + styles: participant.perks.styles.map((style) => ({ + styleId: style.style, + perkIds: style.selections.map((selection) => selection.perk), + })), + statPerks: { + offense: participant.perks.statPerks.offense, + flex: participant.perks.statPerks.flex, + defense: participant.perks.statPerks.defense, + }, + }; + } + + private toBuildEventsByParticipantId( + timeline?: RiotMatchTimelineDto, + ): Map { + const buildEventsByParticipantId = new Map(); + 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, + 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, + ): Map { + const blueTeamId = rawTeamIdBySide.get('blue') ?? 100; + const redTeamId = rawTeamIdBySide.get('red') ?? 200; + const sideByParticipantId = new Map(); + 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, + sideByParticipantId: Map, + ): MatchStatsObjectiveEvent[] { + if (!timeline?.info.frames.length) return []; + + const sideByTeamId = new Map(); + 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 { + const objectives = new Map([ + ['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 +665,27 @@ function average(value: number, total: number): number { return total > 0 ? round(value / total) : 0; } +function isSkillSlot(value: number | undefined): value is 1 | 2 | 3 | 4 { + return value === 1 || value === 2 || value === 3 || value === 4; +} + +function toItemBuildType( + value: string, +): MatchStatsItemBuildEvent['type'] | null { + switch (value) { + case 'ITEM_PURCHASED': + return 'purchased'; + case 'ITEM_SOLD': + return 'sold'; + case 'ITEM_DESTROYED': + return 'destroyed'; + case 'ITEM_UNDO': + return 'undo'; + default: + return null; + } +} + function round(value: number): number { return Math.round(value * 10) / 10; } @@ -365,3 +697,22 @@ function numberField( const value = participant?.[key]; return typeof value === 'number' && Number.isFinite(value) ? value : 0; } + +function booleanField( + participant: RiotMatchParticipantDto | undefined, + key: string, +): boolean { + return participant?.[key] === true; +} + +function emptyObjectives(): MatchStatsObjectiveSummary { + return { + tower: 0, + dragon: 0, + inhibitor: 0, + baron: 0, + riftHerald: 0, + voidGrub: 0, + elderDragon: 0, + }; +} diff --git a/apps/api/src/modules/community-stats/match-stats.service.spec.ts b/apps/api/src/modules/community-stats/match-stats.service.spec.ts index 552cca15..2e5c9945 100644 --- a/apps/api/src/modules/community-stats/match-stats.service.spec.ts +++ b/apps/api/src/modules/community-stats/match-stats.service.spec.ts @@ -29,6 +29,7 @@ describe('MatchStatsService', () => { connectionService, repository, {} as MatchStatsFragmentBuilder, + { getMatchTimeline: jest.fn() } as never, ); await service.buildAndUpsert(matchId); @@ -53,7 +54,20 @@ describe('MatchStatsService', () => { }); const riotFind = jest.fn().mockReturnValue({ lean: () => ({ - exec: jest.fn().mockResolvedValue([{ matchId: 'KR_1', raw: {} }]), + exec: jest.fn().mockResolvedValue([ + { + matchId: 'KR_1', + raw: {}, + timeline: { + metadata: { + dataVersion: '2', + matchId: 'KR_1', + participants: [], + }, + info: { frameInterval: 60_000, frames: [] }, + }, + }, + ]), }), }); const connectionService = { @@ -82,6 +96,7 @@ describe('MatchStatsService', () => { connectionService, repository, builder, + { getMatchTimeline: jest.fn() } as never, ); await service.buildAndUpsert(matchId); @@ -89,6 +104,8 @@ describe('MatchStatsService', () => { expect(builder.buildFragment).toHaveBeenCalledWith({ match, rawByRiotMatchId: expect.any(Map), + timelineByRiotMatchId: expect.any(Map), + timelineLoadAttempted: false, }); expect(repository.upsert).toHaveBeenCalledWith( expect.objectContaining({ @@ -97,7 +114,7 @@ describe('MatchStatsService', () => { scheduledAt, gameCreationMin: 1_000, gameCreationMax: 2_000, - builderVersion: 1, + builderVersion: 7, }), ); }); diff --git a/apps/api/src/modules/community-stats/match-stats.service.ts b/apps/api/src/modules/community-stats/match-stats.service.ts index 00381a9d..6ae8c19a 100644 --- a/apps/api/src/modules/community-stats/match-stats.service.ts +++ b/apps/api/src/modules/community-stats/match-stats.service.ts @@ -1,21 +1,33 @@ -import { Injectable } from '@nestjs/common'; +import { Injectable, Logger } from '@nestjs/common'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import type { MatchDocument } from '../global/database/schema'; -import type { RiotMatchDto } from '../riot/riot.types'; +import { RiotMatchService } from '../riot/riot-match.service'; +import { + RIOT_REGIONAL_ROUTES, + type RiotMatchDto, + type RiotMatchTimelineDto, + type RiotRegionalRoute, +} from '../riot/riot.types'; import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder'; import { MatchStatsRepository } from './match-stats.repository'; import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types'; @Injectable() export class MatchStatsService { + private readonly logger = new Logger(MatchStatsService.name); + constructor( private readonly connectionService: ConnectionService, private readonly repository: MatchStatsRepository, private readonly builder: MatchStatsFragmentBuilder, + private readonly riotMatchService: RiotMatchService, ) {} - public async buildAndUpsert(matchId: mongoose.Types.ObjectId): Promise { + public async buildAndUpsert( + matchId: mongoose.Types.ObjectId, + options: { includeTimeline?: boolean } = {}, + ): Promise { const MatchModel = await this.connectionService.getModel('match'); const RiotMatchModel = await this.connectionService.getModel('riotMatch'); const match = await MatchModel.findById(matchId).exec(); @@ -41,7 +53,51 @@ export class MatchStatsService { const rawByRiotMatchId = new Map( riotDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]), ); - const fragment = this.builder.buildFragment({ match, rawByRiotMatchId }); + const timelineByRiotMatchId = new Map(); + 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, + timelineFetchedAt: new Date(), + }, + }, + ).exec(); + timelineByRiotMatchId.set(doc.matchId, timeline); + } catch (error) { + this.logger.warn( + `Failed to fetch match timeline for ${doc.matchId}: ${ + error instanceof Error ? error.message : error + }`, + ); + } + } + } + + const fragment = this.builder.buildFragment({ + match, + rawByRiotMatchId, + timelineByRiotMatchId, + timelineLoadAttempted: options.includeTimeline === true, + }); await this.repository.upsert({ matchId: match._id, @@ -101,4 +157,29 @@ export class MatchStatsService { Boolean(match.result?.games?.length) ); } + + private async resolveRiotRegion( + communityId: mongoose.Types.ObjectId, + ): Promise { + 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 { + return typeof value === 'object' && value !== null; } diff --git a/apps/api/src/modules/community-stats/match-stats.types.ts b/apps/api/src/modules/community-stats/match-stats.types.ts index ed0901e3..a2af4788 100644 --- a/apps/api/src/modules/community-stats/match-stats.types.ts +++ b/apps/api/src/modules/community-stats/match-stats.types.ts @@ -4,7 +4,7 @@ import type { } from '../global/database/schema'; import type { InternalMatchCardView } from './community-stats.types'; -export const MATCH_STATS_BUILDER_VERSION = 1; +export const MATCH_STATS_BUILDER_VERSION = 7; export type InternalRecord = MatchStatsRecord; export type InternalGameDetail = MatchStatsGameDetail; diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index d8826947..39321434 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -398,6 +398,8 @@ export interface RiotMatch extends MongooseTimestamps { queueId?: number; participantPuuids: string[]; raw: Record; // Riot API Match-V5 원본 응답 전체 + timeline?: Record; // Riot API Match-V5 timeline 원본 응답 전체 + timelineFetchedAt?: Date; fetchedAt: Date; } @@ -666,6 +668,39 @@ export interface AuctionHistoryEntry extends MongooseTimestamps { export type AuctionHistoryEntryDocument = HydratedDocument; // ===== MatchStats (precomputed internal stats fragment) ===== +export interface MatchStatsRuneStyleSelection { + styleId: number; + perkIds: number[]; +} + +export interface MatchStatsRunePerks { + primaryStyle?: number; + subStyle?: number; + keystone?: number; + selectedPerkIds?: number[]; + styles?: MatchStatsRuneStyleSelection[]; + statPerks?: { + offense?: number; + flex?: number; + defense?: number; + }; +} + +export interface MatchStatsItemBuildEvent { + timestamp: number; + itemId: number; + type: 'purchased' | 'sold' | 'destroyed' | 'undo'; + beforeId?: number; + afterId?: number; +} + +export interface MatchStatsSkillBuildEvent { + timestamp: number; + skillSlot: 1 | 2 | 3 | 4; + level: number; + levelUpType?: string; +} + export interface MatchStatsRecord { matchId: string; title: string; @@ -698,10 +733,14 @@ export interface MatchStatsRecord { controlWardsBought: number; wardsPlaced: number; wardsKilled: number; + firstBloodKill: boolean; + firstBloodAssist: boolean; items: number[]; trinket: number; summonerSpells: [number, number]; - perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + perks: MatchStatsRunePerks; + itemBuild: MatchStatsItemBuildEvent[]; + skillBuild: MatchStatsSkillBuildEvent[]; rating: number; } @@ -710,16 +749,46 @@ export interface MatchStatsGameDetail { riotMatchId: string; gameCreation: number; gameDuration: number; + gameVersion?: string; winnerSide: TeamSide; + timeline: MatchStatsTimelinePoint[]; + timelineLoaded?: boolean; + objectiveEvents: MatchStatsObjectiveEvent[]; teams: Array<{ teamIndex: number; side: TeamSide; win: boolean; - objectives: { baron: number; dragon: number; tower: number }; + objectives: MatchStatsObjectiveSummary; + bans: Array<{ championId: number; pickTurn: number }>; participants: MatchStatsRecord[]; }>; } +export interface MatchStatsObjectiveSummary { + tower: number; + dragon: number; + inhibitor: number; + baron: number; + riftHerald: number; + voidGrub: number; + elderDragon: number; +} + +export interface MatchStatsObjectiveEvent { + timestamp: number; + side: TeamSide; + type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub'; + monsterSubType?: string; +} + +export interface MatchStatsTimelinePoint { + timestamp: number; + blue: { gold: number; xp: number }; + red: { gold: number; xp: number }; + goldDiff: number; + xpDiff: number; +} + export interface MatchStats extends MongooseTimestamps { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; @@ -1135,6 +1204,8 @@ export const RiotMatchSchema = new Schema( queueId: { type: Number }, participantPuuids: { type: [String], required: true, default: [] }, raw: { type: Schema.Types.Mixed, required: true, default: () => ({}) }, + timeline: { type: Schema.Types.Mixed }, + timelineFetchedAt: { type: Date }, fetchedAt: { type: Date, required: true, default: Date.now }, }, { diff --git a/apps/api/src/modules/match-history/match-history.types.ts b/apps/api/src/modules/match-history/match-history.types.ts index 92727c11..800a132a 100644 --- a/apps/api/src/modules/match-history/match-history.types.ts +++ b/apps/api/src/modules/match-history/match-history.types.ts @@ -1,4 +1,4 @@ -import type { RiotLane } from '../global/database/schema'; +import type { MatchStatsRunePerks, RiotLane } from '../global/database/schema'; import type { RiotQueueGroup, RiotRankFilter, @@ -121,7 +121,7 @@ export interface RecentMatchTeamParticipantView { items: number[]; trinket: number; summonerSpells: [number, number]; - perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + perks: MatchStatsRunePerks; totalCs: number; csPerMin: number; goldEarned: number; @@ -162,7 +162,7 @@ export interface RecentMatchView { items: number[]; trinket: number; summonerSpells: [number, number]; - perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + perks: MatchStatsRunePerks; teams: Array<{ side: 100 | 200; win: boolean; diff --git a/apps/api/src/modules/riot/riot-match.service.spec.ts b/apps/api/src/modules/riot/riot-match.service.spec.ts index 6aef710b..bcc3b321 100644 --- a/apps/api/src/modules/riot/riot-match.service.spec.ts +++ b/apps/api/src/modules/riot/riot-match.service.spec.ts @@ -106,4 +106,112 @@ describe('RiotMatchService', () => { expect(match.info.participants[0].teamPosition).toBe(''); expect(match.info.participants[0].individualPosition).toBe(''); }); + + it('fetches and parses match timeline frames', async () => { + const payload = { + metadata: { + dataVersion: '2', + matchId: 'KR_8188913502', + participants: ['puuid-1'], + }, + info: { + frameInterval: 60_000, + gameId: 8188913502, + participants: [{ participantId: 1, puuid: 'puuid-1' }], + frames: [ + { + timestamp: 60_000, + events: [ + { + type: 'ELITE_MONSTER_KILL', + timestamp: 30_000, + killerTeamId: 100, + monsterType: 'DRAGON', + monsterSubType: 'ELDER_DRAGON', + }, + { + type: 'ITEM_PURCHASED', + timestamp: 40_000, + participantId: 1, + itemId: 1054, + }, + { + type: 'ITEM_UNDO', + timestamp: 45_000, + participantId: 1, + beforeId: 1054, + afterId: 3071, + }, + { + type: 'SKILL_LEVEL_UP', + timestamp: 50_000, + participantId: 1, + skillSlot: 3, + levelUpType: 'NORMAL', + }, + ], + participantFrames: { + '1': { + currentGold: 650, + jungleMinionsKilled: 0, + level: 2, + minionsKilled: 6, + participantId: 1, + totalGold: 1_150, + xp: 550, + }, + }, + }, + ], + }, + }; + const riotClientService = { + get: jest.fn( + async ( + _path: string, + _options: unknown, + parser?: RiotResponseParser, + ) => (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', + }); + }); }); diff --git a/apps/api/src/modules/riot/riot-match.service.ts b/apps/api/src/modules/riot/riot-match.service.ts index 33aaeb86..2f82ce4d 100644 --- a/apps/api/src/modules/riot/riot-match.service.ts +++ b/apps/api/src/modules/riot/riot-match.service.ts @@ -15,6 +15,12 @@ import { RiotMatchPerkStyleSelectionDto, RiotMatchStatPerksDto, RiotMatchTeamDto, + RiotMatchTimelineDto, + RiotMatchTimelineEventDto, + RiotMatchTimelineFrameDto, + RiotMatchTimelineInfoDto, + RiotMatchTimelineParticipantDto, + RiotMatchTimelineParticipantFrameDto, RiotMatchType, } from './riot.types'; @@ -66,6 +72,20 @@ export class RiotMatchService { parseMatchResponse, ); } + + public async getMatchTimeline( + matchId: string, + options: RiotMatchLookupOptions = {}, + ): Promise { + return this.riotClientService.get( + `/lol/match/v5/matches/${encodeURIComponent(matchId)}/timeline`, + { + region: options.region, + signal: options.signal, + }, + parseMatchTimelineResponse, + ); + } } function validateMatchIdsLookupOptions( @@ -115,6 +135,48 @@ function parseMatchResponse(value: unknown): RiotMatchDto { }; } +function parseMatchTimelineResponse(value: unknown): RiotMatchTimelineDto { + if (!isRecord(value)) { + throw new TypeError('Riot match timeline response must be an object.'); + } + + return { + metadata: parseMatchMetadata(value.metadata), + info: parseMatchTimelineInfo(value.info), + }; +} + +function parseMatchTimelineInfo(value: unknown): RiotMatchTimelineInfoDto { + if (!isRecord(value)) { + throw new TypeError('Riot match timeline info must be an object.'); + } + + const frames = value.frames; + if (!Array.isArray(frames)) { + throw new TypeError('Riot match timeline info.frames must be an array.'); + } + + const participants = value.participants; + if (participants !== undefined && !Array.isArray(participants)) { + throw new TypeError( + 'Riot match timeline info.participants must be an array when present.', + ); + } + + return { + ...value, + frameInterval: requireNumber( + value.frameInterval, + 'timeline.info.frameInterval', + ), + frames: frames.map((frame, index) => parseTimelineFrame(frame, index)), + gameId: optionalNumber(value.gameId, 'timeline.info.gameId'), + participants: participants?.map((participant, index) => + parseTimelineParticipant(participant, index), + ), + }; +} + function parseMatchMetadata(value: unknown): RiotMatchMetadataDto { if (!isRecord(value)) { throw new TypeError('Riot match metadata must be an object.'); @@ -211,6 +273,195 @@ function parseMatchInfo(value: unknown): RiotMatchInfoDto { }; } +function parseTimelineParticipant( + value: unknown, + index: number, +): RiotMatchTimelineParticipantDto { + if (!isRecord(value)) { + throw new TypeError(`timeline.info.participants[${index}] must be an object.`); + } + + return { + ...value, + participantId: requireNumber( + value.participantId, + `timeline.info.participants[${index}].participantId`, + ), + puuid: requireString(value.puuid, `timeline.info.participants[${index}].puuid`), + }; +} + +function parseTimelineFrame( + value: unknown, + index: number, +): RiotMatchTimelineFrameDto { + if (!isRecord(value)) { + throw new TypeError(`timeline.info.frames[${index}] must be an object.`); + } + + const participantFrames = value.participantFrames; + if (!isRecord(participantFrames)) { + throw new TypeError( + `timeline.info.frames[${index}].participantFrames must be an object.`, + ); + } + const events = value.events; + if (events !== undefined && !Array.isArray(events)) { + throw new TypeError( + `timeline.info.frames[${index}].events must be an array when present.`, + ); + } + + return { + ...value, + events: (events ?? []).map((event, eventIndex) => + parseTimelineEvent(event, index, eventIndex), + ), + timestamp: requireNumber( + value.timestamp, + `timeline.info.frames[${index}].timestamp`, + ), + participantFrames: Object.fromEntries( + Object.entries(participantFrames).map(([key, participantFrame]) => [ + key, + parseTimelineParticipantFrame(participantFrame, index, key), + ]), + ), + }; +} + +function parseTimelineEvent( + value: unknown, + frameIndex: number, + eventIndex: number, +): RiotMatchTimelineEventDto { + if (!isRecord(value)) { + throw new TypeError( + `timeline.info.frames[${frameIndex}].events[${eventIndex}] must be an object.`, + ); + } + + const assistingParticipantIds = value.assistingParticipantIds; + if ( + assistingParticipantIds !== undefined && + (!Array.isArray(assistingParticipantIds) || + !assistingParticipantIds.every(isFiniteNumber)) + ) { + throw new TypeError( + `timeline.info.frames[${frameIndex}].events[${eventIndex}].assistingParticipantIds must be an array of numbers when present.`, + ); + } + + return { + ...value, + afterId: optionalNumber( + value.afterId, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].afterId`, + ), + assistingParticipantIds, + beforeId: optionalNumber( + value.beforeId, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].beforeId`, + ), + buildingType: optionalString( + value.buildingType, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].buildingType`, + ), + itemId: optionalNumber( + value.itemId, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].itemId`, + ), + killerId: optionalNumber( + value.killerId, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].killerId`, + ), + killerTeamId: optionalNumber( + value.killerTeamId, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].killerTeamId`, + ), + levelUpType: optionalString( + value.levelUpType, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].levelUpType`, + ), + monsterSubType: optionalString( + value.monsterSubType, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].monsterSubType`, + ), + monsterType: optionalString( + value.monsterType, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].monsterType`, + ), + participantId: optionalNumber( + value.participantId, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].participantId`, + ), + skillSlot: optionalNumber( + value.skillSlot, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].skillSlot`, + ), + teamId: optionalNumber( + value.teamId, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].teamId`, + ), + timestamp: requireNumber( + value.timestamp, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].timestamp`, + ), + towerType: optionalString( + value.towerType, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].towerType`, + ), + type: requireString( + value.type, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].type`, + ), + }; +} + +function parseTimelineParticipantFrame( + value: unknown, + frameIndex: number, + key: string, +): RiotMatchTimelineParticipantFrameDto { + if (!isRecord(value)) { + throw new TypeError( + `timeline.info.frames[${frameIndex}].participantFrames.${key} must be an object.`, + ); + } + + return { + ...value, + currentGold: optionalNumber( + value.currentGold, + `timeline.info.frames[${frameIndex}].participantFrames.${key}.currentGold`, + ), + jungleMinionsKilled: optionalNumber( + value.jungleMinionsKilled, + `timeline.info.frames[${frameIndex}].participantFrames.${key}.jungleMinionsKilled`, + ), + level: optionalNumber( + value.level, + `timeline.info.frames[${frameIndex}].participantFrames.${key}.level`, + ), + minionsKilled: optionalNumber( + value.minionsKilled, + `timeline.info.frames[${frameIndex}].participantFrames.${key}.minionsKilled`, + ), + participantId: requireNumber( + value.participantId, + `timeline.info.frames[${frameIndex}].participantFrames.${key}.participantId`, + ), + totalGold: requireNumber( + value.totalGold, + `timeline.info.frames[${frameIndex}].participantFrames.${key}.totalGold`, + ), + xp: requireNumber( + value.xp, + `timeline.info.frames[${frameIndex}].participantFrames.${key}.xp`, + ), + }; +} + function parseParticipant( value: unknown, index: number, @@ -504,12 +755,22 @@ function parseObjectives( baron: parseObjective(value.baron, teamIndex, 'baron'), champion: parseObjective(value.champion, teamIndex, 'champion'), dragon: parseObjective(value.dragon, teamIndex, 'dragon'), + horde: optionalObjective(value.horde, teamIndex, 'horde'), inhibitor: parseObjective(value.inhibitor, teamIndex, 'inhibitor'), riftHerald: parseObjective(value.riftHerald, teamIndex, 'riftHerald'), tower: parseObjective(value.tower, teamIndex, 'tower'), }; } +function optionalObjective( + value: unknown, + teamIndex: number, + key: keyof RiotMatchObjectivesDto, +): RiotMatchObjectiveDto | undefined { + if (value === undefined || value === null) return undefined; + return parseObjective(value, teamIndex, key); +} + function parseObjective( value: unknown, teamIndex: number, diff --git a/apps/api/src/modules/riot/riot.types.ts b/apps/api/src/modules/riot/riot.types.ts index fa890349..2590b7de 100644 --- a/apps/api/src/modules/riot/riot.types.ts +++ b/apps/api/src/modules/riot/riot.types.ts @@ -134,6 +134,11 @@ export interface RiotMatchDto { info: RiotMatchInfoDto; } +export interface RiotMatchTimelineDto { + metadata: RiotMatchMetadataDto; + info: RiotMatchTimelineInfoDto; +} + export interface RiotMatchMetadataDto { dataVersion: string; matchId: string; @@ -240,6 +245,7 @@ export interface RiotMatchObjectivesDto { baron: RiotMatchObjectiveDto; champion: RiotMatchObjectiveDto; dragon: RiotMatchObjectiveDto; + horde?: RiotMatchObjectiveDto; inhibitor: RiotMatchObjectiveDto; riftHerald: RiotMatchObjectiveDto; tower: RiotMatchObjectiveDto; @@ -249,3 +255,51 @@ export interface RiotMatchObjectiveDto { first: boolean; kills: number; } + +export interface RiotMatchTimelineInfoDto extends Record { + frameInterval: number; + frames: RiotMatchTimelineFrameDto[]; + gameId?: number; + participants?: RiotMatchTimelineParticipantDto[]; +} + +export interface RiotMatchTimelineParticipantDto extends Record { + participantId: number; + puuid: string; +} + +export interface RiotMatchTimelineFrameDto extends Record { + timestamp: number; + events: RiotMatchTimelineEventDto[]; + participantFrames: Record; +} + +export interface RiotMatchTimelineEventDto extends Record { + 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 { + participantId: number; + totalGold: number; + xp: number; + currentGold?: number; + jungleMinionsKilled?: number; + level?: number; + minionsKilled?: number; +} diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index ed8d4b43..d63a55f8 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -10,6 +10,7 @@ import AuthCallbackPage from "./pages/AuthCallback"; import HomePage from "./pages/HomePage"; import LoginPage from "./pages/Login"; import MatchDetailPage from "./pages/MatchDetailPage"; +import MatchGameDetailPage from "./pages/MatchGameDetailPage"; import MatchTeamProgressPage from "./pages/MatchTeamProgressPage"; import AuctionPage from "./pages/AuctionPage"; import UserHistoryPage from "./pages/UserHistoryPage"; @@ -151,6 +152,10 @@ function App() { } /> } /> } /> + } + /> } diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index 68e0ec40..9473f226 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -562,6 +562,39 @@ export interface ApiRecentSummaryResponse { lastFetchedAt: string | null; } +export interface ApiRuneStyleSelection { + styleId: number; + perkIds: number[]; +} + +export interface ApiRunePerks { + primaryStyle?: number; + subStyle?: number; + keystone?: number; + selectedPerkIds?: number[]; + styles?: ApiRuneStyleSelection[]; + statPerks?: { + offense?: number; + flex?: number; + defense?: number; + }; +} + +export interface ApiItemBuildEvent { + timestamp: number; + itemId: number; + type: 'purchased' | 'sold' | 'destroyed' | 'undo'; + beforeId?: number; + afterId?: number; +} + +export interface ApiSkillBuildEvent { + timestamp: number; + skillSlot: 1 | 2 | 3 | 4; + level: number; + levelUpType?: string; +} + export interface ApiRecentMatchTeamParticipant { puuid: string; gameName: string; @@ -575,7 +608,7 @@ export interface ApiRecentMatchTeamParticipant { items: number[]; trinket: number; summonerSpells: [number, number]; - perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + perks: ApiRunePerks; totalCs: number; csPerMin: number; goldEarned: number; @@ -623,7 +656,7 @@ export interface ApiRecentMatchView { items: number[]; trinket: number; summonerSpells: [number, number]; - perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + perks: ApiRunePerks; teams: ApiRecentMatchTeam[]; } @@ -732,11 +765,34 @@ export interface ApiInternalMatchDetailResponse { riotMatchId: string; gameCreation: number; gameDuration: number; + gameVersion?: string; + timeline: Array<{ + timestamp: number; + blue: { gold: number; xp: number }; + red: { gold: number; xp: number }; + goldDiff: number; + xpDiff: number; + }>; + objectiveEvents: Array<{ + timestamp: number; + side: TeamSide; + type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub'; + monsterSubType?: string; + }>; teams: Array<{ teamIndex: number; side: TeamSide; win: boolean; - objectives: { baron: number; dragon: number; tower: number }; + objectives: { + tower: number; + dragon: number; + inhibitor: number; + baron: number; + riftHerald: number; + voidGrub: number; + elderDragon: number; + }; + bans: Array<{ championId: number; pickTurn: number }>; participants: Array<{ userId: string | null; summonerName: string; @@ -744,6 +800,7 @@ export interface ApiInternalMatchDetailResponse { side: TeamSide; teamPosition: string; championId: number; + championLevel: number; kills: number; deaths: number; assists: number; @@ -752,13 +809,21 @@ export interface ApiInternalMatchDetailResponse { gold: number; gpm: number; damageDealtToChampions: number; + damageTaken: number; damageShare: number; killParticipation: number; visionScore: number; + wardsPlaced: number; + wardsKilled: number; + controlWardsBought: number; + firstBloodKill: boolean; + firstBloodAssist: boolean; items: number[]; trinket: number; summonerSpells: [number, number]; - perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + perks: ApiRunePerks; + itemBuild: ApiItemBuildEvent[]; + skillBuild: ApiSkillBuildEvent[]; win: boolean; }>; }>; diff --git a/apps/web/src/lib/ddragon.ts b/apps/web/src/lib/ddragon.ts index 7c4e31d4..923d15f8 100644 --- a/apps/web/src/lib/ddragon.ts +++ b/apps/web/src/lib/ddragon.ts @@ -69,3 +69,10 @@ export function runeKeystoneIconUrl( return rune ? `${cdn(manifest)}/img/${rune.icon}` : null; } + +export function runeIconUrl( + manifest: DdragonManifest | null | undefined, + runeId: number | undefined, +) { + return runeKeystoneIconUrl(manifest, runeId); +} diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index fa92761d..9084ba8e 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -1963,16 +1963,15 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) {
{gameNumbers.map((gameNumber) => { const game = gamesByNumber.get(gameNumber); - return ( -
+ const rowClass = + "grid grid-cols-[56px_1fr_auto] gap-3 items-center px-3 py-2.5 text-xs"; + const content = ( + <> {gameNumber}경기 {game ? ( -
+
@@ -1988,9 +1987,40 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) { ) : ( 대기 중 )} - - {game ? formatGameDuration(game.gameDuration) : "-"} + + {game ? ( + <> + {formatGameDuration(game.gameDuration)} + + 상세 + + + ) : ( + "-" + )} + + ); + + if (game) { + return ( + + {content} + + ); + } + + return ( +
+ {content}
); })} diff --git a/apps/web/src/pages/MatchGameDetailPage.tsx b/apps/web/src/pages/MatchGameDetailPage.tsx new file mode 100644 index 00000000..b9ae2c10 --- /dev/null +++ b/apps/web/src/pages/MatchGameDetailPage.tsx @@ -0,0 +1,1995 @@ +import { useEffect, useRef, useState } from "react"; +import { Link, useLocation, useParams } from "react-router"; +import { + Area, + AreaChart, + CartesianGrid, + Line, + ReferenceLine, + Tooltip, + XAxis, + YAxis, +} from "recharts"; +import { useDdragonManifest, useInternalMatchDetail } from "../api/hooks"; +import type { ApiInternalMatchDetailResponse, TeamSide } from "../api/types"; +import { DEFAULT_COMMUNITY_ID } from "../config"; +import { + championDisplayName, + championIconUrl, + itemIconUrl, + runeIconUrl, + runeKeystoneIconUrl, + runeStyleIconUrl, + summonerSpellIconUrl, +} from "../lib/ddragon"; +import { + sideShortLabel, + teamIndexColorClasses, + teamIndexLabel, +} from "../lib/league"; +import { LANE_LABELS } from "../lib/riot-history"; + +type MatchGameDetail = ApiInternalMatchDetailResponse["games"][number]; +type MatchGameTeam = MatchGameDetail["teams"][number]; +type MatchGameParticipant = MatchGameTeam["participants"][number]; +type MatchGameObjectiveEvent = MatchGameDetail["objectiveEvents"][number]; +type DdragonManifestData = ReturnType["data"]; +type RuneStyleEntry = NonNullable["runesReforged"][number]; +type DetailTab = "summary" | "build" | "damageDealt" | "damageTaken"; +type TimelineMetric = "gold" | "xp"; +type ObjectiveKey = keyof MatchGameTeam["objectives"]; + +const DETAIL_TABS: Array<{ id: DetailTab; label: string }> = [ + { id: "summary", label: "요약" }, + { id: "build", label: "룬 / 빌드" }, + { id: "damageDealt", label: "가한 데미지" }, + { id: "damageTaken", label: "받은 데미지" }, +]; + +const TIMELINE_METRICS: Array<{ id: TimelineMetric; label: string }> = [ + { id: "gold", label: "골드" }, + { id: "xp", label: "경험치" }, +]; + +const OBJECTIVE_ITEMS: Array<{ + key: ObjectiveKey; + label: string; + shortLabel: string; +}> = [ + { key: "tower", label: "타워", shortLabel: "TW" }, + { key: "dragon", label: "드래곤", shortLabel: "DR" }, + { key: "inhibitor", label: "억제기", shortLabel: "IN" }, + { key: "baron", label: "내셔남작", shortLabel: "BN" }, + { key: "riftHerald", label: "전령", shortLabel: "RH" }, + { key: "voidGrub", label: "유충", shortLabel: "VG" }, + { key: "elderDragon", label: "엘더드래곤", shortLabel: "ED" }, +]; + +const SKILL_ROWS: Array<{ + slot: 1 | 2 | 3 | 4; + label: string; + className: string; +}> = [ + { slot: 1, label: "Q", className: "bg-blue-500 text-white" }, + { slot: 2, label: "W", className: "bg-cyan-500 text-white" }, + { slot: 3, label: "E", className: "bg-amber-500 text-black" }, + { slot: 4, label: "R", className: "bg-red-500 text-white" }, +]; + +const STAT_PERK_LABELS: Record = { + 5001: "체력", + 5002: "방어", + 5003: "마저", + 5005: "공속", + 5007: "가속", + 5008: "적응", + 5010: "이속", + 5011: "체력", +}; + +const DRAGON_TYPE_META: Record< + string, + { label: string; dotClass: string; borderClass: string; textClass: string } +> = { + FIRE_DRAGON: { + label: "화염", + dotClass: "bg-red-500", + borderClass: "border-red-500/25", + textClass: "text-red-400", + }, + WATER_DRAGON: { + label: "바다", + dotClass: "bg-blue-500", + borderClass: "border-blue-500/25", + textClass: "text-blue-400", + }, + EARTH_DRAGON: { + label: "대지", + dotClass: "bg-emerald-500", + borderClass: "border-emerald-500/25", + textClass: "text-emerald-400", + }, + AIR_DRAGON: { + label: "바람", + dotClass: "bg-sky-400", + borderClass: "border-sky-400/25", + textClass: "text-sky-400", + }, + HEXTECH_DRAGON: { + label: "마법공학", + dotClass: "bg-violet-500", + borderClass: "border-violet-500/25", + textClass: "text-violet-400", + }, + CHEMTECH_DRAGON: { + label: "화학공학", + dotClass: "bg-lime-500", + borderClass: "border-lime-500/25", + textClass: "text-lime-500", + }, + ELDER_DRAGON: { + label: "엘더", + dotClass: "bg-amber-400", + borderClass: "border-amber-400/30", + textClass: "text-amber-400", + }, +}; + +function formatDateTime(value: string | number) { + return new Intl.DateTimeFormat("ko-KR", { + month: "long", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + }).format(new Date(value)); +} + +function formatDuration(seconds: number) { + const minutes = Math.floor(seconds / 60); + const rest = seconds % 60; + return `${minutes}:${String(rest).padStart(2, "0")}`; +} + +function formatNumber(value: number) { + return new Intl.NumberFormat("ko-KR").format(value); +} + +function formatCompactNumber(value: number) { + if (value >= 1000) return `${(value / 1000).toFixed(1)}K`; + return String(value); +} + +function formatSignedCompactNumber(value: number) { + if (value === 0) return "0"; + return `${value > 0 ? "+" : "-"}${formatCompactNumber(Math.abs(value))}`; +} + +function formatGameVersion(value: string | undefined) { + if (!value) return null; + const [major, minor] = value.split("."); + return major && minor ? `${major}.${minor}` : value; +} + +function formatKda(kills: number, deaths: number, assists: number) { + if (deaths === 0) return kills + assists > 0 ? "Perfect" : "-"; + return ((kills + assists) / deaths).toFixed(2); +} + +function formatPercent(value: number) { + return `${value}%`; +} + +function barWidth(value: number, max: number) { + return `${Math.max(0, Math.min(100, max > 0 ? (value / max) * 100 : 0))}%`; +} + +function sideLabel(side: TeamSide) { + return sideShortLabel(side); +} + +function sideTone(side: TeamSide) { + return side === "blue" + ? { + border: "border-blue-500/20", + bg: "bg-blue-500/5", + text: "text-blue-400", + bar: "bg-blue-500", + } + : { + border: "border-red-500/20", + bg: "bg-red-500/5", + text: "text-red-400", + bar: "bg-red-500", + }; +} + +function sideObjectiveTone(side: TeamSide) { + return side === "blue" + ? "border-blue-500/25 bg-blue-500/5 text-blue-400" + : "border-red-500/25 bg-red-500/5 text-red-400"; +} + +function dragonTypeMeta(event: MatchGameObjectiveEvent) { + return ( + DRAGON_TYPE_META[event.monsterSubType ?? ""] ?? { + label: event.type === "elderDragon" ? "엘더" : "드래곤", + dotClass: event.type === "elderDragon" ? "bg-amber-400" : "bg-base-content/35", + borderClass: + event.type === "elderDragon" + ? "border-amber-400/30" + : "border-base-content/10", + textClass: + event.type === "elderDragon" ? "text-amber-400" : "text-base-content/55", + } + ); +} + +function teamTotals(team: MatchGameTeam) { + return team.participants.reduce( + (totals, participant) => ({ + kills: totals.kills + participant.kills, + deaths: totals.deaths + participant.deaths, + assists: totals.assists + participant.assists, + gold: totals.gold + participant.gold, + damage: totals.damage + participant.damageDealtToChampions, + vision: totals.vision + participant.visionScore, + }), + { kills: 0, deaths: 0, assists: 0, gold: 0, damage: 0, vision: 0 }, + ); +} + +function objectiveCount(team: MatchGameTeam | undefined, key: ObjectiveKey) { + return team?.objectives?.[key] ?? 0; +} + +function getTeamName( + detail: ApiInternalMatchDetailResponse, + teamIndex: number, +) { + return teamIndexLabel( + teamIndex, + detail.match.teams.find((team) => team.teamIndex === teamIndex)?.name, + ); +} + +function resolveSelectedSeries( + detail: ApiInternalMatchDetailResponse, + selectedGame: MatchGameDetail, +) { + const teamIndexes = selectedGame.teams.map((team) => team.teamIndex); + return detail.match.seriesResults.find( + (series) => + teamIndexes.includes(series.teamAIndex) && + teamIndexes.includes(series.teamBIndex), + ); +} + +function participantBuildKey(participant: MatchGameParticipant) { + return `${participant.side}-${participant.userId ?? participant.summonerName}-${participant.championId}`; +} + +function findRuneStyle( + manifest: DdragonManifestData, + styleId: number | undefined, +) { + return manifest?.runesReforged.find((style) => style.id === styleId) ?? null; +} + +function selectedRuneIds(participant: MatchGameParticipant) { + const explicit = participant.perks.selectedPerkIds ?? []; + const fromStyles = + participant.perks.styles?.flatMap((style) => style.perkIds) ?? []; + return new Set([ + ...explicit, + ...fromStyles, + ...(participant.perks.keystone ? [participant.perks.keystone] : []), + ]); +} + +function runeStyleSelection( + participant: MatchGameParticipant, + styleId: number | undefined, +) { + return participant.perks.styles?.find((style) => style.styleId === styleId); +} + +function StatBlock({ + label, + value, +}: { + label: string; + value: string | number; +}) { + return ( +
+
+ {label} +
+
+ {value} +
+
+ ); +} + +function ChampionCell({ + participant, + manifest, +}: { + participant: MatchGameParticipant; + manifest: ReturnType["data"]; +}) { + const icon = championIconUrl(manifest, participant.championId); + const name = + championDisplayName(manifest, participant.championId) ?? + String(participant.championId); + + return ( +
+ + {icon ? ( + {name} + ) : null} + {participant.championLevel > 0 && ( + + {participant.championLevel} + + )} + +
+ + {name} + + + {LANE_LABELS[participant.teamPosition] ?? + participant.teamPosition ?? + "-"} + +
+
+ ); +} + +function SpellRuneStrip({ + participant, + manifest, +}: { + participant: MatchGameParticipant; + manifest: ReturnType["data"]; +}) { + const spellIcons = participant.summonerSpells + .map((spellId) => summonerSpellIconUrl(manifest, spellId)) + .filter((icon): icon is string => Boolean(icon)); + const runeIcons = [ + runeKeystoneIconUrl(manifest, participant.perks.keystone), + runeStyleIconUrl(manifest, participant.perks.subStyle), + ].filter((icon): icon is string => Boolean(icon)); + + return ( +
+
+ {[0, 1].map((index) => ( + + {spellIcons[index] ? ( + + ) : null} + + ))} +
+
+ {[0, 1].map((index) => ( + + {runeIcons[index] ? ( + + ) : null} + + ))} +
+
+ ); +} + +function ItemStrip({ + participant, + manifest, +}: { + participant: MatchGameParticipant; + manifest: ReturnType["data"]; +}) { + const itemIds = [ + ...Array.from({ length: 6 }, (_, index) => participant.items[index] ?? 0), + participant.trinket, + ]; + + return ( +
+ {itemIds.map((itemId, index) => { + const icon = itemIconUrl(manifest, itemId); + return ( + + {icon ? ( + + ) : null} + + ); + })} +
+ ); +} + +function PercentBar({ + value, + side, +}: { + value: number; + side: TeamSide; +}) { + const width = `${Math.max(0, Math.min(100, value))}%`; + return ( +
+
+
+ ); +} + +function PlayerRow({ + participant, + manifest, +}: { + participant: MatchGameParticipant; + manifest: ReturnType["data"]; +}) { + const location = useLocation(); + const historyBackTo = `${location.pathname}${location.search}${location.hash}`; + + return ( + + + + + + + + + {participant.userId ? ( + + {participant.summonerName} + + ) : ( + + {participant.summonerName} + + )} + {(participant.firstBloodKill || participant.firstBloodAssist) && ( + + {participant.firstBloodKill ? "FB" : "FBA"} + + )} + + +
+ {participant.kills} + / + {participant.deaths} + / + {participant.assists} +
+
+ {formatKda(participant.kills, participant.deaths, participant.assists)} + {participant.deaths === 0 ? "" : " KDA"} +
+ + + {formatCompactNumber(participant.damageDealtToChampions)} +
+ +
+ + {formatPercent(participant.damageShare)} + + + + {participant.visionScore} + + 와드 {participant.wardsPlaced ?? 0}/{participant.wardsKilled ?? 0} + + + 제어 {participant.controlWardsBought ?? 0} + + + + {participant.cs} + + {participant.csPerMin}/m + + + + + + + ); +} + +function TeamScoreHeader({ + team, + detail, +}: { + team: MatchGameTeam; + detail: ApiInternalMatchDetailResponse; +}) { + const tone = sideTone(team.side); + const teamTone = teamIndexColorClasses(team.teamIndex); + const totals = teamTotals(team); + + return ( +
+
+
+
+
+ + + + + + +
+
+
+ ); +} + +function BanStrip({ + bans, + manifest, +}: { + bans: MatchGameTeam["bans"] | undefined; + manifest: ReturnType["data"]; +}) { + const sortedBans = [...(bans ?? [])].sort( + (left, right) => left.pickTurn - right.pickTurn, + ); + return ( +
+ {sortedBans.length > 0 + ? sortedBans.map((ban) => { + const icon = championIconUrl(manifest, ban.championId); + const name = + championDisplayName(manifest, ban.championId) ?? + String(ban.championId); + return ( + + {icon ? ( + {name} + ) : null} + + ); + }) + : Array.from({ length: 5 }, (_, index) => ( + + ))} +
+ ); +} + +function PostgameBreakdown({ + selectedGame, + detail, + manifest, +}: { + selectedGame: MatchGameDetail; + detail: ApiInternalMatchDetailResponse; + manifest: ReturnType["data"]; +}) { + const orderedTeams = [...selectedGame.teams].sort((left, right) => + left.side === right.side ? 0 : left.side === "blue" ? -1 : 1, + ); + const version = formatGameVersion(selectedGame.gameVersion); + const maxGold = Math.max(1, ...orderedTeams.map((team) => teamTotals(team).gold)); + + return ( +
+
+

세트 요약

+
+ {version ? Ver. {version} : null} + {formatDuration(selectedGame.gameDuration)} + {selectedGame.riotMatchId} +
+
+
+ {orderedTeams.map((team) => { + const totals = teamTotals(team); + const tone = sideTone(team.side); + const teamTone = teamIndexColorClasses(team.teamIndex); + return ( +
+
+
+
+ + {getTeamName(detail, team.teamIndex)} + + + {sideLabel(team.side)} + + + {team.win ? "승리" : "패배"} + +
+
+ + + + +
+
+
+
+ Bans +
+ +
+
+
+
+
+
+ ); + })} +
+ + +
+ ); +} + +function GoldComparisonStrip({ + selectedGame, + detail, +}: { + selectedGame: MatchGameDetail; + detail: ApiInternalMatchDetailResponse; +}) { + const blueTeam = selectedGame.teams.find((team) => team.side === "blue"); + const redTeam = selectedGame.teams.find((team) => team.side === "red"); + if (!blueTeam || !redTeam) return null; + + const blueTotals = teamTotals(blueTeam); + const redTotals = teamTotals(redTeam); + const goldDiff = blueTotals.gold - redTotals.gold; + const maxGold = Math.max(1, blueTotals.gold, redTotals.gold); + const leaderSide = + goldDiff > 0 ? "blue" : goldDiff < 0 ? "red" : ("blue" as TeamSide); + const leaderName = + goldDiff === 0 + ? "동률" + : getTeamName(detail, leaderSide === "blue" ? blueTeam.teamIndex : redTeam.teamIndex); + + return ( +
+
+
+
+ {getTeamName(detail, blueTeam.teamIndex)} + {formatNumber(blueTotals.gold)} +
+
+
+
+
+
+
+ 골드 차이 +
+
0 + ? "text-blue-400" + : goldDiff < 0 + ? "text-red-400" + : "text-base-content/55" + }`} + > + {formatSignedCompactNumber(goldDiff)} +
+
+ {leaderName} +
+
+
+
+ {formatNumber(redTotals.gold)} + + {getTeamName(detail, redTeam.teamIndex)} + +
+
+
+
+
+
+
+ ); +} + +function ObjectiveSummaryStrip({ + selectedGame, + detail, +}: { + selectedGame: MatchGameDetail; + detail: ApiInternalMatchDetailResponse; +}) { + const blueTeam = selectedGame.teams.find((team) => team.side === "blue"); + const redTeam = selectedGame.teams.find((team) => team.side === "red"); + const blueTeamName = blueTeam ? getTeamName(detail, blueTeam.teamIndex) : "BLUE"; + const redTeamName = redTeam ? getTeamName(detail, redTeam.teamIndex) : "RED"; + const dragonEvents = (selectedGame.objectiveEvents ?? []).filter( + (event) => event.type === "dragon" || event.type === "elderDragon", + ); + + return ( +
+
+

+ 오브젝트 요약 +

+
+ + {blueTeamName} + + VS + {redTeamName} +
+
+
+ {OBJECTIVE_ITEMS.map((item) => { + const blueValue = objectiveCount(blueTeam, item.key); + const redValue = objectiveCount(redTeam, item.key); + return ( +
+ + {blueValue} + +
+ + {item.shortLabel} + + + {item.label} + +
+ + {redValue} + +
+ ); + })} +
+ +
+ ); +} + +function DragonEventTrail({ + events, + selectedGame, + detail, +}: { + events: MatchGameObjectiveEvent[]; + selectedGame: MatchGameDetail; + detail: ApiInternalMatchDetailResponse; +}) { + if (events.length === 0) return null; + + const teamBySide = new Map(selectedGame.teams.map((team) => [team.side, team])); + + return ( +
+
+

+ 드래곤 종류 +

+ + 시간순 + +
+
+ {events.map((event, index) => { + const meta = dragonTypeMeta(event); + const team = teamBySide.get(event.side); + const teamName = team ? getTeamName(detail, team.teamIndex) : event.side; + return ( + + + ); + })} +
+
+ ); +} + +interface TimelineChartPoint { + timestamp: number; + timeLabel: string; + value: number; + positive: number; + negative: number; + blueTotal: number; + redTotal: number; + leaderSide: TeamSide | null; +} + +function TimelineTooltip({ + active, + payload, + blueTeamName, + redTeamName, + metricLabel, +}: { + active?: boolean; + payload?: Array<{ payload: TimelineChartPoint }>; + blueTeamName: string; + redTeamName: string; + metricLabel: string; +}) { + const point = payload?.[0]?.payload; + if (!active || !point) return null; + const leaderName = + point.leaderSide === "blue" + ? blueTeamName + : point.leaderSide === "red" + ? redTeamName + : "동률"; + + return ( +
+
{point.timeLabel}
+
+ {leaderName} {formatSignedCompactNumber(point.value)} +
+
+
+ {blueTeamName} + + {formatNumber(point.blueTotal)} + +
+
+ {redTeamName} + + {formatNumber(point.redTotal)} + +
+
+
+ {metricLabel} +
+
+ ); +} + +function TimelineGraph({ + selectedGame, + detail, +}: { + selectedGame: MatchGameDetail; + detail: ApiInternalMatchDetailResponse; +}) { + const [metric, setMetric] = useState("gold"); + const chartHostRef = useRef(null); + const [chartWidth, setChartWidth] = useState(0); + const blueTeam = selectedGame.teams.find((team) => team.side === "blue"); + const redTeam = selectedGame.teams.find((team) => team.side === "red"); + const blueTeamName = blueTeam ? getTeamName(detail, blueTeam.teamIndex) : "BLUE"; + const redTeamName = redTeam ? getTeamName(detail, redTeam.teamIndex) : "RED"; + const metricLabel = metric === "gold" ? "골드" : "경험치"; + const chartData: TimelineChartPoint[] = (selectedGame.timeline ?? []).map( + (point) => { + const value = metric === "gold" ? point.goldDiff : point.xpDiff; + return { + timestamp: point.timestamp, + timeLabel: formatDuration(point.timestamp), + value, + positive: Math.max(value, 0), + negative: Math.min(value, 0), + blueTotal: metric === "gold" ? point.blue.gold : point.blue.xp, + redTotal: metric === "gold" ? point.red.gold : point.red.xp, + leaderSide: value > 0 ? "blue" : value < 0 ? "red" : null, + }; + }, + ); + const maxAbs = Math.max( + 1, + ...chartData.map((point) => Math.abs(point.value)), + ); + const finalPoint = chartData[chartData.length - 1]; + const finalLeader = + finalPoint?.leaderSide === "blue" + ? blueTeamName + : finalPoint?.leaderSide === "red" + ? redTeamName + : "동률"; + + useEffect(() => { + const node = chartHostRef.current; + if (!node) return; + + let frame = 0; + const updateChartWidth = () => { + window.cancelAnimationFrame(frame); + frame = window.requestAnimationFrame(() => { + setChartWidth( + Math.max(0, Math.floor(node.getBoundingClientRect().width)), + ); + }); + }; + const observer = new ResizeObserver(updateChartWidth); + + updateChartWidth(); + observer.observe(node); + + return () => { + window.cancelAnimationFrame(frame); + observer.disconnect(); + }; + }, []); + + return ( +
+
+
+

경기 흐름

+
+ {finalPoint + ? `${finalLeader} ${formatSignedCompactNumber(finalPoint.value)}` + : "타임라인 대기"} +
+
+
+ {TIMELINE_METRICS.map((item) => ( + + ))} +
+
+ {chartData.length > 0 ? ( +
+
+ {chartWidth > 0 ? ( + + + `${Math.round(Number(value) / 60)}분`} + tick={{ fill: "currentColor", fontSize: 11 }} + tickLine={false} + axisLine={false} + /> + + formatSignedCompactNumber(Number(value)) + } + tick={{ fill: "currentColor", fontSize: 11 }} + tickLine={false} + axisLine={false} + width={58} + /> + + } + /> + + + + + + ) : null} +
+
+ {blueTeamName} + 0 + {redTeamName} +
+
+ ) : ( +
+ 타임라인 데이터가 아직 없습니다 +
+ )} +
+ ); +} + +function TeamTable({ + team, + detail, + manifest, +}: { + team: MatchGameTeam; + detail: ApiInternalMatchDetailResponse; + manifest: ReturnType["data"]; +}) { + return ( +
+ +
+ + + + + + + + + + + + + + + {team.participants.map((participant) => ( + + ))} + +
챔피언스펠/룬선수KDA피해량시야CS아이템
+
+
+ ); +} + +function DetailTabBar({ + activeTab, + onChange, +}: { + activeTab: DetailTab; + onChange: (tab: DetailTab) => void; +}) { + return ( +
+ {DETAIL_TABS.map((tab) => ( + + ))} +
+ ); +} + +function RuneBuildPanel({ + selectedGame, + detail, + manifest, +}: { + selectedGame: MatchGameDetail; + detail: ApiInternalMatchDetailResponse; + manifest: DdragonManifestData; +}) { + const orderedTeams = [...selectedGame.teams].sort((left, right) => + left.side === right.side ? 0 : left.side === "blue" ? -1 : 1, + ); + const participants = orderedTeams.flatMap((team) => team.participants); + const defaultKey = participants[0] ? participantBuildKey(participants[0]) : ""; + const [selectedKey, setSelectedKey] = useState(defaultKey); + const effectiveSelectedKey = participants.some( + (participant) => participantBuildKey(participant) === selectedKey, + ) + ? selectedKey + : defaultKey; + const selectedParticipant = + participants.find( + (participant) => + participantBuildKey(participant) === effectiveSelectedKey, + ) ?? participants[0]; + + if (!selectedParticipant) { + return ( +
+ 빌드 데이터가 없습니다 +
+ ); + } + + return ( +
+ +
+ +
+ + +
+
+
+ ); +} + +function BuildChampionSelector({ + selectedGame, + detail, + manifest, + selectedKey, + onSelect, +}: { + selectedGame: MatchGameDetail; + detail: ApiInternalMatchDetailResponse; + manifest: DdragonManifestData; + selectedKey: string; + onSelect: (key: string) => void; +}) { + const orderedTeams = [...selectedGame.teams].sort((left, right) => + left.side === right.side ? 0 : left.side === "blue" ? -1 : 1, + ); + + return ( +
+ {orderedTeams.map((team) => { + const tone = sideTone(team.side); + return ( +
+
+
+ {sideLabel(team.side)} Side +
+
+ {getTeamName(detail, team.teamIndex)} +
+
+
+ {team.participants.map((participant) => ( + onSelect(participantBuildKey(participant))} + /> + ))} +
+
+ ); + })} +
+ ); +} + +function BuildChampionButton({ + participant, + manifest, + selected, + onClick, +}: { + participant: MatchGameParticipant; + manifest: DdragonManifestData; + selected: boolean; + onClick: () => void; +}) { + const icon = championIconUrl(manifest, participant.championId); + const championName = + championDisplayName(manifest, participant.championId) ?? + String(participant.championId); + const tone = sideTone(participant.side); + + return ( + + ); +} + +function RunesPanel({ + participant, + manifest, +}: { + participant: MatchGameParticipant; + manifest: DdragonManifestData; +}) { + const selectedIds = selectedRuneIds(participant); + const primaryStyleId = + participant.perks.primaryStyle ?? participant.perks.styles?.[0]?.styleId; + const subStyleId = + participant.perks.subStyle ?? participant.perks.styles?.[1]?.styleId; + const primaryStyle = findRuneStyle(manifest, primaryStyleId); + const subStyle = findRuneStyle(manifest, subStyleId); + + return ( +
+
+
+
Runes
+
+ {participant.summonerName} +
+
+ +
+
+ + +
+ +
+ ); +} + +function RuneTreeColumn({ + label, + runeStyle, + selection, + selectedIds, + manifest, +}: { + label: string; + runeStyle: RuneStyleEntry | null; + selection: ReturnType; + selectedIds: Set; + manifest: DdragonManifestData; +}) { + if (!runeStyle) { + return ( +
+
{label}
+
+ 룬 데이터 없음 +
+
+ ); + } + + const styleIcon = runeStyleIconUrl(manifest, runeStyle.id); + const selectionIds = new Set(selection?.perkIds ?? []); + + return ( +
+
+ + {styleIcon ? ( + + ) : null} + +
+
{label}
+
+ {runeStyle.name} +
+
+
+
+ {runeStyle.slots.map((slot, slotIndex) => ( +
+ {slot.runes.map((rune) => { + const selected = + selectedIds.has(rune.id) || selectionIds.has(rune.id); + const icon = runeIconUrl(manifest, rune.id); + return ( + + {icon ? ( + + ) : null} + + ); + })} +
+ ))} +
+
+ ); +} + +function RuneShardRows({ participant }: { participant: MatchGameParticipant }) { + const statPerks = participant.perks.statPerks; + const shards = [ + { label: "공격", value: statPerks?.offense }, + { label: "보조", value: statPerks?.flex }, + { label: "방어", value: statPerks?.defense }, + ].filter((shard) => typeof shard.value === "number" && shard.value > 0); + + if (shards.length === 0) return null; + + return ( +
+
스탯 파편
+
+ {shards.map((shard) => ( + + {shard.label} + {STAT_PERK_LABELS[shard.value ?? 0] ?? shard.value} + + ))} +
+
+ ); +} + +function ItemBuildPanel({ + participant, + manifest, +}: { + participant: MatchGameParticipant; + manifest: DdragonManifestData; +}) { + const buildEvents = (participant.itemBuild ?? []).filter( + (event) => event.itemId > 0 && event.type === "purchased", + ); + const fallbackItems = [ + ...participant.items.filter((itemId) => itemId > 0), + participant.trinket, + ].filter((itemId) => itemId > 0); + + return ( +
+
Item Build
+ {buildEvents.length > 0 ? ( +
+ {buildEvents.map((event, index) => ( +
+ + {index < buildEvents.length - 1 ? ( + + > + + ) : null} +
+ ))} +
+ ) : fallbackItems.length > 0 ? ( +
+ {fallbackItems.map((itemId, index) => { + const icon = itemIconUrl(manifest, itemId); + return ( + + {icon ? ( + + ) : null} + + ); + })} +
+ ) : ( +
+ 아이템 빌드 데이터 없음 +
+ )} +
+ ); +} + +function ItemBuildNode({ + itemId, + timestamp, + manifest, +}: { + itemId: number; + timestamp: number; + manifest: DdragonManifestData; +}) { + const icon = itemIconUrl(manifest, itemId); + + return ( +
+ + {icon ? ( + + ) : null} + + + {formatDuration(timestamp)} + +
+ ); +} + +function SkillBuildPanel({ participant }: { participant: MatchGameParticipant }) { + const skillEvents = participant.skillBuild ?? []; + const skillByLevel = new Map( + skillEvents.map((event) => [event.level, event]), + ); + + return ( +
+
+
Skill Build
+
+ Lv. {skillEvents.length || participant.championLevel || "-"} +
+
+ {skillEvents.length > 0 ? ( +
+
+ {SKILL_ROWS.map((row) => ( +
+
+ {row.label} +
+ {Array.from({ length: 18 }, (_, index) => index + 1).map( + (level) => { + const event = skillByLevel.get(level); + const active = event?.skillSlot === row.slot; + return ( +
+ {active ? level : ""} +
+ ); + }, + )} +
+ ))} +
+
+ ) : ( +
+ 스킬 빌드 데이터 없음 +
+ )} +
+ ); +} + +function DamagePanel({ + selectedGame, + detail, + manifest, + metric, +}: { + selectedGame: MatchGameDetail; + detail: ApiInternalMatchDetailResponse; + manifest: ReturnType["data"]; + metric: "dealt" | "taken"; +}) { + const participants = selectedGame.teams.flatMap((team) => team.participants); + const maxValue = Math.max( + 1, + ...participants.map((participant) => + metric === "dealt" + ? participant.damageDealtToChampions + : (participant.damageTaken ?? 0), + ), + ); + const orderedTeams = [...selectedGame.teams].sort((left, right) => + left.side === right.side ? 0 : left.side === "blue" ? -1 : 1, + ); + + return ( +
+ {orderedTeams.map((team) => { + const tone = sideTone(team.side); + return ( +
+
+
+ {getTeamName(detail, team.teamIndex)} · {sideLabel(team.side)} +
+
+
+
+ {team.participants.map((participant) => { + const value = + metric === "dealt" + ? participant.damageDealtToChampions + : (participant.damageTaken ?? 0); + return ( +
+ +
+
+
+
+ {formatNumber(value)} +
+
+ ); + })} +
+
+
+ ); + })} +
+ ); +} + +function GameAnalysisPanel({ + activeTab, + selectedGame, + detail, + manifest, +}: { + activeTab: DetailTab; + selectedGame: MatchGameDetail; + detail: ApiInternalMatchDetailResponse; + manifest: ReturnType["data"]; +}) { + const orderedTeams = [...selectedGame.teams].sort((left, right) => + left.side === right.side ? 0 : left.side === "blue" ? -1 : 1, + ); + + if (activeTab === "build") { + return ( + + ); + } + + if (activeTab === "damageDealt") { + return ( + + ); + } + + if (activeTab === "damageTaken") { + return ( + + ); + } + + return ( +
+ {orderedTeams.map((team) => ( + + ))} +
+ ); +} + +function GameTabs({ + detail, + currentGameNumber, +}: { + detail: ApiInternalMatchDetailResponse; + currentGameNumber: number; +}) { + return ( + + ); +} + +function MatchScoreHero({ + detail, + selectedGame, +}: { + detail: ApiInternalMatchDetailResponse; + selectedGame: MatchGameDetail; +}) { + const selectedSeries = resolveSelectedSeries(detail, selectedGame); + const [leftTeam, rightTeam] = selectedGame.teams; + const leftScore = + selectedSeries?.teamAIndex === leftTeam?.teamIndex + ? selectedSeries?.teamAWins + : selectedSeries?.teamBWins; + const rightScore = + selectedSeries?.teamBIndex === rightTeam?.teamIndex + ? selectedSeries?.teamBWins + : selectedSeries?.teamAWins; + + return ( +
+
+
+ + ← 경기 결과로 돌아가기 + +

+ {detail.match.title} · {selectedGame.gameNumber}세트 +

+

+ {formatDateTime(selectedGame.gameCreation)} ·{" "} + {formatDuration(selectedGame.gameDuration)} ·{" "} + {selectedGame.riotMatchId} +

+
+ {leftTeam && rightTeam && ( +
+
+
+ {getTeamName(detail, leftTeam.teamIndex)} +
+
+ {sideLabel(leftTeam.side)} +
+
+
+ + {leftScore ?? (leftTeam.win ? 1 : 0)} + + VS + + {rightScore ?? (rightTeam.win ? 1 : 0)} + +
+
+
+ {getTeamName(detail, rightTeam.teamIndex)} +
+
+ {sideLabel(rightTeam.side)} +
+
+
+ )} +
+ +
+ ); +} + +export default function MatchGameDetailPage() { + const { id, gameNumber } = useParams(); + const [activeTab, setActiveTab] = useState("summary"); + const requestedGameNumber = Number(gameNumber); + const detailQuery = useInternalMatchDetail(id, DEFAULT_COMMUNITY_ID); + const { data: ddragon } = useDdragonManifest(); + const detail = detailQuery.data; + + if (detailQuery.isLoading) { + return ( +
+ 세트 상세 기록을 불러오는 중... +
+ ); + } + + if (detailQuery.error || !detail) { + return ( +
+

세트 기록을 찾을 수 없습니다

+ + 경기 결과로 돌아가기 + +
+ ); + } + + const selectedGame = + detail.games.find((game) => game.gameNumber === requestedGameNumber) ?? + detail.games[0]; + + if (!selectedGame) { + return ( +
+

수집된 세트 기록이 없습니다

+ + 경기 결과로 돌아가기 + +
+ ); + } + + return ( +
+ + + + + + +
+ + +
+
+ ); +}