diff --git a/apps/api/src/modules/riot/riot-recent-stats.service.spec.ts b/apps/api/src/modules/riot/riot-recent-stats.service.spec.ts new file mode 100644 index 00000000..326f1166 --- /dev/null +++ b/apps/api/src/modules/riot/riot-recent-stats.service.spec.ts @@ -0,0 +1,304 @@ +import { RiotRecentStatsService } from './riot-recent-stats.service'; +import type { RiotMatchDto } from './riot.types'; + +function makeMatch(params: { + matchId: string; + gameCreation: number; + gameDuration: number; + puuid: string; + championId: number; + kills: number; + deaths: number; + assists: number; + cs: number; + neutralCs?: number; + win?: boolean; + teamPosition?: string; + individualPosition?: string; +}): RiotMatchDto { + return { + metadata: { + dataVersion: '2', + matchId: params.matchId, + participants: [params.puuid, 'other-1'], + }, + info: { + gameCreation: params.gameCreation, + gameDuration: params.gameDuration, + gameId: 1, + gameMode: 'CLASSIC', + gameName: 'teambuilder-match-1', + gameStartTimestamp: params.gameCreation, + gameType: 'MATCHED_GAME', + gameVersion: '15.8.1', + mapId: 11, + platformId: 'KR', + queueId: 420, + participants: [ + { + assists: params.assists, + champExperience: 10000, + champLevel: 16, + championId: params.championId, + championName: `Champion-${params.championId}`, + deaths: params.deaths, + goldEarned: 12000, + goldSpent: 11000, + individualPosition: params.individualPosition ?? '', + item0: 0, + item1: 0, + item2: 0, + item3: 0, + item4: 0, + item5: 0, + item6: 0, + kills: params.kills, + neutralMinionsKilled: params.neutralCs ?? 0, + participantId: 1, + perks: { + statPerks: { defense: 0, flex: 0, offense: 0 }, + styles: [], + }, + puuid: params.puuid, + riotIdGameName: 'tester', + riotIdTagLine: 'KR1', + summoner1Id: 4, + summoner2Id: 14, + summonerId: 'summoner-1', + summonerLevel: 100, + summonerName: 'tester', + teamId: 100, + teamPosition: params.teamPosition ?? '', + timePlayed: params.gameDuration, + totalDamageDealtToChampions: 10000, + totalDamageTaken: 5000, + totalMinionsKilled: params.cs, + visionScore: 20, + wardsKilled: 2, + wardsPlaced: 10, + win: params.win ?? true, + }, + { + assists: 1, + champExperience: 9000, + champLevel: 15, + championId: 1, + championName: 'Other', + deaths: 5, + goldEarned: 10000, + goldSpent: 9000, + individualPosition: 'TOP', + item0: 0, + item1: 0, + item2: 0, + item3: 0, + item4: 0, + item5: 0, + item6: 0, + kills: 3, + neutralMinionsKilled: 0, + participantId: 2, + perks: { + statPerks: { defense: 0, flex: 0, offense: 0 }, + styles: [], + }, + puuid: 'other-1', + riotIdGameName: 'other', + riotIdTagLine: 'KR1', + summoner1Id: 4, + summoner2Id: 14, + summonerId: 'summoner-2', + summonerLevel: 90, + summonerName: 'other', + teamId: 100, + teamPosition: 'TOP', + timePlayed: params.gameDuration, + totalDamageDealtToChampions: 8000, + totalDamageTaken: 7000, + totalMinionsKilled: 180, + visionScore: 10, + wardsKilled: 1, + wardsPlaced: 5, + win: false, + }, + ], + teams: [ + { + bans: [], + objectives: { + baron: { first: false, kills: 0 }, + champion: { first: false, kills: 0 }, + dragon: { first: false, kills: 0 }, + inhibitor: { first: false, kills: 0 }, + riftHerald: { first: false, kills: 0 }, + tower: { first: false, kills: 0 }, + }, + teamId: 100, + win: params.win ?? true, + }, + { + bans: [], + objectives: { + baron: { first: false, kills: 0 }, + champion: { first: false, kills: 0 }, + dragon: { first: false, kills: 0 }, + inhibitor: { first: false, kills: 0 }, + riftHerald: { first: false, kills: 0 }, + tower: { first: false, kills: 0 }, + }, + teamId: 200, + win: !(params.win ?? true), + }, + ], + }, + }; +} + +describe('RiotRecentStatsService', () => { + const service = new RiotRecentStatsService(); + + it('computes overall and lane summaries for recent solo queue matches', () => { + const matches = [ + makeMatch({ + matchId: 'KR_1', + gameCreation: 1_000, + gameDuration: 1800, + puuid: 'puuid-1', + championId: 103, + kills: 8, + deaths: 2, + assists: 6, + cs: 180, + win: true, + teamPosition: 'MIDDLE', + }), + makeMatch({ + matchId: 'KR_2', + gameCreation: 2_000, + gameDuration: 1500, + puuid: 'puuid-1', + championId: 103, + kills: 4, + deaths: 1, + assists: 8, + cs: 150, + neutralCs: 20, + win: false, + teamPosition: 'MIDDLE', + }), + makeMatch({ + matchId: 'KR_3', + gameCreation: 3_000, + gameDuration: 1800, + puuid: 'puuid-1', + championId: 22, + kills: 10, + deaths: 0, + assists: 5, + cs: 210, + win: true, + teamPosition: '', + individualPosition: 'BOTTOM', + }), + ]; + + const summary = service.computeSummary(matches, 'puuid-1'); + + expect(summary.overall).toEqual({ + games: 3, + wins: 2, + losses: 1, + avgKills: 7.3, + avgDeaths: 1, + avgAssists: 6.3, + avgCs: 186.7, + avgCsPerMin: 6.6, + mostPlayedChampionIds: [103, 22], + }); + expect(summary.byLane.MIDDLE).toEqual({ + games: 2, + wins: 1, + losses: 1, + avgKills: 6, + avgDeaths: 1.5, + avgAssists: 7, + avgCs: 175, + avgCsPerMin: 6.4, + mostPlayedChampionIds: [103], + }); + expect(summary.byLane.BOTTOM).toEqual({ + games: 1, + wins: 1, + losses: 0, + avgKills: 10, + avgDeaths: 0, + avgAssists: 5, + avgCs: 210, + avgCsPerMin: 7, + mostPlayedChampionIds: [22], + }); + }); + + it('skips invalid lane positions from byLane while keeping overall stats', () => { + const summary = service.computeSummary( + [ + makeMatch({ + matchId: 'KR_4', + gameCreation: 4_000, + gameDuration: 1800, + puuid: 'puuid-1', + championId: 61, + kills: 6, + deaths: 3, + assists: 9, + cs: 190, + win: true, + teamPosition: 'Invalid', + individualPosition: '', + }), + ], + 'puuid-1', + ); + + expect(summary.overall.games).toBe(1); + expect(summary.byLane).toEqual({}); + }); + + it('filters out matches before seasonStartedAt', () => { + const summary = service.computeSummary( + [ + makeMatch({ + matchId: 'KR_5', + gameCreation: 1_000, + gameDuration: 1800, + puuid: 'puuid-1', + championId: 61, + kills: 6, + deaths: 3, + assists: 9, + cs: 190, + win: true, + teamPosition: 'MIDDLE', + }), + makeMatch({ + matchId: 'KR_6', + gameCreation: 10_000, + gameDuration: 1800, + puuid: 'puuid-1', + championId: 134, + kills: 9, + deaths: 2, + assists: 7, + cs: 205, + win: true, + teamPosition: 'MIDDLE', + }), + ], + 'puuid-1', + { seasonStartedAt: new Date(5_000) }, + ); + + expect(summary.overall.games).toBe(1); + expect(summary.overall.mostPlayedChampionIds).toEqual([134]); + }); +}); diff --git a/apps/api/src/modules/riot/riot-recent-stats.service.ts b/apps/api/src/modules/riot/riot-recent-stats.service.ts new file mode 100644 index 00000000..62886925 --- /dev/null +++ b/apps/api/src/modules/riot/riot-recent-stats.service.ts @@ -0,0 +1,172 @@ +import { Injectable } from '@nestjs/common'; +import { + createEmptyRiotLaneStats, + createEmptyRiotRecentStatsSummary, + RIOT_LANES, + type RiotLane, + type RiotLaneStats, + type RiotRecentStatsSummary, +} from '../global/database/schema'; +import type { RiotMatchDto, RiotMatchParticipantDto } from './riot.types'; + +interface Aggregate { + games: number; + wins: number; + losses: number; + kills: number; + deaths: number; + assists: number; + cs: number; + csPerMin: number; + championCounts: Map; + lastPlayedAtByChampion: Map; +} + +interface ComputeSummaryOptions { + seasonStartedAt?: Date; +} + +@Injectable() +export class RiotRecentStatsService { + public computeSummary( + matches: RiotMatchDto[], + puuid: string, + options: ComputeSummaryOptions = {}, + ): RiotRecentStatsSummary { + const filteredMatches = this.filterMatchesBySeason(matches, options); + if (filteredMatches.length === 0) { + return createEmptyRiotRecentStatsSummary(); + } + + const overall = createAggregate(); + const laneAggregates = new Map( + RIOT_LANES.map((lane) => [lane, createAggregate()]), + ); + + for (const match of filteredMatches) { + const participant = match.info.participants.find((entry) => entry.puuid === puuid); + if (!participant) continue; + + accumulateAggregate(overall, participant, match.info.gameCreation, match.info.gameDuration); + + const lane = resolveLane(participant); + if (!lane) continue; + + const aggregate = laneAggregates.get(lane); + if (!aggregate) continue; + accumulateAggregate(aggregate, participant, match.info.gameCreation, match.info.gameDuration); + } + + if (overall.games === 0) { + return createEmptyRiotRecentStatsSummary(); + } + + const byLane: Partial> = {}; + for (const lane of RIOT_LANES) { + const aggregate = laneAggregates.get(lane); + if (!aggregate || aggregate.games === 0) continue; + byLane[lane] = finalizeAggregate(aggregate); + } + + return { + overall: finalizeAggregate(overall), + byLane, + }; + } + + private filterMatchesBySeason( + matches: RiotMatchDto[], + options: ComputeSummaryOptions, + ): RiotMatchDto[] { + const startedAt = options.seasonStartedAt?.getTime(); + if (!startedAt) return matches; + return matches.filter((match) => match.info.gameCreation >= startedAt); + } +} + +function createAggregate(): Aggregate { + return { + games: 0, + wins: 0, + losses: 0, + kills: 0, + deaths: 0, + assists: 0, + cs: 0, + csPerMin: 0, + championCounts: new Map(), + lastPlayedAtByChampion: new Map(), + }; +} + +function accumulateAggregate( + aggregate: Aggregate, + participant: RiotMatchParticipantDto, + gameCreation: number, + gameDurationSeconds: number, +): void { + aggregate.games += 1; + aggregate.wins += participant.win ? 1 : 0; + aggregate.losses += participant.win ? 0 : 1; + aggregate.kills += participant.kills; + aggregate.deaths += participant.deaths; + aggregate.assists += participant.assists; + + const cs = participant.totalMinionsKilled + participant.neutralMinionsKilled; + aggregate.cs += cs; + if (gameDurationSeconds > 0) { + aggregate.csPerMin += cs / (gameDurationSeconds / 60); + } + + aggregate.championCounts.set( + participant.championId, + (aggregate.championCounts.get(participant.championId) ?? 0) + 1, + ); + aggregate.lastPlayedAtByChampion.set(participant.championId, gameCreation); +} + +function finalizeAggregate(aggregate: Aggregate): RiotLaneStats { + if (aggregate.games === 0) { + return createEmptyRiotLaneStats(); + } + + const mostPlayedChampionIds = [...aggregate.championCounts.entries()] + .sort((left, right) => { + if (right[1] !== left[1]) return right[1] - left[1]; + const rightLastPlayed = aggregate.lastPlayedAtByChampion.get(right[0]) ?? 0; + const leftLastPlayed = aggregate.lastPlayedAtByChampion.get(left[0]) ?? 0; + if (rightLastPlayed !== leftLastPlayed) { + return rightLastPlayed - leftLastPlayed; + } + return left[0] - right[0]; + }) + .slice(0, 3) + .map(([championId]) => championId); + + return { + games: aggregate.games, + wins: aggregate.wins, + losses: aggregate.losses, + avgKills: roundToOneDecimal(aggregate.kills / aggregate.games), + avgDeaths: roundToOneDecimal(aggregate.deaths / aggregate.games), + avgAssists: roundToOneDecimal(aggregate.assists / aggregate.games), + avgCs: roundToOneDecimal(aggregate.cs / aggregate.games), + avgCsPerMin: roundToOneDecimal(aggregate.csPerMin / aggregate.games), + mostPlayedChampionIds, + }; +} + +function resolveLane(participant: RiotMatchParticipantDto): RiotLane | null { + const candidates = [participant.teamPosition, participant.individualPosition]; + for (const candidate of candidates) { + if (!candidate) continue; + if (RIOT_LANES.includes(candidate as RiotLane)) { + return candidate as RiotLane; + } + } + return null; +} + +function roundToOneDecimal(value: number): number { + return Math.round(value * 10) / 10; +}