import { Injectable } from '@nestjs/common'; import mongoose from 'mongoose'; import type { MatchDocument, MatchGameResultParticipant, MatchStatsItemBuildEvent, MatchStatsObjectiveEvent, MatchStatsObjectiveSummary, MatchStatsSkillBuildEvent, MatchStatsTimelinePoint, TeamSide, } from '../global/database/schema'; import type { RiotMatchDto, RiotMatchParticipantDto, RiotMatchTimelineDto, } from '../riot/riot.types'; import type { InternalMatchCardView } from './community-stats.types'; import type { InternalGameDetail, InternalRecord, 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, ); 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, timeline, params.timelineLoadAttempted === true, ) : this.toFallbackGameDetail(params.match, game); }); const records = gameDetails.flatMap((detail) => detail.teams.flatMap((team) => team.participants), ); const gameCreations = gameDetails.map((detail) => detail.gameCreation); return { matchCard, records, gameDetails, userIds: [ ...new Map( records .filter((record) => mongoose.isValidObjectId(record.userId)) .map((record) => [ record.userId, new mongoose.Types.ObjectId(record.userId), ]), ).values(), ], championIds: [...new Set(records.map((record) => record.championId))], gameCreationMin: gameCreations.length > 0 ? Math.min(...gameCreations) : params.match.scheduledAt.getTime(), gameCreationMax: gameCreations.length > 0 ? Math.max(...gameCreations) : params.match.scheduledAt.getTime(), }; } private toMatchCard( match: MatchDocument, games: NonNullable['games'], ): InternalMatchCardView { const participantById = new Map( match.participants.map((participant) => [ participant.userId.toString(), participant, ]), ); return { matchId: match._id.toString(), title: match.title, scheduledAt: match.scheduledAt.toISOString(), status: match.status === 'finished' ? 'finished' : 'in-progress', gameCount: match.gameCount, winnerTeamIndex: match.result?.winnerTeamIndex, seriesResults: match.result?.seriesResults ?? [], games: games.map((game) => ({ gameNumber: game.gameNumber, riotMatchId: game.riotMatchId ?? null, blueTeamIndex: game.blueTeamIndex, redTeamIndex: game.redTeamIndex, winnerTeamIndex: game.winnerTeamIndex ?? null, winnerSide: game.winnerSide ?? null, gameDuration: game.gameDuration, })), teams: match.teams.map((team) => ({ teamIndex: team.teamIndex, name: team.name, members: team.members.map((member) => { const participant = participantById.get(member.userId.toString()); return { userId: member.userId.toString(), summonerName: participant?.gameName ?? 'Unknown', profileIconId: participant?.profileIconId ?? 0, }; }), })), }; } private toGameDetail( match: MatchDocument, game: NonNullable['games'][number], raw: RiotMatchDto, timeline?: RiotMatchTimelineDto, timelineLoadAttempted = false, ): InternalGameDetail { const puuidByUserId = new Map( match.participants .filter((participant) => participant.puuid) .map((participant) => [ participant.userId.toString(), participant.puuid as string, ]), ); const rawByPuuid = new Map( raw.info.participants.map((participant) => [ participant.puuid, participant, ]), ); const rawTeamIdBySide = new Map(); for (const participant of game.participants) { const puuid = puuidByUserId.get(participant.userId.toString()); const rawParticipant = puuid ? rawByPuuid.get(puuid) : undefined; if (rawParticipant) { 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; const rawTeamId = rawTeamIdBySide.get(side); const rawTeam = raw.info.teams.find( (team) => team.teamId === rawTeamId, ); const teamRawParticipants = raw.info.participants.filter( (participant) => participant.teamId === rawTeamId, ); const teamKills = teamRawParticipants.reduce( (sum, participant) => sum + participant.kills, 0, ); const teamDamage = teamRawParticipants.reduce( (sum, participant) => sum + participant.totalDamageDealtToChampions, 0, ); return { teamIndex, side, win: game.winnerSide === side, 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) => { const rawParticipant = rawByPuuid.get( puuidByUserId.get(participant.userId.toString()) ?? '', ); return this.toRecord({ match, game, participant, rawParticipant, buildEvents: rawParticipant ? buildEventsByParticipantId.get( rawParticipant.participantId, ) : undefined, teamKills, teamDamage, }); }), }; }), }; } private toFallbackGameDetail( match: MatchDocument, game: NonNullable['games'][number], ): InternalGameDetail { return { gameNumber: game.gameNumber, riotMatchId: game.riotMatchId, 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: emptyObjectives(), bans: [], participants: game.participants .filter((participant) => participant.side === side) .map((participant) => this.toRecord({ match, game, participant, teamKills: 0, teamDamage: 0, }), ), })), }; } private toRecord(params: { match: MatchDocument; game: NonNullable['games'][number]; participant: MatchGameResultParticipant; rawParticipant?: RiotMatchParticipantDto; buildEvents?: ParticipantBuildEvents; teamKills: number; teamDamage: number; }): InternalRecord { const { match, game, participant, rawParticipant, buildEvents, teamKills, teamDamage, } = params; const snapshot = match.participants.find((item) => item.userId.equals(participant.userId), ); const minutes = Math.max( (rawParticipant?.timePlayed ?? game.gameDuration) / 60, 1, ); const cs = rawParticipant ? rawParticipant.totalMinionsKilled + rawParticipant.neutralMinionsKilled : 0; const damage = rawParticipant?.totalDamageDealtToChampions ?? 0; const killParticipation = percent( participant.kills + participant.assists, teamKills, ); const damageShare = percent(damage, teamDamage); const rating = this.resolveRating({ kills: participant.kills, deaths: participant.deaths, assists: participant.assists, killParticipation, csPerMin: average(cs, minutes), damageShare, visionPerMin: average(rawParticipant?.visionScore ?? 0, minutes), }); return { matchId: match._id.toString(), title: match.title, scheduledAt: match.scheduledAt, gameNumber: game.gameNumber, riotMatchId: game.riotMatchId, gameCreation: game.gameCreation, gameDuration: game.gameDuration, userId: participant.userId.toString(), summonerName: snapshot?.gameName ?? rawParticipant?.riotIdGameName ?? rawParticipant?.summonerName ?? 'Unknown', tagLine: snapshot?.tagLine ?? rawParticipant?.riotIdTagLine ?? '', profileIconId: snapshot?.profileIconId ?? 0, teamIndex: participant.teamIndex, side: participant.side, championId: participant.championId, championLevel: rawParticipant?.champLevel ?? 0, teamPosition: rawParticipant?.teamPosition || rawParticipant?.individualPosition || '', kills: participant.kills, deaths: participant.deaths, assists: participant.assists, win: participant.win, cs, csPerMin: average(cs, minutes), gold: rawParticipant?.goldEarned ?? 0, gpm: average(rawParticipant?.goldEarned ?? 0, minutes), damageDealtToChampions: damage, damageTaken: rawParticipant?.totalDamageTaken ?? 0, damageShare, killParticipation, visionScore: rawParticipant?.visionScore ?? 0, controlWardsBought: numberField( rawParticipant, 'visionWardsBoughtInGame', ), wardsPlaced: rawParticipant?.wardsPlaced ?? 0, wardsKilled: rawParticipant?.wardsKilled ?? 0, firstBloodKill: booleanField(rawParticipant, 'firstBloodKill'), firstBloodAssist: booleanField(rawParticipant, 'firstBloodAssist'), items: [ rawParticipant?.item0 ?? 0, rawParticipant?.item1 ?? 0, rawParticipant?.item2 ?? 0, rawParticipant?.item3 ?? 0, rawParticipant?.item4 ?? 0, rawParticipant?.item5 ?? 0, ], trinket: rawParticipant?.item6 ?? 0, summonerSpells: [ rawParticipant?.summoner1Id ?? 0, rawParticipant?.summoner2Id ?? 0, ], perks: rawParticipant ? this.resolvePerks(rawParticipant) : {}, itemBuild: buildEvents?.items ?? [], skillBuild: buildEvents?.skills ?? [], rating, }; } private resolvePerks(participant: RiotMatchParticipantDto) { const primary = participant.perks.styles.find( (style) => style.description === 'primaryStyle', ); const sub = participant.perks.styles.find( (style) => style.description === 'subStyle', ); return { 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, }; } private resolveRating(params: { kills: number; deaths: number; assists: number; killParticipation: number; csPerMin: number; damageShare: number; visionPerMin: number; }): number { const kdaScore = kda(params.kills, params.deaths, params.assists); const score = Math.min(kdaScore / 6, 1) * 4 + Math.min(params.killParticipation / 100, 1) * 2 + Math.min(params.csPerMin / 9, 1) * 2 + Math.min(params.damageShare / 35, 1) + Math.min(params.visionPerMin / 2, 1); return round(score); } } function kda(kills: number, deaths: number, assists: number): number { return deaths === 0 ? kills + assists : round((kills + assists) / deaths); } function percent(value: number, total: number): number { return total > 0 ? Math.round((value / total) * 100) : 0; } 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; } function numberField( participant: RiotMatchParticipantDto | undefined, key: string, ): number { 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, }; }