import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import { createEmptyRiotRecentStatsSummary, type RiotRecentStatsSummary, } from '../global/database/schema'; import { RiotAccountEnrichmentService } from './riot-account-enrichment.service'; import { RiotAccountService } from './riot-account.service'; import { RiotChampionMasteryService } from './riot-champion-mastery.service'; import { RiotApiError } from './riot.client.service'; import { RiotLeagueService } from './riot-league.service'; import { RiotRecentMatchesService } from './riot-recent-matches.service'; import { RiotRecentStatsService } from './riot-recent-stats.service'; import { RiotSummonerService } from './riot-summoner.service'; interface FakeAccount { puuid: string; profileIconId: number; revisionDate: number; summonerLevel: number; matchIds: string[]; matchIdsFetchedAt?: Date; recentStatsSummary?: RiotRecentStatsSummary; recentStatsFetchedAt?: Date; tiers: Array<{ leagueId: string; queueType: string; tier: string; rank: string; puuid: string; leaguePoints: number; wins: number; losses: number; fetchedAt: Date; }>; tierHistory: Array<{ queueType: string; tier: string; rank?: string; leaguePoints?: number; wins?: number; losses?: number; recordedAt: Date; }>; championMasteries: Array<{ puuid: string; championId: number; championLevel: number; championPoints: number; }>; championMasteriesFetchedAt?: Date; championRecords: Record; championRecordsFetchedAt?: Date; } function makeAccount(overrides: Partial = {}): FakeAccount { return { puuid: 'puuid-1', profileIconId: 0, revisionDate: 0, summonerLevel: 0, matchIds: [], tiers: [], tierHistory: [], championMasteries: [], championRecords: {}, ...overrides, }; } function makeUser(account: FakeAccount) { const _id = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId(); const save = jest.fn().mockResolvedValue(undefined); return { _id, communityId, riotAccounts: [account], save, }; } function makeService(overrides?: { user?: any; account?: Partial; summoner?: Partial; league?: Partial; mastery?: Partial; recentMatches?: Partial; recentStats?: Partial; match?: any; }) { const user = overrides?.user; const userFindById = jest.fn().mockReturnValue({ exec: () => Promise.resolve(user ?? null), }); const communityFindById = jest.fn().mockReturnValue({ select: () => ({ lean: () => ({ exec: () => Promise.resolve({ riotPlatform: 'kr', riotRegion: 'asia', }), }), }), }); const matchUpdateManyExec = jest.fn().mockResolvedValue({ modifiedCount: 0 }); const matchModel = { updateMany: jest.fn().mockReturnValue({ exec: matchUpdateManyExec }), ...overrides?.match, }; const connectionService = { getModel: jest.fn().mockImplementation(async (modelName: string) => { if (modelName === 'user') { return { findById: userFindById }; } if (modelName === 'community') { return { findById: communityFindById }; } if (modelName === 'match') { return matchModel; } throw new Error(`Unexpected model: ${modelName}`); }), } as unknown as ConnectionService; const summonerService = { getByPuuid: jest.fn(), ...overrides?.summoner, } as unknown as RiotSummonerService; const accountService = { getRegionByPuuid: jest.fn(), ...overrides?.account, } as unknown as RiotAccountService; const leagueService = { getEntriesByPuuid: jest.fn(), ...overrides?.league, } as unknown as RiotLeagueService; const masteryService = { getTopByPuuid: jest.fn(), ...overrides?.mastery, } as unknown as RiotChampionMasteryService; const recentMatchesService = { syncRecentMatches: jest.fn().mockResolvedValue([]), loadFromDb: jest.fn().mockResolvedValue([]), ...overrides?.recentMatches, } as unknown as RiotRecentMatchesService; const recentStatsService = { computeSummary: jest .fn() .mockReturnValue(createEmptyRiotRecentStatsSummary()), ...overrides?.recentStats, } as unknown as RiotRecentStatsService; const service = new RiotAccountEnrichmentService( connectionService, accountService, summonerService, leagueService, masteryService, recentMatchesService, recentStatsService, ); return { service, user, accountService, summonerService, leagueService, masteryService, recentMatchesService, recentStatsService, matchModel, matchUpdateManyExec, }; } describe('RiotAccountEnrichmentService', () => { it('returns failed for unknown user', async () => { const { service } = makeService(); const result = await service.enrichRiotAccount({ userId: new mongoose.Types.ObjectId(), puuid: 'puuid-1', }); expect(result.summoner).toBe('failed'); expect(result.recentMatches).toBe('failed'); expect(result.account).toBeNull(); }); it('fills summoner / league / mastery on first attach (force)', async () => { const account = makeAccount(); const user = makeUser(account); const { service, summonerService, leagueService, masteryService, recentMatchesService, recentStatsService, } = makeService({ user, summoner: { getByPuuid: jest.fn().mockResolvedValue({ puuid: 'puuid-1', profileIconId: 588, revisionDate: 1776977597000, summonerLevel: 529, }), } as Partial, league: { getEntriesByPuuid: jest.fn().mockResolvedValue([ { leagueId: 'L1', queueType: 'RANKED_SOLO_5x5', tier: 'EMERALD', rank: 'I', puuid: 'puuid-1', leaguePoints: 75, wins: 160, losses: 148, }, ]), } as Partial, mastery: { getTopByPuuid: jest.fn().mockResolvedValue([ { puuid: 'puuid-1', championId: 7, championLevel: 70, championPoints: 742560, }, ]), } as Partial, recentMatches: { syncRecentMatches: jest.fn().mockResolvedValue([]), loadFromDb: jest.fn().mockResolvedValue([ { matchId: 'KR_1', raw: {} }, { matchId: 'KR_2', raw: {} }, ]), } as Partial, recentStats: { computeSummary: jest.fn().mockReturnValue({ overall: { games: 2, wins: 1, losses: 1, avgKills: 5.5, avgDeaths: 2.5, avgAssists: 7, avgCs: 175, avgCsPerMin: 6.4, mostPlayedChampionIds: [7, 103], }, byLane: {}, }), } as Partial, }); const result = await service.enrichRiotAccount({ userId: user._id, puuid: 'puuid-1', options: { force: true }, }); expect(result.summoner).toBe('updated'); expect(result.league).toBe('updated'); expect(result.masteries).toBe('updated'); expect(result.recentMatches).toBe('updated'); expect(account.profileIconId).toBe(588); expect(account.summonerLevel).toBe(529); expect(account.matchIds).toEqual(['KR_1', 'KR_2']); expect(account.recentStatsSummary).toMatchObject({ overall: { games: 2, wins: 1, losses: 1, avgKills: 5.5, avgDeaths: 2.5, avgAssists: 7, avgCs: 175, avgCsPerMin: 6.4, mostPlayedChampionIds: [7, 103], }, }); expect(account.tiers).toHaveLength(1); expect(account.tiers[0]).toMatchObject({ leagueId: 'L1', queueType: 'RANKED_SOLO_5x5', tier: 'EMERALD', rank: 'I', puuid: 'puuid-1', leaguePoints: 75, }); expect(account.tierHistory).toHaveLength(1); expect(account.tierHistory[0]).toMatchObject({ queueType: 'RANKED_SOLO_5x5', tier: 'EMERALD', rank: 'I', leaguePoints: 75, wins: 160, losses: 148, }); expect(account.championMasteries).toEqual([ { puuid: 'puuid-1', championId: 7, championLevel: 70, championPoints: 742560, }, ]); expect(account.championRecords).toEqual({}); expect(user.save).toHaveBeenCalledTimes(1); expect(summonerService.getByPuuid).toHaveBeenCalledWith('puuid-1', { platform: 'kr', }); expect(leagueService.getEntriesByPuuid).toHaveBeenCalledWith('puuid-1', { platform: 'kr', }); expect(masteryService.getTopByPuuid).toHaveBeenCalledWith('puuid-1', { platform: 'kr', count: 10, }); expect(recentMatchesService.syncRecentMatches).toHaveBeenCalledWith({ puuid: 'puuid-1', region: 'asia', limit: 20, }); expect(recentStatsService.computeSummary).toHaveBeenCalled(); }); it('skips fresh data when within TTL and not forced', async () => { const recent = new Date(Date.now() - 60_000); const account = makeAccount({ profileIconId: 1, revisionDate: Date.now() - 60_000, summonerLevel: 100, tiers: [ { leagueId: 'L1', queueType: 'RANKED_SOLO_5x5', tier: 'GOLD', rank: 'II', puuid: 'puuid-1', leaguePoints: 1, wins: 1, losses: 1, fetchedAt: recent, }, ], championMasteriesFetchedAt: recent, recentStatsFetchedAt: recent, recentStatsSummary: createEmptyRiotRecentStatsSummary(), }); const user = makeUser(account); const summoner = jest.fn(); const league = jest.fn(); const mastery = jest.fn(); const { service } = makeService({ user, summoner: { getByPuuid: summoner } as Partial, league: { getEntriesByPuuid: league, } as Partial, mastery: { getTopByPuuid: mastery, } as Partial, }); const result = await service.enrichRiotAccount({ userId: user._id, puuid: 'puuid-1', }); expect(result.summoner).toBe('fresh'); expect(result.league).toBe('fresh'); expect(result.masteries).toBe('fresh'); expect(result.recentMatches).toBe('fresh'); expect(summoner).not.toHaveBeenCalled(); expect(league).not.toHaveBeenCalled(); expect(mastery).not.toHaveBeenCalled(); expect(user.save).not.toHaveBeenCalled(); }); it('refreshes league entries without refreshing recent matches', async () => { const recent = new Date(Date.now() - 60_000); const account = makeAccount({ revisionDate: Date.now() - 60_000, tiers: [ { leagueId: 'L1', queueType: 'RANKED_SOLO_5x5', tier: 'GOLD', rank: 'II', puuid: 'puuid-1', leaguePoints: 1, wins: 1, losses: 1, fetchedAt: recent, }, ], recentStatsFetchedAt: recent, recentStatsSummary: createEmptyRiotRecentStatsSummary(), }); const user = makeUser(account); const { service, leagueService, recentMatchesService } = makeService({ user, league: { getEntriesByPuuid: jest.fn().mockResolvedValue([ { leagueId: 'L2', queueType: 'RANKED_SOLO_5x5', tier: 'PLATINUM', rank: 'IV', puuid: 'puuid-1', leaguePoints: 20, wins: 10, losses: 8, }, ]), } as Partial, }); const result = await service.refreshLeagueEntries({ userId: user._id, puuid: 'puuid-1', platform: 'kr', }); expect(result).toBe('updated'); expect(leagueService.getEntriesByPuuid).toHaveBeenCalledWith('puuid-1', { platform: 'kr', }); expect(recentMatchesService.syncRecentMatches).not.toHaveBeenCalled(); expect(account.tiers).toHaveLength(1); expect(account.tiers[0]).toMatchObject({ leagueId: 'L2', queueType: 'RANKED_SOLO_5x5', tier: 'PLATINUM', rank: 'IV', leaguePoints: 20, }); expect(account.tierHistory.at(-1)).toMatchObject({ queueType: 'RANKED_SOLO_5x5', tier: 'PLATINUM', rank: 'IV', leaguePoints: 20, }); expect(user.save).toHaveBeenCalledTimes(1); }); it('appends tier history when LP changes without tier or rank changes', async () => { const recent = new Date(Date.now() - 60_000); const account = makeAccount({ revisionDate: Date.now() - 60_000, tiers: [ { leagueId: 'L1', queueType: 'RANKED_SOLO_5x5', tier: 'GOLD', rank: 'II', puuid: 'puuid-1', leaguePoints: 10, wins: 20, losses: 12, fetchedAt: recent, }, ], tierHistory: [ { queueType: 'RANKED_SOLO_5x5', tier: 'GOLD', rank: 'II', leaguePoints: 10, wins: 20, losses: 12, recordedAt: recent, }, ], recentStatsFetchedAt: recent, recentStatsSummary: createEmptyRiotRecentStatsSummary(), }); const user = makeUser(account); const { service } = makeService({ user, league: { getEntriesByPuuid: jest.fn().mockResolvedValue([ { leagueId: 'L1', queueType: 'RANKED_SOLO_5x5', tier: 'GOLD', rank: 'II', puuid: 'puuid-1', leaguePoints: 44, wins: 21, losses: 12, }, ]), } as Partial, }); await service.refreshLeagueEntries({ userId: user._id, puuid: 'puuid-1', platform: 'kr', }); expect(account.tierHistory).toHaveLength(2); expect(account.tierHistory.at(-1)).toMatchObject({ queueType: 'RANKED_SOLO_5x5', tier: 'GOLD', rank: 'II', leaguePoints: 44, wins: 21, losses: 12, }); }); it('syncs refreshed league tier into active match participant snapshots', async () => { const recent = new Date(Date.now() - 60_000); const account = makeAccount({ revisionDate: Date.now() - 60_000, tiers: [ { leagueId: 'L1', queueType: 'RANKED_SOLO_5x5', tier: 'GOLD', rank: 'II', puuid: 'puuid-1', leaguePoints: 1, wins: 1, losses: 1, fetchedAt: recent, }, ], recentStatsFetchedAt: recent, recentStatsSummary: createEmptyRiotRecentStatsSummary(), }); const user = makeUser(account); const { service, matchModel } = makeService({ user, league: { getEntriesByPuuid: jest.fn().mockResolvedValue([ { leagueId: 'L2', queueType: 'RANKED_SOLO_5x5', tier: 'PLATINUM', rank: 'IV', puuid: 'puuid-1', leaguePoints: 20, wins: 10, losses: 8, }, ]), } as Partial, }); await service.refreshLeagueEntries({ userId: user._id, puuid: 'puuid-1', platform: 'kr', }); expect(matchModel.updateMany).toHaveBeenCalledWith( { status: { $in: ['recruiting', 'team-built', 'in-progress'] }, participants: { $elemMatch: { userId: user._id, puuid: 'puuid-1', }, }, }, { $set: { 'participants.$[participant].tier': expect.objectContaining({ leagueId: 'L2', queueType: 'RANKED_SOLO_5x5', tier: 'PLATINUM', rank: 'IV', leaguePoints: 20, }), }, }, { arrayFilters: [ { 'participant.userId': user._id, 'participant.puuid': 'puuid-1', }, ], }, ); }); it('clears active match participant tier when refreshed league entries are empty', async () => { const recent = new Date(Date.now() - 60_000); const account = makeAccount({ revisionDate: Date.now() - 60_000, tiers: [ { leagueId: 'L1', queueType: 'RANKED_SOLO_5x5', tier: 'GOLD', rank: 'II', puuid: 'puuid-1', leaguePoints: 1, wins: 1, losses: 1, fetchedAt: recent, }, ], recentStatsFetchedAt: recent, recentStatsSummary: createEmptyRiotRecentStatsSummary(), }); const user = makeUser(account); const { service, matchModel } = makeService({ user, league: { getEntriesByPuuid: jest.fn().mockResolvedValue([]), } as Partial, }); await service.refreshLeagueEntries({ userId: user._id, puuid: 'puuid-1', platform: 'kr', }); expect(matchModel.updateMany).toHaveBeenCalledWith( { status: { $in: ['recruiting', 'team-built', 'in-progress'] }, participants: { $elemMatch: { userId: user._id, puuid: 'puuid-1', }, }, }, { $unset: { 'participants.$[participant].tier': '' } }, { arrayFilters: [ { 'participant.userId': user._id, 'participant.puuid': 'puuid-1', }, ], }, ); }); it('records failed for individual failing fetches but updates the rest', async () => { const account = makeAccount(); const user = makeUser(account); const { service } = makeService({ user, summoner: { getByPuuid: jest.fn().mockRejectedValue(new Error('boom')), } as Partial, league: { getEntriesByPuuid: jest.fn().mockResolvedValue([]), } as Partial, mastery: { getTopByPuuid: jest.fn().mockResolvedValue([]), } as Partial, }); const result = await service.enrichRiotAccount({ userId: user._id, puuid: 'puuid-1', options: { force: true }, }); expect(result.summoner).toBe('failed'); expect(result.league).toBe('updated'); expect(result.masteries).toBe('updated'); expect(result.recentMatches).toBe('updated'); expect(user.save).toHaveBeenCalled(); }); it('retries summoner lookup with region/by-puuid platform on 404', async () => { const account = makeAccount(); const user = makeUser(account); const summoner = jest .fn() .mockRejectedValueOnce(new RiotApiError('not found', 404, 'url')) .mockResolvedValueOnce({ puuid: 'puuid-1', profileIconId: 100, revisionDate: 1776977597000, summonerLevel: 30, }); const region = jest.fn().mockResolvedValue({ puuid: 'puuid-1', game: 'lol', region: 'jp1', }); const league = jest.fn().mockResolvedValue([]); const mastery = jest.fn().mockResolvedValue([]); const { service } = makeService({ user, account: { getRegionByPuuid: region } as Partial, summoner: { getByPuuid: summoner } as Partial, league: { getEntriesByPuuid: league, } as Partial, mastery: { getTopByPuuid: mastery, } as Partial, }); const result = await service.enrichRiotAccount({ userId: user._id, puuid: 'puuid-1', options: { force: true, platform: 'kr' }, }); expect(result.summoner).toBe('updated'); expect(region).toHaveBeenCalledWith('puuid-1', { region: 'asia' }); expect(summoner).toHaveBeenNthCalledWith(1, 'puuid-1', { platform: 'kr', }); expect(summoner).toHaveBeenNthCalledWith(2, 'puuid-1', { platform: 'jp1', }); expect(league).toHaveBeenCalledWith('puuid-1', { platform: 'jp1' }); expect(mastery).toHaveBeenCalledWith('puuid-1', { platform: 'jp1', count: 10, }); }); it('deduplicates concurrent enrichment for the same user and puuid', async () => { const account = makeAccount(); const user = makeUser(account); let resolveSummoner: (value: unknown) => void; const summonerPromise = new Promise((resolve) => { resolveSummoner = resolve; }); const summoner = jest.fn().mockReturnValue(summonerPromise); const { service } = makeService({ user, summoner: { getByPuuid: summoner } as Partial, league: { getEntriesByPuuid: jest.fn().mockResolvedValue([]), } as Partial, mastery: { getTopByPuuid: jest.fn().mockResolvedValue([]), } as Partial, }); const first = service.enrichRiotAccount({ userId: user._id, puuid: 'puuid-1', options: { force: true }, }); const second = service.enrichRiotAccount({ userId: user._id, puuid: 'puuid-1', options: { force: true }, }); resolveSummoner!({ puuid: 'puuid-1', profileIconId: 100, revisionDate: 1776977597000, summonerLevel: 30, }); await Promise.all([first, second]); expect(summoner).toHaveBeenCalledTimes(1); expect(user.save).toHaveBeenCalledTimes(1); }); });