This commit is contained in:
dahyeon committed 2026-04-26 06:39:00 -07:00
1 parent 60928bc165
commit ca56af79e5
19 files changed
+3450 -21

No files matched your search

+2
View File
@@ -7,6 +7,7 @@ import { AuthModule } from './modules/auth/auth.module';
import { CommunityModule } from './modules/community/community.module';
import { DakaoModule } from './modules/dakao/dakao.module';
import { GlobalModule } from './modules/global/global.module';
import { MatchHistoryModule } from './modules/match-history/match-history.module';
import { MatchModule } from './modules/match/match.module';
import { RiotModule } from './modules/riot/riot.module';
import { UserModule } from './modules/user/user.module';
@@ -22,6 +23,7 @@ import { UserModule } from './modules/user/user.module';
RiotModule,
CommunityModule,
MatchModule,
MatchHistoryModule,
AuctionModule,
UserModule,
DakaoModule,
@@ -176,6 +176,8 @@ export interface RiotAccount extends MongooseTimestamps {
// Riot matchId 참조 (원본은 RiotMatch 컬렉션에 저장)
matchIds: string[];
matchIdsFetchedAt?: Date;
matchIdsByQueueFetchedAt?: Map<string, Date>;
lastRefreshRequestedAt?: Date;
// 최근 경기 요약
recentStatsSummary?: RiotRecentStatsSummary;
@@ -212,6 +214,14 @@ export interface Community extends MongooseTimestamps {
riotPlatform?: RiotPlatformRoute;
riotRegion?: RiotRegionalRoute;
seasonStartedAt?: Date;
seasons?: CommunitySeason[];
}
export interface CommunitySeason {
id: string;
label: string;
startedAt: Date;
endedAt?: Date;
}
export type CommunityDocument = HydratedDocument<Community>;
@@ -468,6 +478,8 @@ const RiotAccountSubSchema = new Schema<RiotAccount>(
matchIds: { type: [String], required: true, default: [] },
matchIdsFetchedAt: { type: Date },
matchIdsByQueueFetchedAt: { type: Map, of: Date },
lastRefreshRequestedAt: { type: Date },
recentStatsSummary: { type: RiotRecentStatsSummarySubSchema },
recentStatsFetchedAt: { type: Date },
@@ -518,6 +530,20 @@ export const CommunitySchema = new Schema<Community>(
riotPlatform: { type: String },
riotRegion: { type: String },
seasonStartedAt: { type: Date },
seasons: {
type: [
new Schema<CommunitySeason>(
{
id: { type: String, required: true },
label: { type: String, required: true },
startedAt: { type: Date, required: true },
endedAt: { type: Date },
},
{ _id: false },
),
],
required: false,
},
},
{
timestamps: true,
@@ -636,6 +662,7 @@ export const RiotMatchSchema = new Schema<RiotMatch>(
);
RiotMatchSchema.index({ participantPuuids: 1, gameCreation: -1 });
RiotMatchSchema.index({ participantPuuids: 1, queueId: 1, gameCreation: -1 });
const MatchParticipantSubSchema = new Schema<MatchParticipant>(
{
@@ -0,0 +1,95 @@
import { Controller, Get, Param, Query } from '@nestjs/common';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import { MatchHistoryService } from './match-history.service';
@Controller('communities/:communityId/users/:userId')
export class MatchHistoryController {
constructor(private readonly matchHistoryService: MatchHistoryService) {}
@Get('history-profile')
@AllowPublicAccess()
public getProfile(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
) {
return this.matchHistoryService.getProfile({ communityId, userId });
}
@Get('champion-stats')
@AllowPublicAccess()
public getChampionStats(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Query('queueGroup') queueGroup?: string,
@Query('rank') rank?: string,
@Query('seasonId') seasonId?: string,
) {
return this.matchHistoryService.getChampionStats({
communityId,
userId,
filters: { queueGroup, rank, seasonId },
});
}
@Get('recent-summary')
@AllowPublicAccess()
public getRecentSummary(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Query('queueGroup') queueGroup?: string,
@Query('rank') rank?: string,
@Query('seasonId') seasonId?: string,
@Query('championId') championId?: string,
@Query('limit') limit?: string,
) {
return this.matchHistoryService.getRecentSummary({
communityId,
userId,
filters: {
queueGroup,
rank,
seasonId,
championId: this.toNumber(championId),
limit: this.toNumber(limit),
},
});
}
@Get('recent-matches')
@AllowPublicAccess()
public getRecentMatches(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Query('queueGroup') queueGroup?: string,
@Query('rank') rank?: string,
@Query('seasonId') seasonId?: string,
@Query('championId') championId?: string,
@Query('limit') limit?: string,
@Query('cursor') cursor?: string,
) {
return this.matchHistoryService.getRecentMatches({
communityId,
userId,
filters: {
queueGroup,
rank,
seasonId,
championId: this.toNumber(championId),
limit: this.toNumber(limit),
cursor: this.toNumber(cursor),
},
});
}
private toNumber(value: string | undefined): number | undefined {
if (!value) return undefined;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : undefined;
}
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { MatchHistoryController } from './match-history.controller';
import { MatchHistoryService } from './match-history.service';
@Module({
controllers: [MatchHistoryController],
providers: [MatchHistoryService],
exports: [MatchHistoryService],
})
export class MatchHistoryModule {}
@@ -0,0 +1,753 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type {
CommunityDocument,
RiotAccount,
RiotLane,
RiotMatchDocument,
UserDocument,
} from '../global/database/schema';
import {
isRiotQueueGroup,
isRiotRankFilter,
RIOT_QUEUE_LABELS,
resolveRiotQueueIds,
type RiotQueueGroup,
type RiotRankFilter,
} from '../riot/riot-queue.constants';
import type {
RiotMatchDto,
RiotMatchParticipantDto,
} from '../riot/riot.types';
import type {
ChampionStatsResponse,
ChampionStatsRow,
HistorySeasonDto,
RecentMatchesResponse,
RecentMatchView,
RecentSummaryResponse,
UserHistoryProfileResponse,
} from './match-history.types';
const DEFAULT_QUEUE_GROUP: RiotQueueGroup = 'summoners-rift';
const DEFAULT_RANK: RiotRankFilter = 'all';
const DEFAULT_RECENT_LIMIT = 10;
const DEFAULT_SUMMARY_LIMIT = 20;
const MAX_AGGREGATE_MATCHES = 500;
const MAX_RECENT_SCAN = 120;
interface HistoryContext {
community: CommunityDocument;
user: UserDocument;
account: RiotAccount;
season: HistorySeasonDto;
seasonStartedAt: Date | null;
}
interface MatchFilters {
queueGroup?: string;
rank?: string;
seasonId?: string;
championId?: number;
limit?: number;
cursor?: number;
}
interface AggregatedChampion {
championId: number;
games: number;
wins: number;
totalKills: number;
totalDeaths: number;
totalAssists: number;
totalCs: number;
totalGameMinutes: number;
doubleKills: number;
tripleKills: number;
quadraKills: number;
pentaKills: number;
}
@Injectable()
export class MatchHistoryService {
constructor(private readonly connectionService: ConnectionService) {}
public async getProfile(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
}): Promise<UserHistoryProfileResponse> {
const context = await this.resolveContext(params);
const lastFetchedAt =
context.account.recentStatsFetchedAt ??
context.account.matchIdsFetchedAt ??
null;
return {
userId: context.user._id.toString(),
puuid: context.account.puuid,
gameName: context.account.gameName,
tagLine: context.account.tagLine,
profileIconId: context.account.profileIconId,
summonerLevel: context.account.summonerLevel,
tiers: context.account.tiers.map((tier) => ({
queueType: tier.queueType,
tier: tier.tier,
rank: tier.rank,
leaguePoints: tier.leaguePoints,
wins: tier.wins,
losses: tier.losses,
fetchedAt: tier.fetchedAt.toISOString(),
})),
season: context.season,
seasons: this.resolveSeasons(context.community),
lastFetchedAt: lastFetchedAt?.toISOString() ?? null,
};
}
public async getChampionStats(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
filters: MatchFilters;
}): Promise<ChampionStatsResponse> {
const context = await this.resolveContext({
...params,
seasonId: params.filters.seasonId,
});
const { queueGroup, rank, queueIds } = this.resolveQueueFilters(
params.filters,
);
const docs = await this.findStoredMatches({
context,
queueIds,
limit: MAX_AGGREGATE_MATCHES,
});
const aggregates = new Map<number, AggregatedChampion>();
for (const doc of docs) {
const dto = doc.raw as unknown as RiotMatchDto;
const participant = this.findParticipant(dto, context.account.puuid);
if (!participant) continue;
const aggregate =
aggregates.get(participant.championId) ??
this.createChampionAggregate(participant.championId);
this.addParticipantToChampionAggregate(aggregate, participant, dto);
aggregates.set(participant.championId, aggregate);
}
const champions = [...aggregates.values()]
.map((aggregate) => this.toChampionStatsRow(aggregate))
.sort((a, b) => b.games - a.games || b.winRate - a.winRate);
const totals = this.toChampionStatsRow(
[...aggregates.values()].reduce(
(acc, aggregate) => this.mergeChampionAggregate(acc, aggregate),
this.createChampionAggregate(0),
),
);
return {
queueGroup,
rank,
queueIds,
season: context.season,
lastFetchedAt: this.resolveLastFetchedAt(docs, context),
champions,
totals,
};
}
public async getRecentSummary(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
filters: MatchFilters;
}): Promise<RecentSummaryResponse> {
const context = await this.resolveContext({
...params,
seasonId: params.filters.seasonId,
});
const { queueIds } = this.resolveQueueFilters(params.filters);
const limit = this.clampLimit(params.filters.limit, DEFAULT_SUMMARY_LIMIT, 50);
const docs = await this.findStoredMatches({
context,
queueIds,
championId: params.filters.championId,
limit,
scanLimit: params.filters.championId ? MAX_RECENT_SCAN : undefined,
});
const views = docs
.map((doc) => this.toRecentMatchView(doc, context.account.puuid))
.filter((view): view is RecentMatchView => Boolean(view))
.slice(0, limit);
return this.createRecentSummary(views, docs, context, limit);
}
public async getRecentMatches(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
filters: MatchFilters;
}): Promise<RecentMatchesResponse> {
const context = await this.resolveContext({
...params,
seasonId: params.filters.seasonId,
});
const { queueIds } = this.resolveQueueFilters(params.filters);
const limit = this.clampLimit(params.filters.limit, DEFAULT_RECENT_LIMIT, 30);
const docs = await this.findStoredMatches({
context,
queueIds,
championId: params.filters.championId,
limit: limit + 1,
cursor: params.filters.cursor,
scanLimit: params.filters.championId ? MAX_RECENT_SCAN : undefined,
});
const views = docs
.map((doc) => this.toRecentMatchView(doc, context.account.puuid))
.filter((view): view is RecentMatchView => Boolean(view));
const page = views.slice(0, limit);
return {
matches: page,
nextCursor: views.length > limit ? page[page.length - 1]?.gameCreation ?? null : null,
lastFetchedAt: this.resolveLastFetchedAt(docs, context),
season: context.season,
};
}
private async resolveContext(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
seasonId?: string;
}): Promise<HistoryContext> {
const UserModel = await this.connectionService.getModel('user');
const CommunityModel = await this.connectionService.getModel('community');
const [user, community] = await Promise.all([
UserModel.findById(params.userId).exec(),
CommunityModel.findById(params.communityId).exec(),
]);
if (!community) throw new NotFoundException('Community not found.');
if (!user || !user.communityId.equals(params.communityId)) {
throw new NotFoundException('User not found.');
}
const account =
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
user.riotAccounts[0];
if (!account) {
throw new NotFoundException('Riot account not found.');
}
const season = this.resolveSeason(community, params.seasonId);
const seasonStartedAt = season.startedAt
? new Date(season.startedAt)
: (community.seasonStartedAt ?? null);
return { community, user, account, season, seasonStartedAt };
}
private resolveSeason(
community: CommunityDocument,
seasonId?: string,
): HistorySeasonDto {
const seasons = this.resolveSeasons(community);
if (seasonId && seasonId !== 'current') {
const selected = seasons.find((season) => season.id === seasonId);
if (!selected) throw new BadRequestException('Invalid seasonId.');
return selected;
}
const configured =
seasons.find((season) => !season.endedAt) ??
[...seasons].sort((left, right) =>
(right.startedAt ?? '').localeCompare(left.startedAt ?? ''),
)[0];
if (configured) return configured;
return {
id: 'current',
label: '현재 시즌',
startedAt: community.seasonStartedAt?.toISOString() ?? null,
endedAt: null,
};
}
private resolveSeasons(community: CommunityDocument): HistorySeasonDto[] {
const configured = community.seasons?.map((season) => ({
id: season.id,
label: season.label,
startedAt: season.startedAt.toISOString(),
endedAt: season.endedAt?.toISOString() ?? null,
}));
if (configured?.length) return configured;
return [
{
id: 'current',
label: '현재 시즌',
startedAt: community.seasonStartedAt?.toISOString() ?? null,
endedAt: null,
},
];
}
private resolveQueueFilters(filters: MatchFilters): {
queueGroup: RiotQueueGroup;
rank: RiotRankFilter;
queueIds: number[];
} {
const queueGroup = filters.queueGroup ?? DEFAULT_QUEUE_GROUP;
const rank = filters.rank ?? DEFAULT_RANK;
if (!isRiotQueueGroup(queueGroup)) {
throw new BadRequestException('Invalid queueGroup.');
}
if (!isRiotRankFilter(rank)) {
throw new BadRequestException('Invalid rank filter.');
}
return {
queueGroup,
rank,
queueIds: resolveRiotQueueIds(queueGroup, rank),
};
}
private async findStoredMatches(params: {
context: HistoryContext;
queueIds: number[];
limit: number;
cursor?: number;
championId?: number;
scanLimit?: number;
}): Promise<RiotMatchDocument[]> {
if (params.queueIds.length === 0) return [];
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const gameCreation: Record<string, number> = {};
if (params.context.seasonStartedAt) {
gameCreation.$gte = params.context.seasonStartedAt.getTime();
}
if (params.cursor) gameCreation.$lt = params.cursor;
const query: Record<string, unknown> = {
participantPuuids: params.context.account.puuid,
queueId: { $in: params.queueIds },
};
if (Object.keys(gameCreation).length > 0) query.gameCreation = gameCreation;
const docs = await RiotMatchModel.find(query)
.sort({ gameCreation: -1 })
.limit(params.scanLimit ?? params.limit)
.exec();
if (!params.championId) return docs.slice(0, params.limit);
return docs
.filter((doc) => {
const participant = this.findParticipant(
doc.raw as unknown as RiotMatchDto,
params.context.account.puuid,
);
return participant?.championId === params.championId;
})
.slice(0, params.limit);
}
private findParticipant(
match: RiotMatchDto,
puuid: string,
): RiotMatchParticipantDto | null {
return (
match.info.participants.find((participant) => participant.puuid === puuid) ??
null
);
}
private createChampionAggregate(championId: number): AggregatedChampion {
return {
championId,
games: 0,
wins: 0,
totalKills: 0,
totalDeaths: 0,
totalAssists: 0,
totalCs: 0,
totalGameMinutes: 0,
doubleKills: 0,
tripleKills: 0,
quadraKills: 0,
pentaKills: 0,
};
}
private addParticipantToChampionAggregate(
aggregate: AggregatedChampion,
participant: RiotMatchParticipantDto,
match: RiotMatchDto,
): void {
const minutes = this.resolveGameMinutes(match, participant);
aggregate.games += 1;
aggregate.wins += participant.win ? 1 : 0;
aggregate.totalKills += participant.kills;
aggregate.totalDeaths += participant.deaths;
aggregate.totalAssists += participant.assists;
aggregate.totalCs += this.resolveTotalCs(participant);
aggregate.totalGameMinutes += minutes;
aggregate.doubleKills += this.numberField(participant, 'doubleKills');
aggregate.tripleKills += this.numberField(participant, 'tripleKills');
aggregate.quadraKills += this.numberField(participant, 'quadraKills');
aggregate.pentaKills += this.numberField(participant, 'pentaKills');
}
private mergeChampionAggregate(
acc: AggregatedChampion,
aggregate: AggregatedChampion,
): AggregatedChampion {
acc.games += aggregate.games;
acc.wins += aggregate.wins;
acc.totalKills += aggregate.totalKills;
acc.totalDeaths += aggregate.totalDeaths;
acc.totalAssists += aggregate.totalAssists;
acc.totalCs += aggregate.totalCs;
acc.totalGameMinutes += aggregate.totalGameMinutes;
acc.doubleKills += aggregate.doubleKills;
acc.tripleKills += aggregate.tripleKills;
acc.quadraKills += aggregate.quadraKills;
acc.pentaKills += aggregate.pentaKills;
return acc;
}
private toChampionStatsRow(aggregate: AggregatedChampion): ChampionStatsRow {
const losses = aggregate.games - aggregate.wins;
return {
championId: aggregate.championId,
games: aggregate.games,
wins: aggregate.wins,
losses,
winRate: this.percent(aggregate.wins, aggregate.games),
avgKills: this.average(aggregate.totalKills, aggregate.games),
avgDeaths: this.average(aggregate.totalDeaths, aggregate.games),
avgAssists: this.average(aggregate.totalAssists, aggregate.games),
kda: this.resolveKda(
aggregate.totalKills,
aggregate.totalDeaths,
aggregate.totalAssists,
),
totalKills: aggregate.totalKills,
totalDeaths: aggregate.totalDeaths,
totalAssists: aggregate.totalAssists,
doubleKills: aggregate.doubleKills,
tripleKills: aggregate.tripleKills,
quadraKills: aggregate.quadraKills,
pentaKills: aggregate.pentaKills,
avgCs: this.average(aggregate.totalCs, aggregate.games),
avgCsPerMin: this.average(aggregate.totalCs, aggregate.totalGameMinutes),
};
}
private toRecentMatchView(
doc: RiotMatchDocument,
puuid: string,
): RecentMatchView | null {
const dto = doc.raw as unknown as RiotMatchDto;
const participant = this.findParticipant(dto, puuid);
if (!participant) return null;
const teamParticipants = dto.info.participants.filter(
(candidate) => candidate.teamId === participant.teamId,
);
const teamKills = teamParticipants.reduce(
(sum, candidate) => sum + candidate.kills,
0,
);
const minutes = this.resolveGameMinutes(dto, participant);
const totalCs = this.resolveTotalCs(participant);
const damageShare = this.resolveDamageShare(dto, participant);
const rating = this.resolveRating({
participant,
teamKills,
minutes,
damageShare,
});
return {
matchId: dto.metadata.matchId,
queueId: dto.info.queueId,
queueLabel: RIOT_QUEUE_LABELS[dto.info.queueId] ?? `큐 ${dto.info.queueId}`,
gameCreation: dto.info.gameCreation,
gameDuration: dto.info.gameDuration,
win: participant.win,
remake:
this.booleanField(participant, 'gameEndedInEarlySurrender') ||
dto.info.gameDuration < 240,
championId: participant.championId,
championLevel: participant.champLevel,
teamPosition: participant.teamPosition || participant.individualPosition,
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
kda: this.resolveKda(
participant.kills,
participant.deaths,
participant.assists,
),
rating,
totalCs,
csPerMin: this.average(totalCs, minutes),
killParticipation: this.percent(
participant.kills + participant.assists,
teamKills,
),
visionScore: participant.visionScore,
controlWardsBought: this.numberField(
participant,
'visionWardsBoughtInGame',
),
wardsPlaced: participant.wardsPlaced,
wardsKilled: participant.wardsKilled,
damageDealtToChampions: participant.totalDamageDealtToChampions,
damageTaken: participant.totalDamageTaken,
goldEarned: participant.goldEarned,
items: [
participant.item0,
participant.item1,
participant.item2,
participant.item3,
participant.item4,
participant.item5,
],
trinket: participant.item6,
summonerSpells: [participant.summoner1Id, participant.summoner2Id],
perks: this.resolvePerks(participant),
teams: this.resolveTeams(dto),
};
}
private createRecentSummary(
views: RecentMatchView[],
docs: RiotMatchDocument[],
context: HistoryContext,
requestedLimit: number,
): RecentSummaryResponse {
const totals = views.reduce(
(acc, view) => {
acc.wins += view.win ? 1 : 0;
acc.kills += view.kills;
acc.deaths += view.deaths;
acc.assists += view.assists;
return acc;
},
{ wins: 0, kills: 0, deaths: 0, assists: 0 },
);
const losses = views.length - totals.wins;
const best = views.reduce<RecentMatchView | null>((acc, view) => {
if (!acc) return view;
return view.deaths === 0 || view.rating > acc.rating ? view : acc;
}, null);
return {
windowSize: Math.min(views.length, requestedLimit),
winRate: this.percent(totals.wins, views.length),
wins: totals.wins,
losses,
streak: this.resolveStreak(views),
kda: this.resolveKda(totals.kills, totals.deaths, totals.assists),
avgKills: this.average(totals.kills, views.length),
avgDeaths: this.average(totals.deaths, views.length),
avgAssists: this.average(totals.assists, views.length),
bestRating: best
? {
rating: best.deaths === 0 ? 'Perfect' : best.rating,
kills: best.kills,
deaths: best.deaths,
assists: best.assists,
matchId: best.matchId,
}
: null,
positionRates: this.resolvePositionRates(views),
topChampions: this.resolveTopChampions(views),
lastFetchedAt: this.resolveLastFetchedAt(docs, context),
};
}
private resolveTeams(match: RiotMatchDto): RecentMatchView['teams'] {
return match.info.teams.map((team) => ({
side: team.teamId as 100 | 200,
win: team.win,
objectives: {
baron: team.objectives?.baron?.kills,
dragon: team.objectives?.dragon?.kills,
tower: team.objectives?.tower?.kills,
},
participants: match.info.participants
.filter((participant) => participant.teamId === team.teamId)
.map((participant) => ({
puuid: participant.puuid,
gameName: participant.riotIdGameName || participant.summonerName || 'Unknown',
tagLine: participant.riotIdTagLine || '',
championId: participant.championId,
teamPosition: participant.teamPosition || participant.individualPosition,
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
})),
}));
}
private resolvePerks(participant: RiotMatchParticipantDto): RecentMatchView['perks'] {
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 resolvePositionRates(
views: RecentMatchView[],
): Partial<Record<RiotLane, number>> {
const counts = new Map<string, number>();
for (const view of views) {
if (!view.teamPosition) continue;
counts.set(view.teamPosition, (counts.get(view.teamPosition) ?? 0) + 1);
}
return Object.fromEntries(
[...counts.entries()].map(([lane, count]) => [
lane,
this.percent(count, views.length),
]),
) as Partial<Record<RiotLane, number>>;
}
private resolveTopChampions(views: RecentMatchView[]): RecentSummaryResponse['topChampions'] {
const byChampion = new Map<number, { games: number; wins: number; rating: number }>();
for (const view of views) {
const stat =
byChampion.get(view.championId) ?? { games: 0, wins: 0, rating: 0 };
stat.games += 1;
stat.wins += view.win ? 1 : 0;
stat.rating += view.rating;
byChampion.set(view.championId, stat);
}
return [...byChampion.entries()]
.map(([championId, stat]) => ({
championId,
games: stat.games,
winRate: this.percent(stat.wins, stat.games),
pickRate: this.percent(stat.games, views.length),
avgRating: this.average(stat.rating, stat.games),
}))
.sort((a, b) => b.games - a.games || b.winRate - a.winRate)
.slice(0, 3);
}
private resolveStreak(
views: RecentMatchView[],
): RecentSummaryResponse['streak'] {
if (views.length === 0) return null;
const firstWin = views[0].win;
let count = 0;
for (const view of views) {
if (view.win !== firstWin) break;
count += 1;
}
return { type: firstWin ? 'win' : 'loss', count };
}
private resolveRating(params: {
participant: RiotMatchParticipantDto;
teamKills: number;
minutes: number;
damageShare: number;
}): number {
const { participant, teamKills, minutes, damageShare } = params;
const kda = this.resolveKda(
participant.kills,
participant.deaths,
participant.assists,
);
const kp = teamKills > 0 ? (participant.kills + participant.assists) / teamKills : 0;
const csPerMin = this.resolveTotalCs(participant) / Math.max(minutes, 1);
const visionPerMin = participant.visionScore / Math.max(minutes, 1);
const score =
Math.min(kda / 6, 1) * 4 +
Math.min(kp, 1) * 2 +
Math.min(csPerMin / 9, 1) * 2 +
Math.min(damageShare / 0.35, 1) +
Math.min(visionPerMin / 2, 1);
return this.round(score);
}
private resolveDamageShare(
match: RiotMatchDto,
participant: RiotMatchParticipantDto,
): number {
const teamDamage = match.info.participants
.filter((candidate) => candidate.teamId === participant.teamId)
.reduce((sum, candidate) => sum + candidate.totalDamageDealtToChampions, 0);
return teamDamage > 0 ? participant.totalDamageDealtToChampions / teamDamage : 0;
}
private resolveTotalCs(participant: RiotMatchParticipantDto): number {
return participant.totalMinionsKilled + participant.neutralMinionsKilled;
}
private resolveGameMinutes(
match: RiotMatchDto,
participant: RiotMatchParticipantDto,
): number {
return Math.max((participant.timePlayed || match.info.gameDuration) / 60, 1);
}
private resolveKda(kills: number, deaths: number, assists: number): number {
return deaths === 0 ? kills + assists : this.round((kills + assists) / deaths);
}
private resolveLastFetchedAt(
docs: RiotMatchDocument[],
context: HistoryContext,
): string | null {
if (docs.length === 0) {
return context.account.recentStatsFetchedAt?.toISOString() ?? null;
}
const oldest = docs.reduce((acc, doc) =>
doc.fetchedAt.getTime() < acc.getTime() ? doc.fetchedAt : acc,
docs[0].fetchedAt);
return oldest.toISOString();
}
private clampLimit(value: number | undefined, fallback: number, max: number): number {
if (!value || !Number.isFinite(value)) return fallback;
return Math.max(1, Math.min(Math.floor(value), max));
}
private percent(value: number, total: number): number {
return total > 0 ? Math.round((value / total) * 100) : 0;
}
private average(value: number, total: number): number {
return total > 0 ? this.round(value / total) : 0;
}
private round(value: number): number {
return Math.round(value * 10) / 10;
}
private numberField(
value: RiotMatchParticipantDto,
key: string,
): number {
const field = value[key];
return typeof field === 'number' && Number.isFinite(field) ? field : 0;
}
private booleanField(
value: RiotMatchParticipantDto,
key: string,
): boolean {
return value[key] === true;
}
}
@@ -0,0 +1,146 @@
import type { RiotLane } from '../global/database/schema';
import type {
RiotQueueGroup,
RiotRankFilter,
} from '../riot/riot-queue.constants';
export interface HistorySeasonDto {
id: string;
label: string;
startedAt: string | null;
endedAt: string | null;
}
export interface UserHistoryProfileResponse {
userId: string;
puuid: string;
gameName: string;
tagLine: string;
profileIconId: number;
summonerLevel: number;
tiers: Array<{
queueType: string;
tier: string;
rank: string;
leaguePoints: number;
wins: number;
losses: number;
fetchedAt: string;
}>;
season: HistorySeasonDto;
seasons: HistorySeasonDto[];
lastFetchedAt: string | null;
}
export interface ChampionStatsRow {
championId: number;
games: number;
wins: number;
losses: number;
winRate: number;
avgKills: number;
avgDeaths: number;
avgAssists: number;
kda: number;
totalKills: number;
totalDeaths: number;
totalAssists: number;
doubleKills: number;
tripleKills: number;
quadraKills: number;
pentaKills: number;
avgCs: number;
avgCsPerMin: number;
}
export interface ChampionStatsResponse {
queueGroup: RiotQueueGroup;
rank: RiotRankFilter;
queueIds: number[];
season: HistorySeasonDto;
lastFetchedAt: string | null;
champions: ChampionStatsRow[];
totals: ChampionStatsRow;
}
export interface RecentSummaryResponse {
windowSize: number;
winRate: number;
wins: number;
losses: number;
streak: { type: 'win' | 'loss'; count: number } | null;
kda: number;
avgKills: number;
avgDeaths: number;
avgAssists: number;
bestRating: {
rating: number | 'Perfect';
kills: number;
deaths: number;
assists: number;
matchId: string;
} | null;
positionRates: Partial<Record<RiotLane, number>>;
topChampions: Array<{
championId: number;
games: number;
winRate: number;
pickRate: number;
avgRating: number;
}>;
lastFetchedAt: string | null;
}
export interface RecentMatchesResponse {
matches: RecentMatchView[];
nextCursor: number | null;
lastFetchedAt: string | null;
season: HistorySeasonDto;
}
export interface RecentMatchView {
matchId: string;
queueId: number;
queueLabel: string;
gameCreation: number;
gameDuration: number;
win: boolean;
remake: boolean;
championId: number;
championLevel: number;
teamPosition: string;
kills: number;
deaths: number;
assists: number;
kda: number;
rating: number;
totalCs: number;
csPerMin: number;
killParticipation: number;
visionScore: number;
controlWardsBought: number;
wardsPlaced: number;
wardsKilled: number;
damageDealtToChampions: number;
damageTaken: number;
goldEarned: number;
items: number[];
trinket: number;
summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
teams: Array<{
side: 100 | 200;
win: boolean;
objectives?: { baron?: number; dragon?: number; tower?: number };
participants: Array<{
puuid: string;
gameName: string;
tagLine: string;
championId: number;
teamPosition: string;
kills: number;
deaths: number;
assists: number;
}>;
}>;
}
@@ -0,0 +1,88 @@
export type RiotQueueGroup =
| 'all'
| 'summoners-rift'
| 'aram'
| 'urf'
| 'arena';
export type RiotRankFilter = 'all' | 'solo' | 'flex' | 'normal';
export interface RiotQueueGroupConfig {
label: string;
queues: Record<RiotRankFilter, number[]>;
}
export const RIOT_QUEUE_GROUPS: Record<RiotQueueGroup, RiotQueueGroupConfig> = {
all: {
label: '전체',
queues: {
all: [400, 420, 430, 440, 450, 900, 1900, 1700, 1710],
solo: [420],
flex: [440],
normal: [400, 430, 450, 900, 1900, 1700, 1710],
},
},
'summoners-rift': {
label: '소환사의 협곡',
queues: {
all: [400, 420, 430, 440],
solo: [420],
flex: [440],
normal: [400, 430],
},
},
aram: {
label: '칼바람 나락',
queues: {
all: [450],
solo: [],
flex: [],
normal: [450],
},
},
urf: {
label: '우르프',
queues: {
all: [900, 1900],
solo: [],
flex: [],
normal: [900, 1900],
},
},
arena: {
label: '아레나',
queues: {
all: [1700, 1710],
solo: [],
flex: [],
normal: [1700, 1710],
},
},
};
export const RIOT_QUEUE_LABELS: Record<number, string> = {
400: '일반 교차 선택',
420: '솔로 랭크',
430: '일반 비공개 선택',
440: '자유 랭크',
450: '칼바람 나락',
900: '우르프',
1700: '아레나',
1710: '아레나',
1900: '우르프',
};
export function resolveRiotQueueIds(
queueGroup: RiotQueueGroup,
rank: RiotRankFilter,
): number[] {
return RIOT_QUEUE_GROUPS[queueGroup].queues[rank];
}
export function isRiotQueueGroup(value: string): value is RiotQueueGroup {
return value in RIOT_QUEUE_GROUPS;
}
export function isRiotRankFilter(value: string): value is RiotRankFilter {
return value === 'all' || value === 'solo' || value === 'flex' || value === 'normal';
}
+2
View File
@@ -9,6 +9,7 @@ import HomePage from './pages/HomePage';
import LoginPage from './pages/Login';
import MatchDetailPage from './pages/MatchDetailPage';
import AuctionPage from './pages/AuctionPage';
import UserHistoryPage from './pages/UserHistoryPage';
function MsalHeaderActions() {
const { accounts, instance } = useMsal();
@@ -69,6 +70,7 @@ function App() {
<Route path="/auth/callback" element={<AuthCallbackPage />} />
<Route path="/match/:id" element={<MatchDetailPage />} />
<Route path="/match/:id/auction" element={<AuctionPage />} />
<Route path="/users/:userId/history" element={<UserHistoryPage />} />
</Routes>
<DevAuthSwitcher />
</div>
+124 -1
View File
@@ -1,6 +1,6 @@
import { InteractionStatus } from '@azure/msal-browser';
import { useMsal } from '@azure/msal-react';
import { useQuery } from '@tanstack/react-query';
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config';
import { apiFetch } from '../lib/api';
import {
@@ -9,12 +9,18 @@ import {
} from '../lib/auth/msal.config';
import type {
ApiAuction,
ApiChampionStatsResponse,
ApiCommunity,
ApiMatch,
ApiRecentMatchesResponse,
ApiRecentSummaryResponse,
ApiUserHistoryProfile,
DdragonManifest,
MatchStatus,
MatchesResponse,
MeResponse,
RiotQueueGroup,
RiotRankFilter,
} from './types';
const DDRAGON_MANIFEST_STALE_MS = 24 * 60 * 60 * 1000;
@@ -24,6 +30,13 @@ interface MatchesQueryOptions {
limit?: number;
}
export interface UserHistoryFilters {
queueGroup?: RiotQueueGroup;
rank?: RiotRankFilter;
seasonId?: string;
championId?: number;
}
function createMatchesPath(
communityId: string,
options: MatchesQueryOptions = {},
@@ -83,6 +96,116 @@ export function useAuction(
});
}
function createUserHistoryPath(
communityId: string,
userId: string,
resource: string,
filters: UserHistoryFilters = {},
extra: Record<string, string | number | null | undefined> = {},
) {
const searchParams = new URLSearchParams();
if (filters.queueGroup) searchParams.set('queueGroup', filters.queueGroup);
if (filters.rank) searchParams.set('rank', filters.rank);
if (filters.seasonId) searchParams.set('seasonId', filters.seasonId);
if (filters.championId) searchParams.set('championId', String(filters.championId));
for (const [key, value] of Object.entries(extra)) {
if (value !== null && value !== undefined && value !== '') {
searchParams.set(key, String(value));
}
}
const queryString = searchParams.toString();
return `/communities/${communityId}/users/${userId}/${resource}${queryString ? `?${queryString}` : ''}`;
}
export function useUserHistoryProfile(
userId: string | undefined,
communityId = DEFAULT_COMMUNITY_ID,
) {
return useQuery({
queryKey: ['user-history-profile', communityId, userId ?? null],
queryFn: () =>
apiFetch<ApiUserHistoryProfile>(
`/communities/${communityId}/users/${userId}/history-profile`,
),
enabled: Boolean(communityId && userId),
retry: false,
});
}
export function useChampionStats(
userId: string | undefined,
filters: UserHistoryFilters,
communityId = DEFAULT_COMMUNITY_ID,
) {
return useQuery({
queryKey: [
'user-champion-stats',
communityId,
userId ?? null,
filters.queueGroup ?? null,
filters.rank ?? null,
filters.seasonId ?? null,
],
queryFn: () =>
apiFetch<ApiChampionStatsResponse>(
createUserHistoryPath(communityId, userId ?? '', 'champion-stats', filters),
),
enabled: Boolean(communityId && userId),
});
}
export function useRecentSummary(
userId: string | undefined,
filters: UserHistoryFilters,
communityId = DEFAULT_COMMUNITY_ID,
) {
return useQuery({
queryKey: [
'user-recent-summary',
communityId,
userId ?? null,
filters.queueGroup ?? null,
filters.rank ?? null,
filters.seasonId ?? null,
filters.championId ?? null,
],
queryFn: () =>
apiFetch<ApiRecentSummaryResponse>(
createUserHistoryPath(communityId, userId ?? '', 'recent-summary', filters),
),
enabled: Boolean(communityId && userId),
});
}
export function useRecentMatches(
userId: string | undefined,
filters: UserHistoryFilters,
communityId = DEFAULT_COMMUNITY_ID,
) {
return useInfiniteQuery({
queryKey: [
'user-recent-matches',
communityId,
userId ?? null,
filters.queueGroup ?? null,
filters.rank ?? null,
filters.seasonId ?? null,
filters.championId ?? null,
],
queryFn: ({ pageParam }) =>
apiFetch<ApiRecentMatchesResponse>(
createUserHistoryPath(communityId, userId ?? '', 'recent-matches', filters, {
cursor: pageParam,
limit: 10,
}),
),
initialPageParam: null as number | null,
getNextPageParam: (lastPage) => lastPage.nextCursor,
enabled: Boolean(communityId && userId),
});
}
export function useDdragonManifest(locale = 'ko_KR') {
return useQuery({
queryKey: ['ddragon-manifest', locale],
+143
View File
@@ -247,3 +247,146 @@ export interface DdragonManifest {
champions: Record<string, DdragonChampionEntry>;
fetchedAt: string;
}
export type RiotQueueGroup =
| 'all'
| 'summoners-rift'
| 'aram'
| 'urf'
| 'arena';
export type RiotRankFilter = 'all' | 'solo' | 'flex' | 'normal';
export interface ApiHistorySeason {
id: string;
label: string;
startedAt: string | null;
endedAt: string | null;
}
export interface ApiUserHistoryProfile {
userId: string;
puuid: string;
gameName: string;
tagLine: string;
profileIconId: number;
summonerLevel: number;
tiers: ApiTierInfo[];
season: ApiHistorySeason;
seasons: ApiHistorySeason[];
lastFetchedAt: string | null;
}
export interface ApiChampionStatsRow {
championId: number;
games: number;
wins: number;
losses: number;
winRate: number;
avgKills: number;
avgDeaths: number;
avgAssists: number;
kda: number;
totalKills: number;
totalDeaths: number;
totalAssists: number;
doubleKills: number;
tripleKills: number;
quadraKills: number;
pentaKills: number;
avgCs: number;
avgCsPerMin: number;
}
export interface ApiChampionStatsResponse {
queueGroup: RiotQueueGroup;
rank: RiotRankFilter;
queueIds: number[];
season: ApiHistorySeason;
lastFetchedAt: string | null;
champions: ApiChampionStatsRow[];
totals: ApiChampionStatsRow;
}
export interface ApiRecentSummaryResponse {
windowSize: number;
winRate: number;
wins: number;
losses: number;
streak: { type: 'win' | 'loss'; count: number } | null;
kda: number;
avgKills: number;
avgDeaths: number;
avgAssists: number;
bestRating: {
rating: number | 'Perfect';
kills: number;
deaths: number;
assists: number;
matchId: string;
} | null;
positionRates: Partial<Record<RiotLane, number>>;
topChampions: Array<{
championId: number;
games: number;
winRate: number;
pickRate: number;
avgRating: number;
}>;
lastFetchedAt: string | null;
}
export interface ApiRecentMatchTeam {
side: 100 | 200;
win: boolean;
objectives?: { baron?: number; dragon?: number; tower?: number };
participants: Array<{
puuid: string;
gameName: string;
tagLine: string;
championId: number;
teamPosition: string;
kills: number;
deaths: number;
assists: number;
}>;
}
export interface ApiRecentMatchView {
matchId: string;
queueId: number;
queueLabel: string;
gameCreation: number;
gameDuration: number;
win: boolean;
remake: boolean;
championId: number;
championLevel: number;
teamPosition: string;
kills: number;
deaths: number;
assists: number;
kda: number;
rating: number;
totalCs: number;
csPerMin: number;
killParticipation: number;
visionScore: number;
controlWardsBought: number;
wardsPlaced: number;
wardsKilled: number;
damageDealtToChampions: number;
damageTaken: number;
goldEarned: number;
items: number[];
trinket: number;
summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
teams: ApiRecentMatchTeam[];
}
export interface ApiRecentMatchesResponse {
matches: ApiRecentMatchView[];
nextCursor: number | null;
lastFetchedAt: string | null;
season: ApiHistorySeason;
}
+28 -17
View File
@@ -235,19 +235,24 @@ function TeamPanel({
) : (
team.members.map((member) => (
<div key={`${member.userId}-${member.assignedPosition}`} className="px-3 py-1.5 flex items-center gap-2">
<div className="w-6 h-6 bg-base-content/10 overflow-hidden shrink-0">
<img
src={profileIconUrl(ddragon, member.profileIconId)}
alt=""
className="w-full h-full object-cover"
loading="lazy"
/>
</div>
<div className="flex-1 min-w-0">
<span className="text-[12px] font-medium text-base-content truncate block leading-tight">
{member.summonerName}
</span>
</div>
<Link
to={`/users/${member.userId}/history`}
className="flex flex-1 min-w-0 items-center gap-2 group"
>
<div className="w-6 h-6 bg-base-content/10 overflow-hidden shrink-0">
<img
src={profileIconUrl(ddragon, member.profileIconId)}
alt=""
className="w-full h-full object-cover"
loading="lazy"
/>
</div>
<div className="flex-1 min-w-0">
<span className="text-[12px] font-medium text-base-content truncate block leading-tight group-hover:text-primary transition-colors">
{member.summonerName}
</span>
</div>
</Link>
<PosBadge pos={member.assignedPosition} />
<span className="text-[10px] text-amber-400/60 tabular-nums w-8 text-right">
{member.cost}
@@ -285,18 +290,24 @@ function PlayerSpotlight({
<div className="border border-base-content/10 bg-base-100">
<div className="p-5 border-b border-base-content/8">
<div className="flex items-start gap-4">
<div className="w-16 h-16 bg-base-content/10 overflow-hidden shrink-0">
<Link
to={`/users/${player.userId}/history`}
className="w-16 h-16 bg-base-content/10 overflow-hidden shrink-0"
>
<img
src={profileIconUrl(ddragon, player.profileIconId)}
alt=""
className="w-full h-full object-cover"
/>
</div>
</Link>
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
<h3 className="text-lg font-bold text-base-content leading-tight">
<Link
to={`/users/${player.userId}/history`}
className="text-lg font-bold text-base-content leading-tight hover:text-primary transition-colors"
>
{player.summonerName}
</h3>
</Link>
<span className="text-[10px] text-base-content/25">
#{player.tag}
</span>
+6 -3
View File
@@ -100,7 +100,10 @@ function ParticipantRow({
{index + 1}
</td>
<td className="py-2 px-3">
<div className="flex items-center gap-2">
<Link
to={`/users/${participant.userId}/history`}
className="flex items-center gap-2 group"
>
<div className="w-7 h-7 bg-base-content/10 overflow-hidden shrink-0">
<img
src={profileIconUrl(ddragon, participant.profileIconId)}
@@ -110,14 +113,14 @@ function ParticipantRow({
/>
</div>
<div className="min-w-0">
<span className="font-medium text-[13px] text-base-content truncate block leading-tight">
<span className="font-medium text-[13px] text-base-content truncate block leading-tight group-hover:text-primary transition-colors">
{participant.summonerName}
</span>
<span className="text-[10px] text-base-content/25 leading-tight">
#{participant.tag}
</span>
</div>
</div>
</Link>
</td>
<td className="py-2 px-3">
<TierCell participant={participant} />
+775
View File
@@ -0,0 +1,775 @@
import { useMemo, useState } from 'react';
import { Link, useParams, useSearchParams } from 'react-router';
import {
useChampionStats,
useDdragonManifest,
useRecentMatches,
useRecentSummary,
useUserHistoryProfile,
type UserHistoryFilters,
} from '../api/hooks';
import {
formatTierLabel,
getTierColorToken,
} from '../api/mappers';
import type {
ApiChampionStatsRow,
ApiRecentMatchView,
DdragonManifest,
RiotQueueGroup,
RiotRankFilter,
} from '../api/types';
import { DEFAULT_COMMUNITY_ID } from '../config';
import {
championDisplayName,
championIconUrl,
itemIconUrl,
profileIconUrl,
} from '../lib/ddragon';
import {
isRiotQueueGroup,
isRiotRankFilter,
LANE_LABELS,
QUEUE_GROUP_TABS,
RANK_FILTER_TABS,
} from '../lib/riot-history';
type ChampionSortKey = 'games' | 'winRate' | 'kda' | 'avgCsPerMin';
const SORT_LABELS: Record<ChampionSortKey, string> = {
games: '게임 수',
winRate: '승률',
kda: 'KDA',
avgCsPerMin: '분당 CS',
};
function formatDuration(seconds: number) {
const minutes = Math.floor(seconds / 60);
const rest = seconds % 60;
return `${minutes}:${String(rest).padStart(2, '0')}`;
}
function formatDate(ms: number) {
return new Intl.DateTimeFormat('ko-KR', {
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(ms));
}
function formatLastFetched(value: string | null | undefined) {
if (!value) return '저장된 갱신 시각 없음';
return new Intl.DateTimeFormat('ko-KR', {
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(value));
}
function ratioClass(value: number) {
if (value >= 55) return 'text-blue-400';
if (value >= 50) return 'text-amber-400';
return 'text-base-content/50';
}
function kdaClass(value: number) {
if (value >= 4) return 'text-amber-400';
if (value >= 3) return 'text-emerald-400';
return 'text-base-content/60';
}
function FilterButton({
active,
children,
onClick,
}: {
active: boolean;
children: React.ReactNode;
onClick: () => void;
}) {
return (
<button
type="button"
onClick={onClick}
className={`px-3 py-2 text-[12px] font-semibold border-b-2 transition-colors ${
active
? 'border-primary text-primary bg-primary/5'
: 'border-transparent text-base-content/45 hover:text-base-content'
}`}
>
{children}
</button>
);
}
function ChampionIcon({
championId,
manifest,
size = 'md',
}: {
championId: number;
manifest: DdragonManifest | null | undefined;
size?: 'sm' | 'md' | 'lg';
}) {
const iconUrl = championIconUrl(manifest, championId);
const displayName = championDisplayName(manifest, championId) ?? String(championId);
const sizeClass = size === 'lg' ? 'w-12 h-12' : size === 'sm' ? 'w-5 h-5' : 'w-8 h-8';
return (
<div className={`${sizeClass} bg-base-content/10 overflow-hidden shrink-0`}>
{iconUrl ? (
<img
src={iconUrl}
alt={displayName}
className="w-full h-full object-cover"
loading="lazy"
/>
) : null}
</div>
);
}
function SummaryCard({
label,
value,
sub,
}: {
label: string;
value: React.ReactNode;
sub?: React.ReactNode;
}) {
return (
<div className="border border-base-content/8 bg-base-100 p-4">
<div className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
{label}
</div>
<div className="mt-2 text-2xl font-black text-base-content tabular-nums">
{value}
</div>
{sub && <div className="mt-1 text-[11px] text-base-content/40">{sub}</div>}
</div>
);
}
function ChampionStatsTable({
rows,
manifest,
selectedChampionId,
onChampionSelect,
}: {
rows: ApiChampionStatsRow[];
manifest: DdragonManifest | null | undefined;
selectedChampionId?: number;
onChampionSelect: (championId: number | null) => void;
}) {
if (rows.length === 0) {
return (
<div className="border border-base-content/10 bg-base-100 px-4 py-10 text-center text-sm text-base-content/35">
조건에 맞는 챔피언 통계가 아직 없습니다.
</div>
);
}
return (
<div className="border border-base-content/10 bg-base-100 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-left min-w-[860px]">
<thead>
<tr className="bg-base-200/50 border-b border-base-content/10 text-[11px] text-base-content/35 uppercase tracking-wider">
<th className="px-3 py-2.5">챔피언</th>
<th className="px-3 py-2.5 text-center">승률</th>
<th className="px-3 py-2.5 text-center">게임</th>
<th className="px-3 py-2.5 text-center">승/패</th>
<th className="px-3 py-2.5 text-center">KDA</th>
<th className="px-3 py-2.5 text-center">킬</th>
<th className="px-3 py-2.5 text-center">데스</th>
<th className="px-3 py-2.5 text-center">어시스트</th>
<th className="px-3 py-2.5 text-center">멀티킬</th>
<th className="px-3 py-2.5 text-center">CS</th>
<th className="px-3 py-2.5 text-center">필터</th>
</tr>
</thead>
<tbody>
{rows.map((row) => {
const displayName =
championDisplayName(manifest, row.championId) ??
String(row.championId);
const selected = selectedChampionId === row.championId;
return (
<tr
key={row.championId}
className="border-b border-base-content/5 last:border-b-0 hover:bg-base-content/[0.02]"
>
<td className="px-3 py-2.5">
<div className="flex items-center gap-2">
<ChampionIcon championId={row.championId} manifest={manifest} />
<span className="text-[13px] font-bold text-base-content">
{displayName}
</span>
</div>
</td>
<td className={`px-3 py-2.5 text-center text-[13px] font-bold ${ratioClass(row.winRate)}`}>
{row.winRate}%
</td>
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
{row.games}
</td>
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums text-base-content/55">
<span className="text-blue-400">{row.wins}</span> /{' '}
<span className="text-red-400">{row.losses}</span>
</td>
<td className={`px-3 py-2.5 text-center text-[13px] font-bold tabular-nums ${kdaClass(row.kda)}`}>
{row.kda}
</td>
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
{row.totalKills}
</td>
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
{row.totalDeaths}
</td>
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
{row.totalAssists}
</td>
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums text-base-content/55">
{row.doubleKills}/{row.tripleKills}/{row.quadraKills}/{row.pentaKills}
</td>
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
{row.avgCs} · {row.avgCsPerMin}/m
</td>
<td className="px-3 py-2.5 text-center">
<button
type="button"
className={`text-[11px] px-2 py-1 border ${
selected
? 'border-primary/40 bg-primary/10 text-primary'
: 'border-base-content/10 text-base-content/40 hover:text-base-content'
}`}
onClick={() => onChampionSelect(selected ? null : row.championId)}
>
{selected ? '해제' : '보기'}
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
);
}
function ItemGrid({
match,
manifest,
}: {
match: ApiRecentMatchView;
manifest: DdragonManifest | null | undefined;
}) {
const slots = [...match.items, match.trinket];
return (
<div className="grid grid-cols-4 gap-1 w-[92px]">
{slots.map((itemId, index) => {
const url = itemIconUrl(manifest, itemId);
return (
<div
key={`${match.matchId}-item-${index}`}
className="w-5 h-5 bg-base-content/8 overflow-hidden border border-base-content/5"
>
{url ? (
<img
src={url}
alt=""
className="w-full h-full object-cover"
loading="lazy"
/>
) : null}
</div>
);
})}
</div>
);
}
function TeamMini({
match,
manifest,
}: {
match: ApiRecentMatchView;
manifest: DdragonManifest | null | undefined;
}) {
return (
<div className="grid sm:grid-cols-2 gap-2 text-[11px]">
{match.teams.map((team) => (
<div
key={`${match.matchId}-${team.side}`}
className={`space-y-0.5 ${team.win ? 'text-base-content/70' : 'text-base-content/35'}`}
>
{team.participants.map((participant) => {
const championName =
championDisplayName(manifest, participant.championId) ??
String(participant.championId);
return (
<div
key={`${participant.puuid}-${participant.championId}`}
className="flex items-center gap-1 min-w-0"
>
<ChampionIcon
championId={participant.championId}
manifest={manifest}
size="sm"
/>
<span className="truncate">
{participant.gameName || championName}
</span>
</div>
);
})}
</div>
))}
</div>
);
}
function RecentMatchCard({
match,
manifest,
}: {
match: ApiRecentMatchView;
manifest: DdragonManifest | null | undefined;
}) {
const championName =
championDisplayName(manifest, match.championId) ?? String(match.championId);
const accent = match.win ? 'border-l-blue-500' : 'border-l-red-500';
const resultClass = match.win ? 'text-blue-400' : 'text-red-400';
return (
<article className={`border border-l-4 ${accent} border-base-content/10 bg-base-100`}>
<div className="p-4 grid lg:grid-cols-[120px_1fr_120px_1.5fr_32px] gap-4 items-center">
<div className="text-center lg:text-left">
<div className={`text-[12px] font-black ${resultClass}`}>
{match.remake ? '다시하기' : match.win ? '승리' : '패배'}
</div>
<div className="text-[11px] text-base-content/35 mt-1">
{match.queueLabel}
</div>
<div className="text-[11px] text-base-content/25">
{formatDate(match.gameCreation)}
</div>
<div className="text-[11px] text-base-content/25">
{formatDuration(match.gameDuration)}
</div>
</div>
<div className="flex items-center gap-3 min-w-0">
<ChampionIcon championId={match.championId} manifest={manifest} size="lg" />
<div className="min-w-0">
<div className="font-bold text-base-content truncate">
{championName}
</div>
<div className="text-[11px] text-base-content/35">
Lv.{match.championLevel} ·{' '}
{(LANE_LABELS[match.teamPosition] ?? match.teamPosition) || '포지션 없음'}
</div>
<div className="mt-1 text-[10px] text-base-content/30">
스펠 {match.summonerSpells.join(' / ')}
</div>
</div>
</div>
<div className="text-center">
<div className="text-lg font-black tabular-nums">
<span>{match.kills}</span>
<span className="text-base-content/25"> / </span>
<span className="text-red-400">{match.deaths}</span>
<span className="text-base-content/25"> / </span>
<span>{match.assists}</span>
</div>
<div className={`text-[12px] font-bold tabular-nums ${kdaClass(match.kda)}`}>
{match.deaths === 0 ? 'Perfect' : `${match.kda} 평점`}
</div>
<div className="mt-1 text-[11px] text-base-content/35">
킬 관여 {match.killParticipation}%
</div>
</div>
<div className="grid sm:grid-cols-[100px_1fr] gap-4 items-center">
<div className="space-y-1 text-[11px] text-base-content/45">
<div>
CS <span className="font-bold text-base-content/70">{match.totalCs}</span>{' '}
({match.csPerMin}/m)
</div>
<div>
시야 <span className="font-bold text-base-content/70">{match.visionScore}</span>{' '}
제어와드 {match.controlWardsBought}
</div>
<div>
피해량{' '}
<span className="font-bold text-base-content/70">
{match.damageDealtToChampions.toLocaleString()}
</span>
</div>
</div>
<div className="flex items-start gap-3">
<ItemGrid match={match} manifest={manifest} />
<TeamMini match={match} manifest={manifest} />
</div>
</div>
<div className="hidden lg:flex justify-end">
<div className={`w-2 h-14 ${match.win ? 'bg-blue-500/70' : 'bg-red-500/70'}`} />
</div>
</div>
</article>
);
}
export default function UserHistoryPage() {
const { userId } = useParams();
const [searchParams, setSearchParams] = useSearchParams();
const [championSearch, setChampionSearch] = useState('');
const [sortKey, setSortKey] = useState<ChampionSortKey>('games');
const queueGroupParam = searchParams.get('queueGroup');
const rankParam = searchParams.get('rank');
const queueGroup: RiotQueueGroup = isRiotQueueGroup(queueGroupParam)
? queueGroupParam
: 'summoners-rift';
const rank: RiotRankFilter = isRiotRankFilter(rankParam) ? rankParam : 'all';
const championIdParam = Number(searchParams.get('championId'));
const championId = Number.isFinite(championIdParam) && championIdParam > 0
? championIdParam
: undefined;
const filters: UserHistoryFilters = {
queueGroup,
rank,
championId,
seasonId: searchParams.get('seasonId') ?? undefined,
};
const aggregateFilters: UserHistoryFilters = {
queueGroup,
rank,
seasonId: filters.seasonId,
};
const { data: ddragon } = useDdragonManifest();
const profileQuery = useUserHistoryProfile(userId, DEFAULT_COMMUNITY_ID);
const championStatsQuery = useChampionStats(
userId,
aggregateFilters,
DEFAULT_COMMUNITY_ID,
);
const summaryQuery = useRecentSummary(userId, filters, DEFAULT_COMMUNITY_ID);
const recentMatchesQuery = useRecentMatches(userId, filters, DEFAULT_COMMUNITY_ID);
const profile = profileQuery.data;
const primaryTier =
profile?.tiers.find((tier) => tier.queueType === 'RANKED_SOLO_5x5') ??
profile?.tiers[0];
const matches =
recentMatchesQuery.data?.pages.flatMap((page) => page.matches) ?? [];
const selectedChampionName = championId
? championDisplayName(ddragon, championId) ?? String(championId)
: null;
const visibleChampionRows = useMemo(() => {
const rows = championStatsQuery.data?.champions ?? [];
const keyword = championSearch.trim().toLowerCase();
return rows
.filter((row) => {
if (!keyword) return true;
const displayName =
championDisplayName(ddragon, row.championId) ?? String(row.championId);
return displayName.toLowerCase().includes(keyword);
})
.sort((left, right) => right[sortKey] - left[sortKey]);
}, [championSearch, championStatsQuery.data?.champions, ddragon, sortKey]);
function updateSearch(next: Partial<Record<string, string | number | null>>) {
const params = new URLSearchParams(searchParams);
for (const [key, value] of Object.entries(next)) {
if (value === null || value === undefined || value === '') {
params.delete(key);
} else {
params.set(key, String(value));
}
}
setSearchParams(params);
}
if (!DEFAULT_COMMUNITY_ID) {
return (
<main className="max-w-6xl mx-auto px-4 py-20 text-center">
<span className="text-sm text-amber-600">
`VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다.
</span>
</main>
);
}
if (profileQuery.isLoading) {
return (
<main className="max-w-6xl mx-auto px-4 py-20 text-center">
<span className="text-sm text-base-content/40">
소환사 전적을 불러오는 중...
</span>
</main>
);
}
if (profileQuery.error || !profile) {
return (
<main className="max-w-6xl mx-auto px-4 py-20 text-center">
<h2 className="text-lg font-bold mb-2">소환사를 찾을 수 없습니다</h2>
<Link to="/" className="btn btn-ghost btn-sm mt-4">
홈으로 돌아가기
</Link>
</main>
);
}
return (
<main className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
<Link
to="/"
className="inline-flex items-center gap-1 text-xs text-base-content/40 hover:text-base-content transition-colors mb-5"
>
← 목록으로
</Link>
<section className="border border-base-content/10 bg-base-100 p-5 mb-5">
<div className="flex flex-col sm:flex-row sm:items-center gap-4">
<div className="w-16 h-16 bg-base-content/10 overflow-hidden shrink-0">
<img
src={profileIconUrl(ddragon, profile.profileIconId)}
alt=""
className="w-full h-full object-cover"
/>
</div>
<div className="flex-1 min-w-0">
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-2xl font-black text-base-content">
{profile.gameName}
</h1>
<span className="text-sm text-base-content/35">
#{profile.tagLine}
</span>
</div>
<div className="mt-2 flex flex-wrap items-center gap-3 text-xs text-base-content/40">
<span>Lv.{profile.summonerLevel}</span>
{primaryTier ? (
<span className={`font-bold ${getTierColorToken(primaryTier)}`}>
{formatTierLabel(primaryTier)} {primaryTier.leaguePoints}LP
</span>
) : (
<span>랭크 정보 없음</span>
)}
<span>시즌: {profile.season.label}</span>
<span>최근 저장: {formatLastFetched(profile.lastFetchedAt)}</span>
</div>
</div>
<div className="border border-dashed border-base-content/10 px-3 py-2 text-[11px] text-base-content/35 sm:text-right">
이 페이지는 저장된 경기 DB만 조회합니다.
<br />
화면 진입 시 Riot Match API 호출은 없습니다.
</div>
</div>
</section>
<section className="border border-base-content/10 bg-base-100 mb-5">
<div className="flex flex-wrap border-b border-base-content/8">
{QUEUE_GROUP_TABS.map((tab) => (
<FilterButton
key={tab.value}
active={queueGroup === tab.value}
onClick={() => updateSearch({ queueGroup: tab.value, championId: null })}
>
{tab.label}
</FilterButton>
))}
</div>
<div className="flex flex-wrap items-center justify-between gap-3 px-3 py-2">
<div className="flex flex-wrap">
{RANK_FILTER_TABS.map((tab) => (
<FilterButton
key={tab.value}
active={rank === tab.value}
onClick={() => updateSearch({ rank: tab.value, championId: null })}
>
{tab.label}
</FilterButton>
))}
</div>
{selectedChampionName && (
<button
type="button"
className="text-[11px] px-2.5 py-1 border border-primary/30 text-primary bg-primary/5"
onClick={() => updateSearch({ championId: null })}
>
{selectedChampionName} 필터 해제
</button>
)}
{profile.seasons.length > 0 && (
<select
value={filters.seasonId ?? profile.season.id}
onChange={(event) =>
updateSearch({ seasonId: event.target.value, championId: null })
}
className="border border-base-content/10 bg-transparent px-3 py-2 text-xs"
>
{profile.seasons.map((season) => (
<option key={season.id} value={season.id}>
{season.label}
</option>
))}
</select>
)}
</div>
</section>
<section className="mb-6">
<h2 className="text-sm font-bold text-base-content mb-3">
최근 {summaryQuery.data?.windowSize ?? 20}게임 전적 요약
</h2>
<div className="grid sm:grid-cols-2 lg:grid-cols-5 gap-3">
<SummaryCard
label="승률"
value={`${summaryQuery.data?.winRate ?? 0}%`}
sub={`${summaryQuery.data?.wins ?? 0}승 ${summaryQuery.data?.losses ?? 0}패`}
/>
<SummaryCard
label="KDA"
value={summaryQuery.data?.kda ?? 0}
sub={`${summaryQuery.data?.avgKills ?? 0} / ${summaryQuery.data?.avgDeaths ?? 0} / ${summaryQuery.data?.avgAssists ?? 0}`}
/>
<SummaryCard
label="최고 평점"
value={summaryQuery.data?.bestRating?.rating ?? '-'}
sub={
summaryQuery.data?.bestRating
? `${summaryQuery.data.bestRating.kills}/${summaryQuery.data.bestRating.deaths}/${summaryQuery.data.bestRating.assists}`
: '기록 없음'
}
/>
<SummaryCard
label="연승/연패"
value={
summaryQuery.data?.streak
? `${summaryQuery.data.streak.count}${summaryQuery.data.streak.type === 'win' ? '연승' : '연패'}`
: '-'
}
sub="가장 최근 경기 기준"
/>
<div className="border border-base-content/8 bg-base-100 p-4">
<div className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
자주 플레이한 챔피언
</div>
<div className="mt-3 flex items-center gap-3">
{(summaryQuery.data?.topChampions ?? []).map((champion) => (
<button
type="button"
key={champion.championId}
className="text-center group"
onClick={() => updateSearch({ championId: champion.championId })}
>
<ChampionIcon
championId={champion.championId}
manifest={ddragon}
/>
<div className="mt-1 text-[10px] text-base-content/40 group-hover:text-primary">
{champion.winRate}%
</div>
</button>
))}
{(summaryQuery.data?.topChampions ?? []).length === 0 && (
<span className="text-[11px] text-base-content/25">기록 없음</span>
)}
</div>
</div>
</div>
</section>
<section className="mb-6">
<div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3 mb-3">
<div>
<h2 className="text-sm font-bold text-base-content">
챔피언 통계
</h2>
<p className="mt-1 text-[11px] text-base-content/35">
저장된 매치 기준으로 집계합니다. Riot API 갱신은 별도 큐 작업으로 분리 예정입니다.
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<input
value={championSearch}
onChange={(event) => setChampionSearch(event.target.value)}
placeholder="챔피언 검색"
className="border border-base-content/10 bg-transparent px-3 py-2 text-xs focus:outline-none focus:border-primary/30"
/>
<select
value={sortKey}
onChange={(event) => setSortKey(event.target.value as ChampionSortKey)}
className="border border-base-content/10 bg-transparent px-3 py-2 text-xs"
>
{(Object.keys(SORT_LABELS) as ChampionSortKey[]).map((key) => (
<option key={key} value={key}>
{SORT_LABELS[key]}순
</option>
))}
</select>
</div>
</div>
<ChampionStatsTable
rows={visibleChampionRows}
manifest={ddragon}
selectedChampionId={championId}
onChampionSelect={(nextChampionId) =>
updateSearch({ championId: nextChampionId })
}
/>
</section>
<section>
<div className="flex items-center justify-between gap-3 mb-3">
<h2 className="text-sm font-bold text-base-content">
매치 히스토리
</h2>
<span className="text-[11px] text-base-content/35">
최근 저장: {formatLastFetched(recentMatchesQuery.data?.pages[0]?.lastFetchedAt)}
</span>
</div>
{recentMatchesQuery.isLoading ? (
<div className="border border-base-content/10 bg-base-100 px-4 py-10 text-center text-sm text-base-content/35">
최근 경기를 불러오는 중...
</div>
) : matches.length === 0 ? (
<div className="border border-base-content/10 bg-base-100 px-4 py-10 text-center text-sm text-base-content/35">
조건에 맞는 최근 경기 기록이 없습니다.
</div>
) : (
<div className="space-y-2">
{matches.map((match) => (
<RecentMatchCard
key={match.matchId}
match={match}
manifest={ddragon}
/>
))}
</div>
)}
{recentMatchesQuery.hasNextPage && (
<button
type="button"
className="mt-3 w-full border border-base-content/15 bg-base-100 py-3 text-sm font-bold text-base-content/60 hover:border-primary/30 hover:text-primary disabled:opacity-40"
disabled={recentMatchesQuery.isFetchingNextPage}
onClick={() => recentMatchesQuery.fetchNextPage()}
>
{recentMatchesQuery.isFetchingNextPage ? '불러오는 중...' : '+ 더 보기'}
</button>
)}
</section>
</main>
);
}