import { BadRequestException, Injectable, Logger, NotFoundException, } from '@nestjs/common'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import type { CommunityDocument, RiotLane } from '../global/database/schema'; import type { HistorySeasonDto, RecentMatchView, } from '../match-history/match-history.types'; import { CommunityStatsCacheService } from './community-stats-cache.service'; import type { CommunityStatsFilters, InternalMatchCardView, InternalMatchDetailResponse, InternalMatchListResponse, LeaderboardChampionStats, LeaderboardResponse, LeaderboardRow, LeaderHighlight, TeamInsightsResponse, UserInternalHistoryResponse, } from './community-stats.types'; import { MatchStatsDetailFragment, MatchStatsRepository, MatchStatsUserRecordFragment, } from './match-stats.repository'; import { MatchStatsService } from './match-stats.service'; import { InternalGameDetail, InternalRecord, MATCH_STATS_BUILDER_VERSION, } from './match-stats.types'; const DEFAULT_LIST_LIMIT = 20; const MAX_LIST_LIMIT = 50; const MAX_MATCH_SCAN = 300; const MIN_HIGHLIGHT_GAMES = 5; const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 4; const INCOMPLETE_MATCH_DETAIL_TTL_SECONDS = 60; interface CommunityStatsContext { community: CommunityDocument; season: HistorySeasonDto; from: Date | null; to: Date | null; } interface BaseDataset { season: HistorySeasonDto; matches: InternalMatchCardView[]; records: InternalRecord[]; detailsByMatchId: Map; } @Injectable() export class CommunityStatsService { private readonly logger = new Logger(CommunityStatsService.name); private readonly matchDetailInFlight = new Map< string, Promise >(); private readonly userInternalHistoryInFlight = new Map< string, Promise >(); constructor( private readonly connectionService: ConnectionService, private readonly cacheService: CommunityStatsCacheService, private readonly matchStatsRepository: MatchStatsRepository, private readonly matchStatsService: MatchStatsService, ) {} public async getMatches(params: { communityId: mongoose.Types.ObjectId; filters: CommunityStatsFilters; }): Promise { const key = this.cacheKey('matches', params.communityId, params.filters); const cached = await this.cacheService.get(key); if (cached) return cached; const limit = this.clampLimit( params.filters.limit, DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT, ); const dataset = await this.buildBaseDataset( params.communityId, params.filters, ); const filtered = params.filters.championId ? dataset.matches.filter((match) => dataset.records.some( (record) => record.matchId === match.matchId && record.championId === params.filters.championId, ), ) : dataset.matches; const cursor = params.filters.cursor; const page = filtered .filter( (match) => !cursor || new Date(match.scheduledAt).getTime() < cursor, ) .slice(0, limit + 1); const visible = page.slice(0, limit); const response: InternalMatchListResponse = { matches: visible, nextCursor: page.length > limit ? new Date(visible[visible.length - 1]?.scheduledAt ?? 0).getTime() : null, season: dataset.season, }; await this.cacheService.set(key, response); return response; } public async getLeaderboard(params: { communityId: mongoose.Types.ObjectId; filters: CommunityStatsFilters; }): Promise { const key = this.cacheKey( 'leaderboard', params.communityId, params.filters, ); const cached = await this.cacheService.get(key); if (cached) return cached; const dataset = await this.buildBaseDataset( params.communityId, params.filters, ); const records = this.applyChampionFilter(dataset.records, params.filters); const rows = this.buildLeaderboardRows(records); const response = { rows, season: dataset.season }; await this.cacheService.set(key, response); return response; } public async getTeamInsights(params: { communityId: mongoose.Types.ObjectId; filters: CommunityStatsFilters; }): Promise { const key = this.cacheKey( 'teamInsights', params.communityId, params.filters, ); const cached = await this.cacheService.get(key); if (cached) return cached; const dataset = await this.buildBaseDataset( params.communityId, params.filters, ); const records = this.applyChampionFilter(dataset.records, params.filters); const rows = this.buildLeaderboardRows(records); const gameDetails = [...dataset.detailsByMatchId.values()].flat(); const blueGames = gameDetails.length; const redGames = gameDetails.length; const blueWins = gameDetails.filter( (game) => game.winnerSide === 'blue', ).length; const redWins = gameDetails.filter( (game) => game.winnerSide === 'red', ).length; const response: TeamInsightsResponse = { season: dataset.season, sideWinRate: { blue: this.percent(blueWins, blueGames), red: this.percent(redWins, redGames), bluePicks: blueGames, redPicks: redGames, }, topKda: this.toHighlight( rows .filter((row) => row.games >= MIN_HIGHLIGHT_GAMES) .sort((left, right) => right.kda - left.kda)[0], 'kda', ), mostKills: this.toHighlight( rows.sort((left, right) => right.totalKills - left.totalKills)[0], 'totalKills', ), topTeamGpm: this.toSingleGameHighlight( records.sort((left, right) => right.gpm - left.gpm)[0], 'gpm', ), topKillParticipation: this.toHighlight( rows .filter((row) => row.games >= MIN_HIGHLIGHT_GAMES) .sort( (left, right) => right.avgKillParticipation - left.avgKillParticipation, )[0], 'avgKillParticipation', ), bestFarm: this.toHighlight( rows .filter((row) => row.games >= MIN_HIGHLIGHT_GAMES) .sort((left, right) => right.avgCsPerMin - left.avgCsPerMin)[0], 'avgCsPerMin', ), minGamesThreshold: MIN_HIGHLIGHT_GAMES, }; await this.cacheService.set(key, response); return response; } public async getMatchDetail(params: { communityId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId; }): Promise { const key = `riot:communitystats:matchDetail:v${MATCH_STATS_BUILDER_VERSION}:r${MATCH_DETAIL_RESPONSE_CACHE_VERSION}:${params.communityId.toString()}:${params.matchId.toString()}`; const cached = await this.cacheService.get(key); if (cached && isCompleteMatchDetailResponse(cached)) return cached; const inFlight = this.matchDetailInFlight.get(key); if (inFlight) return inFlight; const promise = this.buildMatchDetailResponse(params, key); this.matchDetailInFlight.set(key, promise); try { return await promise; } finally { if (this.matchDetailInFlight.get(key) === promise) { this.matchDetailInFlight.delete(key); } } } private async buildMatchDetailResponse( params: { communityId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId; }, key: string, ): Promise { const dataset = await this.buildBaseDataset(params.communityId, { seasonId: 'all', }); const match = dataset.matches.find( (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: gameDetails.map((game) => ({ gameNumber: game.gameNumber, riotMatchId: game.riotMatchId, gameCreation: game.gameCreation, gameDuration: game.gameDuration, gameVersion: game.gameVersion, timeline: game.timeline ?? [], objectiveEvents: game.objectiveEvents ?? [], timelineEvents: game.timelineEvents ?? 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) => ({ participantId: record.participantId, checkpoints: record.checkpoints, userId: record.userId, summonerName: record.summonerName, tagLine: record.tagLine, teamIndex: record.teamIndex, side: record.side, teamPosition: record.teamPosition, championId: record.championId, championLevel: record.championLevel, kills: record.kills, deaths: record.deaths, assists: record.assists, cs: record.cs, csPerMin: record.csPerMin, 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, })), })), })), }; if (gameDetails.every((game) => game.timelineLoaded === true)) { await this.cacheService.setDetail(key, response); } else { await this.cacheService.set( key, response, INCOMPLETE_MATCH_DETAIL_TTL_SECONDS, ); } return response; } public async getUserInternalHistory(params: { communityId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId; filters: CommunityStatsFilters; }): Promise { const key = this.cacheKey( `userInternal:v3:${params.userId.toString()}`, params.communityId, params.filters, ); const cached = await this.cacheService.get(key); if (cached) return cached; // Auction viewers can all request the same next player's internal history // at once. Coalesce local cache misses so one player change does one DB read. const inFlight = this.userInternalHistoryInFlight.get(key); if (inFlight) return inFlight; const promise = this.buildUserInternalHistoryResponse(params, key); this.userInternalHistoryInFlight.set(key, promise); try { return await promise; } finally { if (this.userInternalHistoryInFlight.get(key) === promise) { this.userInternalHistoryInFlight.delete(key); } } } public invalidateCommunity( communityId: mongoose.Types.ObjectId, ): Promise { return this.cacheService.invalidateCommunity(communityId.toString()); } private async buildBaseDataset( communityId: mongoose.Types.ObjectId, filters: CommunityStatsFilters, ): Promise { const context = await this.resolveContext(communityId, filters); let fragments = await this.matchStatsRepository.findByCommunity({ communityId, fromGameCreation: context.from?.getTime(), toGameCreation: context.to?.getTime(), limit: MAX_MATCH_SCAN, }); const rebuilt = await this.rebuildMissingOrStaleFragments(communityId); if (rebuilt > 0) { fragments = await this.matchStatsRepository.findByCommunity({ communityId, fromGameCreation: context.from?.getTime(), toGameCreation: context.to?.getTime(), limit: MAX_MATCH_SCAN, }); } const cards: InternalMatchCardView[] = []; const records: InternalRecord[] = []; const detailsByMatchId = new Map(); for (const fragment of fragments) { const filteredGames = fragment.gameDetails .filter((game) => this.isGameInRange(game.gameCreation, context)) .sort((left, right) => left.gameNumber - right.gameNumber); if (filteredGames.length === 0) continue; const card = this.adjustCardForRange( fragment.matchCard as unknown as InternalMatchCardView, filteredGames, ); cards.push(card); detailsByMatchId.set(fragment.matchId.toString(), filteredGames); const allowedGameNumbers = new Set( filteredGames.map((game) => game.gameNumber), ); records.push( ...fragment.records.filter((record) => allowedGameNumbers.has(record.gameNumber), ), ); } return { season: context.season, matches: cards, records, detailsByMatchId, }; } private async buildUserInternalHistoryResponse( params: { communityId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId; filters: CommunityStatsFilters; }, cacheKey: string, ): Promise { const context = await this.resolveContext( params.communityId, params.filters, ); const userId = params.userId.toString(); const fragments = await this.matchStatsRepository.findUserRecordFragments({ communityId: params.communityId, userId: params.userId, fromGameCreation: context.from?.getTime(), toGameCreation: context.to?.getTime(), limit: MAX_MATCH_SCAN, }); const allUserRecords = this.extractUserRecords(fragments, userId, context); const records = this.applyChampionFilter(allUserRecords, params.filters); const limit = this.clampLimit(params.filters.limit, 30, 50); const cursor = params.filters.cursor; const page = records .filter((record) => !cursor || record.gameCreation < cursor) .slice(0, limit + 1); const visible = page.slice(0, limit); const detailsByMatchId = await this.loadVisibleDetails( params.communityId, visible, context, ); const dataset: BaseDataset = { season: context.season, matches: [], records: allUserRecords, detailsByMatchId, }; const response: UserInternalHistoryResponse = { season: context.season, championStats: this.buildUserChampionStats( allUserRecords, context.season, ), summary: this.buildUserSummary(records, visible.length || limit), matches: visible.map((record) => this.toRecentMatchView(record, dataset)), nextCursor: page.length > limit ? (visible[visible.length - 1]?.gameCreation ?? null) : null, lastFetchedAt: records[0] ? new Date(records[0].gameCreation).toISOString() : null, }; await this.cacheService.set(cacheKey, response); return response; } private extractUserRecords( fragments: MatchStatsUserRecordFragment[], userId: string, context: CommunityStatsContext, ): InternalRecord[] { return fragments .flatMap((fragment) => fragment.records.filter( (record) => record.userId === userId && this.isGameInRange(record.gameCreation, context), ), ) .sort((left, right) => right.gameCreation - left.gameCreation); } private async loadVisibleDetails( communityId: mongoose.Types.ObjectId, visible: InternalRecord[], context: CommunityStatsContext, ): Promise> { const matchIds = [ ...new Set( visible .map((record) => record.matchId) .filter((matchId) => mongoose.isValidObjectId(matchId)), ), ].map((matchId) => new mongoose.Types.ObjectId(matchId)); const fragments = await this.matchStatsRepository.findDetailsByMatches({ communityId, matchIds, }); return this.toDetailsByMatchId(fragments, context); } private toDetailsByMatchId( fragments: MatchStatsDetailFragment[], context: CommunityStatsContext, ): Map { const detailsByMatchId = new Map(); for (const fragment of fragments) { detailsByMatchId.set( fragment.matchId.toString(), fragment.gameDetails.filter((game) => this.isGameInRange(game.gameCreation, context), ), ); } return detailsByMatchId; } private async rebuildMissingOrStaleFragments( communityId: mongoose.Types.ObjectId, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const [matches, fragments] = await Promise.all([ MatchModel.find({ communityId, status: { $in: ['finished', 'in-progress'] }, $or: [ { competitionId: { $exists: true } }, { 'result.games.0': { $exists: true } }, ], }) .sort({ scheduledAt: -1 }) .limit(MAX_MATCH_SCAN) .select({ _id: 1, competitionId: 1 }) .exec(), this.matchStatsRepository.findByCommunity({ communityId, limit: MAX_MATCH_SCAN, }), ]); const fragmentByMatchId = new Map( fragments.map((fragment) => [fragment.matchId.toString(), fragment]), ); const competitionIds = matches.flatMap((match) => match.competitionId ? [match.competitionId] : [], ); const CompetitionModel = await this.connectionService.getModel('competition'); const competitions = competitionIds.length > 0 ? await CompetitionModel.find({ _id: { $in: competitionIds } }) .select({ _id: 1, revision: 1, projectorVersion: 1 }) .lean() .exec() : []; const competitionById = new Map( competitions.map((competition) => [ competition._id.toString(), competition, ]), ); let rebuilt = 0; for (const match of matches) { const fragment = fragmentByMatchId.get(match._id.toString()); const competition = match.competitionId ? competitionById.get(match.competitionId.toString()) : undefined; const sourceIsCurrent = match.competitionId ? Boolean( competition && fragment?.sourceCompetitionId?.toString() === competition._id.toString() && (fragment.sourceRevision ?? -1) >= competition.revision && (fragment.projectorVersion ?? -1) >= competition.projectorVersion, ) : true; if ( fragment && fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION && sourceIsCurrent ) { continue; } try { await this.matchStatsService.buildAndUpsert(match._id); rebuilt += 1; } catch (error) { this.logger.warn( `Failed to build match stats fragment for ${match._id.toString()}: ${ error instanceof Error ? error.message : error }`, ); } } return rebuilt; } private adjustCardForRange( card: InternalMatchCardView, filteredGames: InternalGameDetail[], ): InternalMatchCardView { const allowedGameNumbers = new Set( filteredGames.map((game) => game.gameNumber), ); const games = card.games.filter((game) => allowedGameNumbers.has(game.gameNumber), ); const seriesResults = this.rebuildSeriesResults(games); return { ...card, games, seriesResults, winnerTeamIndex: this.resolveWinnerTeamIndex(seriesResults), }; } private rebuildSeriesResults( games: InternalMatchCardView['games'], ): InternalMatchCardView['seriesResults'] { const bySeries = new Map< string, InternalMatchCardView['seriesResults'][number] >(); for (const game of games) { if (game.winnerTeamIndex === null) continue; const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex); const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex); const key = `${teamAIndex}:${teamBIndex}`; const current = bySeries.get(key) ?? { teamAIndex, teamBIndex, teamAWins: 0, teamBWins: 0, }; if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1; if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1; current.winnerTeamIndex = current.teamAWins > current.teamBWins ? teamAIndex : current.teamBWins > current.teamAWins ? teamBIndex : undefined; bySeries.set(key, current); } return [...bySeries.values()].sort( (left, right) => left.teamAIndex - right.teamAIndex || left.teamBIndex - right.teamBIndex, ); } private resolveWinnerTeamIndex( seriesResults: InternalMatchCardView['seriesResults'], ): number | undefined { const wins = new Map(); for (const series of seriesResults) { if (!series.winnerTeamIndex) continue; wins.set( series.winnerTeamIndex, (wins.get(series.winnerTeamIndex) ?? 0) + 1, ); } return [...wins.entries()].sort( (left, right) => right[1] - left[1] || left[0] - right[0], )[0]?.[0]; } private async resolveContext( communityId: mongoose.Types.ObjectId, filters: CommunityStatsFilters, ): Promise { const CommunityModel = await this.connectionService.getModel('community'); const community = await CommunityModel.findById(communityId).exec(); if (!community) throw new NotFoundException('Community not found.'); const season = this.resolveSeason(community, filters.seasonId); const from = filters.from ? new Date(filters.from) : season.startedAt ? new Date(season.startedAt) : null; const to = filters.to ? new Date(filters.to) : null; if (from && Number.isNaN(from.getTime())) { throw new BadRequestException('Invalid from date.'); } if (to && Number.isNaN(to.getTime())) { throw new BadRequestException('Invalid to date.'); } return { community, season, from, to }; } private resolveSeason( community: CommunityDocument, seasonId?: string, ): HistorySeasonDto { const seasons = this.resolveSeasons(community); if (seasonId === 'all') { return { id: 'all', label: '전체 시즌', startedAt: null, endedAt: null }; } if (seasonId && seasonId !== 'current') { const selected = seasons.find((season) => season.id === seasonId); if (!selected) throw new BadRequestException('Invalid seasonId.'); return selected; } return ( seasons.find((season) => !season.endedAt) ?? seasons[0] ?? { id: 'current', label: '현재 시즌', startedAt: community.seasonStartedAt?.toISOString() ?? null, endedAt: null, } ); } private resolveSeasons(community: CommunityDocument): HistorySeasonDto[] { const configured = community.seasons?.map((season) => ({ id: season.id, label: season.label, startedAt: season.startedAt.toISOString(), endedAt: season.endedAt?.toISOString() ?? null, })); if (configured?.length) return configured; return [ { id: 'current', label: '현재 시즌', startedAt: community.seasonStartedAt?.toISOString() ?? null, endedAt: null, }, ]; } private buildLeaderboardRows(records: InternalRecord[]): LeaderboardRow[] { const byUser = new Map(); for (const record of records) { byUser.set(record.userId, [...(byUser.get(record.userId) ?? []), record]); } return [...byUser.entries()] .map(([userId, rows]) => this.toLeaderboardRow(userId, rows)) .sort( (left, right) => right.games - left.games || right.winRate - left.winRate, ); } private toLeaderboardRow( userId: string, records: InternalRecord[], ): LeaderboardRow { const first = records[0]; const wins = records.filter((record) => record.win).length; const kills = this.sum(records, 'kills'); const deaths = this.sum(records, 'deaths'); const assists = this.sum(records, 'assists'); const byLane: LeaderboardRow['byLane'] = {}; for (const lane of [ 'TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY', ] as RiotLane[]) { const laneRecords = records.filter( (record) => record.teamPosition === lane, ); if (laneRecords.length === 0) continue; byLane[lane] = { games: laneRecords.length, wins: laneRecords.filter((record) => record.win).length, kda: this.kda( this.sum(laneRecords, 'kills'), this.sum(laneRecords, 'deaths'), this.sum(laneRecords, 'assists'), ), }; } const championCounts = new Map(); for (const record of records) { const current = championCounts.get(record.championId) ?? { games: 0, wins: 0, }; current.games += 1; current.wins += record.win ? 1 : 0; championCounts.set(record.championId, current); } return { userId, summonerName: first?.summonerName ?? 'Unknown', profileIconId: first?.profileIconId ?? 0, games: records.length, wins, losses: records.length - wins, winRate: this.percent(wins, records.length), totalKills: kills, totalDeaths: deaths, totalAssists: assists, kda: this.kda(kills, deaths, assists), avgGoldPerMin: this.average(this.sum(records, 'gpm'), records.length), avgKillParticipation: this.average( this.sum(records, 'killParticipation'), records.length, ), avgCsPerMin: this.average(this.sum(records, 'csPerMin'), records.length), avgDamageShare: this.average( this.sum(records, 'damageShare'), records.length, ), avgVisionScore: this.average( this.sum(records, 'visionScore'), records.length, ), byLane, topChampions: [...championCounts.entries()] .map(([championId, stat]) => ({ championId, games: stat.games, winRate: this.percent(stat.wins, stat.games), })) .sort( (left, right) => right.games - left.games || right.winRate - left.winRate, ) .slice(0, 3), }; } private buildUserChampionStats( records: InternalRecord[], season: HistorySeasonDto, ): LeaderboardChampionStats { const byChampion = new Map(); for (const record of records) { byChampion.set(record.championId, [ ...(byChampion.get(record.championId) ?? []), record, ]); } const champions = [...byChampion.entries()] .map(([championId, rows]) => this.toChampionRow(championId, rows)) .sort( (left, right) => right.games - left.games || right.winRate - left.winRate, ); const totals = this.toChampionRow(0, records); return { queueGroup: 'internal', rank: 'all', queueIds: [], season, lastFetchedAt: records[0] ? new Date(records[0].gameCreation).toISOString() : null, champions, totals, }; } private toChampionRow(championId: number, rows: InternalRecord[]) { const wins = rows.filter((record) => record.win).length; const kills = this.sum(rows, 'kills'); const deaths = this.sum(rows, 'deaths'); const assists = this.sum(rows, 'assists'); const gameMinutes = rows.reduce( (sum, record) => sum + Math.max(record.gameDuration / 60, 1), 0, ); return { championId, games: rows.length, wins, losses: rows.length - wins, winRate: this.percent(wins, rows.length), avgKills: this.average(kills, rows.length), avgDeaths: this.average(deaths, rows.length), avgAssists: this.average(assists, rows.length), kda: this.kda(kills, deaths, assists), totalKills: kills, totalDeaths: deaths, totalAssists: assists, doubleKills: 0, tripleKills: 0, quadraKills: 0, pentaKills: 0, avgCs: this.average(this.sum(rows, 'cs'), rows.length), avgCsPerMin: this.average(this.sum(rows, 'cs'), gameMinutes), }; } private buildUserSummary( records: InternalRecord[], requestedLimit: number, ): UserInternalHistoryResponse['summary'] { const views = records.slice(0, requestedLimit); const wins = views.filter((record) => record.win).length; const kills = this.sum(views, 'kills'); const deaths = this.sum(views, 'deaths'); const assists = this.sum(views, 'assists'); const best = views.reduce((bestRecord, record) => { if (!bestRecord) return record; return record.deaths === 0 || record.rating > bestRecord.rating ? record : bestRecord; }, null); return { windowSize: views.length, winRate: this.percent(wins, views.length), wins, losses: views.length - wins, streak: this.resolveStreak(views), kda: this.kda(kills, deaths, assists), avgKills: this.average(kills, views.length), avgDeaths: this.average(deaths, views.length), avgAssists: this.average(assists, views.length), bestRating: best ? { rating: best.deaths === 0 ? 'Perfect' : best.rating, kills: best.kills, deaths: best.deaths, assists: best.assists, matchId: best.riotMatchId, } : null, positionRates: this.resolvePositionRates(views), topChampions: this.resolveTopChampions(views), lastFetchedAt: views[0] ? new Date(views[0].gameCreation).toISOString() : null, }; } private toRecentMatchView( record: InternalRecord, dataset: BaseDataset, ): RecentMatchView { const detail = dataset.detailsByMatchId .get(record.matchId) ?.find((game) => game.riotMatchId === record.riotMatchId); return { matchId: record.riotMatchId, internalMatchId: record.matchId, gameNumber: record.gameNumber, queueId: 0, queueLabel: '내전', gameCreation: record.gameCreation, gameDuration: record.gameDuration, win: record.win, remake: false, championId: record.championId, championLevel: record.championLevel, teamPosition: record.teamPosition, kills: record.kills, deaths: record.deaths, assists: record.assists, kda: this.kda(record.kills, record.deaths, record.assists), rating: record.rating, totalCs: record.cs, csPerMin: record.csPerMin, killParticipation: record.killParticipation, visionScore: record.visionScore, controlWardsBought: record.controlWardsBought, wardsPlaced: record.wardsPlaced, wardsKilled: record.wardsKilled, damageDealtToChampions: record.damageDealtToChampions, damageTaken: record.damageTaken, goldEarned: record.gold, items: record.items, trinket: record.trinket, summonerSpells: record.summonerSpells, perks: record.perks, teams: (detail?.teams ?? []).map((team) => ({ side: team.side === 'blue' ? 100 : 200, win: team.win, objectives: team.objectives, participants: team.participants.map((participant) => ({ puuid: participant.userId, gameName: participant.summonerName, tagLine: '', championId: participant.championId, championLevel: participant.championLevel, teamPosition: participant.teamPosition, kills: participant.kills, deaths: participant.deaths, assists: participant.assists, items: participant.items, trinket: participant.trinket, summonerSpells: participant.summonerSpells, perks: participant.perks, totalCs: participant.cs, csPerMin: participant.csPerMin, goldEarned: participant.gold, damageDealtToChampions: participant.damageDealtToChampions, damageTaken: participant.damageTaken, visionScore: participant.visionScore, wardsPlaced: participant.wardsPlaced, wardsKilled: participant.wardsKilled, controlWardsBought: participant.controlWardsBought, })), })), }; } private applyChampionFilter( records: InternalRecord[], filters: CommunityStatsFilters, ): InternalRecord[] { if (!filters.championId) return records; return records.filter((record) => record.championId === filters.championId); } private isGameInRange( gameCreation: number, context: CommunityStatsContext, ): boolean { if (context.from && gameCreation < context.from.getTime()) return false; if (context.to && gameCreation > context.to.getTime()) return false; return true; } private toHighlight( row: LeaderboardRow | undefined, field: keyof Pick< LeaderboardRow, 'kda' | 'totalKills' | 'avgKillParticipation' | 'avgCsPerMin' >, ): LeaderHighlight | null { if (!row) return null; return { metric: Number(row[field]), userId: row.userId, summonerName: row.summonerName, isSingleGame: false, }; } private toSingleGameHighlight( record: InternalRecord | undefined, field: keyof Pick, ): LeaderHighlight | null { if (!record) return null; return { metric: record[field], userId: record.userId, summonerName: record.summonerName, championId: record.championId, matchId: record.riotMatchId, isSingleGame: true, }; } private resolveStreak( records: InternalRecord[], ): UserInternalHistoryResponse['summary']['streak'] { if (records.length === 0) return null; const firstWin = records[0].win; let count = 0; for (const record of records) { if (record.win !== firstWin) break; count += 1; } return { type: firstWin ? 'win' : 'loss', count }; } private resolvePositionRates( records: InternalRecord[], ): Partial> { const counts = new Map(); for (const record of records) { if (!record.teamPosition) continue; counts.set( record.teamPosition, (counts.get(record.teamPosition) ?? 0) + 1, ); } return Object.fromEntries( [...counts.entries()].map(([lane, count]) => [ lane, this.percent(count, records.length), ]), ) as Partial>; } private resolveTopChampions(records: InternalRecord[]) { const byChampion = new Map< number, { games: number; wins: number; rating: number } >(); for (const record of records) { const current = byChampion.get(record.championId) ?? { games: 0, wins: 0, rating: 0, }; current.games += 1; current.wins += record.win ? 1 : 0; current.rating += record.rating; byChampion.set(record.championId, current); } return [...byChampion.entries()] .map(([championId, stat]) => ({ championId, games: stat.games, winRate: this.percent(stat.wins, stat.games), pickRate: this.percent(stat.games, records.length), avgRating: this.average(stat.rating, stat.games), })) .sort( (left, right) => right.games - left.games || right.winRate - left.winRate, ) .slice(0, 3); } private cacheKey( scope: string, communityId: mongoose.Types.ObjectId, filters: CommunityStatsFilters, ): string { return [ 'riot:communitystats', scope, communityId.toString(), filters.seasonId ?? 'current', filters.from ?? '', filters.to ?? '', filters.championId ?? '', filters.cursor ?? '', filters.limit ?? '', ].join(':'); } private clampLimit( value: number | undefined, fallback: number, max: number, ): number { if (!value || !Number.isFinite(value)) return fallback; return Math.max(1, Math.min(Math.floor(value), max)); } private sum( records: InternalRecord[], field: T, ): number { return records.reduce((total, record) => { const value = record[field]; return total + (typeof value === 'number' ? value : 0); }, 0); } private kda(kills: number, deaths: number, assists: number): number { return deaths === 0 ? kills + assists : this.round((kills + assists) / deaths); } private percent(value: number, total: number): number { return total > 0 ? Math.round((value / total) * 100) : 0; } private average(value: number, total: number): number { return total > 0 ? this.round(value / total) : 0; } private round(value: number): number { return Math.round(value * 10) / 10; } } function isCompleteMatchDetailResponse( response: InternalMatchDetailResponse, ): boolean { return response.games.every( (game) => Array.isArray(game.timeline) && Array.isArray(game.objectiveEvents) && Array.isArray(game.timelineEvents) && game.teams.every( (team) => Array.isArray(team.bans) && team.participants.every( (participant) => typeof participant.tagLine === 'string' && Array.isArray(participant.itemBuild) && Array.isArray(participant.skillBuild) && isOptionalFiniteNumber(participant.participantId) && isCompleteParticipantCheckpoints(participant.checkpoints), ), ), ); } function isCompleteParticipantCheckpoints(value: unknown): boolean { if (value === undefined) return true; if (!isRecord(value)) return false; return ['at10', 'at15'].every((key) => { const checkpoint = value[key]; if (checkpoint === undefined) return true; if (!isRecord(checkpoint)) return false; return [ 'timestamp', 'gold', 'cs', 'xp', 'kills', 'deaths', 'assists', ].every((field) => isFiniteNumber(checkpoint[field])); }); } function isOptionalFiniteNumber(value: unknown): boolean { return value === undefined || isFiniteNumber(value); } function isFiniteNumber(value: unknown): value is number { return typeof value === 'number' && Number.isFinite(value); } function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); }