.
This commit is contained in:
1 parent
3b3c564075
commit
00448c94f3
16 files changed
+1478
-459
No files matched your search
@@ -1,7 +1,7 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
import { GarnetService } from '../global/garnet/garnet.service';
|
import { GarnetService } from '../global/garnet/garnet.service';
|
||||||
|
|
||||||
const COMMUNITY_STATS_TTL_SECONDS = 60 * 60;
|
const COMMUNITY_STATS_TTL_SECONDS = 5 * 60;
|
||||||
const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60;
|
const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60;
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
|
|||||||
@@ -2,10 +2,19 @@ import { Module } from '@nestjs/common';
|
|||||||
import { CommunityStatsCacheService } from './community-stats-cache.service';
|
import { CommunityStatsCacheService } from './community-stats-cache.service';
|
||||||
import { CommunityStatsController } from './community-stats.controller';
|
import { CommunityStatsController } from './community-stats.controller';
|
||||||
import { CommunityStatsService } from './community-stats.service';
|
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({
|
@Module({
|
||||||
controllers: [CommunityStatsController],
|
controllers: [CommunityStatsController],
|
||||||
providers: [CommunityStatsService, CommunityStatsCacheService],
|
providers: [
|
||||||
exports: [CommunityStatsService],
|
CommunityStatsService,
|
||||||
|
CommunityStatsCacheService,
|
||||||
|
MatchStatsFragmentBuilder,
|
||||||
|
MatchStatsRepository,
|
||||||
|
MatchStatsService,
|
||||||
|
],
|
||||||
|
exports: [CommunityStatsService, MatchStatsService],
|
||||||
})
|
})
|
||||||
export class CommunityStatsModule {}
|
export class CommunityStatsModule {}
|
||||||
@@ -1,15 +1,16 @@
|
|||||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Injectable,
|
||||||
|
Logger,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type { CommunityDocument, RiotLane } from '../global/database/schema';
|
||||||
import type {
|
import type {
|
||||||
CommunityDocument,
|
HistorySeasonDto,
|
||||||
MatchDocument,
|
RecentMatchView,
|
||||||
MatchGameResultParticipant,
|
} from '../match-history/match-history.types';
|
||||||
RiotLane,
|
|
||||||
TeamSide,
|
|
||||||
} from '../global/database/schema';
|
|
||||||
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
|
|
||||||
import type { HistorySeasonDto, RecentMatchView } from '../match-history/match-history.types';
|
|
||||||
import { CommunityStatsCacheService } from './community-stats-cache.service';
|
import { CommunityStatsCacheService } from './community-stats-cache.service';
|
||||||
import type {
|
import type {
|
||||||
CommunityStatsFilters,
|
CommunityStatsFilters,
|
||||||
@@ -23,6 +24,13 @@ import type {
|
|||||||
TeamInsightsResponse,
|
TeamInsightsResponse,
|
||||||
UserInternalHistoryResponse,
|
UserInternalHistoryResponse,
|
||||||
} from './community-stats.types';
|
} 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 DEFAULT_LIST_LIMIT = 20;
|
||||||
const MAX_LIST_LIMIT = 50;
|
const MAX_LIST_LIMIT = 50;
|
||||||
@@ -36,60 +44,6 @@ interface CommunityStatsContext {
|
|||||||
to: Date | null;
|
to: Date | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface InternalRecord {
|
|
||||||
matchId: string;
|
|
||||||
title: string;
|
|
||||||
scheduledAt: Date;
|
|
||||||
gameNumber: number;
|
|
||||||
riotMatchId: string;
|
|
||||||
gameCreation: number;
|
|
||||||
gameDuration: number;
|
|
||||||
userId: string;
|
|
||||||
summonerName: string;
|
|
||||||
profileIconId: number;
|
|
||||||
teamIndex: number;
|
|
||||||
side: TeamSide;
|
|
||||||
championId: number;
|
|
||||||
championLevel: number;
|
|
||||||
teamPosition: string;
|
|
||||||
kills: number;
|
|
||||||
deaths: number;
|
|
||||||
assists: number;
|
|
||||||
win: boolean;
|
|
||||||
cs: number;
|
|
||||||
csPerMin: number;
|
|
||||||
gold: number;
|
|
||||||
gpm: number;
|
|
||||||
damageDealtToChampions: number;
|
|
||||||
damageTaken: number;
|
|
||||||
damageShare: number;
|
|
||||||
killParticipation: number;
|
|
||||||
visionScore: number;
|
|
||||||
controlWardsBought: number;
|
|
||||||
wardsPlaced: number;
|
|
||||||
wardsKilled: number;
|
|
||||||
items: number[];
|
|
||||||
trinket: number;
|
|
||||||
summonerSpells: [number, number];
|
|
||||||
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
|
|
||||||
rating: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface InternalGameDetail {
|
|
||||||
gameNumber: number;
|
|
||||||
riotMatchId: string;
|
|
||||||
gameCreation: number;
|
|
||||||
gameDuration: number;
|
|
||||||
winnerSide: TeamSide;
|
|
||||||
teams: Array<{
|
|
||||||
teamIndex: number;
|
|
||||||
side: TeamSide;
|
|
||||||
win: boolean;
|
|
||||||
objectives: { baron: number; dragon: number; tower: number };
|
|
||||||
participants: InternalRecord[];
|
|
||||||
}>;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface BaseDataset {
|
interface BaseDataset {
|
||||||
season: HistorySeasonDto;
|
season: HistorySeasonDto;
|
||||||
matches: InternalMatchCardView[];
|
matches: InternalMatchCardView[];
|
||||||
@@ -99,9 +53,13 @@ interface BaseDataset {
|
|||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class CommunityStatsService {
|
export class CommunityStatsService {
|
||||||
|
private readonly logger = new Logger(CommunityStatsService.name);
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly connectionService: ConnectionService,
|
private readonly connectionService: ConnectionService,
|
||||||
private readonly cacheService: CommunityStatsCacheService,
|
private readonly cacheService: CommunityStatsCacheService,
|
||||||
|
private readonly matchStatsRepository: MatchStatsRepository,
|
||||||
|
private readonly matchStatsService: MatchStatsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public async getMatches(params: {
|
public async getMatches(params: {
|
||||||
@@ -112,8 +70,15 @@ export class CommunityStatsService {
|
|||||||
const cached = await this.cacheService.get<InternalMatchListResponse>(key);
|
const cached = await this.cacheService.get<InternalMatchListResponse>(key);
|
||||||
if (cached) return cached;
|
if (cached) return cached;
|
||||||
|
|
||||||
const limit = this.clampLimit(params.filters.limit, DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT);
|
const limit = this.clampLimit(
|
||||||
const dataset = await this.buildBaseDataset(params.communityId, params.filters);
|
params.filters.limit,
|
||||||
|
DEFAULT_LIST_LIMIT,
|
||||||
|
MAX_LIST_LIMIT,
|
||||||
|
);
|
||||||
|
const dataset = await this.buildBaseDataset(
|
||||||
|
params.communityId,
|
||||||
|
params.filters,
|
||||||
|
);
|
||||||
const filtered = params.filters.championId
|
const filtered = params.filters.championId
|
||||||
? dataset.matches.filter((match) =>
|
? dataset.matches.filter((match) =>
|
||||||
dataset.records.some(
|
dataset.records.some(
|
||||||
@@ -125,7 +90,9 @@ export class CommunityStatsService {
|
|||||||
: dataset.matches;
|
: dataset.matches;
|
||||||
const cursor = params.filters.cursor;
|
const cursor = params.filters.cursor;
|
||||||
const page = filtered
|
const page = filtered
|
||||||
.filter((match) => !cursor || new Date(match.scheduledAt).getTime() < cursor)
|
.filter(
|
||||||
|
(match) => !cursor || new Date(match.scheduledAt).getTime() < cursor,
|
||||||
|
)
|
||||||
.slice(0, limit + 1);
|
.slice(0, limit + 1);
|
||||||
const visible = page.slice(0, limit);
|
const visible = page.slice(0, limit);
|
||||||
const response: InternalMatchListResponse = {
|
const response: InternalMatchListResponse = {
|
||||||
@@ -144,11 +111,18 @@ export class CommunityStatsService {
|
|||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
filters: CommunityStatsFilters;
|
filters: CommunityStatsFilters;
|
||||||
}): Promise<LeaderboardResponse> {
|
}): Promise<LeaderboardResponse> {
|
||||||
const key = this.cacheKey('leaderboard', params.communityId, params.filters);
|
const key = this.cacheKey(
|
||||||
|
'leaderboard',
|
||||||
|
params.communityId,
|
||||||
|
params.filters,
|
||||||
|
);
|
||||||
const cached = await this.cacheService.get<LeaderboardResponse>(key);
|
const cached = await this.cacheService.get<LeaderboardResponse>(key);
|
||||||
if (cached) return cached;
|
if (cached) return cached;
|
||||||
|
|
||||||
const dataset = await this.buildBaseDataset(params.communityId, params.filters);
|
const dataset = await this.buildBaseDataset(
|
||||||
|
params.communityId,
|
||||||
|
params.filters,
|
||||||
|
);
|
||||||
const records = this.applyChampionFilter(dataset.records, params.filters);
|
const records = this.applyChampionFilter(dataset.records, params.filters);
|
||||||
const rows = this.buildLeaderboardRows(records);
|
const rows = this.buildLeaderboardRows(records);
|
||||||
const response = { rows, season: dataset.season };
|
const response = { rows, season: dataset.season };
|
||||||
@@ -160,18 +134,29 @@ export class CommunityStatsService {
|
|||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
filters: CommunityStatsFilters;
|
filters: CommunityStatsFilters;
|
||||||
}): Promise<TeamInsightsResponse> {
|
}): Promise<TeamInsightsResponse> {
|
||||||
const key = this.cacheKey('teamInsights', params.communityId, params.filters);
|
const key = this.cacheKey(
|
||||||
|
'teamInsights',
|
||||||
|
params.communityId,
|
||||||
|
params.filters,
|
||||||
|
);
|
||||||
const cached = await this.cacheService.get<TeamInsightsResponse>(key);
|
const cached = await this.cacheService.get<TeamInsightsResponse>(key);
|
||||||
if (cached) return cached;
|
if (cached) return cached;
|
||||||
|
|
||||||
const dataset = await this.buildBaseDataset(params.communityId, params.filters);
|
const dataset = await this.buildBaseDataset(
|
||||||
|
params.communityId,
|
||||||
|
params.filters,
|
||||||
|
);
|
||||||
const records = this.applyChampionFilter(dataset.records, params.filters);
|
const records = this.applyChampionFilter(dataset.records, params.filters);
|
||||||
const rows = this.buildLeaderboardRows(records);
|
const rows = this.buildLeaderboardRows(records);
|
||||||
const gameDetails = [...dataset.detailsByMatchId.values()].flat();
|
const gameDetails = [...dataset.detailsByMatchId.values()].flat();
|
||||||
const blueGames = gameDetails.length;
|
const blueGames = gameDetails.length;
|
||||||
const redGames = gameDetails.length;
|
const redGames = gameDetails.length;
|
||||||
const blueWins = gameDetails.filter((game) => game.winnerSide === 'blue').length;
|
const blueWins = gameDetails.filter(
|
||||||
const redWins = gameDetails.filter((game) => game.winnerSide === 'red').length;
|
(game) => game.winnerSide === 'blue',
|
||||||
|
).length;
|
||||||
|
const redWins = gameDetails.filter(
|
||||||
|
(game) => game.winnerSide === 'red',
|
||||||
|
).length;
|
||||||
|
|
||||||
const response: TeamInsightsResponse = {
|
const response: TeamInsightsResponse = {
|
||||||
season: dataset.season,
|
season: dataset.season,
|
||||||
@@ -221,7 +206,8 @@ export class CommunityStatsService {
|
|||||||
matchId: mongoose.Types.ObjectId;
|
matchId: mongoose.Types.ObjectId;
|
||||||
}): Promise<InternalMatchDetailResponse> {
|
}): Promise<InternalMatchDetailResponse> {
|
||||||
const key = `riot:communitystats:matchDetail:${params.communityId.toString()}:${params.matchId.toString()}`;
|
const key = `riot:communitystats:matchDetail:${params.communityId.toString()}:${params.matchId.toString()}`;
|
||||||
const cached = await this.cacheService.get<InternalMatchDetailResponse>(key);
|
const cached =
|
||||||
|
await this.cacheService.get<InternalMatchDetailResponse>(key);
|
||||||
if (cached) return cached;
|
if (cached) return cached;
|
||||||
|
|
||||||
const dataset = await this.buildBaseDataset(params.communityId, {
|
const dataset = await this.buildBaseDataset(params.communityId, {
|
||||||
@@ -233,7 +219,8 @@ export class CommunityStatsService {
|
|||||||
if (!match) throw new NotFoundException('Internal match not found.');
|
if (!match) throw new NotFoundException('Internal match not found.');
|
||||||
const response: InternalMatchDetailResponse = {
|
const response: InternalMatchDetailResponse = {
|
||||||
match,
|
match,
|
||||||
games: (dataset.detailsByMatchId.get(match.matchId) ?? []).map((game) => ({
|
games: (dataset.detailsByMatchId.get(match.matchId) ?? []).map(
|
||||||
|
(game) => ({
|
||||||
gameNumber: game.gameNumber,
|
gameNumber: game.gameNumber,
|
||||||
riotMatchId: game.riotMatchId,
|
riotMatchId: game.riotMatchId,
|
||||||
gameCreation: game.gameCreation,
|
gameCreation: game.gameCreation,
|
||||||
@@ -268,7 +255,8 @@ export class CommunityStatsService {
|
|||||||
win: record.win,
|
win: record.win,
|
||||||
})),
|
})),
|
||||||
})),
|
})),
|
||||||
})),
|
}),
|
||||||
|
),
|
||||||
};
|
};
|
||||||
await this.cacheService.setDetail(key, response);
|
await this.cacheService.setDetail(key, response);
|
||||||
return response;
|
return response;
|
||||||
@@ -284,10 +272,14 @@ export class CommunityStatsService {
|
|||||||
params.communityId,
|
params.communityId,
|
||||||
params.filters,
|
params.filters,
|
||||||
);
|
);
|
||||||
const cached = await this.cacheService.get<UserInternalHistoryResponse>(key);
|
const cached =
|
||||||
|
await this.cacheService.get<UserInternalHistoryResponse>(key);
|
||||||
if (cached) return cached;
|
if (cached) return cached;
|
||||||
|
|
||||||
const dataset = await this.buildBaseDataset(params.communityId, params.filters);
|
const dataset = await this.buildBaseDataset(
|
||||||
|
params.communityId,
|
||||||
|
params.filters,
|
||||||
|
);
|
||||||
const allUserRecords = dataset.records
|
const allUserRecords = dataset.records
|
||||||
.filter((record) => record.userId === params.userId.toString())
|
.filter((record) => record.userId === params.userId.toString())
|
||||||
.sort((left, right) => right.gameCreation - left.gameCreation);
|
.sort((left, right) => right.gameCreation - left.gameCreation);
|
||||||
@@ -300,20 +292,27 @@ export class CommunityStatsService {
|
|||||||
const visible = page.slice(0, limit);
|
const visible = page.slice(0, limit);
|
||||||
const response: UserInternalHistoryResponse = {
|
const response: UserInternalHistoryResponse = {
|
||||||
season: dataset.season,
|
season: dataset.season,
|
||||||
championStats: this.buildUserChampionStats(allUserRecords, dataset.season),
|
championStats: this.buildUserChampionStats(
|
||||||
|
allUserRecords,
|
||||||
|
dataset.season,
|
||||||
|
),
|
||||||
summary: this.buildUserSummary(records, visible.length || limit),
|
summary: this.buildUserSummary(records, visible.length || limit),
|
||||||
matches: visible.map((record) => this.toRecentMatchView(record, dataset)),
|
matches: visible.map((record) => this.toRecentMatchView(record, dataset)),
|
||||||
nextCursor:
|
nextCursor:
|
||||||
page.length > limit
|
page.length > limit
|
||||||
? visible[visible.length - 1]?.gameCreation ?? null
|
? (visible[visible.length - 1]?.gameCreation ?? null)
|
||||||
|
: null,
|
||||||
|
lastFetchedAt: records[0]
|
||||||
|
? new Date(records[0].gameCreation).toISOString()
|
||||||
: null,
|
: null,
|
||||||
lastFetchedAt: records[0] ? new Date(records[0].gameCreation).toISOString() : null,
|
|
||||||
};
|
};
|
||||||
await this.cacheService.set(key, response);
|
await this.cacheService.set(key, response);
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
public invalidateCommunity(communityId: mongoose.Types.ObjectId): Promise<number> {
|
public invalidateCommunity(
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
): Promise<number> {
|
||||||
return this.cacheService.invalidateCommunity(communityId.toString());
|
return this.cacheService.invalidateCommunity(communityId.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -322,52 +321,47 @@ export class CommunityStatsService {
|
|||||||
filters: CommunityStatsFilters,
|
filters: CommunityStatsFilters,
|
||||||
): Promise<BaseDataset> {
|
): Promise<BaseDataset> {
|
||||||
const context = await this.resolveContext(communityId, filters);
|
const context = await this.resolveContext(communityId, filters);
|
||||||
const MatchModel = await this.connectionService.getModel('match');
|
let fragments = await this.matchStatsRepository.findByCommunity({
|
||||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
|
||||||
const matches = await MatchModel.find({
|
|
||||||
communityId,
|
communityId,
|
||||||
status: { $in: ['finished', 'in-progress'] },
|
fromGameCreation: context.from?.getTime(),
|
||||||
'result.games.0': { $exists: true },
|
toGameCreation: context.to?.getTime(),
|
||||||
})
|
limit: MAX_MATCH_SCAN,
|
||||||
.sort({ scheduledAt: -1 })
|
});
|
||||||
.limit(MAX_MATCH_SCAN)
|
const rebuilt = await this.rebuildMissingOrStaleFragments(communityId);
|
||||||
.exec();
|
if (rebuilt > 0) {
|
||||||
const riotMatchIds = [
|
fragments = await this.matchStatsRepository.findByCommunity({
|
||||||
...new Set(
|
communityId,
|
||||||
matches.flatMap((match) =>
|
fromGameCreation: context.from?.getTime(),
|
||||||
(match.result?.games ?? []).map((game) => game.riotMatchId),
|
toGameCreation: context.to?.getTime(),
|
||||||
),
|
limit: MAX_MATCH_SCAN,
|
||||||
),
|
});
|
||||||
];
|
}
|
||||||
const riotDocs = await RiotMatchModel.find({ matchId: { $in: riotMatchIds } })
|
|
||||||
.lean()
|
|
||||||
.exec();
|
|
||||||
const rawByMatchId = new Map(
|
|
||||||
riotDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]),
|
|
||||||
);
|
|
||||||
|
|
||||||
const cards: InternalMatchCardView[] = [];
|
const cards: InternalMatchCardView[] = [];
|
||||||
const records: InternalRecord[] = [];
|
const records: InternalRecord[] = [];
|
||||||
const detailsByMatchId = new Map<string, InternalGameDetail[]>();
|
const detailsByMatchId = new Map<string, InternalGameDetail[]>();
|
||||||
|
|
||||||
for (const match of matches) {
|
for (const fragment of fragments) {
|
||||||
const games = (match.result?.games ?? [])
|
const filteredGames = (fragment.gameDetails as InternalGameDetail[])
|
||||||
.filter((game) => this.isGameInRange(game.gameCreation, context))
|
.filter((game) => this.isGameInRange(game.gameCreation, context))
|
||||||
.sort((left, right) => left.gameNumber - right.gameNumber);
|
.sort((left, right) => left.gameNumber - right.gameNumber);
|
||||||
if (games.length === 0) continue;
|
if (filteredGames.length === 0) continue;
|
||||||
cards.push(this.toMatchCard(match, games));
|
|
||||||
|
|
||||||
for (const game of games) {
|
const card = this.adjustCardForRange(
|
||||||
const raw = rawByMatchId.get(game.riotMatchId);
|
fragment.matchCard as unknown as InternalMatchCardView,
|
||||||
const detail = raw
|
filteredGames,
|
||||||
? this.toGameDetail(match, game, raw)
|
);
|
||||||
: this.toFallbackGameDetail(match, game);
|
cards.push(card);
|
||||||
detailsByMatchId.set(match._id.toString(), [
|
detailsByMatchId.set(fragment.matchId.toString(), filteredGames);
|
||||||
...(detailsByMatchId.get(match._id.toString()) ?? []),
|
|
||||||
detail,
|
const allowedGameNumbers = new Set(
|
||||||
]);
|
filteredGames.map((game) => game.gameNumber),
|
||||||
records.push(...detail.teams.flatMap((team) => team.participants));
|
);
|
||||||
}
|
records.push(
|
||||||
|
...(fragment.records as InternalRecord[]).filter((record) =>
|
||||||
|
allowedGameNumbers.has(record.gameNumber),
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -378,6 +372,123 @@ export class CommunityStatsService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async rebuildMissingOrStaleFragments(
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
): Promise<number> {
|
||||||
|
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<number, number>();
|
||||||
|
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(
|
private async resolveContext(
|
||||||
communityId: mongoose.Types.ObjectId,
|
communityId: mongoose.Types.ObjectId,
|
||||||
filters: CommunityStatsFilters,
|
filters: CommunityStatsFilters,
|
||||||
@@ -386,10 +497,11 @@ export class CommunityStatsService {
|
|||||||
const community = await CommunityModel.findById(communityId).exec();
|
const community = await CommunityModel.findById(communityId).exec();
|
||||||
if (!community) throw new NotFoundException('Community not found.');
|
if (!community) throw new NotFoundException('Community not found.');
|
||||||
const season = this.resolveSeason(community, filters.seasonId);
|
const season = this.resolveSeason(community, filters.seasonId);
|
||||||
const from =
|
const from = filters.from
|
||||||
filters.from ? new Date(filters.from) :
|
? new Date(filters.from)
|
||||||
season.startedAt ? new Date(season.startedAt) :
|
: season.startedAt
|
||||||
null;
|
? new Date(season.startedAt)
|
||||||
|
: null;
|
||||||
const to = filters.to ? new Date(filters.to) : null;
|
const to = filters.to ? new Date(filters.to) : null;
|
||||||
if (from && Number.isNaN(from.getTime())) {
|
if (from && Number.isNaN(from.getTime())) {
|
||||||
throw new BadRequestException('Invalid from date.');
|
throw new BadRequestException('Invalid from date.');
|
||||||
@@ -442,235 +554,6 @@ export class CommunityStatsService {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
private toMatchCard(
|
|
||||||
match: MatchDocument,
|
|
||||||
games: NonNullable<MatchDocument['result']>['games'],
|
|
||||||
): InternalMatchCardView {
|
|
||||||
const participantById = new Map(
|
|
||||||
match.participants.map((participant) => [
|
|
||||||
participant.userId.toString(),
|
|
||||||
participant,
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
return {
|
|
||||||
matchId: match._id.toString(),
|
|
||||||
title: match.title,
|
|
||||||
scheduledAt: match.scheduledAt.toISOString(),
|
|
||||||
status: match.status === 'finished' ? 'finished' : 'in-progress',
|
|
||||||
gameCount: match.gameCount,
|
|
||||||
winnerTeamIndex: match.result?.winnerTeamIndex,
|
|
||||||
seriesResults: match.result?.seriesResults ?? [],
|
|
||||||
games: games.map((game) => ({
|
|
||||||
gameNumber: game.gameNumber,
|
|
||||||
riotMatchId: game.riotMatchId ?? null,
|
|
||||||
blueTeamIndex: game.blueTeamIndex,
|
|
||||||
redTeamIndex: game.redTeamIndex,
|
|
||||||
winnerTeamIndex: game.winnerTeamIndex ?? null,
|
|
||||||
winnerSide: game.winnerSide ?? null,
|
|
||||||
gameDuration: game.gameDuration,
|
|
||||||
})),
|
|
||||||
teams: match.teams.map((team) => ({
|
|
||||||
teamIndex: team.teamIndex,
|
|
||||||
name: team.name,
|
|
||||||
members: team.members.map((member) => {
|
|
||||||
const participant = participantById.get(member.userId.toString());
|
|
||||||
return {
|
|
||||||
userId: member.userId.toString(),
|
|
||||||
summonerName: participant?.gameName ?? 'Unknown',
|
|
||||||
profileIconId: participant?.profileIconId ?? 0,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
})),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private toGameDetail(
|
|
||||||
match: MatchDocument,
|
|
||||||
game: NonNullable<MatchDocument['result']>['games'][number],
|
|
||||||
raw: RiotMatchDto,
|
|
||||||
): InternalGameDetail {
|
|
||||||
const puuidByUserId = new Map(
|
|
||||||
match.participants
|
|
||||||
.filter((participant) => participant.puuid)
|
|
||||||
.map((participant) => [
|
|
||||||
participant.userId.toString(),
|
|
||||||
participant.puuid as string,
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
const rawByPuuid = new Map(
|
|
||||||
raw.info.participants.map((participant) => [participant.puuid, participant]),
|
|
||||||
);
|
|
||||||
const rawTeamIdBySide = new Map<TeamSide, number>();
|
|
||||||
for (const participant of game.participants) {
|
|
||||||
const puuid = puuidByUserId.get(participant.userId.toString());
|
|
||||||
const rawParticipant = puuid ? rawByPuuid.get(puuid) : undefined;
|
|
||||||
if (rawParticipant) rawTeamIdBySide.set(participant.side, rawParticipant.teamId);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
gameNumber: game.gameNumber,
|
|
||||||
riotMatchId: game.riotMatchId,
|
|
||||||
gameCreation: game.gameCreation,
|
|
||||||
gameDuration: game.gameDuration,
|
|
||||||
winnerSide: game.winnerSide,
|
|
||||||
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
|
|
||||||
const teamIndex =
|
|
||||||
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
|
|
||||||
const rawTeamId = rawTeamIdBySide.get(side);
|
|
||||||
const rawTeam = raw.info.teams.find((team) => team.teamId === rawTeamId);
|
|
||||||
const teamRawParticipants = raw.info.participants.filter(
|
|
||||||
(participant) => participant.teamId === rawTeamId,
|
|
||||||
);
|
|
||||||
const teamKills = teamRawParticipants.reduce(
|
|
||||||
(sum, participant) => sum + participant.kills,
|
|
||||||
0,
|
|
||||||
);
|
|
||||||
const teamDamage = teamRawParticipants.reduce(
|
|
||||||
(sum, participant) => sum + participant.totalDamageDealtToChampions,
|
|
||||||
0,
|
|
||||||
);
|
|
||||||
return {
|
|
||||||
teamIndex,
|
|
||||||
side,
|
|
||||||
win: game.winnerSide === side,
|
|
||||||
objectives: {
|
|
||||||
baron: rawTeam?.objectives?.baron?.kills ?? 0,
|
|
||||||
dragon: rawTeam?.objectives?.dragon?.kills ?? 0,
|
|
||||||
tower: rawTeam?.objectives?.tower?.kills ?? 0,
|
|
||||||
},
|
|
||||||
participants: game.participants
|
|
||||||
.filter((participant) => participant.side === side)
|
|
||||||
.map((participant) =>
|
|
||||||
this.toRecord({
|
|
||||||
match,
|
|
||||||
game,
|
|
||||||
participant,
|
|
||||||
rawParticipant: rawByPuuid.get(
|
|
||||||
puuidByUserId.get(participant.userId.toString()) ?? '',
|
|
||||||
),
|
|
||||||
teamKills,
|
|
||||||
teamDamage,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private toFallbackGameDetail(
|
|
||||||
match: MatchDocument,
|
|
||||||
game: NonNullable<MatchDocument['result']>['games'][number],
|
|
||||||
): InternalGameDetail {
|
|
||||||
return {
|
|
||||||
gameNumber: game.gameNumber,
|
|
||||||
riotMatchId: game.riotMatchId,
|
|
||||||
gameCreation: game.gameCreation,
|
|
||||||
gameDuration: game.gameDuration,
|
|
||||||
winnerSide: game.winnerSide,
|
|
||||||
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
|
|
||||||
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
|
|
||||||
side,
|
|
||||||
win: game.winnerSide === side,
|
|
||||||
objectives: { baron: 0, dragon: 0, tower: 0 },
|
|
||||||
participants: game.participants
|
|
||||||
.filter((participant) => participant.side === side)
|
|
||||||
.map((participant) =>
|
|
||||||
this.toRecord({ match, game, participant, teamKills: 0, teamDamage: 0 }),
|
|
||||||
),
|
|
||||||
})),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private toRecord(params: {
|
|
||||||
match: MatchDocument;
|
|
||||||
game: NonNullable<MatchDocument['result']>['games'][number];
|
|
||||||
participant: MatchGameResultParticipant;
|
|
||||||
rawParticipant?: RiotMatchParticipantDto;
|
|
||||||
teamKills: number;
|
|
||||||
teamDamage: number;
|
|
||||||
}): InternalRecord {
|
|
||||||
const { match, game, participant, rawParticipant, teamKills, teamDamage } = params;
|
|
||||||
const snapshot = match.participants.find((item) =>
|
|
||||||
item.userId.equals(participant.userId),
|
|
||||||
);
|
|
||||||
const minutes = Math.max(
|
|
||||||
(rawParticipant?.timePlayed ?? game.gameDuration) / 60,
|
|
||||||
1,
|
|
||||||
);
|
|
||||||
const cs = rawParticipant
|
|
||||||
? rawParticipant.totalMinionsKilled + rawParticipant.neutralMinionsKilled
|
|
||||||
: 0;
|
|
||||||
const damage = rawParticipant?.totalDamageDealtToChampions ?? 0;
|
|
||||||
const killParticipation = this.percent(
|
|
||||||
participant.kills + participant.assists,
|
|
||||||
teamKills,
|
|
||||||
);
|
|
||||||
const damageShare = this.percent(damage, teamDamage);
|
|
||||||
const rating = this.resolveRating({
|
|
||||||
kills: participant.kills,
|
|
||||||
deaths: participant.deaths,
|
|
||||||
assists: participant.assists,
|
|
||||||
killParticipation,
|
|
||||||
csPerMin: this.average(cs, minutes),
|
|
||||||
damageShare,
|
|
||||||
visionPerMin: this.average(rawParticipant?.visionScore ?? 0, minutes),
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
matchId: match._id.toString(),
|
|
||||||
title: match.title,
|
|
||||||
scheduledAt: match.scheduledAt,
|
|
||||||
gameNumber: game.gameNumber,
|
|
||||||
riotMatchId: game.riotMatchId,
|
|
||||||
gameCreation: game.gameCreation,
|
|
||||||
gameDuration: game.gameDuration,
|
|
||||||
userId: participant.userId.toString(),
|
|
||||||
summonerName:
|
|
||||||
snapshot?.gameName ??
|
|
||||||
rawParticipant?.riotIdGameName ??
|
|
||||||
rawParticipant?.summonerName ??
|
|
||||||
'Unknown',
|
|
||||||
profileIconId: snapshot?.profileIconId ?? 0,
|
|
||||||
teamIndex: participant.teamIndex,
|
|
||||||
side: participant.side,
|
|
||||||
championId: participant.championId,
|
|
||||||
championLevel: rawParticipant?.champLevel ?? 0,
|
|
||||||
teamPosition:
|
|
||||||
rawParticipant?.teamPosition || rawParticipant?.individualPosition || '',
|
|
||||||
kills: participant.kills,
|
|
||||||
deaths: participant.deaths,
|
|
||||||
assists: participant.assists,
|
|
||||||
win: participant.win,
|
|
||||||
cs,
|
|
||||||
csPerMin: this.average(cs, minutes),
|
|
||||||
gold: rawParticipant?.goldEarned ?? 0,
|
|
||||||
gpm: this.average(rawParticipant?.goldEarned ?? 0, minutes),
|
|
||||||
damageDealtToChampions: damage,
|
|
||||||
damageTaken: rawParticipant?.totalDamageTaken ?? 0,
|
|
||||||
damageShare,
|
|
||||||
killParticipation,
|
|
||||||
visionScore: rawParticipant?.visionScore ?? 0,
|
|
||||||
controlWardsBought: this.numberField(rawParticipant, 'visionWardsBoughtInGame'),
|
|
||||||
wardsPlaced: rawParticipant?.wardsPlaced ?? 0,
|
|
||||||
wardsKilled: rawParticipant?.wardsKilled ?? 0,
|
|
||||||
items: [
|
|
||||||
rawParticipant?.item0 ?? 0,
|
|
||||||
rawParticipant?.item1 ?? 0,
|
|
||||||
rawParticipant?.item2 ?? 0,
|
|
||||||
rawParticipant?.item3 ?? 0,
|
|
||||||
rawParticipant?.item4 ?? 0,
|
|
||||||
rawParticipant?.item5 ?? 0,
|
|
||||||
],
|
|
||||||
trinket: rawParticipant?.item6 ?? 0,
|
|
||||||
summonerSpells: [
|
|
||||||
rawParticipant?.summoner1Id ?? 0,
|
|
||||||
rawParticipant?.summoner2Id ?? 0,
|
|
||||||
],
|
|
||||||
perks: rawParticipant ? this.resolvePerks(rawParticipant) : {},
|
|
||||||
rating,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private buildLeaderboardRows(records: InternalRecord[]): LeaderboardRow[] {
|
private buildLeaderboardRows(records: InternalRecord[]): LeaderboardRow[] {
|
||||||
const byUser = new Map<string, InternalRecord[]>();
|
const byUser = new Map<string, InternalRecord[]>();
|
||||||
for (const record of records) {
|
for (const record of records) {
|
||||||
@@ -678,18 +561,32 @@ export class CommunityStatsService {
|
|||||||
}
|
}
|
||||||
return [...byUser.entries()]
|
return [...byUser.entries()]
|
||||||
.map(([userId, rows]) => this.toLeaderboardRow(userId, rows))
|
.map(([userId, rows]) => this.toLeaderboardRow(userId, rows))
|
||||||
.sort((left, right) => right.games - left.games || right.winRate - left.winRate);
|
.sort(
|
||||||
|
(left, right) =>
|
||||||
|
right.games - left.games || right.winRate - left.winRate,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private toLeaderboardRow(userId: string, records: InternalRecord[]): LeaderboardRow {
|
private toLeaderboardRow(
|
||||||
|
userId: string,
|
||||||
|
records: InternalRecord[],
|
||||||
|
): LeaderboardRow {
|
||||||
const first = records[0];
|
const first = records[0];
|
||||||
const wins = records.filter((record) => record.win).length;
|
const wins = records.filter((record) => record.win).length;
|
||||||
const kills = this.sum(records, 'kills');
|
const kills = this.sum(records, 'kills');
|
||||||
const deaths = this.sum(records, 'deaths');
|
const deaths = this.sum(records, 'deaths');
|
||||||
const assists = this.sum(records, 'assists');
|
const assists = this.sum(records, 'assists');
|
||||||
const byLane: LeaderboardRow['byLane'] = {};
|
const byLane: LeaderboardRow['byLane'] = {};
|
||||||
for (const lane of ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'] as RiotLane[]) {
|
for (const lane of [
|
||||||
const laneRecords = records.filter((record) => record.teamPosition === lane);
|
'TOP',
|
||||||
|
'JUNGLE',
|
||||||
|
'MIDDLE',
|
||||||
|
'BOTTOM',
|
||||||
|
'UTILITY',
|
||||||
|
] as RiotLane[]) {
|
||||||
|
const laneRecords = records.filter(
|
||||||
|
(record) => record.teamPosition === lane,
|
||||||
|
);
|
||||||
if (laneRecords.length === 0) continue;
|
if (laneRecords.length === 0) continue;
|
||||||
byLane[lane] = {
|
byLane[lane] = {
|
||||||
games: laneRecords.length,
|
games: laneRecords.length,
|
||||||
@@ -703,8 +600,10 @@ export class CommunityStatsService {
|
|||||||
}
|
}
|
||||||
const championCounts = new Map<number, { games: number; wins: number }>();
|
const championCounts = new Map<number, { games: number; wins: number }>();
|
||||||
for (const record of records) {
|
for (const record of records) {
|
||||||
const current =
|
const current = championCounts.get(record.championId) ?? {
|
||||||
championCounts.get(record.championId) ?? { games: 0, wins: 0 };
|
games: 0,
|
||||||
|
wins: 0,
|
||||||
|
};
|
||||||
current.games += 1;
|
current.games += 1;
|
||||||
current.wins += record.win ? 1 : 0;
|
current.wins += record.win ? 1 : 0;
|
||||||
championCounts.set(record.championId, current);
|
championCounts.set(record.championId, current);
|
||||||
@@ -728,8 +627,14 @@ export class CommunityStatsService {
|
|||||||
records.length,
|
records.length,
|
||||||
),
|
),
|
||||||
avgCsPerMin: this.average(this.sum(records, 'csPerMin'), records.length),
|
avgCsPerMin: this.average(this.sum(records, 'csPerMin'), records.length),
|
||||||
avgDamageShare: this.average(this.sum(records, 'damageShare'), records.length),
|
avgDamageShare: this.average(
|
||||||
avgVisionScore: this.average(this.sum(records, 'visionScore'), records.length),
|
this.sum(records, 'damageShare'),
|
||||||
|
records.length,
|
||||||
|
),
|
||||||
|
avgVisionScore: this.average(
|
||||||
|
this.sum(records, 'visionScore'),
|
||||||
|
records.length,
|
||||||
|
),
|
||||||
byLane,
|
byLane,
|
||||||
topChampions: [...championCounts.entries()]
|
topChampions: [...championCounts.entries()]
|
||||||
.map(([championId, stat]) => ({
|
.map(([championId, stat]) => ({
|
||||||
@@ -737,7 +642,10 @@ export class CommunityStatsService {
|
|||||||
games: stat.games,
|
games: stat.games,
|
||||||
winRate: this.percent(stat.wins, stat.games),
|
winRate: this.percent(stat.wins, stat.games),
|
||||||
}))
|
}))
|
||||||
.sort((left, right) => right.games - left.games || right.winRate - left.winRate)
|
.sort(
|
||||||
|
(left, right) =>
|
||||||
|
right.games - left.games || right.winRate - left.winRate,
|
||||||
|
)
|
||||||
.slice(0, 3),
|
.slice(0, 3),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -755,14 +663,19 @@ export class CommunityStatsService {
|
|||||||
}
|
}
|
||||||
const champions = [...byChampion.entries()]
|
const champions = [...byChampion.entries()]
|
||||||
.map(([championId, rows]) => this.toChampionRow(championId, rows))
|
.map(([championId, rows]) => this.toChampionRow(championId, rows))
|
||||||
.sort((left, right) => right.games - left.games || right.winRate - left.winRate);
|
.sort(
|
||||||
|
(left, right) =>
|
||||||
|
right.games - left.games || right.winRate - left.winRate,
|
||||||
|
);
|
||||||
const totals = this.toChampionRow(0, records);
|
const totals = this.toChampionRow(0, records);
|
||||||
return {
|
return {
|
||||||
queueGroup: 'internal',
|
queueGroup: 'internal',
|
||||||
rank: 'all',
|
rank: 'all',
|
||||||
queueIds: [],
|
queueIds: [],
|
||||||
season,
|
season,
|
||||||
lastFetchedAt: records[0] ? new Date(records[0].gameCreation).toISOString() : null,
|
lastFetchedAt: records[0]
|
||||||
|
? new Date(records[0].gameCreation).toISOString()
|
||||||
|
: null,
|
||||||
champions,
|
champions,
|
||||||
totals,
|
totals,
|
||||||
};
|
};
|
||||||
@@ -836,11 +749,16 @@ export class CommunityStatsService {
|
|||||||
: null,
|
: null,
|
||||||
positionRates: this.resolvePositionRates(views),
|
positionRates: this.resolvePositionRates(views),
|
||||||
topChampions: this.resolveTopChampions(views),
|
topChampions: this.resolveTopChampions(views),
|
||||||
lastFetchedAt: views[0] ? new Date(views[0].gameCreation).toISOString() : null,
|
lastFetchedAt: views[0]
|
||||||
|
? new Date(views[0].gameCreation).toISOString()
|
||||||
|
: null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private toRecentMatchView(record: InternalRecord, dataset: BaseDataset): RecentMatchView {
|
private toRecentMatchView(
|
||||||
|
record: InternalRecord,
|
||||||
|
dataset: BaseDataset,
|
||||||
|
): RecentMatchView {
|
||||||
const detail = dataset.detailsByMatchId
|
const detail = dataset.detailsByMatchId
|
||||||
.get(record.matchId)
|
.get(record.matchId)
|
||||||
?.find((game) => game.riotMatchId === record.riotMatchId);
|
?.find((game) => game.riotMatchId === record.riotMatchId);
|
||||||
@@ -973,7 +891,10 @@ export class CommunityStatsService {
|
|||||||
const counts = new Map<string, number>();
|
const counts = new Map<string, number>();
|
||||||
for (const record of records) {
|
for (const record of records) {
|
||||||
if (!record.teamPosition) continue;
|
if (!record.teamPosition) continue;
|
||||||
counts.set(record.teamPosition, (counts.get(record.teamPosition) ?? 0) + 1);
|
counts.set(
|
||||||
|
record.teamPosition,
|
||||||
|
(counts.get(record.teamPosition) ?? 0) + 1,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return Object.fromEntries(
|
return Object.fromEntries(
|
||||||
[...counts.entries()].map(([lane, count]) => [
|
[...counts.entries()].map(([lane, count]) => [
|
||||||
@@ -984,10 +905,16 @@ export class CommunityStatsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private resolveTopChampions(records: InternalRecord[]) {
|
private resolveTopChampions(records: InternalRecord[]) {
|
||||||
const byChampion = new Map<number, { games: number; wins: number; rating: number }>();
|
const byChampion = new Map<
|
||||||
|
number,
|
||||||
|
{ games: number; wins: number; rating: number }
|
||||||
|
>();
|
||||||
for (const record of records) {
|
for (const record of records) {
|
||||||
const current =
|
const current = byChampion.get(record.championId) ?? {
|
||||||
byChampion.get(record.championId) ?? { games: 0, wins: 0, rating: 0 };
|
games: 0,
|
||||||
|
wins: 0,
|
||||||
|
rating: 0,
|
||||||
|
};
|
||||||
current.games += 1;
|
current.games += 1;
|
||||||
current.wins += record.win ? 1 : 0;
|
current.wins += record.win ? 1 : 0;
|
||||||
current.rating += record.rating;
|
current.rating += record.rating;
|
||||||
@@ -1001,43 +928,13 @@ export class CommunityStatsService {
|
|||||||
pickRate: this.percent(stat.games, records.length),
|
pickRate: this.percent(stat.games, records.length),
|
||||||
avgRating: this.average(stat.rating, stat.games),
|
avgRating: this.average(stat.rating, stat.games),
|
||||||
}))
|
}))
|
||||||
.sort((left, right) => right.games - left.games || right.winRate - left.winRate)
|
.sort(
|
||||||
|
(left, right) =>
|
||||||
|
right.games - left.games || right.winRate - left.winRate,
|
||||||
|
)
|
||||||
.slice(0, 3);
|
.slice(0, 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolvePerks(participant: RiotMatchParticipantDto) {
|
|
||||||
const primary = participant.perks.styles.find(
|
|
||||||
(style) => style.description === 'primaryStyle',
|
|
||||||
);
|
|
||||||
const sub = participant.perks.styles.find(
|
|
||||||
(style) => style.description === 'subStyle',
|
|
||||||
);
|
|
||||||
return {
|
|
||||||
primaryStyle: primary?.style,
|
|
||||||
subStyle: sub?.style,
|
|
||||||
keystone: primary?.selections[0]?.perk,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private resolveRating(params: {
|
|
||||||
kills: number;
|
|
||||||
deaths: number;
|
|
||||||
assists: number;
|
|
||||||
killParticipation: number;
|
|
||||||
csPerMin: number;
|
|
||||||
damageShare: number;
|
|
||||||
visionPerMin: number;
|
|
||||||
}): number {
|
|
||||||
const kda = this.kda(params.kills, params.deaths, params.assists);
|
|
||||||
const score =
|
|
||||||
Math.min(kda / 6, 1) * 4 +
|
|
||||||
Math.min(params.killParticipation / 100, 1) * 2 +
|
|
||||||
Math.min(params.csPerMin / 9, 1) * 2 +
|
|
||||||
Math.min(params.damageShare / 35, 1) +
|
|
||||||
Math.min(params.visionPerMin / 2, 1);
|
|
||||||
return this.round(score);
|
|
||||||
}
|
|
||||||
|
|
||||||
private cacheKey(
|
private cacheKey(
|
||||||
scope: string,
|
scope: string,
|
||||||
communityId: mongoose.Types.ObjectId,
|
communityId: mongoose.Types.ObjectId,
|
||||||
@@ -1056,7 +953,11 @@ export class CommunityStatsService {
|
|||||||
].join(':');
|
].join(':');
|
||||||
}
|
}
|
||||||
|
|
||||||
private clampLimit(value: number | undefined, fallback: number, max: number): number {
|
private clampLimit(
|
||||||
|
value: number | undefined,
|
||||||
|
fallback: number,
|
||||||
|
max: number,
|
||||||
|
): number {
|
||||||
if (!value || !Number.isFinite(value)) return fallback;
|
if (!value || !Number.isFinite(value)) return fallback;
|
||||||
return Math.max(1, Math.min(Math.floor(value), max));
|
return Math.max(1, Math.min(Math.floor(value), max));
|
||||||
}
|
}
|
||||||
@@ -1072,7 +973,9 @@ export class CommunityStatsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private kda(kills: number, deaths: number, assists: number): number {
|
private kda(kills: number, deaths: number, assists: number): number {
|
||||||
return deaths === 0 ? kills + assists : this.round((kills + assists) / deaths);
|
return deaths === 0
|
||||||
|
? kills + assists
|
||||||
|
: this.round((kills + assists) / deaths);
|
||||||
}
|
}
|
||||||
|
|
||||||
private percent(value: number, total: number): number {
|
private percent(value: number, total: number): number {
|
||||||
@@ -1086,12 +989,4 @@ export class CommunityStatsService {
|
|||||||
private round(value: number): number {
|
private round(value: number): number {
|
||||||
return Math.round(value * 10) / 10;
|
return Math.round(value * 10) / 10;
|
||||||
}
|
}
|
||||||
|
|
||||||
private numberField(
|
|
||||||
participant: RiotMatchParticipantDto | undefined,
|
|
||||||
key: string,
|
|
||||||
): number {
|
|
||||||
const value = participant?.[key];
|
|
||||||
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import mongoose from 'mongoose';
|
||||||
|
import type { MatchDocument } from '../global/database/schema';
|
||||||
|
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
|
||||||
|
|
||||||
|
function makeMatch(): MatchDocument {
|
||||||
|
const userId = new mongoose.Types.ObjectId();
|
||||||
|
return {
|
||||||
|
_id: new mongoose.Types.ObjectId(),
|
||||||
|
communityId: new mongoose.Types.ObjectId(),
|
||||||
|
title: '내전',
|
||||||
|
scheduledAt: new Date('2026-05-03T00:00:00.000Z'),
|
||||||
|
status: 'finished',
|
||||||
|
gameCount: 1,
|
||||||
|
participants: [
|
||||||
|
{
|
||||||
|
userId,
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
gameName: 'Player',
|
||||||
|
profileIconId: 7,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
teams: [
|
||||||
|
{
|
||||||
|
teamIndex: 1,
|
||||||
|
name: 'A',
|
||||||
|
members: [{ userId, assignedPosition: 'TOP' }],
|
||||||
|
},
|
||||||
|
{ teamIndex: 2, name: 'B', members: [] },
|
||||||
|
],
|
||||||
|
result: {
|
||||||
|
winnerTeamIndex: 1,
|
||||||
|
riotMatchIds: ['KR_1'],
|
||||||
|
games: [
|
||||||
|
{
|
||||||
|
gameNumber: 1,
|
||||||
|
riotMatchId: 'KR_1',
|
||||||
|
blueTeamIndex: 1,
|
||||||
|
redTeamIndex: 2,
|
||||||
|
winnerTeamIndex: 1,
|
||||||
|
winnerSide: 'blue',
|
||||||
|
gameCreation: 1_000,
|
||||||
|
gameDuration: 1_800,
|
||||||
|
participants: [
|
||||||
|
{
|
||||||
|
userId,
|
||||||
|
teamIndex: 1,
|
||||||
|
side: 'blue',
|
||||||
|
championId: 266,
|
||||||
|
kills: 5,
|
||||||
|
deaths: 1,
|
||||||
|
assists: 7,
|
||||||
|
win: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
seriesResults: [
|
||||||
|
{
|
||||||
|
teamAIndex: 1,
|
||||||
|
teamBIndex: 2,
|
||||||
|
teamAWins: 1,
|
||||||
|
teamBWins: 0,
|
||||||
|
winnerTeamIndex: 1,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
} as unknown as MatchDocument;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('MatchStatsFragmentBuilder', () => {
|
||||||
|
it('builds a fallback fragment without raw Riot match data', () => {
|
||||||
|
const builder = new MatchStatsFragmentBuilder();
|
||||||
|
const match = makeMatch();
|
||||||
|
|
||||||
|
const fragment = builder.buildFragment({
|
||||||
|
match,
|
||||||
|
rawByRiotMatchId: new Map(),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(fragment.matchCard.matchId).toBe(match._id.toString());
|
||||||
|
expect(fragment.gameCreationMin).toBe(1_000);
|
||||||
|
expect(fragment.gameCreationMax).toBe(1_000);
|
||||||
|
expect(fragment.userIds.map((id) => id.toString())).toEqual([
|
||||||
|
match.participants[0].userId.toString(),
|
||||||
|
]);
|
||||||
|
expect(fragment.championIds).toEqual([266]);
|
||||||
|
expect(fragment.records).toHaveLength(1);
|
||||||
|
expect(fragment.records[0]).toMatchObject({
|
||||||
|
summonerName: 'Player',
|
||||||
|
championId: 266,
|
||||||
|
kills: 5,
|
||||||
|
deaths: 1,
|
||||||
|
assists: 7,
|
||||||
|
win: true,
|
||||||
|
});
|
||||||
|
expect(fragment.gameDetails[0].teams[0].participants).toHaveLength(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,367 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import type {
|
||||||
|
MatchDocument,
|
||||||
|
MatchGameResultParticipant,
|
||||||
|
TeamSide,
|
||||||
|
} from '../global/database/schema';
|
||||||
|
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
|
||||||
|
import type { InternalMatchCardView } from './community-stats.types';
|
||||||
|
import type {
|
||||||
|
InternalGameDetail,
|
||||||
|
InternalRecord,
|
||||||
|
MatchStatsFragment,
|
||||||
|
} from './match-stats.types';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MatchStatsFragmentBuilder {
|
||||||
|
public buildFragment(params: {
|
||||||
|
match: MatchDocument;
|
||||||
|
rawByRiotMatchId: Map<string, RiotMatchDto>;
|
||||||
|
}): MatchStatsFragment {
|
||||||
|
const games = [...(params.match.result?.games ?? [])].sort(
|
||||||
|
(left, right) => left.gameNumber - right.gameNumber,
|
||||||
|
);
|
||||||
|
const matchCard = this.toMatchCard(params.match, games);
|
||||||
|
const gameDetails = games.map((game) => {
|
||||||
|
const raw = params.rawByRiotMatchId.get(game.riotMatchId);
|
||||||
|
return raw
|
||||||
|
? this.toGameDetail(params.match, game, raw)
|
||||||
|
: this.toFallbackGameDetail(params.match, game);
|
||||||
|
});
|
||||||
|
const records = gameDetails.flatMap((detail) =>
|
||||||
|
detail.teams.flatMap((team) => team.participants),
|
||||||
|
);
|
||||||
|
const gameCreations = gameDetails.map((detail) => detail.gameCreation);
|
||||||
|
|
||||||
|
return {
|
||||||
|
matchCard,
|
||||||
|
records,
|
||||||
|
gameDetails,
|
||||||
|
userIds: [
|
||||||
|
...new Map(
|
||||||
|
records
|
||||||
|
.filter((record) => mongoose.isValidObjectId(record.userId))
|
||||||
|
.map((record) => [
|
||||||
|
record.userId,
|
||||||
|
new mongoose.Types.ObjectId(record.userId),
|
||||||
|
]),
|
||||||
|
).values(),
|
||||||
|
],
|
||||||
|
championIds: [...new Set(records.map((record) => record.championId))],
|
||||||
|
gameCreationMin:
|
||||||
|
gameCreations.length > 0
|
||||||
|
? Math.min(...gameCreations)
|
||||||
|
: params.match.scheduledAt.getTime(),
|
||||||
|
gameCreationMax:
|
||||||
|
gameCreations.length > 0
|
||||||
|
? Math.max(...gameCreations)
|
||||||
|
: params.match.scheduledAt.getTime(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private toMatchCard(
|
||||||
|
match: MatchDocument,
|
||||||
|
games: NonNullable<MatchDocument['result']>['games'],
|
||||||
|
): InternalMatchCardView {
|
||||||
|
const participantById = new Map(
|
||||||
|
match.participants.map((participant) => [
|
||||||
|
participant.userId.toString(),
|
||||||
|
participant,
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
matchId: match._id.toString(),
|
||||||
|
title: match.title,
|
||||||
|
scheduledAt: match.scheduledAt.toISOString(),
|
||||||
|
status: match.status === 'finished' ? 'finished' : 'in-progress',
|
||||||
|
gameCount: match.gameCount,
|
||||||
|
winnerTeamIndex: match.result?.winnerTeamIndex,
|
||||||
|
seriesResults: match.result?.seriesResults ?? [],
|
||||||
|
games: games.map((game) => ({
|
||||||
|
gameNumber: game.gameNumber,
|
||||||
|
riotMatchId: game.riotMatchId ?? null,
|
||||||
|
blueTeamIndex: game.blueTeamIndex,
|
||||||
|
redTeamIndex: game.redTeamIndex,
|
||||||
|
winnerTeamIndex: game.winnerTeamIndex ?? null,
|
||||||
|
winnerSide: game.winnerSide ?? null,
|
||||||
|
gameDuration: game.gameDuration,
|
||||||
|
})),
|
||||||
|
teams: match.teams.map((team) => ({
|
||||||
|
teamIndex: team.teamIndex,
|
||||||
|
name: team.name,
|
||||||
|
members: team.members.map((member) => {
|
||||||
|
const participant = participantById.get(member.userId.toString());
|
||||||
|
return {
|
||||||
|
userId: member.userId.toString(),
|
||||||
|
summonerName: participant?.gameName ?? 'Unknown',
|
||||||
|
profileIconId: participant?.profileIconId ?? 0,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private toGameDetail(
|
||||||
|
match: MatchDocument,
|
||||||
|
game: NonNullable<MatchDocument['result']>['games'][number],
|
||||||
|
raw: RiotMatchDto,
|
||||||
|
): InternalGameDetail {
|
||||||
|
const puuidByUserId = new Map(
|
||||||
|
match.participants
|
||||||
|
.filter((participant) => participant.puuid)
|
||||||
|
.map((participant) => [
|
||||||
|
participant.userId.toString(),
|
||||||
|
participant.puuid as string,
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
const rawByPuuid = new Map(
|
||||||
|
raw.info.participants.map((participant) => [
|
||||||
|
participant.puuid,
|
||||||
|
participant,
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
const rawTeamIdBySide = new Map<TeamSide, number>();
|
||||||
|
for (const participant of game.participants) {
|
||||||
|
const puuid = puuidByUserId.get(participant.userId.toString());
|
||||||
|
const rawParticipant = puuid ? rawByPuuid.get(puuid) : undefined;
|
||||||
|
if (rawParticipant) {
|
||||||
|
rawTeamIdBySide.set(participant.side, rawParticipant.teamId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
gameNumber: game.gameNumber,
|
||||||
|
riotMatchId: game.riotMatchId,
|
||||||
|
gameCreation: game.gameCreation,
|
||||||
|
gameDuration: game.gameDuration,
|
||||||
|
winnerSide: game.winnerSide,
|
||||||
|
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
|
||||||
|
const teamIndex =
|
||||||
|
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
|
||||||
|
const rawTeamId = rawTeamIdBySide.get(side);
|
||||||
|
const rawTeam = raw.info.teams.find(
|
||||||
|
(team) => team.teamId === rawTeamId,
|
||||||
|
);
|
||||||
|
const teamRawParticipants = raw.info.participants.filter(
|
||||||
|
(participant) => participant.teamId === rawTeamId,
|
||||||
|
);
|
||||||
|
const teamKills = teamRawParticipants.reduce(
|
||||||
|
(sum, participant) => sum + participant.kills,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
const teamDamage = teamRawParticipants.reduce(
|
||||||
|
(sum, participant) => sum + participant.totalDamageDealtToChampions,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
teamIndex,
|
||||||
|
side,
|
||||||
|
win: game.winnerSide === side,
|
||||||
|
objectives: {
|
||||||
|
baron: rawTeam?.objectives?.baron?.kills ?? 0,
|
||||||
|
dragon: rawTeam?.objectives?.dragon?.kills ?? 0,
|
||||||
|
tower: rawTeam?.objectives?.tower?.kills ?? 0,
|
||||||
|
},
|
||||||
|
participants: game.participants
|
||||||
|
.filter((participant) => participant.side === side)
|
||||||
|
.map((participant) =>
|
||||||
|
this.toRecord({
|
||||||
|
match,
|
||||||
|
game,
|
||||||
|
participant,
|
||||||
|
rawParticipant: rawByPuuid.get(
|
||||||
|
puuidByUserId.get(participant.userId.toString()) ?? '',
|
||||||
|
),
|
||||||
|
teamKills,
|
||||||
|
teamDamage,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private toFallbackGameDetail(
|
||||||
|
match: MatchDocument,
|
||||||
|
game: NonNullable<MatchDocument['result']>['games'][number],
|
||||||
|
): InternalGameDetail {
|
||||||
|
return {
|
||||||
|
gameNumber: game.gameNumber,
|
||||||
|
riotMatchId: game.riotMatchId,
|
||||||
|
gameCreation: game.gameCreation,
|
||||||
|
gameDuration: game.gameDuration,
|
||||||
|
winnerSide: game.winnerSide,
|
||||||
|
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
|
||||||
|
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
|
||||||
|
side,
|
||||||
|
win: game.winnerSide === side,
|
||||||
|
objectives: { baron: 0, dragon: 0, tower: 0 },
|
||||||
|
participants: game.participants
|
||||||
|
.filter((participant) => participant.side === side)
|
||||||
|
.map((participant) =>
|
||||||
|
this.toRecord({
|
||||||
|
match,
|
||||||
|
game,
|
||||||
|
participant,
|
||||||
|
teamKills: 0,
|
||||||
|
teamDamage: 0,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private toRecord(params: {
|
||||||
|
match: MatchDocument;
|
||||||
|
game: NonNullable<MatchDocument['result']>['games'][number];
|
||||||
|
participant: MatchGameResultParticipant;
|
||||||
|
rawParticipant?: RiotMatchParticipantDto;
|
||||||
|
teamKills: number;
|
||||||
|
teamDamage: number;
|
||||||
|
}): InternalRecord {
|
||||||
|
const { match, game, participant, rawParticipant, teamKills, teamDamage } =
|
||||||
|
params;
|
||||||
|
const snapshot = match.participants.find((item) =>
|
||||||
|
item.userId.equals(participant.userId),
|
||||||
|
);
|
||||||
|
const minutes = Math.max(
|
||||||
|
(rawParticipant?.timePlayed ?? game.gameDuration) / 60,
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
const cs = rawParticipant
|
||||||
|
? rawParticipant.totalMinionsKilled + rawParticipant.neutralMinionsKilled
|
||||||
|
: 0;
|
||||||
|
const damage = rawParticipant?.totalDamageDealtToChampions ?? 0;
|
||||||
|
const killParticipation = percent(
|
||||||
|
participant.kills + participant.assists,
|
||||||
|
teamKills,
|
||||||
|
);
|
||||||
|
const damageShare = percent(damage, teamDamage);
|
||||||
|
const rating = this.resolveRating({
|
||||||
|
kills: participant.kills,
|
||||||
|
deaths: participant.deaths,
|
||||||
|
assists: participant.assists,
|
||||||
|
killParticipation,
|
||||||
|
csPerMin: average(cs, minutes),
|
||||||
|
damageShare,
|
||||||
|
visionPerMin: average(rawParticipant?.visionScore ?? 0, minutes),
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
matchId: match._id.toString(),
|
||||||
|
title: match.title,
|
||||||
|
scheduledAt: match.scheduledAt,
|
||||||
|
gameNumber: game.gameNumber,
|
||||||
|
riotMatchId: game.riotMatchId,
|
||||||
|
gameCreation: game.gameCreation,
|
||||||
|
gameDuration: game.gameDuration,
|
||||||
|
userId: participant.userId.toString(),
|
||||||
|
summonerName:
|
||||||
|
snapshot?.gameName ??
|
||||||
|
rawParticipant?.riotIdGameName ??
|
||||||
|
rawParticipant?.summonerName ??
|
||||||
|
'Unknown',
|
||||||
|
profileIconId: snapshot?.profileIconId ?? 0,
|
||||||
|
teamIndex: participant.teamIndex,
|
||||||
|
side: participant.side,
|
||||||
|
championId: participant.championId,
|
||||||
|
championLevel: rawParticipant?.champLevel ?? 0,
|
||||||
|
teamPosition:
|
||||||
|
rawParticipant?.teamPosition ||
|
||||||
|
rawParticipant?.individualPosition ||
|
||||||
|
'',
|
||||||
|
kills: participant.kills,
|
||||||
|
deaths: participant.deaths,
|
||||||
|
assists: participant.assists,
|
||||||
|
win: participant.win,
|
||||||
|
cs,
|
||||||
|
csPerMin: average(cs, minutes),
|
||||||
|
gold: rawParticipant?.goldEarned ?? 0,
|
||||||
|
gpm: average(rawParticipant?.goldEarned ?? 0, minutes),
|
||||||
|
damageDealtToChampions: damage,
|
||||||
|
damageTaken: rawParticipant?.totalDamageTaken ?? 0,
|
||||||
|
damageShare,
|
||||||
|
killParticipation,
|
||||||
|
visionScore: rawParticipant?.visionScore ?? 0,
|
||||||
|
controlWardsBought: numberField(
|
||||||
|
rawParticipant,
|
||||||
|
'visionWardsBoughtInGame',
|
||||||
|
),
|
||||||
|
wardsPlaced: rawParticipant?.wardsPlaced ?? 0,
|
||||||
|
wardsKilled: rawParticipant?.wardsKilled ?? 0,
|
||||||
|
items: [
|
||||||
|
rawParticipant?.item0 ?? 0,
|
||||||
|
rawParticipant?.item1 ?? 0,
|
||||||
|
rawParticipant?.item2 ?? 0,
|
||||||
|
rawParticipant?.item3 ?? 0,
|
||||||
|
rawParticipant?.item4 ?? 0,
|
||||||
|
rawParticipant?.item5 ?? 0,
|
||||||
|
],
|
||||||
|
trinket: rawParticipant?.item6 ?? 0,
|
||||||
|
summonerSpells: [
|
||||||
|
rawParticipant?.summoner1Id ?? 0,
|
||||||
|
rawParticipant?.summoner2Id ?? 0,
|
||||||
|
],
|
||||||
|
perks: rawParticipant ? this.resolvePerks(rawParticipant) : {},
|
||||||
|
rating,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolvePerks(participant: RiotMatchParticipantDto) {
|
||||||
|
const primary = participant.perks.styles.find(
|
||||||
|
(style) => style.description === 'primaryStyle',
|
||||||
|
);
|
||||||
|
const sub = participant.perks.styles.find(
|
||||||
|
(style) => style.description === 'subStyle',
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
primaryStyle: primary?.style,
|
||||||
|
subStyle: sub?.style,
|
||||||
|
keystone: primary?.selections[0]?.perk,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveRating(params: {
|
||||||
|
kills: number;
|
||||||
|
deaths: number;
|
||||||
|
assists: number;
|
||||||
|
killParticipation: number;
|
||||||
|
csPerMin: number;
|
||||||
|
damageShare: number;
|
||||||
|
visionPerMin: number;
|
||||||
|
}): number {
|
||||||
|
const kdaScore = kda(params.kills, params.deaths, params.assists);
|
||||||
|
const score =
|
||||||
|
Math.min(kdaScore / 6, 1) * 4 +
|
||||||
|
Math.min(params.killParticipation / 100, 1) * 2 +
|
||||||
|
Math.min(params.csPerMin / 9, 1) * 2 +
|
||||||
|
Math.min(params.damageShare / 35, 1) +
|
||||||
|
Math.min(params.visionPerMin / 2, 1);
|
||||||
|
return round(score);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function kda(kills: number, deaths: number, assists: number): number {
|
||||||
|
return deaths === 0 ? kills + assists : round((kills + assists) / deaths);
|
||||||
|
}
|
||||||
|
|
||||||
|
function percent(value: number, total: number): number {
|
||||||
|
return total > 0 ? Math.round((value / total) * 100) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function average(value: number, total: number): number {
|
||||||
|
return total > 0 ? round(value / total) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function round(value: number): number {
|
||||||
|
return Math.round(value * 10) / 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
function numberField(
|
||||||
|
participant: RiotMatchParticipantDto | undefined,
|
||||||
|
key: string,
|
||||||
|
): number {
|
||||||
|
const value = participant?.[key];
|
||||||
|
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MatchStatsRepository {
|
||||||
|
constructor(private readonly connectionService: ConnectionService) {}
|
||||||
|
|
||||||
|
public async upsert(
|
||||||
|
fragment: Omit<MatchStats, 'createdAt' | 'updatedAt'>,
|
||||||
|
): Promise<void> {
|
||||||
|
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||||
|
await MatchStatsModel.updateOne(
|
||||||
|
{ matchId: fragment.matchId },
|
||||||
|
{ $set: fragment },
|
||||||
|
{ upsert: true },
|
||||||
|
).exec();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async deleteByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
|
||||||
|
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||||
|
await MatchStatsModel.deleteOne({ matchId }).exec();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async deleteByMatches(
|
||||||
|
matchIds: mongoose.Types.ObjectId[],
|
||||||
|
): Promise<void> {
|
||||||
|
if (matchIds.length === 0) return;
|
||||||
|
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||||
|
await MatchStatsModel.deleteMany({ matchId: { $in: matchIds } }).exec();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async findByMatch(
|
||||||
|
matchId: mongoose.Types.ObjectId,
|
||||||
|
): Promise<MatchStatsDocument | null> {
|
||||||
|
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||||
|
return MatchStatsModel.findOne({ matchId }).exec();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async findByCommunity(params: {
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
fromGameCreation?: number;
|
||||||
|
toGameCreation?: number;
|
||||||
|
limit?: number;
|
||||||
|
}): Promise<MatchStatsDocument[]> {
|
||||||
|
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||||
|
const filter: Record<string, unknown> = {
|
||||||
|
communityId: params.communityId,
|
||||||
|
};
|
||||||
|
if (params.fromGameCreation !== undefined) {
|
||||||
|
filter.gameCreationMax = { $gte: params.fromGameCreation };
|
||||||
|
}
|
||||||
|
if (params.toGameCreation !== undefined) {
|
||||||
|
filter.gameCreationMin = { $lte: params.toGameCreation };
|
||||||
|
}
|
||||||
|
|
||||||
|
return MatchStatsModel.find(filter)
|
||||||
|
.sort({ scheduledAt: -1 })
|
||||||
|
.limit(params.limit ?? 300)
|
||||||
|
.exec();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async findByUser(params: {
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
userId: mongoose.Types.ObjectId;
|
||||||
|
fromGameCreation?: number;
|
||||||
|
toGameCreation?: number;
|
||||||
|
}): Promise<MatchStatsDocument[]> {
|
||||||
|
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||||
|
const filter: Record<string, unknown> = {
|
||||||
|
communityId: params.communityId,
|
||||||
|
userIds: params.userId,
|
||||||
|
};
|
||||||
|
if (params.fromGameCreation !== undefined) {
|
||||||
|
filter.gameCreationMax = { $gte: params.fromGameCreation };
|
||||||
|
}
|
||||||
|
if (params.toGameCreation !== undefined) {
|
||||||
|
filter.gameCreationMin = { $lte: params.toGameCreation };
|
||||||
|
}
|
||||||
|
|
||||||
|
return MatchStatsModel.find(filter).sort({ scheduledAt: -1 }).exec();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
|
||||||
|
import { MatchStatsRepository } from './match-stats.repository';
|
||||||
|
import { MatchStatsService } from './match-stats.service';
|
||||||
|
|
||||||
|
describe('MatchStatsService', () => {
|
||||||
|
it('deletes an existing fragment when the match is no longer eligible', async () => {
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const findById = jest.fn().mockReturnValue({
|
||||||
|
exec: jest.fn().mockResolvedValue({
|
||||||
|
_id: matchId,
|
||||||
|
status: 'recruiting',
|
||||||
|
result: undefined,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||||
|
if (name === 'match') return { findById };
|
||||||
|
if (name === 'riotMatch') return {};
|
||||||
|
throw new Error(`Unexpected model: ${name}`);
|
||||||
|
}),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const repository = {
|
||||||
|
deleteByMatch: jest.fn().mockResolvedValue(undefined),
|
||||||
|
upsert: jest.fn(),
|
||||||
|
} as unknown as jest.Mocked<MatchStatsRepository>;
|
||||||
|
const service = new MatchStatsService(
|
||||||
|
connectionService,
|
||||||
|
repository,
|
||||||
|
{} as MatchStatsFragmentBuilder,
|
||||||
|
);
|
||||||
|
|
||||||
|
await service.buildAndUpsert(matchId);
|
||||||
|
|
||||||
|
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId);
|
||||||
|
expect(repository.upsert).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('upserts a fragment for eligible matches', async () => {
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
|
const scheduledAt = new Date('2026-05-03T00:00:00.000Z');
|
||||||
|
const match = {
|
||||||
|
_id: matchId,
|
||||||
|
communityId,
|
||||||
|
scheduledAt,
|
||||||
|
status: 'finished',
|
||||||
|
result: { games: [{ riotMatchId: 'KR_1' }] },
|
||||||
|
};
|
||||||
|
const findById = jest.fn().mockReturnValue({
|
||||||
|
exec: jest.fn().mockResolvedValue(match),
|
||||||
|
});
|
||||||
|
const riotFind = jest.fn().mockReturnValue({
|
||||||
|
lean: () => ({
|
||||||
|
exec: jest.fn().mockResolvedValue([{ matchId: 'KR_1', raw: {} }]),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||||
|
if (name === 'match') return { findById };
|
||||||
|
if (name === 'riotMatch') return { find: riotFind };
|
||||||
|
throw new Error(`Unexpected model: ${name}`);
|
||||||
|
}),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const repository = {
|
||||||
|
upsert: jest.fn().mockResolvedValue(undefined),
|
||||||
|
deleteByMatch: jest.fn(),
|
||||||
|
} as unknown as jest.Mocked<MatchStatsRepository>;
|
||||||
|
const builder = {
|
||||||
|
buildFragment: jest.fn().mockReturnValue({
|
||||||
|
matchCard: { matchId: matchId.toString() },
|
||||||
|
records: [],
|
||||||
|
gameDetails: [],
|
||||||
|
userIds: [],
|
||||||
|
championIds: [],
|
||||||
|
gameCreationMin: 1_000,
|
||||||
|
gameCreationMax: 2_000,
|
||||||
|
}),
|
||||||
|
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
|
||||||
|
const service = new MatchStatsService(
|
||||||
|
connectionService,
|
||||||
|
repository,
|
||||||
|
builder,
|
||||||
|
);
|
||||||
|
|
||||||
|
await service.buildAndUpsert(matchId);
|
||||||
|
|
||||||
|
expect(builder.buildFragment).toHaveBeenCalledWith({
|
||||||
|
match,
|
||||||
|
rawByRiotMatchId: expect.any(Map),
|
||||||
|
});
|
||||||
|
expect(repository.upsert).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
matchId,
|
||||||
|
communityId,
|
||||||
|
scheduledAt,
|
||||||
|
gameCreationMin: 1_000,
|
||||||
|
gameCreationMax: 2_000,
|
||||||
|
builderVersion: 1,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type { MatchDocument } from '../global/database/schema';
|
||||||
|
import type { RiotMatchDto } from '../riot/riot.types';
|
||||||
|
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
|
||||||
|
import { MatchStatsRepository } from './match-stats.repository';
|
||||||
|
import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MatchStatsService {
|
||||||
|
constructor(
|
||||||
|
private readonly connectionService: ConnectionService,
|
||||||
|
private readonly repository: MatchStatsRepository,
|
||||||
|
private readonly builder: MatchStatsFragmentBuilder,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public async buildAndUpsert(matchId: mongoose.Types.ObjectId): Promise<void> {
|
||||||
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
|
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||||
|
const match = await MatchModel.findById(matchId).exec();
|
||||||
|
if (!match) return;
|
||||||
|
if (!this.isEligible(match)) {
|
||||||
|
await this.repository.deleteByMatch(matchId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const riotIds = [
|
||||||
|
...new Set(
|
||||||
|
(match.result?.games ?? [])
|
||||||
|
.map((game) => game.riotMatchId)
|
||||||
|
.filter((riotMatchId): riotMatchId is string => Boolean(riotMatchId)),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
const riotDocs =
|
||||||
|
riotIds.length > 0
|
||||||
|
? await RiotMatchModel.find({ matchId: { $in: riotIds } })
|
||||||
|
.lean()
|
||||||
|
.exec()
|
||||||
|
: [];
|
||||||
|
const rawByRiotMatchId = new Map(
|
||||||
|
riotDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]),
|
||||||
|
);
|
||||||
|
const fragment = this.builder.buildFragment({ match, rawByRiotMatchId });
|
||||||
|
|
||||||
|
await this.repository.upsert({
|
||||||
|
matchId: match._id,
|
||||||
|
communityId: match.communityId,
|
||||||
|
scheduledAt: match.scheduledAt,
|
||||||
|
gameCreationMin: fragment.gameCreationMin,
|
||||||
|
gameCreationMax: fragment.gameCreationMax,
|
||||||
|
userIds: fragment.userIds,
|
||||||
|
championIds: fragment.championIds,
|
||||||
|
matchCard: fragment.matchCard as unknown as Record<string, unknown>,
|
||||||
|
records: fragment.records,
|
||||||
|
gameDetails: fragment.gameDetails,
|
||||||
|
builtAt: new Date(),
|
||||||
|
builderVersion: MATCH_STATS_BUILDER_VERSION,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public async removeByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
|
||||||
|
await this.repository.deleteByMatch(matchId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async removeByMatches(
|
||||||
|
matchIds: mongoose.Types.ObjectId[],
|
||||||
|
): Promise<void> {
|
||||||
|
await this.repository.deleteByMatches(matchIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async backfillCommunity(
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
): Promise<{ processed: number; failed: number }> {
|
||||||
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
|
const matches = await MatchModel.find({
|
||||||
|
communityId,
|
||||||
|
status: { $in: ['finished', 'in-progress'] },
|
||||||
|
'result.games.0': { $exists: true },
|
||||||
|
})
|
||||||
|
.sort({ scheduledAt: -1 })
|
||||||
|
.select({ _id: 1 })
|
||||||
|
.exec();
|
||||||
|
|
||||||
|
let processed = 0;
|
||||||
|
let failed = 0;
|
||||||
|
for (const match of matches) {
|
||||||
|
try {
|
||||||
|
await this.buildAndUpsert(match._id);
|
||||||
|
processed += 1;
|
||||||
|
} catch {
|
||||||
|
failed += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { processed, failed };
|
||||||
|
}
|
||||||
|
|
||||||
|
private isEligible(match: MatchDocument): boolean {
|
||||||
|
return (
|
||||||
|
(match.status === 'finished' || match.status === 'in-progress') &&
|
||||||
|
Boolean(match.result?.games?.length)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import type {
|
||||||
|
MatchStatsGameDetail,
|
||||||
|
MatchStatsRecord,
|
||||||
|
} from '../global/database/schema';
|
||||||
|
import type { InternalMatchCardView } from './community-stats.types';
|
||||||
|
|
||||||
|
export const MATCH_STATS_BUILDER_VERSION = 1;
|
||||||
|
|
||||||
|
export type InternalRecord = MatchStatsRecord;
|
||||||
|
export type InternalGameDetail = MatchStatsGameDetail;
|
||||||
|
|
||||||
|
export interface MatchStatsFragment {
|
||||||
|
matchCard: InternalMatchCardView;
|
||||||
|
records: InternalRecord[];
|
||||||
|
gameDetails: InternalGameDetail[];
|
||||||
|
userIds: import('mongoose').Types.ObjectId[];
|
||||||
|
championIds: number[];
|
||||||
|
gameCreationMin: number;
|
||||||
|
gameCreationMax: number;
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { AppModule } from '../../../../app.module';
|
||||||
|
import { ConnectionService } from '../connection.service';
|
||||||
|
import { MatchStatsService } from '../../../community-stats/match-stats.service';
|
||||||
|
|
||||||
|
interface Options {
|
||||||
|
communityId?: mongoose.Types.ObjectId;
|
||||||
|
dryRun: boolean;
|
||||||
|
force: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const options = parseArgs(process.argv.slice(2));
|
||||||
|
const app = await NestFactory.createApplicationContext(AppModule, {
|
||||||
|
logger: ['log', 'warn', 'error'],
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const connectionService = app.get(ConnectionService);
|
||||||
|
const matchStatsService = app.get(MatchStatsService);
|
||||||
|
const MatchModel = await connectionService.getModel('match');
|
||||||
|
const MatchStatsModel = await connectionService.getModel('matchStats');
|
||||||
|
|
||||||
|
const filter: Record<string, unknown> = {
|
||||||
|
status: { $in: ['finished', 'in-progress'] },
|
||||||
|
'result.games.0': { $exists: true },
|
||||||
|
};
|
||||||
|
if (options.communityId) filter.communityId = options.communityId;
|
||||||
|
|
||||||
|
const matches = await MatchModel.find(filter)
|
||||||
|
.sort({ scheduledAt: -1 })
|
||||||
|
.select({ _id: 1 })
|
||||||
|
.exec();
|
||||||
|
console.log(`match_stats backfill target=${matches.length}`);
|
||||||
|
|
||||||
|
let processed = 0;
|
||||||
|
let skipped = 0;
|
||||||
|
let failed = 0;
|
||||||
|
|
||||||
|
for (const match of matches) {
|
||||||
|
if (!options.force) {
|
||||||
|
const existing = await MatchStatsModel.exists({ matchId: match._id });
|
||||||
|
if (existing) {
|
||||||
|
skipped += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (options.dryRun) {
|
||||||
|
processed += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await matchStatsService.buildAndUpsert(match._id);
|
||||||
|
processed += 1;
|
||||||
|
} catch (error) {
|
||||||
|
failed += 1;
|
||||||
|
console.warn(
|
||||||
|
`failed ${match._id.toString()}: ${
|
||||||
|
error instanceof Error ? error.message : error
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((processed + skipped + failed) % 50 === 0) {
|
||||||
|
console.log(
|
||||||
|
`progress processed=${processed} skipped=${skipped} failed=${failed}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`done processed=${processed} skipped=${skipped} failed=${failed}`,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseArgs(args: string[]): Options {
|
||||||
|
const options: Options = { dryRun: false, force: false };
|
||||||
|
for (let index = 0; index < args.length; index += 1) {
|
||||||
|
const arg = args[index];
|
||||||
|
if (arg === '--dry-run') options.dryRun = true;
|
||||||
|
if (arg === '--force') options.force = true;
|
||||||
|
if (arg === '--community-id') {
|
||||||
|
const value = args[index + 1];
|
||||||
|
if (!value || !mongoose.isValidObjectId(value)) {
|
||||||
|
throw new Error('--community-id requires a valid ObjectId');
|
||||||
|
}
|
||||||
|
options.communityId = new mongoose.Types.ObjectId(value);
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
void main().catch((error) => {
|
||||||
|
console.error(error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -65,7 +65,11 @@ export const TOURNAMENT_SPECTATOR_TYPES: TournamentSpectatorType[] = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
export type MatchResultPollOutcome = 'matched' | 'not-found' | 'failed';
|
export type MatchResultPollOutcome = 'matched' | 'not-found' | 'failed';
|
||||||
export type MatchResultPollStateValue = 'polling' | 'complete' | 'expired' | 'failed';
|
export type MatchResultPollStateValue =
|
||||||
|
| 'polling'
|
||||||
|
| 'complete'
|
||||||
|
| 'expired'
|
||||||
|
| 'failed';
|
||||||
export const MATCH_RESULT_POLL_STATES: MatchResultPollStateValue[] = [
|
export const MATCH_RESULT_POLL_STATES: MatchResultPollStateValue[] = [
|
||||||
'polling',
|
'polling',
|
||||||
'complete',
|
'complete',
|
||||||
@@ -562,8 +566,79 @@ export interface AuctionHistoryEntry extends MongooseTimestamps {
|
|||||||
takenAt: Date;
|
takenAt: Date;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AuctionHistoryEntryDocument =
|
export type AuctionHistoryEntryDocument = HydratedDocument<AuctionHistoryEntry>;
|
||||||
HydratedDocument<AuctionHistoryEntry>;
|
|
||||||
|
// ===== MatchStats (precomputed internal stats fragment) =====
|
||||||
|
export interface MatchStatsRecord {
|
||||||
|
matchId: string;
|
||||||
|
title: string;
|
||||||
|
scheduledAt: Date;
|
||||||
|
gameNumber: number;
|
||||||
|
riotMatchId: string;
|
||||||
|
gameCreation: number;
|
||||||
|
gameDuration: number;
|
||||||
|
userId: string;
|
||||||
|
summonerName: string;
|
||||||
|
profileIconId: number;
|
||||||
|
teamIndex: number;
|
||||||
|
side: TeamSide;
|
||||||
|
championId: number;
|
||||||
|
championLevel: number;
|
||||||
|
teamPosition: string;
|
||||||
|
kills: number;
|
||||||
|
deaths: number;
|
||||||
|
assists: number;
|
||||||
|
win: boolean;
|
||||||
|
cs: number;
|
||||||
|
csPerMin: number;
|
||||||
|
gold: number;
|
||||||
|
gpm: number;
|
||||||
|
damageDealtToChampions: number;
|
||||||
|
damageTaken: number;
|
||||||
|
damageShare: number;
|
||||||
|
killParticipation: number;
|
||||||
|
visionScore: number;
|
||||||
|
controlWardsBought: number;
|
||||||
|
wardsPlaced: number;
|
||||||
|
wardsKilled: number;
|
||||||
|
items: number[];
|
||||||
|
trinket: number;
|
||||||
|
summonerSpells: [number, number];
|
||||||
|
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
|
||||||
|
rating: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MatchStatsGameDetail {
|
||||||
|
gameNumber: number;
|
||||||
|
riotMatchId: string;
|
||||||
|
gameCreation: number;
|
||||||
|
gameDuration: number;
|
||||||
|
winnerSide: TeamSide;
|
||||||
|
teams: Array<{
|
||||||
|
teamIndex: number;
|
||||||
|
side: TeamSide;
|
||||||
|
win: boolean;
|
||||||
|
objectives: { baron: number; dragon: number; tower: number };
|
||||||
|
participants: MatchStatsRecord[];
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MatchStats extends MongooseTimestamps {
|
||||||
|
matchId: mongoose.Types.ObjectId;
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
scheduledAt: Date;
|
||||||
|
gameCreationMin: number;
|
||||||
|
gameCreationMax: number;
|
||||||
|
userIds: mongoose.Types.ObjectId[];
|
||||||
|
championIds: number[];
|
||||||
|
matchCard: Record<string, unknown>;
|
||||||
|
records: MatchStatsRecord[];
|
||||||
|
gameDetails: MatchStatsGameDetail[];
|
||||||
|
builtAt: Date;
|
||||||
|
builderVersion: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MatchStatsDocument = HydratedDocument<MatchStats>;
|
||||||
|
|
||||||
// ===== Sub-schemas =====
|
// ===== Sub-schemas =====
|
||||||
const PositionPreferenceSubSchema = new Schema<PositionPreference>(
|
const PositionPreferenceSubSchema = new Schema<PositionPreference>(
|
||||||
@@ -1068,7 +1143,9 @@ const MatchScheduleItemSubSchema = new Schema<MatchScheduleItem>(
|
|||||||
{ _id: false },
|
{ _id: false },
|
||||||
);
|
);
|
||||||
|
|
||||||
const MatchLegacyImportSourceSubSchema = new Schema<NonNullable<Match['legacyImportSource']>>(
|
const MatchLegacyImportSourceSubSchema = new Schema<
|
||||||
|
NonNullable<Match['legacyImportSource']>
|
||||||
|
>(
|
||||||
{
|
{
|
||||||
importedAt: { type: Date, required: true },
|
importedAt: { type: Date, required: true },
|
||||||
importedBy: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
importedBy: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||||
@@ -1109,7 +1186,8 @@ export const MatchSchema = new Schema<Match>(
|
|||||||
default: 10,
|
default: 10,
|
||||||
min: 10,
|
min: 10,
|
||||||
validate: {
|
validate: {
|
||||||
validator: (value: number) => Number.isInteger(value) && value % 10 === 0,
|
validator: (value: number) =>
|
||||||
|
Number.isInteger(value) && value % 10 === 0,
|
||||||
message: 'maxParticipants must be a multiple of 10.',
|
message: 'maxParticipants must be a multiple of 10.',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1379,7 +1457,15 @@ const AuctionHistoryEntrySchema = new Schema<AuctionHistoryEntry>(
|
|||||||
sequence: { type: Number, required: true, min: 1 },
|
sequence: { type: Number, required: true, min: 1 },
|
||||||
action: {
|
action: {
|
||||||
type: String,
|
type: String,
|
||||||
enum: ['start', 'open-bidding', 'bid', 'sold', 'passed', 'next', 'complete'],
|
enum: [
|
||||||
|
'start',
|
||||||
|
'open-bidding',
|
||||||
|
'bid',
|
||||||
|
'sold',
|
||||||
|
'passed',
|
||||||
|
'next',
|
||||||
|
'complete',
|
||||||
|
],
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
actorUserId: { type: Schema.Types.ObjectId, ref: 'user', required: false },
|
actorUserId: { type: Schema.Types.ObjectId, ref: 'user', required: false },
|
||||||
@@ -1394,6 +1480,42 @@ const AuctionHistoryEntrySchema = new Schema<AuctionHistoryEntry>(
|
|||||||
|
|
||||||
AuctionHistoryEntrySchema.index({ auctionId: 1, sequence: -1 });
|
AuctionHistoryEntrySchema.index({ auctionId: 1, sequence: -1 });
|
||||||
|
|
||||||
|
export const MatchStatsSchema: mongoose.Schema<MatchStats> = new Schema(
|
||||||
|
{
|
||||||
|
matchId: {
|
||||||
|
type: Schema.Types.ObjectId,
|
||||||
|
ref: 'match',
|
||||||
|
required: true,
|
||||||
|
unique: true,
|
||||||
|
},
|
||||||
|
communityId: {
|
||||||
|
type: Schema.Types.ObjectId,
|
||||||
|
ref: 'community',
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
scheduledAt: { type: Date, required: true },
|
||||||
|
gameCreationMin: { type: Number, required: true },
|
||||||
|
gameCreationMax: { type: Number, required: true },
|
||||||
|
userIds: { type: [Schema.Types.ObjectId], required: true, default: [] },
|
||||||
|
championIds: { type: [Number], required: true, default: [] },
|
||||||
|
matchCard: { type: Schema.Types.Mixed, required: true },
|
||||||
|
records: { type: [Schema.Types.Mixed], required: true, default: [] },
|
||||||
|
gameDetails: { type: [Schema.Types.Mixed], required: true, default: [] },
|
||||||
|
builtAt: { type: Date, required: true, default: Date.now },
|
||||||
|
builderVersion: { type: Number, required: true, default: 1 },
|
||||||
|
} as mongoose.SchemaDefinition,
|
||||||
|
{ timestamps: true, collection: 'match_stats' },
|
||||||
|
) as mongoose.Schema<MatchStats>;
|
||||||
|
|
||||||
|
MatchStatsSchema.index({ communityId: 1, scheduledAt: -1 });
|
||||||
|
MatchStatsSchema.index({
|
||||||
|
communityId: 1,
|
||||||
|
gameCreationMin: 1,
|
||||||
|
gameCreationMax: 1,
|
||||||
|
});
|
||||||
|
MatchStatsSchema.index({ communityId: 1, userIds: 1 });
|
||||||
|
MatchStatsSchema.index({ communityId: 1, championIds: 1 });
|
||||||
|
|
||||||
export const tournamentModelDefinitions: ModelDefinition[] = [
|
export const tournamentModelDefinitions: ModelDefinition[] = [
|
||||||
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
|
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
|
||||||
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
|
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
|
||||||
@@ -1416,6 +1538,11 @@ export const tournamentModelDefinitions: ModelDefinition[] = [
|
|||||||
schema: AuctionHistoryEntrySchema,
|
schema: AuctionHistoryEntrySchema,
|
||||||
schemaName: 'auctionHistory',
|
schemaName: 'auctionHistory',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'matchStats',
|
||||||
|
schema: MatchStatsSchema,
|
||||||
|
schemaName: 'matchStats',
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
export interface TournamentModelTypes {
|
export interface TournamentModelTypes {
|
||||||
@@ -1428,4 +1555,5 @@ export interface TournamentModelTypes {
|
|||||||
match: Match;
|
match: Match;
|
||||||
auction: Auction;
|
auction: Auction;
|
||||||
auctionHistory: AuctionHistoryEntry;
|
auctionHistory: AuctionHistoryEntry;
|
||||||
|
matchStats: MatchStats;
|
||||||
}
|
}
|
||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { randomUUID } from 'crypto';
|
import { randomUUID } from 'crypto';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
|
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import type {
|
import type {
|
||||||
@@ -55,6 +56,7 @@ export class LegacyImportService {
|
|||||||
private readonly garnetService: GarnetService,
|
private readonly garnetService: GarnetService,
|
||||||
private readonly riotMatchService: RiotMatchService,
|
private readonly riotMatchService: RiotMatchService,
|
||||||
private readonly communityStatsService: CommunityStatsService,
|
private readonly communityStatsService: CommunityStatsService,
|
||||||
|
private readonly matchStatsService: MatchStatsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public async previewMembers(params: {
|
public async previewMembers(params: {
|
||||||
@@ -107,8 +109,12 @@ export class LegacyImportService {
|
|||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
const windows = users
|
const windows = users
|
||||||
.map((user) => this.resolveMemberWindow(user, windowStart, windowEnd, overrides))
|
.map((user) =>
|
||||||
.filter((window) => window.startTime.getTime() <= window.endTime.getTime());
|
this.resolveMemberWindow(user, windowStart, windowEnd, overrides),
|
||||||
|
)
|
||||||
|
.filter(
|
||||||
|
(window) => window.startTime.getTime() <= window.endTime.getTime(),
|
||||||
|
);
|
||||||
const LegacyImportJobModel =
|
const LegacyImportJobModel =
|
||||||
await this.connectionService.getModel('legacyImportJob');
|
await this.connectionService.getModel('legacyImportJob');
|
||||||
await LegacyImportJobModel.create({
|
await LegacyImportJobModel.create({
|
||||||
@@ -174,7 +180,9 @@ export class LegacyImportService {
|
|||||||
}): Promise<{ jobs: LegacyImportJobDocument[] }> {
|
}): Promise<{ jobs: LegacyImportJobDocument[] }> {
|
||||||
const LegacyImportJobModel =
|
const LegacyImportJobModel =
|
||||||
await this.connectionService.getModel('legacyImportJob');
|
await this.connectionService.getModel('legacyImportJob');
|
||||||
const jobs = await LegacyImportJobModel.find({ communityId: params.communityId })
|
const jobs = await LegacyImportJobModel.find({
|
||||||
|
communityId: params.communityId,
|
||||||
|
})
|
||||||
.sort({ startedAt: -1 })
|
.sort({ startedAt: -1 })
|
||||||
.limit(Math.min(params.limit ?? 10, 50))
|
.limit(Math.min(params.limit ?? 10, 50))
|
||||||
.exec();
|
.exec();
|
||||||
@@ -210,7 +218,8 @@ export class LegacyImportService {
|
|||||||
{ $set: { state: 'cancelled', completedAt: new Date() } },
|
{ $set: { state: 'cancelled', completedAt: new Date() } },
|
||||||
{ returnDocument: 'after' },
|
{ returnDocument: 'after' },
|
||||||
).exec();
|
).exec();
|
||||||
if (!job) throw new NotFoundException('Running legacy import job not found.');
|
if (!job)
|
||||||
|
throw new NotFoundException('Running legacy import job not found.');
|
||||||
await this.garnetService.delete(this.communityLockKey(params.communityId));
|
await this.garnetService.delete(this.communityLockKey(params.communityId));
|
||||||
return job;
|
return job;
|
||||||
}
|
}
|
||||||
@@ -284,7 +293,9 @@ export class LegacyImportService {
|
|||||||
.map((match) => match.result?.games[0]?.riotMatchId)
|
.map((match) => match.result?.games[0]?.riotMatchId)
|
||||||
.filter((matchId): matchId is string => Boolean(matchId));
|
.filter((matchId): matchId is string => Boolean(matchId));
|
||||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||||
const rawDocs = await RiotMatchModel.find({ matchId: { $in: riotMatchIds } })
|
const rawDocs = await RiotMatchModel.find({
|
||||||
|
matchId: { $in: riotMatchIds },
|
||||||
|
})
|
||||||
.lean()
|
.lean()
|
||||||
.exec();
|
.exec();
|
||||||
const rawById = new Map(
|
const rawById = new Map(
|
||||||
@@ -314,7 +325,7 @@ export class LegacyImportService {
|
|||||||
}),
|
}),
|
||||||
nextCursor:
|
nextCursor:
|
||||||
matches.length > limit
|
matches.length > limit
|
||||||
? visible[visible.length - 1]?.scheduledAt.getTime() ?? null
|
? (visible[visible.length - 1]?.scheduledAt.getTime() ?? null)
|
||||||
: null,
|
: null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -328,11 +339,22 @@ export class LegacyImportService {
|
|||||||
.map((id) => new mongoose.Types.ObjectId(id));
|
.map((id) => new mongoose.Types.ObjectId(id));
|
||||||
if (ids.length === 0) return { deleted: 0 };
|
if (ids.length === 0) return { deleted: 0 };
|
||||||
const MatchModel = await this.connectionService.getModel('match');
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
const result = await MatchModel.deleteMany({
|
const targets = await MatchModel.find({
|
||||||
_id: { $in: ids },
|
_id: { $in: ids },
|
||||||
communityId: params.communityId,
|
communityId: params.communityId,
|
||||||
legacyImported: true,
|
legacyImported: true,
|
||||||
|
})
|
||||||
|
.select({ _id: 1 })
|
||||||
|
.exec();
|
||||||
|
const targetIds = targets.map((match) => match._id);
|
||||||
|
if (targetIds.length === 0) return { deleted: 0 };
|
||||||
|
|
||||||
|
const result = await MatchModel.deleteMany({
|
||||||
|
_id: { $in: targetIds },
|
||||||
|
communityId: params.communityId,
|
||||||
|
legacyImported: true,
|
||||||
}).exec();
|
}).exec();
|
||||||
|
await this.matchStatsService.removeByMatches(targetIds);
|
||||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||||
return { deleted: result.deletedCount ?? 0 };
|
return { deleted: result.deletedCount ?? 0 };
|
||||||
}
|
}
|
||||||
@@ -348,12 +370,15 @@ export class LegacyImportService {
|
|||||||
const riotMatchIds = matches
|
const riotMatchIds = matches
|
||||||
.map(
|
.map(
|
||||||
(match) =>
|
(match) =>
|
||||||
match.result?.games[0]?.riotMatchId ?? match.result?.riotMatchIds?.[0],
|
match.result?.games[0]?.riotMatchId ??
|
||||||
|
match.result?.riotMatchIds?.[0],
|
||||||
)
|
)
|
||||||
.filter((matchId): matchId is string => Boolean(matchId));
|
.filter((matchId): matchId is string => Boolean(matchId));
|
||||||
|
|
||||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||||
const rawDocs = await RiotMatchModel.find({ matchId: { $in: riotMatchIds } })
|
const rawDocs = await RiotMatchModel.find({
|
||||||
|
matchId: { $in: riotMatchIds },
|
||||||
|
})
|
||||||
.lean()
|
.lean()
|
||||||
.exec();
|
.exec();
|
||||||
const rawById = new Map<string, RiotMatchDto>();
|
const rawById = new Map<string, RiotMatchDto>();
|
||||||
@@ -387,7 +412,11 @@ export class LegacyImportService {
|
|||||||
if (!raw || !riotMatchId) {
|
if (!raw || !riotMatchId) {
|
||||||
result.skippedMissingRaw += 1;
|
result.skippedMissingRaw += 1;
|
||||||
if (Object.keys(update).length > 0) {
|
if (Object.keys(update).length > 0) {
|
||||||
await MatchModel.updateOne({ _id: match._id }, { $set: update }).exec();
|
await MatchModel.updateOne(
|
||||||
|
{ _id: match._id },
|
||||||
|
{ $set: update },
|
||||||
|
).exec();
|
||||||
|
await this.matchStatsService.buildAndUpsert(match._id);
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -397,7 +426,11 @@ export class LegacyImportService {
|
|||||||
if (!gameResult || participants.length === 0) {
|
if (!gameResult || participants.length === 0) {
|
||||||
result.skippedNoKnownParticipants += 1;
|
result.skippedNoKnownParticipants += 1;
|
||||||
if (Object.keys(update).length > 0) {
|
if (Object.keys(update).length > 0) {
|
||||||
await MatchModel.updateOne({ _id: match._id }, { $set: update }).exec();
|
await MatchModel.updateOne(
|
||||||
|
{ _id: match._id },
|
||||||
|
{ $set: update },
|
||||||
|
).exec();
|
||||||
|
await this.matchStatsService.buildAndUpsert(match._id);
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -429,6 +462,7 @@ export class LegacyImportService {
|
|||||||
},
|
},
|
||||||
{ $set: update },
|
{ $set: update },
|
||||||
).exec();
|
).exec();
|
||||||
|
await this.matchStatsService.buildAndUpsert(match._id);
|
||||||
result.rebuilt += 1;
|
result.rebuilt += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -439,7 +473,9 @@ export class LegacyImportService {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async collectMatchIds(job: LegacyImportMemberJob): Promise<Set<string>> {
|
private async collectMatchIds(
|
||||||
|
job: LegacyImportMemberJob,
|
||||||
|
): Promise<Set<string>> {
|
||||||
const matchIds = new Set<string>();
|
const matchIds = new Set<string>();
|
||||||
let start = 0;
|
let start = 0;
|
||||||
while (true) {
|
while (true) {
|
||||||
@@ -478,7 +514,10 @@ export class LegacyImportService {
|
|||||||
});
|
});
|
||||||
if (existing) return 'duplicate';
|
if (existing) return 'duplicate';
|
||||||
|
|
||||||
const detail = await this.ensureRiotMatchPersisted(riotMatchId, job.region);
|
const detail = await this.ensureRiotMatchPersisted(
|
||||||
|
riotMatchId,
|
||||||
|
job.region,
|
||||||
|
);
|
||||||
if (!detail.info.tournamentCode) return 'skipped';
|
if (!detail.info.tournamentCode) return 'skipped';
|
||||||
const counts = countKnownParticipants(detail, userByPuuid);
|
const counts = countKnownParticipants(detail, userByPuuid);
|
||||||
if (counts.total === 0) return 'skipped';
|
if (counts.total === 0) return 'skipped';
|
||||||
@@ -527,7 +566,8 @@ export class LegacyImportService {
|
|||||||
notices: [],
|
notices: [],
|
||||||
schedule: [],
|
schedule: [],
|
||||||
};
|
};
|
||||||
await MatchModel.create(matchPayload);
|
const match = await MatchModel.create(matchPayload);
|
||||||
|
await this.matchStatsService.buildAndUpsert(match._id);
|
||||||
return 'imported';
|
return 'imported';
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await this.recordError(job.parentJobId, {
|
await this.recordError(job.parentJobId, {
|
||||||
@@ -546,7 +586,9 @@ export class LegacyImportService {
|
|||||||
region: RiotRegionalRoute,
|
region: RiotRegionalRoute,
|
||||||
): Promise<RiotMatchDto> {
|
): Promise<RiotMatchDto> {
|
||||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||||
const stored = await RiotMatchModel.findOne({ matchId: riotMatchId }).exec();
|
const stored = await RiotMatchModel.findOne({
|
||||||
|
matchId: riotMatchId,
|
||||||
|
}).exec();
|
||||||
if (isRiotMatchDto(stored?.raw)) return stored.raw;
|
if (isRiotMatchDto(stored?.raw)) return stored.raw;
|
||||||
|
|
||||||
const dto = await this.riotMatchService.getMatch(riotMatchId, { region });
|
const dto = await this.riotMatchService.getMatch(riotMatchId, { region });
|
||||||
@@ -588,7 +630,9 @@ export class LegacyImportService {
|
|||||||
const average =
|
const average =
|
||||||
current.averageMemberSeconds === undefined
|
current.averageMemberSeconds === undefined
|
||||||
? stats.elapsedSeconds
|
? stats.elapsedSeconds
|
||||||
: Math.round(current.averageMemberSeconds * 0.7 + stats.elapsedSeconds * 0.3);
|
: Math.round(
|
||||||
|
current.averageMemberSeconds * 0.7 + stats.elapsedSeconds * 0.3,
|
||||||
|
);
|
||||||
|
|
||||||
const nextProcessed = current.processedMembers + 1;
|
const nextProcessed = current.processedMembers + 1;
|
||||||
const completed = nextProcessed >= current.totalMembers;
|
const completed = nextProcessed >= current.totalMembers;
|
||||||
@@ -631,7 +675,8 @@ export class LegacyImportService {
|
|||||||
jobId: job.parentJobId,
|
jobId: job.parentJobId,
|
||||||
}).exec();
|
}).exec();
|
||||||
if (!legacyJob || legacyJob.state === 'cancelled') return null;
|
if (!legacyJob || legacyJob.state === 'cancelled') return null;
|
||||||
if (legacyJob.state === 'completed' || legacyJob.state === 'failed') return null;
|
if (legacyJob.state === 'completed' || legacyJob.state === 'failed')
|
||||||
|
return null;
|
||||||
return legacyJob;
|
return legacyJob;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -686,7 +731,12 @@ export class LegacyImportService {
|
|||||||
windowStart: Date,
|
windowStart: Date,
|
||||||
windowEnd: Date,
|
windowEnd: Date,
|
||||||
): LegacyImportMemberWindowView {
|
): LegacyImportMemberWindowView {
|
||||||
const resolved = this.resolveMemberWindow(user, windowStart, windowEnd, new Map());
|
const resolved = this.resolveMemberWindow(
|
||||||
|
user,
|
||||||
|
windowStart,
|
||||||
|
windowEnd,
|
||||||
|
new Map(),
|
||||||
|
);
|
||||||
const account =
|
const account =
|
||||||
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
|
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
|
||||||
user.riotAccounts[0];
|
user.riotAccounts[0];
|
||||||
@@ -731,10 +781,7 @@ export class LegacyImportService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolveWindow(params: {
|
private resolveWindow(params: { windowStart?: string; windowEnd?: string }) {
|
||||||
windowStart?: string;
|
|
||||||
windowEnd?: string;
|
|
||||||
}) {
|
|
||||||
const windowStart =
|
const windowStart =
|
||||||
this.parseOptionalDate(params.windowStart) ??
|
this.parseOptionalDate(params.windowStart) ??
|
||||||
new Date(LEGACY_IMPORT_DEFAULT_START_ISO);
|
new Date(LEGACY_IMPORT_DEFAULT_START_ISO);
|
||||||
@@ -755,7 +802,9 @@ export class LegacyImportService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private minDate(...values: Array<Date | undefined>): Date {
|
private minDate(...values: Array<Date | undefined>): Date {
|
||||||
return new Date(Math.min(...values.filter(Boolean).map((date) => date!.getTime())));
|
return new Date(
|
||||||
|
Math.min(...values.filter(Boolean).map((date) => date!.getTime())),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private normalizeLegacyTitle(title: string, gameCreation: number): string {
|
private normalizeLegacyTitle(title: string, gameCreation: number): string {
|
||||||
|
|||||||
@@ -19,14 +19,20 @@ describe('MatchService', () => {
|
|||||||
const communityStatsService = {
|
const communityStatsService = {
|
||||||
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
|
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
|
||||||
};
|
};
|
||||||
|
const matchStatsService = {
|
||||||
|
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
|
||||||
|
removeByMatch: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
service: new MatchService(
|
service: new MatchService(
|
||||||
connectionService as never,
|
connectionService as never,
|
||||||
tournamentCodeService as never,
|
tournamentCodeService as never,
|
||||||
communityStatsService as never,
|
communityStatsService as never,
|
||||||
|
matchStatsService as never,
|
||||||
),
|
),
|
||||||
tournamentCodeService,
|
tournamentCodeService,
|
||||||
|
matchStatsService,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,7 +55,8 @@ describe('MatchService', () => {
|
|||||||
}),
|
}),
|
||||||
save: jest.fn().mockResolvedValue(undefined),
|
save: jest.fn().mockResolvedValue(undefined),
|
||||||
};
|
};
|
||||||
const { service, tournamentCodeService } = createService(match);
|
const { service, tournamentCodeService, matchStatsService } =
|
||||||
|
createService(match);
|
||||||
|
|
||||||
await service.update({
|
await service.update({
|
||||||
matchId: new mongoose.Types.ObjectId(),
|
matchId: new mongoose.Types.ObjectId(),
|
||||||
@@ -64,6 +71,7 @@ describe('MatchService', () => {
|
|||||||
expect(match.result).toBeUndefined();
|
expect(match.result).toBeUndefined();
|
||||||
expect(match.resultPollState).toBeUndefined();
|
expect(match.resultPollState).toBeUndefined();
|
||||||
expect(match.save).toHaveBeenCalledTimes(1);
|
expect(match.save).toHaveBeenCalledTimes(1);
|
||||||
|
expect(matchStatsService.removeByMatch).toHaveBeenCalledWith(match._id);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('releases reserved codes when returning a built match to recruiting', async () => {
|
it('releases reserved codes when returning a built match to recruiting', async () => {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
|
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import {
|
import {
|
||||||
@@ -59,6 +60,7 @@ export class MatchService {
|
|||||||
private readonly connectionService: ConnectionService,
|
private readonly connectionService: ConnectionService,
|
||||||
private readonly tournamentCodeService: TournamentCodeService,
|
private readonly tournamentCodeService: TournamentCodeService,
|
||||||
private readonly communityStatsService: CommunityStatsService,
|
private readonly communityStatsService: CommunityStatsService,
|
||||||
|
private readonly matchStatsService: MatchStatsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public async create(params: CreateMatchParams): Promise<MatchDocument> {
|
public async create(params: CreateMatchParams): Promise<MatchDocument> {
|
||||||
@@ -172,6 +174,13 @@ export class MatchService {
|
|||||||
match.resultPollState = undefined;
|
match.resultPollState = undefined;
|
||||||
}
|
}
|
||||||
await match.save();
|
await match.save();
|
||||||
|
if (previousStatus !== 'recruiting' && match.status === 'recruiting') {
|
||||||
|
await this.matchStatsService.removeByMatch(match._id);
|
||||||
|
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||||
|
} else if (match.result?.games?.length) {
|
||||||
|
await this.matchStatsService.buildAndUpsert(match._id);
|
||||||
|
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||||
|
}
|
||||||
return match;
|
return match;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -186,6 +195,7 @@ export class MatchService {
|
|||||||
throw new BadRequestException('Match does not belong to this community.');
|
throw new BadRequestException('Match does not belong to this community.');
|
||||||
}
|
}
|
||||||
await this.tournamentCodeService.releaseFromMatch(match);
|
await this.tournamentCodeService.releaseFromMatch(match);
|
||||||
|
await this.matchStatsService.removeByMatch(match._id);
|
||||||
await match.deleteOne();
|
await match.deleteOne();
|
||||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ function createService() {
|
|||||||
{} as never,
|
{} as never,
|
||||||
{} as never,
|
{} as never,
|
||||||
{} as never,
|
{} as never,
|
||||||
|
{} as never,
|
||||||
) as unknown as TournamentResultServiceInternals;
|
) as unknown as TournamentResultServiceInternals;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -189,6 +190,7 @@ describe('TournamentResultService manual result collection', () => {
|
|||||||
riotMatchService as never,
|
riotMatchService as never,
|
||||||
{} as never,
|
{} as never,
|
||||||
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
|
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
|
||||||
|
{ buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never,
|
||||||
);
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
|
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import type {
|
import type {
|
||||||
@@ -55,6 +56,7 @@ export class TournamentResultService {
|
|||||||
private readonly riotMatchService: RiotMatchService,
|
private readonly riotMatchService: RiotMatchService,
|
||||||
private readonly riotJobQueueService: RiotJobQueueService,
|
private readonly riotJobQueueService: RiotJobQueueService,
|
||||||
private readonly communityStatsService: CommunityStatsService,
|
private readonly communityStatsService: CommunityStatsService,
|
||||||
|
private readonly matchStatsService: MatchStatsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public async scheduleInitialPoll(
|
public async scheduleInitialPoll(
|
||||||
@@ -98,7 +100,9 @@ export class TournamentResultService {
|
|||||||
}
|
}
|
||||||
const result = await this.scheduleInitialPoll(match, 'high');
|
const result = await this.scheduleInitialPoll(match, 'high');
|
||||||
if (!result) {
|
if (!result) {
|
||||||
throw new BadRequestException('Tournament result polling is not available.');
|
throw new BadRequestException(
|
||||||
|
'Tournament result polling is not available.',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -119,7 +123,10 @@ export class TournamentResultService {
|
|||||||
|
|
||||||
const region = await this.resolveRiotRegion(match);
|
const region = await this.resolveRiotRegion(match);
|
||||||
const lookup = await this.buildPuuidLookup(match);
|
const lookup = await this.buildPuuidLookup(match);
|
||||||
const puuids = this.collectPollingPuuids(collectMatchUserIds(match), lookup);
|
const puuids = this.collectPollingPuuids(
|
||||||
|
collectMatchUserIds(match),
|
||||||
|
lookup,
|
||||||
|
);
|
||||||
const startTime = Math.floor(params.startTime.getTime() / 1000);
|
const startTime = Math.floor(params.startTime.getTime() / 1000);
|
||||||
const endTime = Math.floor(params.endTime.getTime() / 1000);
|
const endTime = Math.floor(params.endTime.getTime() / 1000);
|
||||||
const riotMatchIds = new Set<string>();
|
const riotMatchIds = new Set<string>();
|
||||||
@@ -240,7 +247,9 @@ export class TournamentResultService {
|
|||||||
if (checkedRiotMatchIds.has(riotMatchId)) continue;
|
if (checkedRiotMatchIds.has(riotMatchId)) continue;
|
||||||
checkedRiotMatchIds.add(riotMatchId);
|
checkedRiotMatchIds.add(riotMatchId);
|
||||||
|
|
||||||
const alreadyMatched = await TournamentCodeModel.exists({ riotMatchId });
|
const alreadyMatched = await TournamentCodeModel.exists({
|
||||||
|
riotMatchId,
|
||||||
|
});
|
||||||
if (alreadyMatched) continue;
|
if (alreadyMatched) continue;
|
||||||
|
|
||||||
let detail: RiotMatchDto;
|
let detail: RiotMatchDto;
|
||||||
@@ -309,7 +318,9 @@ export class TournamentResultService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
code.state = 'used';
|
code.state = 'used';
|
||||||
code.usedAt = new Date(detail.info.gameEndTimestamp ?? detail.info.gameCreation);
|
code.usedAt = new Date(
|
||||||
|
detail.info.gameEndTimestamp ?? detail.info.gameCreation,
|
||||||
|
);
|
||||||
code.riotMatchId = detail.metadata.matchId;
|
code.riotMatchId = detail.metadata.matchId;
|
||||||
await code.save();
|
await code.save();
|
||||||
|
|
||||||
@@ -318,6 +329,7 @@ export class TournamentResultService {
|
|||||||
match.status = 'in-progress';
|
match.status = 'in-progress';
|
||||||
}
|
}
|
||||||
await match.save();
|
await match.save();
|
||||||
|
await this.rebuildMatchStatsSafe(match);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -346,7 +358,11 @@ export class TournamentResultService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.upsertGameResult(match, gameResult);
|
this.upsertGameResult(match, gameResult);
|
||||||
await this.markTournamentCodeUsedForManualResult(match, gameResult, detail);
|
await this.markTournamentCodeUsedForManualResult(
|
||||||
|
match,
|
||||||
|
gameResult,
|
||||||
|
detail,
|
||||||
|
);
|
||||||
appliedRiotMatchIds.push(detail.metadata.matchId);
|
appliedRiotMatchIds.push(detail.metadata.matchId);
|
||||||
appliedGameNumbers.push(gameResult.gameNumber);
|
appliedGameNumbers.push(gameResult.gameNumber);
|
||||||
}
|
}
|
||||||
@@ -356,6 +372,9 @@ export class TournamentResultService {
|
|||||||
}
|
}
|
||||||
this.updateManualCollectionState(match, appliedRiotMatchIds.length);
|
this.updateManualCollectionState(match, appliedRiotMatchIds.length);
|
||||||
await match.save();
|
await match.save();
|
||||||
|
if (appliedRiotMatchIds.length > 0) {
|
||||||
|
await this.rebuildMatchStatsSafe(match);
|
||||||
|
}
|
||||||
if (this.hasAllRequiredGameResults(match)) {
|
if (this.hasAllRequiredGameResults(match)) {
|
||||||
await this.finishMatchFromManualResults(match);
|
await this.finishMatchFromManualResults(match);
|
||||||
}
|
}
|
||||||
@@ -393,6 +412,7 @@ export class TournamentResultService {
|
|||||||
state: 'complete',
|
state: 'complete',
|
||||||
};
|
};
|
||||||
await match.save();
|
await match.save();
|
||||||
|
await this.rebuildMatchStatsSafe(match);
|
||||||
void this.communityStatsService
|
void this.communityStatsService
|
||||||
.invalidateCommunity(match.communityId)
|
.invalidateCommunity(match.communityId)
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
@@ -419,7 +439,8 @@ export class TournamentResultService {
|
|||||||
lastPolledAt: pollState?.lastPolledAt,
|
lastPolledAt: pollState?.lastPolledAt,
|
||||||
lastPollOutcome: pollState?.lastPollOutcome,
|
lastPollOutcome: pollState?.lastPollOutcome,
|
||||||
matchedCount: match.result?.games?.length ?? 0,
|
matchedCount: match.result?.games?.length ?? 0,
|
||||||
expandedToAllPuuids: pollState?.expandedToAllPuuids ?? job.expandedToAllPuuids,
|
expandedToAllPuuids:
|
||||||
|
pollState?.expandedToAllPuuids ?? job.expandedToAllPuuids,
|
||||||
state: 'expired',
|
state: 'expired',
|
||||||
};
|
};
|
||||||
await match.save();
|
await match.save();
|
||||||
@@ -431,7 +452,8 @@ export class TournamentResultService {
|
|||||||
|
|
||||||
const expandedToAllPuuids =
|
const expandedToAllPuuids =
|
||||||
job.expandedToAllPuuids ||
|
job.expandedToAllPuuids ||
|
||||||
(elapsedMs >= EXPAND_AFTER_MS && (match.result?.games?.length ?? 0) === 0);
|
(elapsedMs >= EXPAND_AFTER_MS &&
|
||||||
|
(match.result?.games?.length ?? 0) === 0);
|
||||||
await this.riotJobQueueService.enqueueTournamentResultPoll({
|
await this.riotJobQueueService.enqueueTournamentResultPoll({
|
||||||
matchId: match._id.toString(),
|
matchId: match._id.toString(),
|
||||||
attempt: job.attempt + 1,
|
attempt: job.attempt + 1,
|
||||||
@@ -446,7 +468,9 @@ export class TournamentResultService {
|
|||||||
region: RiotRegionalRoute,
|
region: RiotRegionalRoute,
|
||||||
): Promise<RiotMatchDto> {
|
): Promise<RiotMatchDto> {
|
||||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||||
const stored = await RiotMatchModel.findOne({ matchId: riotMatchId }).exec();
|
const stored = await RiotMatchModel.findOne({
|
||||||
|
matchId: riotMatchId,
|
||||||
|
}).exec();
|
||||||
if (isRiotMatchDto(stored?.raw)) return stored.raw;
|
if (isRiotMatchDto(stored?.raw)) return stored.raw;
|
||||||
|
|
||||||
const dto = await this.riotMatchService.getMatch(riotMatchId, { region });
|
const dto = await this.riotMatchService.getMatch(riotMatchId, { region });
|
||||||
@@ -491,7 +515,9 @@ export class TournamentResultService {
|
|||||||
return details;
|
return details;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async buildPuuidLookup(match: MatchDocument): Promise<MatchPuuidLookup> {
|
private async buildPuuidLookup(
|
||||||
|
match: MatchDocument,
|
||||||
|
): Promise<MatchPuuidLookup> {
|
||||||
const puuidByUserId = new Map<string, string>();
|
const puuidByUserId = new Map<string, string>();
|
||||||
const userIdByPuuid = new Map<string, mongoose.Types.ObjectId>();
|
const userIdByPuuid = new Map<string, mongoose.Types.ObjectId>();
|
||||||
|
|
||||||
@@ -651,6 +677,7 @@ export class TournamentResultService {
|
|||||||
state: 'complete',
|
state: 'complete',
|
||||||
};
|
};
|
||||||
await match.save();
|
await match.save();
|
||||||
|
await this.rebuildMatchStatsSafe(match);
|
||||||
void this.communityStatsService
|
void this.communityStatsService
|
||||||
.invalidateCommunity(match.communityId)
|
.invalidateCommunity(match.communityId)
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
@@ -662,6 +689,18 @@ export class TournamentResultService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async rebuildMatchStatsSafe(match: MatchDocument): Promise<void> {
|
||||||
|
try {
|
||||||
|
await this.matchStatsService.buildAndUpsert(match._id);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.warn(
|
||||||
|
`Failed to rebuild match stats for ${match._id.toString()}: ${
|
||||||
|
error instanceof Error ? error.message : error
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async markTournamentCodeUsedForManualResult(
|
private async markTournamentCodeUsedForManualResult(
|
||||||
match: MatchDocument,
|
match: MatchDocument,
|
||||||
gameResult: MatchGameResult,
|
gameResult: MatchGameResult,
|
||||||
@@ -705,9 +744,7 @@ export class TournamentResultService {
|
|||||||
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
||||||
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
|
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
|
||||||
const key = `${teamAIndex}:${teamBIndex}`;
|
const key = `${teamAIndex}:${teamBIndex}`;
|
||||||
const current =
|
const current = bySeries.get(key) ?? {
|
||||||
bySeries.get(key) ??
|
|
||||||
{
|
|
||||||
teamAIndex,
|
teamAIndex,
|
||||||
teamBIndex,
|
teamBIndex,
|
||||||
teamAWins: 0,
|
teamAWins: 0,
|
||||||
@@ -750,10 +787,12 @@ export class TournamentResultService {
|
|||||||
|
|
||||||
const perSeries = match.gameCount || 1;
|
const perSeries = match.gameCount || 1;
|
||||||
const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1);
|
const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1);
|
||||||
return roundRobinPairs(resolveRoundRobinTeamCount(match))[pairIndex] ?? {
|
return (
|
||||||
|
roundRobinPairs(resolveRoundRobinTeamCount(match))[pairIndex] ?? {
|
||||||
teamAIndex: 1,
|
teamAIndex: 1,
|
||||||
teamBIndex: 2,
|
teamBIndex: 2,
|
||||||
};
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const perSeries = match.gameCount || 1;
|
const perSeries = match.gameCount || 1;
|
||||||
|
|||||||
Reference in new issue
Block a user