diff --git a/123123.png b/123123.png new file mode 100644 index 00000000..8b2f0b30 Binary files /dev/null and b/123123.png differ diff --git a/Riot-소환사전적-플랜.md b/Riot-소환사전적-플랜.md new file mode 100644 index 00000000..77f55f27 --- /dev/null +++ b/Riot-소환사전적-플랜.md @@ -0,0 +1,628 @@ +# 소환사 전적 페이지 플랜 + +> **대상**: codex 가 이어서 작업 가능한 수준의 실행 플랜 +> **레포**: `/Users/dahyeon/source/lolympus-tournament-support` (pnpm workspace) +> **작성 기준**: 2026-04-26 +> **선행 작업**: `Riot-최근경기-플랜.md` (Throttle / RecentMatches / Scheduler / 시즌·region 인프라) 가 깔려 있어야 함. +> **참고 이미지**: `user-game-history/statistics.png`, `123123.png` (poro.gg 스타일 매치 카드) + +--- + +## 1. Context + +`AuctionPage.tsx`, `MatchDetailPage.tsx` 에서 소환사 프로필 클릭 → 신규 **개인 전적 페이지** 로 이동. + +핵심 정책 (사용자 결정 2026-04-26): + +1. **서버 가진 데이터만 표시.** 페이지 진입 시 Riot API 호출 0회. 야간 prefetch + 명시적 "갱신" 버튼 만 enrichment 트리거. +2. 즉각 갱신은 **전역 Riot API 작업 큐** 에 enqueue → consumer 가 throttle 통과시키며 직렬 처리. UI 는 "예상 ~초 후 갱신" 피드백. +3. 시즌 history 는 추후 구현. 다만 **schema/응답에 seasonId 자리** 미리 마련. + +표시 항목: +- **챔피언 통계** (`statistics.png`): 큐 탭 / 랭크 필터 / 시즌 필터 / 정렬 가능 표 +- **최근 전적** (`123123.png`, poro.gg 스타일): win/lose 좌측 라벨 · 챔프+룬+소주 · KDA · CS · KP% · 양 팀 5명 미니 · 펼치기 시 상세 + +--- + +## 2. 설계 + +### 2.1 라우팅 / 트리거 + +- 신규 라우트: `/users/:userId/history` +- query param: `?queue=summoners-rift&rank=solo&season=current` +- 클릭 트리거: AuctionPage TeamPanel 멤버 row, PlayerSpotlight 헤더, MatchDetailPage ParticipantRow — **소환사명+아이콘 묶음만** Link (행 전체 X — 입찰 버튼 충돌) +- ACL 없음 (외부 공유 OK — 선행 결정) + +### 2.2 큐 매핑 + +```ts +// apps/web/src/lib/riot-queue.ts (신규) + apps/api/src/modules/riot/riot-queue.constants.ts (신규) +export const RIOT_QUEUE_GROUPS = { + '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] } }, +} as const; +``` + +`랭크 전체 = solo ∪ flex`. `일반 = 400/430`. queueId 는 [queues.json](https://static.developer.riotgames.com/docs/lol/queues.json) 1차 기준 — §6.B 검증. + +### 2.3 enrichment 정책 — server-only + on-demand 큐잉 + +페이지 진입 시 **API 호출 0**. 다음 두 경로로만 데이터가 채워짐: + +| 경로 | 트리거 | 우선순위 | +|---|---|---| +| 야간 prefetch (선행 plan §3.8) | 03~07시 KST | low | +| 사용자 "갱신" 버튼 | 명시적 클릭 | high | +| 신규 RiotAccount 등록 | dakao 명령 | high (동기 — 큐 우회) | + +→ **서버 데이터만** 보여줌. 큐 미사용 데이터(예: 첫 방문 사용자, 한 번도 prefetch 안 된 큐) 는 빈 상태 placeholder + "갱신" 버튼 강조. + +#### schema 확장 + +```ts +// RiotAccount 에 추가 +matchIdsByQueueFetchedAt?: Map; // 큐별 마지막 list 페치 시각 +lastRefreshRequestedAt?: Date; // refresh budget 추적 +``` + +### 2.4 전역 Riot API 작업 큐 (핵심) + +#### 왜 Redis Stream (Garnet) + +NATS JetStream 과 비교 검토 결과 **Redis Stream 채택**: + +| 항목 | Redis Stream (Garnet) | NATS JetStream | +|---|---|---| +| 추가 셋업 | **0** (이미 사용 중) | stream/consumer 활성화 필요 | +| 클라이언트 코드 | `garnet.ts` 의 `xAdd/xReadGroup/xAck/xPending/xClaim` wrapping 재사용 | 신규 작성 | +| ack / redelivery | PEL + `xClaim` 기본 | 기본 | +| consumer group | 지원 | 지원 | +| 운영 부담 | Redis 모니터링만 | NATS + JetStream 둘 다 | + +→ 단일 작업 종류 + 우선순위 2단계 + dedup 워크로드에 Redis Stream 충분. 우리 `GarnetClient` 의 stream 메서드 그대로 활용. + +#### 스트림 구조 + +``` +stream: riot:queue:high # 사용자 갱신 요청 +stream: riot:queue:low # 야간 prefetch +consumer group: riot-refresh-worker (양 stream 공통) +``` + +- **우선순위 = stream 분리**. worker 한 사이클에서 high `xReadGroup` 먼저 → 비면 low `xReadGroup` (BLOCK 1s). +- **단일 active worker 인스턴스**. rate limit 자체가 글로벌 직렬화라 분산해도 의미 없음. Garnet `setStringIfAbsent('riot:worker:leader', ..., 60s)` 로 leader election, leader 만 loop. lease 갱신은 worker tick 마다. +- **PEL/xClaim 으로 crash recovery**: leader 가 죽으면 30분 idle 후 새 leader 가 PEL 메시지 claim → 재처리. + +#### 작업 단위 — sub-job 분할 (큐 그룹별 1 job) + +사용자가 `queueGroup='all'` 같은 다중 큐를 요청해도 **백엔드가 큐 그룹 단위로 sub-job 으로 쪼개 enqueue**. 이유: + +- 한 사용자 갱신이 큐를 길게 점유하지 않음 → fairness 향상 +- 큐 그룹 1개 끝나는 즉시 부분 결과 표시 가능 (소협 끝 → 소협 데이터부터 보임) +- ETA 표시가 자연스러움 ("소협 12초 / 칼바람 8초 / ... 합 36초") + +```ts +interface RefreshSubJob { + jobId: string; // uuid + parentJobId?: string; // 그룹 묶음 식별 (UI 진행률 합산용) + userId: string; + puuid: string; + region: RiotRegionalRoute; + platform: RiotPlatformRoute; + queueGroup: keyof typeof RIOT_QUEUE_GROUPS; // 'summoners-rift' 등 + queueIds: number[]; // 그룹 내 모든 큐 + requestedAt: number; + requestedBy?: string; + priority: 'high' | 'low'; +} +``` + +dedup 키: +- `riot:job:dedup::` NX EX 5분 +- 이미 있으면 기존 jobId 반환, 새 enqueue 안 함 + +#### 신규 모듈 + +``` +apps/api/src/modules/riot-job-queue/ + riot-job-queue.module.ts + riot-job-queue.service.ts # enqueue / dedup / status / ETA / parent 그룹 + riot-job-worker.service.ts # leader election + xReadGroup loop + riot-job-queue.types.ts + riot-job-queue.controller.ts # GET /riot/jobs/:jobId, /riot/jobs/stats +``` + +`RiotJobQueueService.enqueueRefresh(params: { puuid, userId, queueGroups: string[], priority, ... }): Promise` +- 입력 큐 그룹별 sub-job 생성 +- 각 sub-job dedup → 기존 또는 신규 publish (`xAdd`) +- 응답: + ```ts + interface EnqueueResult { + parentJobId: string; + subJobs: { jobId: string; queueGroup: string; alreadyQueued: boolean; etaSeconds: number; queuePosition: number }[]; + totalEtaSeconds: number; + } + ``` + +`RiotJobQueueService.getStatus(jobId): Promise` +- Garnet `riot:job:status:` (state, enqueuedAt, startedAt, finishedAt, error, etaSeconds) + +`RiotJobQueueService.getParentStatus(parentJobId): Promise` +- 모든 sub-job 합쳐서 진행률 (`done / total`) + 남은 ETA 계산 + +`RiotJobWorkerService`: +- leader 만 동작. follower 는 lease 만 polling. +- pseudo: + ```ts + while (alive) { + const msg = await garnet.readGroup('riot:queue:high', GROUP, consumer, '>', { count: 1, blockMs: 100 }); + const target = msg ?? await garnet.readGroup('riot:queue:low', GROUP, consumer, '>', { count: 1, blockMs: 1000 }); + if (!target) continue; + await processSubJob(target); // ensureFreshForQueue + 그룹 페치 dedup + await garnet.acknowledgeStream(stream, GROUP, target.id); + await refreshLeaderLease(); + } + ``` +- 작업 시작 → 끝 까지 RiotClientService 가 throttle 통과. 별도 sleep 없음. +- 완료/실패 시 status 업데이트 + Garnet pub `riot:refresh:events` 채널 publish → socket.io 게이트가 broadcast (§2.5.2 참고). +- EWMA 로 평균 작업 시간 갱신 (key: `riot:job:avg-seconds`). + +#### 운영자 controls + +- `GET /riot/jobs/stats` — high/low 큐 길이, 평균 처리 시간, 최근 실패율, 현재 leader instance id +- `POST /riot/jobs/drain` (admin) — 큐 비우기 + +### 2.5 UX 피드백 — 채택 정책 (사용자 결정) + +세 가지 권장안 모두 채택: **(1) Stale-while-revalidate + (2) Refresh broadcast + (3) 그룹 페치 dedup**. + +#### 2.5.1 Stale-while-revalidate + +- 페이지 진입 시 서버 데이터 **즉시 표시** (Riot API 호출 0). +- 동시에 백그라운드로 `enqueueRefresh({puuid, queueGroups: [현재 탭], priority: 'low', requestedBy: 'page-view'})` 자동 호출 — refresh budget 통과 시에만. +- 사용자가 "갱신" 버튼을 누르면 동일 enqueue 를 `priority: 'high'` 로 재발행 (dedup 으로 중복 방지, 단 priority 격상). +- 결과 도착 시 broadcast 로 자동 reload (§2.5.2). + +→ 사용자가 갱신을 의식하지 않아도 자연 신선화. 명시적 클릭은 "지금 당장 + high 우선순위" 의미. + +#### 2.5.2 Refresh broadcast (socket.io) + +- 기존 `useAuctionSocket` 패턴 재활용. 신규 namespace `/riot-refresh` 또는 같은 socket 의 `riot-refresh` event. +- 클라가 페이지 진입 시 `subscribe('puuid:')` join. +- worker 가 sub-job 완료 시 `emit('riot-refresh', { parentJobId, jobId, queueGroup, puuid, state })` broadcast. +- 같은 puuid 페이지를 보는 **모든 클라**가 React Query invalidate → 자동 reload. +- per-queue-group 단위 invalidate 라 부분 결과 점진 표시 가능 (소협 끝 → 소협 표/카드만 reload). + +#### 2.5.3 그룹 페치 dedup + +- worker 가 sub-job (puuid, queueGroup) 처리 시: + 1. `RiotRecentMatchesService.ensureFreshForQueue` 가 큐별 list call (그룹 N큐 면 N call) + 2. **detail call 은 그룹 내 모든 큐의 matchId 합집합에서 RiotMatch 미존재분만** 페치 — 큐 사이 중복 매치 dedup + 3. 같은 puuid 의 이미 처리된 sub-job(같은 parentJobId) 이 동일 detail 을 가져왔으면 skip +- 4개 그룹 동시 갱신 시 detail 호출량 ~30% 감소 추정. + +#### 2.5.4 "갱신" 클릭 흐름 + +``` +[갱신 버튼] 클릭 + │ + ├─→ POST /communities/:cid/users/:uid/refresh + │ body: { queueGroups: ['summoners-rift', ...], priority: 'high' } + │ resp: { parentJobId, subJobs: [{jobId, queueGroup, etaSeconds, queuePosition, alreadyQueued}], totalEtaSeconds } + │ + ├─→ 즉시 토스트: "갱신을 요청했어요. 약 36초 후 반영됩니다 (대기열 4번째)" + │ - alreadyQueued 면 "이미 요청 중입니다 (남은 시간 ~)" + │ + ├─→ socket.io 'riot-refresh' subscribe (parentJobId/puuid 필터) + │ - sub-job 완료 도착마다 해당 큐 그룹 React Query invalidate + │ + └─→ 모든 sub-job 완료 시 토스트 "갱신 완료" + 실패 시 토스트: "갱신 실패: . 잠시 후 다시 시도해 주세요." +``` + +#### 2.5.5 Refresh budget — 폭주 방지 + +- 사용자당 **5분에 1회** (`RiotAccount.lastRefreshRequestedAt` 검사). 단, page-view 로 자동 enqueue 된 low priority 는 별도 카운터 (사용자당 1시간 1회). +- 글로벌 high 큐 길이가 50 초과면 새 high enqueue 거부 (`429 { reason: 'queue-full', retryAfterSeconds }`) +- IP 단위 rate limit 은 Phase 후속. + +#### 2.5.6 빈 데이터 placeholder + +- 챔피언 통계 0 행: "아직 수집된 매치가 없습니다. [갱신 요청] 을 눌러 가져오세요." (Stale-while-revalidate 가 이미 백그라운드로 fetch 중이면 "갱신 중..." 으로 자동 변경) +- 최근 전적 0 건: 동일. +- 마지막 갱신 시각 항상 표시: "마지막 업데이트: 3시간 전" + +### 2.6 시즌 정책 (history 추후 구현, 설계 고려) + +#### 현재 + +- `Community.seasonStartedAt: Date?` (선행 plan) — 단일 시즌 경계. + +#### 미래 호환 schema 자리 (지금 추가) + +```ts +// schema.ts Community +seasons?: Array<{ + id: string; // ex: '2026-split-1' + label: string; // ex: '2026 시즌' + startedAt: Date; + endedAt?: Date; +}>; +// 'current' 시즌 = endedAt 없는 마지막 entry +``` + +본 plan 1차에서는 `seasons` 미사용, 응답에 `seasonId: 'current' | string` 만 노출. 추후 history 도입 시 dropdown 만 채우면 됨. + +#### API 응답에 미리 자리 잡기 + +```ts +interface ChampionStatsResponse { + // ... + season: { id: string; label: string; startedAt: string | null; endedAt: string | null }; +} +``` + +→ 클라 dropdown 이 `[{id: 'current', label: '현재 시즌'}]` 한 개만 받지만 구조는 list. 추후 backend 가 history 풀 때 client 코드 무수정. + +### 2.7 백엔드 aggregate API + +#### A. 챔피언 통계 + +``` +GET /communities/:cid/users/:uid/champion-stats + ?queueGroup=summoners-rift + &rank=solo|flex|all|normal + &seasonId=current (현재 'current' 만) +``` + +응답: +```ts +interface ChampionStatsResponse { + queueIds: number[]; + season: { id: 'current' | string; label: string; startedAt: string | null; endedAt: string | null }; + lastFetchedAt: string | null; // 큐별 fetchedAt 중 가장 오래된 값 + champions: ChampionStatsRow[]; + totals: ChampionStatsRow; +} + +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; +} +``` + +집계: MongoDB aggregation pipeline. `$match: {participantPuuids, queueId: {$in}, gameCreation: {$gte: seasonStartedAt}}` → `$project participant slice` → `$group by championId`. + +캐시: Garnet `riot:champstats::::` TTL 1h. + +#### B. 최근 전적 (페이지네이션) — poro.gg 카드 + +`poro.gg-html.txt` 분석 기준 카드 항목: + +- 좌측 라벨: `승리 / 패배 / 다시 둠(remake)` + 큐 종류 ("자유 랭크") + 날짜 ("4월 19일") + 게임 시간 ("28:52") +- 챔피언 아이콘(52px) + 챔피언 레벨 + 룬 키스톤 + 부 룬 스타일 + 소환사 주문 2개 +- KDA 큰 숫자 ("4 / 14 / 6") + **평점** ("0.71 평점") +- 우측 통계 컬럼: **킬 관여 %** + **CS** (분당 CS 병기) + **시야점수** + (제어와드 / 와드 설치 / 와드 파괴 아이콘 + 숫자) +- 아이템 6칸 + 트링킷 1칸 +- **자주 함께한 챔피언 / 자주 함께한 소환사** 2열 (각 5명, 미니 챔피언 14px + 소환사명) +- 우측 토글 버튼 "매치 상세 정보 열기" + +``` +GET /communities/:cid/users/:uid/recent-matches + ?queueGroup=summoners-rift + &rank=all + &championId=84 (선택, 챔피언 검색 필터) + &limit=10 + &cursor= +``` + +응답: +```ts +interface RecentMatchesResponse { + matches: RecentMatchView[]; + nextCursor: number | null; + lastFetchedAt: string | null; + season: { id: string; label: string; startedAt: string | null; endedAt: string | null }; +} + +interface RecentMatchView { + matchId: string; + queueId: number; + queueLabel: string; // '자유 랭크' 등 + gameCreation: number; + gameDuration: number; // 초 + win: boolean; + remake: boolean; // gameEndedInEarlySurrender 또는 duration < 240s + + // 본인 participant + championId: number; + championLevel: number; + teamPosition: string; // 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY' | '' + + kills: number; deaths: number; assists: number; + kda: number; // (k+a)/d, deaths=0 이면 (k+a) + rating: number; // 평점 — § 2.7.B.1 산식 + + totalCs: number; // totalMinionsKilled + neutralMinionsKilled + csPerMin: number; + killParticipation: number; // 0~100, 본인 (k+a) / 팀 총킬 + visionScore: number; + controlWardsBought: number; // visionWardsBoughtInGame + wardsPlaced: number; + wardsKilled: number; + damageDealtToChampions: number; + damageTaken: number; + goldEarned: number; + + items: number[]; // 6칸 (item0~5) + trinket: number; // item6 + summonerSpells: [number, number]; // summoner1Id, summoner2Id + perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + + // 양 팀 5명씩 미니 (poro.gg 우측 두 컬럼) + 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; + }>; + }>; +} +``` + +##### 2.7.B.1 평점 (rating) 산식 + +poro.gg/op.gg 의 정확한 산식은 비공개. 1차 근사: +``` +rating = 0.4 * normalize(kda) // KDA 기여 + + 0.2 * normalize(killParticipation) + + 0.2 * normalize(csPerMin) + + 0.1 * normalize(damageShare) // damage / 팀 총damage + + 0.1 * normalize(visionScore) // jungle/support 가중 +``` +- normalize 는 라인별 평균 대비 z-score → 0~10 사이 클램프 +- "Perfect" = deaths === 0 일 때 최대값 표시 (poro.gg 동일) +- 정확한 산식은 Phase 후속에서 운영자 캘리브레이션 + +#### B'. 최근 N게임 요약 박스 (poro.gg 헤더) + +이미지 상단의 "최근 20게임 전적 요약" 박스 응답: + +``` +GET /communities/:cid/users/:uid/recent-summary + ?queueGroup=summoners-rift + &rank=all + &championId=84 (선택, 검색 필터와 연동) + &limit=20 (기본 20) +``` + +```ts +interface RecentSummaryResponse { + windowSize: number; // 실제 사용된 매치 수 (≤ limit) + winRate: number; wins: number; losses: number; + streak: { type: 'win' | 'loss'; count: number }; // "2 연패" + kda: number; // 총합 기준 + avgKills: number; avgDeaths: number; avgAssists: number; + bestRating: { rating: number | 'Perfect'; kills: number; deaths: number; assists: number; matchId: string }; + positionRates: Partial>; // "비드 100%" 등 라인별 픽률 + topChampions: Array<{ // 자주 플레이하는 챔프 상위 3 + championId: number; + games: number; + winRate: number; // % + pickRate: number; // 본 큐 그룹 내 비율 % + avgRating: number; + }>; + lastFetchedAt: string | null; +} +``` + +서버 aggregate. Garnet 캐시 1h TTL. 키: `riot:recentsummary:::::`. + +#### C. 갱신 요청 + +``` +POST /communities/:cid/users/:uid/refresh + body: { queueGroups: string[], priority: 'high' | 'low' } +응답: EnqueueResult (§2.4) +또는 429 { reason: 'cooldown' | 'queue-full', retryAfterSeconds } +``` + +#### D. 작업 상태 + +``` +GET /riot/jobs/:jobId +응답: { state: 'queued' | 'processing' | 'completed' | 'failed', + etaSeconds: number, enqueuedAt, startedAt, finishedAt, error? } +``` + +### 2.8 인덱스 보강 + +`RiotMatch` schema 에 추가: +- `{ participantPuuids: 1, queueId: 1, gameCreation: -1 }` (queue 필터 + 정렬) + +--- + +## 3. 변경 사항 (파일 단위) + +### 3.1 백엔드 신규 + +``` +apps/api/src/modules/riot/riot-queue.constants.ts +apps/api/src/modules/riot-job-queue/ + riot-job-queue.module.ts + riot-job-queue.service.ts + riot-job-worker.service.ts + riot-job-queue.types.ts + riot-job-queue.controller.ts # GET /riot/jobs/:jobId, /riot/jobs/stats +apps/api/src/modules/match-history/ + match-history.module.ts + match-history.controller.ts # champion-stats, recent-matches, refresh + match-history.service.ts + match-history-cache.service.ts + match-history.types.ts +``` + +### 3.2 백엔드 수정 + +- `schema.ts`: + - `RiotAccount.matchIdsByQueueFetchedAt: Map` + - `RiotAccount.lastRefreshRequestedAt: Date` + - `Community.seasons` (자리만) + - `RiotMatch` 신규 인덱스 +- `riot-recent-matches.service.ts`: + - `ensureFreshForQueue({puuid, queueId, ttlMs, limit})` — worker 가 호출 +- `RiotJobWorkerService` 가 `RiotRecentMatchesService.ensureFreshForQueue` 직접 호출 +- `app.module.ts`: `RiotJobQueueModule`, `MatchHistoryModule` import + +### 3.3 프런트 신규 + +``` +apps/web/src/lib/riot-queue.ts +apps/web/src/pages/UserHistoryPage.tsx +apps/web/src/components/history/ + UserHistoryHeader.tsx # 프로필 + 마지막 갱신 + 갱신 버튼 + QueueTabs.tsx # 전체/솔로/자유/일반/칼바람/우르프/아레나 + RankFilter.tsx + SeasonSelector.tsx # 'current' 1개만 — 미래 list 호환 + ChampionSearchFilter.tsx # 챔피언 검색 (한글 초성/별명 매칭) — 클라사이드 + ddragon manifest + RecentSummaryBox.tsx # "최근 20게임 전적 요약" (승률/KDA/최고평점/포지션픽률/자주픽챔) + ChampionStatsTable.tsx # 정렬 가능 + RecentMatchesList.tsx # useInfiniteQuery + RecentMatchCard.tsx # poro.gg 스타일 (요약/펼치기) + RecentMatchDetail.tsx # 펼친 상세 (양 팀 5명 풀 정보) + RefreshButton.tsx # ETA 토스트 + socket invalidate + EmptyState.tsx +``` + +> 챔피언 검색: 한글/영문/초성/별명 매칭(가렌, ㄱㄹ, garen 등). ddragon manifest 의 `name` + 별명 사전(별도 정적 파일 `apps/web/src/lib/champion-aliases.ts`)으로 클라사이드 필터. 백엔드는 `championId` 만 받음. + +### 3.4 프런트 수정 + +- `App.tsx`: `} />` +- `api/hooks.ts`: `useChampionStats`, `useRecentMatches` (`useInfiniteQuery`), `useRefreshAccount`, `useJobStatus` +- `api/types.ts`: 응답 타입들 +- `AuctionPage.tsx`, `MatchDetailPage.tsx`: 소환사명+아이콘 묶음을 `` + +### 3.5 socket.io 통합 + +기존 `useAuctionSocket` 패턴 재활용. 신규 namespace `/riot-refresh` 권장 (auction socket 분리): +- 클라가 페이지 진입 시 `socket.emit('subscribe', { puuid })` +- worker 가 sub-job 완료 시 `gateway.to(`puuid:${puuid}`).emit('riot-refresh', { parentJobId, jobId, queueGroup, state })` +- 클라가 메시지 수신 시 해당 큐 그룹 React Query (`['champion-stats', puuid, queueGroup, ...]`, `['recent-matches', ...]`, `['recent-summary', ...]`) invalidate +- 같은 puuid 페이지를 보는 모든 클라가 동시에 새로고침됨 (broadcast 효과) + +--- + +## 4. 단위 테스트 + +- `riot-job-queue.service.spec.ts` + - dedup: 같은 (puuid, queueIds) enqueue 시 동일 jobId 반환 + - ETA 계산: 큐 길이 × avg → seconds + - refresh budget: 5분 안 재요청 시 429 +- `riot-job-worker.service.spec.ts` + - high subject 우선 처리, high 비면 low fetch + - throttle wait 시 작업 그대로 진행 +- `match-history.service.spec.ts` + - queueGroup → queueIds 매핑 + - aggregate 결과 sums/avgs 정확 + - season 필터 적용 (gameCreation < startedAt 제외) + - cursor 페이지네이션 nextCursor 정확 +- `match-history-cache.service.spec.ts` + - 같은 키 두 번째 호출 aggregate 0회 +- 프런트 + - `RefreshButton` 토스트 ETA 문구 + - `ChampionStatsTable` 정렬 토글 + - `RecentMatchCard` win/lose 색상, remake 표시 + +--- + +## 5. Rollout + +1. (PR-1) `riot-queue.constants.ts` + schema 확장 (`matchIdsByQueueFetchedAt`, `lastRefreshRequestedAt`, `Community.seasons` 자리, RiotMatch 인덱스 보강) + `ensureFreshForQueue` +2. (PR-2) `RiotJobQueueModule` (Redis Stream consumer + leader election + dedup + sub-job 분할 + status) + 테스트 +3. (PR-3) `MatchHistoryModule` champion-stats + recent-summary + Garnet 캐시 +4. (PR-4) recent-matches + cursor 페이지네이션 + 평점 산식 +5. (PR-5) refresh 엔드포인트 + budget + socket `/riot-refresh` namespace +6. (PR-6) 그룹 페치 dedup 로직 (worker 내부) +7. (PR-7) 프런트 라우트 + `UserHistoryPage` 골격 + `QueueTabs` + `RankFilter` + `SeasonSelector` +8. (PR-8) `RecentSummaryBox` + `ChampionStatsTable` (정렬) +9. (PR-9) `RecentMatchCard` (poro.gg 스타일) + `RecentMatchDetail` 펼치기 +10. (PR-10) `ChampionSearchFilter` (별명 사전 + 초성 매칭) +11. (PR-11) `RefreshButton` + Stale-while-revalidate 자동 enqueue + ETA 토스트 + socket invalidate +12. (PR-12) AuctionPage / MatchDetailPage 클릭 트리거 +13. (PR-13) 운영 모니터링 (큐 길이 / aggregate 응답 시간 / Garnet hit / leader 상태) + +--- + +## 6. 추가 고려사항 + +### 확정 (사용자 결정 2026-04-26) + +- **서버 데이터만 표시**: 페이지 진입 시 Riot API 호출 0회 +- **전역 작업 큐**: **Redis Stream (Garnet)** — high/low stream 분리 + dedup + leader election + PEL/xClaim 재처리 +- **작업 단위**: queueGroup 단위 sub-job 분할 (한 사용자가 큐 길게 점유 X) +- **UX 정책**: (1) Stale-while-revalidate + (2) Refresh broadcast + (3) 그룹 페치 dedup 모두 채택 +- **Refresh budget**: 5분당 1회 high, 1시간당 1회 low(자동) +- **카드 스타일**: poro.gg (`poro.gg-html.txt` 분석 기준 — 평점/킬관여/시야/와드/자주함께한 챔피언·소환사 포함) +- **챔피언 검색 필터**: 클라사이드 (한글/영문/초성/별명) +- **시즌 history**: 본 plan 1차 미구현, schema/응답에 자리만 마련 + +### 미결 (가벼운 확인 권장) + +#### A. 평점 산식 캘리브레이션 + +§2.7.B.1 의 1차 근사 가중치는 추측. 실제 사용자 데이터로 분포 확인 후 조정 필요. 운영 후 Phase 후속에서 처리. + +#### B. 큐 매핑 검증 + +`RIOT_QUEUE_GROUPS` 의 큐 id 는 [queues.json](https://static.developer.riotgames.com/docs/lol/queues.json) 1차 추정. 운영 사용자 데이터로 검증 필요. + +#### C. Refresh 폭주 시나리오 + +큐가 길 때 "현재 갱신 요청이 많습니다 (대기 12분)" 표시 + 야간 prefetch 안내. 너무 길면 갱신 자체를 비활성화. + +#### D. socket.io 가드 + +`/riot-refresh` namespace 가 외부 공개라 puuid subscribe 가 무제한이면 broadcast 비대화 가능. 동일 socket 당 max subscribe 수 제한 (예: 5) 추가 권장. + +### 추후 (Phase 후속) + +- 시즌 history 본격 도입 (`Community.seasons` 활용 + dropdown) +- 평점 산식 캘리브레이션 +- IP 단위 rate limit +- admin 페이지 (큐 모니터링 / drain) +- aggregation 결과 mat-view (큐가 매우 길어질 때) + +--- + +## 7. Done 정의 + +- AuctionPage 멤버 / PlayerSpotlight, MatchDetailPage 참가자 소환사명 클릭 → `/users/:userId/history` 이동 +- 페이지에 큐 7탭(전체/솔로/자유/일반/칼바람/우르프/아레나) + 챔피언 검색 + 시즌 dropdown(현재 1개) + 최근 N게임 요약 박스 + 챔피언 통계 표 + 최근 전적 무한 스크롤(poro.gg 카드) +- 페이지 진입 시 **Riot API 호출 0회** (서버 로그로 확인) +- 페이지 진입 시 자동 백그라운드 enqueue (low priority) — 1시간 budget 안에서만 +- "갱신" 클릭 시 ETA 토스트 ("약 ~초 후 반영, 대기열 N번째") + sub-job 완료 도착마다 해당 큐 그룹 React Query invalidate (점진 표시) +- 같은 puuid 페이지 보는 다른 클라도 socket broadcast 로 자동 reload +- 같은 사용자 5분 안 high 재요청 시 429 cooldown +- Redis Stream worker 1 인스턴스만 active (leader election 동작), 큐 길이/처리 시간 로그 +- 그룹 페치 dedup: 4개 큐 그룹 동시 갱신 시 detail 호출 중복 0건 (로그 metric) +- 챔피언 통계 컬럼 정렬 토글 (게임수 / 승률 / KDA / CS) +- 챔피언 검색 input 에 "ㄱㄹ" 입력 시 가렌·갈리오·갱플랭크 등 hits +- 같은 (puuid, 큐, 랭크, 시즌) 1h 안 재요청 시 aggregation 0회 (Garnet hit) +- `Community.seasons` schema 자리 추가 (1차 empty, 응답 `season.id = 'current'` 고정) +- 단위 테스트 통과 (sub-job 분할 / leader election / 그룹 페치 dedup / 평점 산식 / 챔피언 검색 매칭) diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts index b63ab722..fe01b00c 100644 --- a/apps/api/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -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, diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index a7ad29b0..4b05a2fa 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -176,6 +176,8 @@ export interface RiotAccount extends MongooseTimestamps { // Riot matchId 참조 (원본은 RiotMatch 컬렉션에 저장) matchIds: string[]; matchIdsFetchedAt?: Date; + matchIdsByQueueFetchedAt?: Map; + 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; @@ -468,6 +478,8 @@ const RiotAccountSubSchema = new Schema( 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( riotPlatform: { type: String }, riotRegion: { type: String }, seasonStartedAt: { type: Date }, + seasons: { + type: [ + new Schema( + { + 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( ); RiotMatchSchema.index({ participantPuuids: 1, gameCreation: -1 }); +RiotMatchSchema.index({ participantPuuids: 1, queueId: 1, gameCreation: -1 }); const MatchParticipantSubSchema = new Schema( { diff --git a/apps/api/src/modules/match-history/match-history.controller.ts b/apps/api/src/modules/match-history/match-history.controller.ts new file mode 100644 index 00000000..c42c2bdc --- /dev/null +++ b/apps/api/src/modules/match-history/match-history.controller.ts @@ -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; + } +} diff --git a/apps/api/src/modules/match-history/match-history.module.ts b/apps/api/src/modules/match-history/match-history.module.ts new file mode 100644 index 00000000..92b9173d --- /dev/null +++ b/apps/api/src/modules/match-history/match-history.module.ts @@ -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 {} diff --git a/apps/api/src/modules/match-history/match-history.service.ts b/apps/api/src/modules/match-history/match-history.service.ts new file mode 100644 index 00000000..43a9644c --- /dev/null +++ b/apps/api/src/modules/match-history/match-history.service.ts @@ -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 { + 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 { + 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(); + + 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 { + 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 { + 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 { + 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 { + if (params.queueIds.length === 0) return []; + const RiotMatchModel = await this.connectionService.getModel('riotMatch'); + const gameCreation: Record = {}; + if (params.context.seasonStartedAt) { + gameCreation.$gte = params.context.seasonStartedAt.getTime(); + } + if (params.cursor) gameCreation.$lt = params.cursor; + + const query: Record = { + 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((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> { + const counts = new Map(); + 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>; + } + + private resolveTopChampions(views: RecentMatchView[]): RecentSummaryResponse['topChampions'] { + const byChampion = new Map(); + 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; + } +} diff --git a/apps/api/src/modules/match-history/match-history.types.ts b/apps/api/src/modules/match-history/match-history.types.ts new file mode 100644 index 00000000..d553c1ca --- /dev/null +++ b/apps/api/src/modules/match-history/match-history.types.ts @@ -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>; + 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; + }>; + }>; +} diff --git a/apps/api/src/modules/riot/riot-queue.constants.ts b/apps/api/src/modules/riot/riot-queue.constants.ts new file mode 100644 index 00000000..70b3ae05 --- /dev/null +++ b/apps/api/src/modules/riot/riot-queue.constants.ts @@ -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; +} + +export const RIOT_QUEUE_GROUPS: Record = { + 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 = { + 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'; +} diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 9445c24e..f01cfd1e 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -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() { } /> } /> } /> + } /> diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts index 3f96aa8a..52194b35 100644 --- a/apps/web/src/api/hooks.ts +++ b/apps/web/src/api/hooks.ts @@ -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 = {}, +) { + 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( + `/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( + 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( + 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( + 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], diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index 4513b564..02a5d7b2 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -247,3 +247,146 @@ export interface DdragonManifest { champions: Record; 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>; + 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; +} diff --git a/apps/web/src/pages/AuctionPage.tsx b/apps/web/src/pages/AuctionPage.tsx index d0cae437..e4317e7a 100644 --- a/apps/web/src/pages/AuctionPage.tsx +++ b/apps/web/src/pages/AuctionPage.tsx @@ -235,19 +235,24 @@ function TeamPanel({ ) : ( team.members.map((member) => (
-
- -
-
- - {member.summonerName} - -
+ +
+ +
+
+ + {member.summonerName} + +
+ {member.cost} @@ -285,18 +290,24 @@ function PlayerSpotlight({
-
+ -
+
-

+ {player.summonerName} -

+ #{player.tag} diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index e60de37b..69e30246 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -100,7 +100,10 @@ function ParticipantRow({ {index + 1} -
+
- + {participant.summonerName} #{participant.tag}
-
+ diff --git a/apps/web/src/pages/UserHistoryPage.tsx b/apps/web/src/pages/UserHistoryPage.tsx new file mode 100644 index 00000000..d87b168a --- /dev/null +++ b/apps/web/src/pages/UserHistoryPage.tsx @@ -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 = { + 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 ( + + ); +} + +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 ( +
+ {iconUrl ? ( + {displayName} + ) : null} +
+ ); +} + +function SummaryCard({ + label, + value, + sub, +}: { + label: string; + value: React.ReactNode; + sub?: React.ReactNode; +}) { + return ( +
+
+ {label} +
+
+ {value} +
+ {sub &&
{sub}
} +
+ ); +} + +function ChampionStatsTable({ + rows, + manifest, + selectedChampionId, + onChampionSelect, +}: { + rows: ApiChampionStatsRow[]; + manifest: DdragonManifest | null | undefined; + selectedChampionId?: number; + onChampionSelect: (championId: number | null) => void; +}) { + if (rows.length === 0) { + return ( +
+ 조건에 맞는 챔피언 통계가 아직 없습니다. +
+ ); + } + + return ( +
+
+ + + + + + + + + + + + + + + + + + {rows.map((row) => { + const displayName = + championDisplayName(manifest, row.championId) ?? + String(row.championId); + const selected = selectedChampionId === row.championId; + return ( + + + + + + + + + + + + + + ); + })} + +
챔피언승률게임승/패KDA킬데스어시스트멀티킬CS필터
+
+ + + {displayName} + +
+
+ {row.winRate}% + + {row.games} + + {row.wins} /{' '} + {row.losses} + + {row.kda} + + {row.totalKills} + + {row.totalDeaths} + + {row.totalAssists} + + {row.doubleKills}/{row.tripleKills}/{row.quadraKills}/{row.pentaKills} + + {row.avgCs} · {row.avgCsPerMin}/m + + +
+
+
+ ); +} + +function ItemGrid({ + match, + manifest, +}: { + match: ApiRecentMatchView; + manifest: DdragonManifest | null | undefined; +}) { + const slots = [...match.items, match.trinket]; + return ( +
+ {slots.map((itemId, index) => { + const url = itemIconUrl(manifest, itemId); + return ( +
+ {url ? ( + + ) : null} +
+ ); + })} +
+ ); +} + +function TeamMini({ + match, + manifest, +}: { + match: ApiRecentMatchView; + manifest: DdragonManifest | null | undefined; +}) { + return ( +
+ {match.teams.map((team) => ( +
+ {team.participants.map((participant) => { + const championName = + championDisplayName(manifest, participant.championId) ?? + String(participant.championId); + return ( +
+ + + {participant.gameName || championName} + +
+ ); + })} +
+ ))} +
+ ); +} + +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 ( +
+
+
+
+ {match.remake ? '다시하기' : match.win ? '승리' : '패배'} +
+
+ {match.queueLabel} +
+
+ {formatDate(match.gameCreation)} +
+
+ {formatDuration(match.gameDuration)} +
+
+ +
+ +
+
+ {championName} +
+
+ Lv.{match.championLevel} ·{' '} + {(LANE_LABELS[match.teamPosition] ?? match.teamPosition) || '포지션 없음'} +
+
+ 스펠 {match.summonerSpells.join(' / ')} +
+
+
+ +
+
+ {match.kills} + / + {match.deaths} + / + {match.assists} +
+
+ {match.deaths === 0 ? 'Perfect' : `${match.kda} 평점`} +
+
+ 킬 관여 {match.killParticipation}% +
+
+ +
+
+
+ CS {match.totalCs}{' '} + ({match.csPerMin}/m) +
+
+ 시야 {match.visionScore}{' '} + 제어와드 {match.controlWardsBought} +
+
+ 피해량{' '} + + {match.damageDealtToChampions.toLocaleString()} + +
+
+
+ + +
+
+ +
+
+
+
+
+ ); +} + +export default function UserHistoryPage() { + const { userId } = useParams(); + const [searchParams, setSearchParams] = useSearchParams(); + const [championSearch, setChampionSearch] = useState(''); + const [sortKey, setSortKey] = useState('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>) { + 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 ( +
+ + `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. + +
+ ); + } + + if (profileQuery.isLoading) { + return ( +
+ + 소환사 전적을 불러오는 중... + +
+ ); + } + + if (profileQuery.error || !profile) { + return ( +
+

소환사를 찾을 수 없습니다

+ + 홈으로 돌아가기 + +
+ ); + } + + return ( +
+ + ← 목록으로 + + +
+
+
+ +
+
+
+

+ {profile.gameName} +

+ + #{profile.tagLine} + +
+
+ Lv.{profile.summonerLevel} + {primaryTier ? ( + + {formatTierLabel(primaryTier)} {primaryTier.leaguePoints}LP + + ) : ( + 랭크 정보 없음 + )} + 시즌: {profile.season.label} + 최근 저장: {formatLastFetched(profile.lastFetchedAt)} +
+
+
+ 이 페이지는 저장된 경기 DB만 조회합니다. +
+ 화면 진입 시 Riot Match API 호출은 없습니다. +
+
+
+ +
+
+ {QUEUE_GROUP_TABS.map((tab) => ( + updateSearch({ queueGroup: tab.value, championId: null })} + > + {tab.label} + + ))} +
+
+
+ {RANK_FILTER_TABS.map((tab) => ( + updateSearch({ rank: tab.value, championId: null })} + > + {tab.label} + + ))} +
+ {selectedChampionName && ( + + )} + {profile.seasons.length > 0 && ( + + )} +
+
+ +
+

+ 최근 {summaryQuery.data?.windowSize ?? 20}게임 전적 요약 +

+
+ + + + +
+
+ 자주 플레이한 챔피언 +
+
+ {(summaryQuery.data?.topChampions ?? []).map((champion) => ( + + ))} + {(summaryQuery.data?.topChampions ?? []).length === 0 && ( + 기록 없음 + )} +
+
+
+
+ +
+
+
+

+ 챔피언 통계 +

+

+ 저장된 매치 기준으로 집계합니다. Riot API 갱신은 별도 큐 작업으로 분리 예정입니다. +

+
+
+ 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" + /> + +
+
+ + updateSearch({ championId: nextChampionId }) + } + /> +
+ +
+
+

+ 매치 히스토리 +

+ + 최근 저장: {formatLastFetched(recentMatchesQuery.data?.pages[0]?.lastFetchedAt)} + +
+ + {recentMatchesQuery.isLoading ? ( +
+ 최근 경기를 불러오는 중... +
+ ) : matches.length === 0 ? ( +
+ 조건에 맞는 최근 경기 기록이 없습니다. +
+ ) : ( +
+ {matches.map((match) => ( + + ))} +
+ )} + + {recentMatchesQuery.hasNextPage && ( + + )} +
+
+ ); +} diff --git a/poro.gg-html.txt b/poro.gg-html.txt new file mode 100644 index 00000000..1bb64a02 --- /dev/null +++ b/poro.gg-html.txt @@ -0,0 +1,623 @@ +
매치 히스토리
+ + +
+ 최근 20게임 전적 요약 +
승률
50%

10승 10패 2 연패

평점
+ 1.89 +

+ 6.9 / 7.3 / + 7.0 +

최고 평점
+ Perfect +

+ 7 / + 0 / + 1 +

+ 포지션 픽률 +
미드 100%
+ 자주 플레이한 챔피언 +
아리

57% (4승 3패)

2.28 평점

르블랑

40% (2승 3패)

2.19 평점

신드라

75% (3승 1패)

1.92 평점

+ + + +
패배
자유 랭크 26:52 22시간 전
14
선제공격
+ + 마법
+ 4 / + 14 / + 6 + 0.71 평점
킬 관여 48% CS 157 (5.8/m) 시야점수 9
제어와드 구매 수 0
와드 설치 수 6
와드 파괴 수 0
패배
자유 랭크 33:23 4월 19일
승리
자유 랭크 28:02 4월 19일
17
감전
+ + 마법
+ 11 / + 4 / + 10 + 5.25 평점
킬 관여 68% CS 221 (7.9/m) 시야점수 13
제어와드 구매 수 1
와드 설치 수 6
와드 파괴 수 2
더블 킬
승리
자유 랭크 40:58 4월 19일
18
선제공격
+ + 결의
+ 14 / + 7 / + 10 + 3.43 평점
킬 관여 69% CS 292 (7.1/m) 시야점수 42
제어와드 구매 수 1
와드 설치 수 15
와드 파괴 수 9
트리플 킬
패배
자유 랭크 22:14 4월 19일
13
감전
+ + 마법
+ 4 / + 7 / + 1 + 0.71 평점
킬 관여 36% CS 141 (6.3/m) 시야점수 10
제어와드 구매 수 0
와드 설치 수 3
와드 파괴 수 1
패배
자유 랭크 28:00 4월 12일
패배
자유 랭크 33:36 4월 12일
16
신비로운 유성
+ + 지배
+ 3 / + 13 / + 9 + 0.92 평점
킬 관여 57% CS 216 (6.4/m) 시야점수 20
제어와드 구매 수 0
와드 설치 수 10
와드 파괴 수 1
승리
자유 랭크 37:04 4월 12일
18
콩콩이 소환
+ + 영감
+ 2 / + 9 / + 14 + 1.78 평점
킬 관여 52% CS 269 (7.3/m) 시야점수 19
제어와드 구매 수 0
와드 설치 수 9
와드 파괴 수 3
승리
자유 랭크 33:08 4월 12일
17
신비로운 유성
+ + 결의
+ 8 / + 5 / + 8 + 3.20 평점
킬 관여 47% CS 214 (6.5/m) 시야점수 24
제어와드 구매 수 0
와드 설치 수 11
와드 파괴 수 3
승리
자유 랭크 31:11 4월 12일
16
감전
+ + 마법
+ 18 / + 3 / + 4 + 7.33 평점
킬 관여 55% CS 209 (6.7/m) 시야점수 26
제어와드 구매 수 0
와드 설치 수 6
와드 파괴 수 7
트리플 킬
패배
자유 랭크 28:56 4월 7일
승리
자유 랭크 29:42 4월 7일
승리
자유 랭크 34:53 4월 7일
18
신비로운 유성
+ + 정밀
+ 9 / + 10 / + 10 + 1.90 평점
킬 관여 44% CS 229 (6.6/m) 시야점수 29
제어와드 구매 수 1
와드 설치 수 12
와드 파괴 수 3
더블 킬
패배
자유 랭크 27:50 4월 7일
15
감전
+ + 마법
+ 4 / + 4 / + 5 + 2.25 평점
킬 관여 43% CS 200 (7.2/m) 시야점수 18
제어와드 구매 수 0
와드 설치 수 6
와드 파괴 수 2
승리
자유 랭크 22:49 4월 7일
14
감전
+ + 마법
+ 1 / + 3 / + 3 + 1.33 평점
킬 관여 13% CS 170 (7.5/m) 시야점수 12
제어와드 구매 수 0
와드 설치 수 5
와드 파괴 수 1
승리
자유 랭크 15:35 4월 7일
12
감전
+ + 마법
+ 7 / + 0 / + 1 + Perfect 평점
킬 관여 44% CS 135 (8.7/m) 시야점수 10
제어와드 구매 수 0
와드 설치 수 5
와드 파괴 수 1
더블 킬
패배
자유 랭크 30:49 4월 4일
더블 킬
승리
자유 랭크 42:30 4월 4일
패배
자유 랭크 31:38 4월 1일
16
감전
+ + 마법
+ 3 / + 10 / + 9 + 1.20 평점
킬 관여 57% CS 224 (7.1/m) 시야점수 26
제어와드 구매 수 0
와드 설치 수 11
와드 파괴 수 3
패배
자유 랭크 27:41 4월 1일
15
감전
+ + 마법
+ 5 / + 3 / + 2 + 2.33 평점
킬 관여 54% CS 205 (7.4/m) 시야점수 17
제어와드 구매 수 1
와드 설치 수 6
와드 파괴 수 3
더블 킬
\ No newline at end of file diff --git a/poro.gg.png b/poro.gg.png new file mode 100644 index 00000000..ec2d87ef Binary files /dev/null and b/poro.gg.png differ diff --git a/user-game-history/history1.png b/user-game-history/history1.png new file mode 100644 index 00000000..b0b368a8 Binary files /dev/null and b/user-game-history/history1.png differ diff --git a/user-game-history/statistics.png b/user-game-history/statistics.png new file mode 100644 index 00000000..006d8183 Binary files /dev/null and b/user-game-history/statistics.png differ