diff --git a/apps/api/src/modules/community-stats/community-stats-cache.service.ts b/apps/api/src/modules/community-stats/community-stats-cache.service.ts new file mode 100644 index 00000000..6f3c26f2 --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats-cache.service.ts @@ -0,0 +1,59 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { GarnetService } from '../global/garnet/garnet.service'; + +const COMMUNITY_STATS_TTL_SECONDS = 5 * 60; +const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60; + +@Injectable() +export class CommunityStatsCacheService { + private readonly logger = new Logger(CommunityStatsCacheService.name); + + constructor(private readonly garnetService: GarnetService) {} + + public get(key: string): Promise { + return this.garnetService.getJson(key); + } + + public set( + key: string, + value: unknown, + ttlSeconds = COMMUNITY_STATS_TTL_SECONDS, + ): Promise { + return this.garnetService.setJson(key, value, ttlSeconds); + } + + public setDetail(key: string, value: unknown): Promise { + return this.set(key, value, COMMUNITY_STATS_DETAIL_TTL_SECONDS); + } + + public async invalidateCommunity(communityId: string): Promise { + const prefix = `riot:communitystats:`; + const match = `${prefix}*${communityId}*`; + const client = this.garnetService.raw(); + let cursor = '0'; + let deleted = 0; + + do { + const reply = (await client.sendCommand([ + 'SCAN', + cursor, + 'MATCH', + match, + 'COUNT', + '100', + ])) as [string, string[]]; + cursor = reply[0]; + const keys = reply[1] ?? []; + if (keys.length > 0) { + deleted += await client.del(keys); + } + } while (cursor !== '0'); + + if (deleted > 0) { + this.logger.debug( + `Invalidated ${deleted} community stats cache keys for ${communityId}.`, + ); + } + return deleted; + } +} diff --git a/apps/api/src/modules/community-stats/community-stats.controller.ts b/apps/api/src/modules/community-stats/community-stats.controller.ts new file mode 100644 index 00000000..e8d4ee69 --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.controller.ts @@ -0,0 +1,115 @@ +import { Controller, Get, Param, Query } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +import { ParseObjectIdPipe } from '../common/parse-object-id.pipe'; +import { CommunityStatsService } from './community-stats.service'; +import type { CommunityStatsFilters } from './community-stats.types'; + +@Controller('communities/:communityId') +export class CommunityStatsController { + constructor(private readonly communityStatsService: CommunityStatsService) {} + + @Get('internal-stats/matches') + @AllowPublicAccess() + public getMatches( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Query('seasonId') seasonId?: string, + @Query('from') from?: string, + @Query('to') to?: string, + @Query('championId') championId?: string, + @Query('cursor') cursor?: string, + @Query('limit') limit?: string, + ) { + return this.communityStatsService.getMatches({ + communityId, + filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }), + }); + } + + @Get('internal-stats/leaderboard') + @AllowPublicAccess() + public getLeaderboard( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Query('seasonId') seasonId?: string, + @Query('from') from?: string, + @Query('to') to?: string, + @Query('championId') championId?: string, + ) { + return this.communityStatsService.getLeaderboard({ + communityId, + filters: this.toFilters({ seasonId, from, to, championId }), + }); + } + + @Get('internal-stats/team-insights') + @AllowPublicAccess() + public getTeamInsights( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Query('seasonId') seasonId?: string, + @Query('from') from?: string, + @Query('to') to?: string, + @Query('championId') championId?: string, + ) { + return this.communityStatsService.getTeamInsights({ + communityId, + filters: this.toFilters({ seasonId, from, to, championId }), + }); + } + + @Get('internal-stats/match/:matchId') + @AllowPublicAccess() + public getMatchDetail( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + return this.communityStatsService.getMatchDetail({ communityId, matchId }); + } + + @Get('users/:userId/internal-history') + @AllowPublicAccess() + public getUserInternalHistory( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + @Query('seasonId') seasonId?: string, + @Query('from') from?: string, + @Query('to') to?: string, + @Query('championId') championId?: string, + @Query('cursor') cursor?: string, + @Query('limit') limit?: string, + ) { + return this.communityStatsService.getUserInternalHistory({ + communityId, + userId, + filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }), + }); + } + + private toFilters(params: { + seasonId?: string; + from?: string; + to?: string; + championId?: string; + cursor?: string; + limit?: string; + }): CommunityStatsFilters { + return { + seasonId: params.seasonId, + from: params.from, + to: params.to, + championId: this.toNumber(params.championId), + cursor: this.toNumber(params.cursor), + limit: this.toNumber(params.limit), + }; + } + + private toNumber(value: string | undefined): number | undefined { + if (!value) return undefined; + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : undefined; + } +} diff --git a/apps/api/src/modules/community-stats/community-stats.module.ts b/apps/api/src/modules/community-stats/community-stats.module.ts new file mode 100644 index 00000000..4be3ae42 --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.module.ts @@ -0,0 +1,20 @@ +import { Module } from '@nestjs/common'; +import { CommunityStatsCacheService } from './community-stats-cache.service'; +import { CommunityStatsController } from './community-stats.controller'; +import { CommunityStatsService } from './community-stats.service'; +import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder'; +import { MatchStatsRepository } from './match-stats.repository'; +import { MatchStatsService } from './match-stats.service'; + +@Module({ + controllers: [CommunityStatsController], + providers: [ + CommunityStatsService, + CommunityStatsCacheService, + MatchStatsFragmentBuilder, + MatchStatsRepository, + MatchStatsService, + ], + exports: [CommunityStatsService, MatchStatsService], +}) +export class CommunityStatsModule {} diff --git a/apps/api/src/modules/community-stats/community-stats.service.ts b/apps/api/src/modules/community-stats/community-stats.service.ts new file mode 100644 index 00000000..df89ea56 --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.service.ts @@ -0,0 +1,992 @@ +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 { MatchStatsRepository } 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; + +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); + + 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:${params.communityId.toString()}:${params.matchId.toString()}`; + const cached = + await this.cacheService.get(key); + if (cached) return cached; + + 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.'); + const response: InternalMatchDetailResponse = { + match, + games: (dataset.detailsByMatchId.get(match.matchId) ?? []).map( + (game) => ({ + gameNumber: game.gameNumber, + riotMatchId: game.riotMatchId, + gameCreation: game.gameCreation, + gameDuration: game.gameDuration, + teams: game.teams.map((team) => ({ + teamIndex: team.teamIndex, + side: team.side, + win: team.win, + objectives: team.objectives, + participants: team.participants.map((record) => ({ + userId: record.userId, + summonerName: record.summonerName, + teamIndex: record.teamIndex, + side: record.side, + teamPosition: record.teamPosition, + championId: record.championId, + kills: record.kills, + deaths: record.deaths, + assists: record.assists, + cs: record.cs, + csPerMin: record.csPerMin, + gold: record.gold, + gpm: record.gpm, + damageDealtToChampions: record.damageDealtToChampions, + damageShare: record.damageShare, + killParticipation: record.killParticipation, + visionScore: record.visionScore, + items: record.items, + trinket: record.trinket, + summonerSpells: record.summonerSpells, + perks: record.perks, + win: record.win, + })), + })), + }), + ), + }; + await this.cacheService.setDetail(key, response); + return response; + } + + public async getUserInternalHistory(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + filters: CommunityStatsFilters; + }): Promise { + const key = this.cacheKey( + `userInternal:${params.userId.toString()}`, + 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 allUserRecords = dataset.records + .filter((record) => record.userId === params.userId.toString()) + .sort((left, right) => right.gameCreation - left.gameCreation); + 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 response: UserInternalHistoryResponse = { + season: dataset.season, + championStats: this.buildUserChampionStats( + allUserRecords, + dataset.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(key, response); + return response; + } + + 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 as InternalGameDetail[]) + .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 as InternalRecord[]).filter((record) => + allowedGameNumbers.has(record.gameNumber), + ), + ); + } + + return { + season: context.season, + matches: cards, + records, + 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'] }, + 'result.games.0': { $exists: true }, + }) + .sort({ scheduledAt: -1 }) + .limit(MAX_MATCH_SCAN) + .select({ _id: 1 }) + .exec(), + this.matchStatsRepository.findByCommunity({ + communityId, + limit: MAX_MATCH_SCAN, + }), + ]); + const fragmentByMatchId = new Map( + fragments.map((fragment) => [fragment.matchId.toString(), fragment]), + ); + let rebuilt = 0; + + for (const match of matches) { + const fragment = fragmentByMatchId.get(match._id.toString()); + if (fragment && fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION) { + 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, + 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; + } +} diff --git a/apps/api/src/modules/community-stats/community-stats.types.ts b/apps/api/src/modules/community-stats/community-stats.types.ts new file mode 100644 index 00000000..ec381dea --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.types.ts @@ -0,0 +1,206 @@ +import type { RiotLane, TeamSide } from '../global/database/schema'; +import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types'; + +export interface CommunityStatsFilters { + seasonId?: string; + from?: string; + to?: string; + championId?: number; + cursor?: number; + limit?: number; +} + +export interface InternalMatchListResponse { + matches: InternalMatchCardView[]; + nextCursor: number | null; + season: HistorySeasonDto; +} + +export interface InternalMatchCardView { + matchId: string; + title: string; + scheduledAt: string; + status: 'finished' | 'in-progress'; + gameCount: number; + winnerTeamIndex?: number; + seriesResults: Array<{ + teamAIndex: number; + teamBIndex: number; + teamAWins: number; + teamBWins: number; + winnerTeamIndex?: number; + }>; + games: Array<{ + gameNumber: number; + riotMatchId: string | null; + blueTeamIndex: number; + redTeamIndex: number; + winnerTeamIndex: number | null; + winnerSide: TeamSide | null; + gameDuration: number; + }>; + teams: Array<{ + teamIndex: number; + name: string; + members: Array<{ + userId: string; + summonerName: string; + profileIconId: number; + }>; + }>; +} + +export interface LeaderboardResponse { + rows: LeaderboardRow[]; + season: HistorySeasonDto; +} + +export interface LeaderboardRow { + userId: string; + summonerName: string; + profileIconId: number; + games: number; + wins: number; + losses: number; + winRate: number; + totalKills: number; + totalDeaths: number; + totalAssists: number; + kda: number; + avgGoldPerMin: number; + avgKillParticipation: number; + avgCsPerMin: number; + avgDamageShare: number; + avgVisionScore: number; + byLane: Partial>; + topChampions: Array<{ championId: number; games: number; winRate: number }>; +} + +export interface LeaderHighlight { + metric: number; + userId: string; + summonerName: string; + championId?: number; + matchId?: string; + isSingleGame: boolean; +} + +export interface TeamInsightsResponse { + season: HistorySeasonDto; + sideWinRate: { + blue: number; + red: number; + bluePicks: number; + redPicks: number; + }; + topKda: LeaderHighlight | null; + mostKills: LeaderHighlight | null; + topTeamGpm: LeaderHighlight | null; + topKillParticipation: LeaderHighlight | null; + bestFarm: LeaderHighlight | null; + minGamesThreshold: number; +} + +export interface InternalMatchDetailResponse { + match: InternalMatchCardView; + games: Array<{ + gameNumber: number; + riotMatchId: string; + gameCreation: number; + gameDuration: number; + teams: Array<{ + teamIndex: number; + side: TeamSide; + win: boolean; + objectives: { baron: number; dragon: number; tower: number }; + participants: Array<{ + userId: string | null; + summonerName: string; + teamIndex: number; + side: TeamSide; + teamPosition: string; + championId: number; + kills: number; + deaths: number; + assists: number; + cs: number; + csPerMin: number; + gold: number; + gpm: number; + damageDealtToChampions: number; + damageShare: number; + killParticipation: number; + visionScore: number; + items: number[]; + trinket: number; + summonerSpells: [number, number]; + perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + win: boolean; + }>; + }>; + }>; +} + +export interface UserInternalHistoryResponse { + season: HistorySeasonDto; + championStats: LeaderboardChampionStats; + summary: { + windowSize: number; + winRate: number; + wins: number; + losses: number; + streak: { type: 'win' | 'loss'; count: number } | null; + kda: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + bestRating: { + rating: number | 'Perfect'; + kills: number; + deaths: number; + assists: number; + matchId: string; + } | null; + positionRates: Partial>; + topChampions: Array<{ + championId: number; + games: number; + winRate: number; + pickRate: number; + avgRating: number; + }>; + lastFetchedAt: string | null; + }; + matches: RecentMatchView[]; + nextCursor: number | null; + lastFetchedAt: string | null; +} + +export interface LeaderboardChampionStats { + queueGroup: 'internal'; + rank: 'all'; + queueIds: number[]; + season: HistorySeasonDto; + lastFetchedAt: string | null; + champions: Array<{ + championId: number; + games: number; + wins: number; + losses: number; + winRate: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + kda: number; + totalKills: number; + totalDeaths: number; + totalAssists: number; + doubleKills: number; + tripleKills: number; + quadraKills: number; + pentaKills: number; + avgCs: number; + avgCsPerMin: number; + }>; + totals: LeaderboardChampionStats['champions'][number]; +}