Files
lolympus-tournament-support/커뮤니티-내전-전적.md
T
2026-04-27 18:55:04 -07:00

451 lines
22 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 커뮤니티 내전 전적 / LCK 스타일 통계 페이지
## Context
현재 상태:
- 내전(Internal Match) 데이터는 `Match.result.games[]` 에 저장되고, 각 게임은 `Match.result.riotMatchIds[]` 를 통해 `RiotMatch.raw`(Match-V5 원본) 와 연결됨. (`Tournament-Result-수집-플랜.md` 의 결과 수집 워커가 이 자리를 채움)
- 그러나 사용자가 "어떤 내전들이 있었고, 우리 커뮤니티 안에서 누가 어떻게 했는지" 를 한눈에 볼 페이지가 없음.
- 또한 `apps/web/src/pages/UserHistoryPage.tsx` 의 큐 탭(소협/칼바람/우르프/아레나) 에서 **내전을 별도로 볼 수 없음**. 내전은 queueId=0 (custom) 이라 일반 큐 필터에 잡히지 않고 일반 솔로/자유랭크와 섞여 무의미함.
추가하려는 것:
1. 신규 **커뮤니티 통계 페이지** (`/communities/:cid/internal-stats`):
- 모든 내전 카드 리스트 (시즌/기간 필터)
- 유저별 누적 통계 leaderboard (전적/KDA/라인별)
- LCK 스타일 팀 통계 카드 (진영별 승률, top KDA, most kill, top team GPM, top kill participation, best farm)
- 외부 공유 OK (인증 불필요)
2. 기존 **`UserHistoryPage` 에 "내전" 탭** (큐 그룹 5번째 탭) — 해당 사용자가 참여한 내전 챔피언 통계 + 게임 카드
3. (Phase 후속) **페어 통계** (같은팀/상대팀 X 와 함께 시 승률) — 데이터 모델/응답에 자리만 마련
## 결정사항 (사용자 결정 2026-04-27)
- **권한**: 외부 공유 OK. 인증/role 가드 없음. UserHistoryPage 와 동일 정책.
- **데이터 소스**: `Match.result.games[]` (이미 매핑된 우리 userId/팀/챔피언) + `RiotMatch.raw` (`info.participants[]` 의 GPM/KP/데미지/시야/farm) 조합. **Garnet 1h TTL 캐시** 로 aggregation 비용 보호.
- **1차 PR 스코프**: 매치 목록 + 시즌/기간 필터 + 유저별 누적 leaderboard + 팀 통계 카드. **페어 통계는 후속 PR**.
- **내전 탭 위치**: `UserHistoryPage` 큐 그룹 탭 5번째 (`소환사의협곡 / 칼바람 / 우르프 / 아레나 / 내전`). 내전 탭 활성 시 랭크 필터(솔로/자유/일반) 자동 숨김.
## 데이터 소스 / 식별
### 내전 식별 기준
```ts
// 통계 대상 매치
{
communityId: <cid>,
status: 'finished',
'result.games': { $exists: true, $ne: [] },
}
```
`result.games[].riotMatchId` 가 있는 게임만 raw lookup. 매핑 실패한 게임(빈 슬롯)은 통계 제외.
### Match.result.games 와 RiotMatch.raw 의 역할 분담
| 필드 | 출처 | 비고 |
| ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | ---------------------------------------------- |
| `userId`, `side(blue/red)`, `championId`, `kills/deaths/assists`, `win` | `Match.result.games[].participants[]` | 우리 userId 매핑 완료 — 1차 키 |
| `gameDuration`, `gameCreation` | `Match.result.games[]` | 정렬·기간 필터 |
| `goldEarned`, `totalMinionsKilled + neutralMinionsKilled`, `damageDealtToChampions`, `visionScore`, `wardsPlaced/Killed`, `teamPosition` | `RiotMatch.raw.info.participants[]` (puuid 매칭) | LCK 통계용 추가 필드 |
| 팀 단위: `objectives.baron/dragon/tower`, `team.win`, 팀 총킬 | `RiotMatch.raw.info.teams[]` | 진영별 승률 / 팀 GPM / kill participation 분모 |
### Aggregation 한 흐름
```
Match (cid, status=finished, period filter)
→ $unwind result.games
→ $lookup riot_match (riotMatchId 매칭, 단 1건)
→ $project { game: result.games, raw: riot_match.raw, communityMembers: $teams }
→ $unwind game.participants
→ $lookup raw.info.participants (puuid 매칭)
→ $group by ... (각 통계마다 다름)
```
→ **공통 베이스 aggregation 결과** 를 Garnet 1h TTL 캐시. 그 위에서 다양한 통계 카드는 client-side reshape.
## 백엔드
### 신규 모듈
```
apps/api/src/modules/community-stats/
community-stats.module.ts
community-stats.service.ts # aggregation pipelines
community-stats-cache.service.ts # Garnet 1h TTL wrapper (key 패턴 분리)
community-stats.controller.ts
community-stats.types.ts
pair-stats.util.ts # (Phase 후속) 페어 카운팅
```
기존 `MatchHistoryModule` 의 캐시·aggregation 패턴 그대로 답습:
- `match-history-cache.service.ts` 와 동일한 key prefix 컨벤션 (`riot:communitystats:<cid>:...`)
- `MatchHistoryService.getChampionStats` 의 `$match → $lookup → $unwind → $group` 패턴 재활용
### 엔드포인트 (모두 `@AllowPublicAccess`)
| Method | Path | 용도 |
| ------ | ------------------------------------------------- | ----------------------------------------------------------------------------- |
| GET | `/communities/:cid/internal-stats/matches` | 내전 카드 리스트 (cursor 페이지네이션) |
| GET | `/communities/:cid/internal-stats/leaderboard` | 유저별 누적 통계 (전적/KDA/라인별/챔프 다양성) |
| GET | `/communities/:cid/internal-stats/team-insights` | LCK 스타일 카드 (진영별 승률, top KDA, most kill, top GPM, top KP, best farm) |
| GET | `/communities/:cid/internal-stats/match/:matchId` | 매치별 게임 detail (게임마다 양 팀 5명 풀 통계 표) |
| GET | `/users/:userId/internal-history` | 사용자 단위 내전 통계 (UserHistoryPage 의 "내전" 탭용) |
공통 query: `?seasonId=current|<id>&from=<ISO>&to=<ISO>&championId=<num>`
#### 응답 schema (요지)
```ts
// /matches
interface InternalMatchListResponse {
matches: InternalMatchCardView[];
nextCursor: number | null;
season: SeasonRef; // {id, label, startedAt, endedAt}
}
interface InternalMatchCardView {
matchId: string;
title: string;
scheduledAt: string;
status: "finished" | "in-progress";
gameCount: number;
blueScore: number;
redScore: number;
winnerSide?: "blue" | "red";
games: Array<{
gameNumber: number;
riotMatchId: string | null;
winnerSide: "blue" | "red" | null;
gameDuration: number;
}>;
teams: Array<{
side: "blue" | "red";
name: string;
members: Array<{
userId: string;
summonerName: string;
profileIconId: number;
}>;
}>;
}
// /leaderboard
interface LeaderboardResponse {
rows: LeaderboardRow[]; // 정렬 가능
season: SeasonRef;
}
interface LeaderboardRow {
userId: string;
summonerName: string;
profileIconId: number;
games: number;
wins: number;
losses: number;
winRate: number;
totalKills: number;
totalDeaths: number;
totalAssists: number;
kda: number;
avgGoldPerMin: number;
avgKillParticipation: number;
avgCsPerMin: number;
avgDamageShare: number;
avgVisionScore: number;
byLane: Partial<
Record<RiotLane, { games: number; wins: number; kda: number }>
>;
topChampions: Array<{ championId: number; games: number; winRate: number }>;
}
// /team-insights
interface TeamInsightsResponse {
season: SeasonRef;
sideWinRate: {
blue: number;
red: number;
bluePicks: number;
redPicks: number;
};
topKda: LeaderHighlight; // 최소 게임 수 임계 적용 (default 5)
mostKills: LeaderHighlight; // 누적 킬
topTeamGpm: LeaderHighlight;
topKillParticipation: LeaderHighlight;
bestFarm: LeaderHighlight; // 분당 CS
// (페어 통계는 미포함 — Phase 후속)
}
interface LeaderHighlight {
metric: number;
userId: string;
summonerName: string;
championId?: number;
matchId?: string; // single-game 기록일 때
isSingleGame: boolean; // false면 누적 평균
}
// /match/:matchId
interface InternalMatchDetailResponse {
match: InternalMatchCardView;
games: Array<{
gameNumber: number;
riotMatchId: string;
gameCreation: number;
gameDuration: number;
teams: Array<{
side: "blue" | "red";
win: boolean;
objectives: { baron: number; dragon: number; tower: number };
participants: Array<{
userId: string | null; // 외부 puuid 면 null
summonerName: string;
side: "blue" | "red";
teamPosition: string;
championId: number;
kills: number;
deaths: number;
assists: number;
cs: number;
csPerMin: number;
gold: number;
gpm: number;
damageDealtToChampions: number;
damageShare: number;
killParticipation: number;
visionScore: number;
items: number[];
trinket: number;
summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
win: boolean;
}>;
}>;
}>;
}
```
### 캐시 키 / TTL
```
riot:communitystats:matches:<cid>:<seasonId>:<from?>:<to?>:<cursor?> # 1h
riot:communitystats:leaderboard:<cid>:<seasonId>:<from?>:<to?> # 1h
riot:communitystats:teamInsights:<cid>:<seasonId>:<from?>:<to?> # 1h
riot:communitystats:matchDetail:<matchId> # 24h (불변)
riot:userInternalStats:<userId>:<cid>:<seasonId>:<from?>:<to?> # 1h
```
매치가 새로 finished 될 때 invalidate: `community-stats.service` 가 `match.service` 의 finished 전환 직후 cache prefix delete (`riot:communitystats:*:<cid>:*`). Garnet `scanIterator + del`.
### 시즌 / 기간 필터
- `seasonId='current'` 기본. `Community.seasonStartedAt` 활용 (선행 plan 의 자리 그대로). `from = seasonStartedAt`.
- `seasonId='all'` 시 전체.
- 추가로 `from`/`to` query param 으로 임의 기간 override.
- `Community.seasons[]` schema 자리는 선행 plan 에서 마련됨 — 본 plan 응답에 `season: SeasonRef` 형태로 노출.
## 프런트
### 신규 페이지 `/communities/:cid/internal-stats`
```
apps/web/src/pages/CommunityInternalStatsPage.tsx
apps/web/src/components/community-stats/
CommunityStatsHeader.tsx # 시즌 셀렉터 + 기간 picker
TeamInsightsGrid.tsx # 6 카드 (진영별 / top KDA / most kill / top GPM / top KP / best farm)
LeaderboardTable.tsx # 정렬 가능
InternalMatchList.tsx # 무한 스크롤 카드
InternalMatchCard.tsx # 매치 1건 — 클릭 시 detail
EmptyState.tsx
```
레이아웃:
```
┌────────────────────────────────────────────┐
│ ← 커뮤니티 │
├────────────────────────────────────────────┤
│ [2026 시즌 ▾] [기간: 전체 ▾] │
├────────────────────────────────────────────┤
│ 팀 인사이트 (LCK 스타일) │
│ ┌─진영별 승률─┐ ┌─top KDA─┐ ┌─most kill─┐ │
│ │ 블루 54% │ │ 6.2 │ │ 312 (홍길동)│ │
│ │ 레드 46% │ │ (이순신) │ │ │ │
│ └─────────────┘ └──────────┘ └────────────┘ │
│ ┌─top GPM─┐ ┌─top KP─┐ ┌─best farm (CS/min)┐│
│ │ 412 │ │ 78% │ │ 9.2 │ │
│ └──────────┘ └────────┘ └───────────────────┘│
├────────────────────────────────────────────┤
│ 누적 통계 (정렬 가능 표) │
├────────────────────────────────────────────┤
│ 최근 내전 │
│ [매치 카드 1] → /match/:id 또는 detail 모달 │
│ [매치 카드 2] │
│ [무한 스크롤] │
└────────────────────────────────────────────┘
```
### 신규 페이지 `/communities/:cid/internal-stats/match/:matchId`
LCK 스타일 풀 detail. 게임마다 양 팀 5명 통계 표 (kda/cs/gpm/damage/vision/items/perks).
- `apps/web/src/pages/InternalMatchDetailPage.tsx`
- 컴포넌트:
- `GameTabs` — 1경기/2경기/3경기 스위처
- `GameStatsTable` — 양 팀 split, 컬럼 정렬 (KDA/CS/GPM/damage/vision)
- `ObjectivesBar` — baron/dragon/tower 시각화
### UserHistoryPage 에 "내전" 탭 추가
`apps/web/src/lib/riot-history.ts` 의 `QUEUE_GROUP_TABS` 에 `'internal'` 추가:
```ts
export const QUEUE_GROUP_TABS = [
{ id: 'summoners-rift', ... },
{ id: 'aram', ... },
{ id: 'urf', ... },
{ id: 'arena', ... },
{ id: 'internal', label: '내전' }, // 신규
] as const;
```
분기 로직:
- `queueGroup === 'internal'` 시 데이터 소스 다른 엔드포인트로 분기 (`/users/:userId/internal-history`)
- 랭크 필터(솔로/자유/일반)와 챔피언 필터는 그대로 노출 — 챔피언 필터는 client-side 재사용
- 솔로/자유/일반 라디오는 자동 숨김 (내전엔 의미 없음)
### 신규 훅 (`apps/web/src/api/hooks.ts`)
```ts
useCommunityInternalStatsMatches(cid, filters) # useInfiniteQuery
useCommunityLeaderboard(cid, filters)
useTeamInsights(cid, filters)
useInternalMatchDetail(matchId)
useUserInternalHistory(userId, filters)
```
queryKey 컨벤션 따름: `['community-stats', 'matches', cid, seasonId, from, to, cursor]`.
### 라우팅 (`apps/web/src/App.tsx`)
```tsx
<Route path="/communities/:cid/internal-stats" element={<CommunityInternalStatsPage />} />
<Route path="/communities/:cid/internal-stats/match/:matchId" element={<InternalMatchDetailPage />} />
```
`HomePage` 또는 navbar 에 진입 링크 추가 (DEFAULT_COMMUNITY_ID 기준 1차).
## Critical files (수정/신규)
### 백엔드
- (수정) `apps/api/src/modules/global/database/schema.ts` — `Match` 인덱스 보강: `{ communityId: 1, status: 1, scheduledAt: -1 }` (커뮤니티 finished 매치 정렬)
- (수정) `apps/api/src/app.module.ts` — `CommunityStatsModule` import
- (신규) `apps/api/src/modules/community-stats/*` (위 5 파일)
- (수정) `apps/api/src/modules/match/match.service.ts` — finished 전환 직후 cache invalidate 호출
- (수정) `apps/api/src/modules/match-history/match-history.service.ts` — `getRecentMatches` 등에 `queueGroup === 'internal'` 분기, 데이터 소스를 `Match.result.games` 로 전환
### 프런트
- (신규) `apps/web/src/pages/CommunityInternalStatsPage.tsx`
- (신규) `apps/web/src/pages/InternalMatchDetailPage.tsx`
- (신규) `apps/web/src/components/community-stats/*` (위 6 컴포넌트)
- (수정) `apps/web/src/lib/riot-history.ts` — `QUEUE_GROUP_TABS` 에 `'internal'` 추가
- (수정) `apps/web/src/pages/UserHistoryPage.tsx` — `queueGroup === 'internal'` 분기 (랭크 필터 숨김 + 신규 데이터 소스 훅)
- (수정) `apps/web/src/api/hooks.ts` — 5개 신규 훅
- (수정) `apps/web/src/api/types.ts` — 응답 타입 추가
- (수정) `apps/web/src/App.tsx` — 2 신규 라우트
- (수정) `apps/web/src/pages/HomePage.tsx` — 진입 링크
## 재사용
- `MatchHistoryService` 의 `$match → $lookup → $unwind → $group` 패턴 (champion-stats 와 동형 구조)
- `MatchHistoryCacheService` 의 Garnet `getJson/setJson + invalidatePrefix` 패턴
- `RiotRateLimiterService` 는 본 plan 에서 호출 X (Riot API 추가 호출 0회 — 모든 데이터 DB 안)
- `useDdragonManifest` 로 챔피언 이름·아이콘 풀이 (이미 web 에 있음)
- UserHistoryPage 의 `FilterButton`, `RecentMatchCard`, `SummaryCard` 를 `apps/web/src/components/history/` 로 추출 후 양쪽 페이지 공유 (1차 PR 안에서 함께)
## Rollout
1. (PR-1) Match 인덱스 보강 + `CommunityStatsModule` 골격 + `community-stats.service` 의 `getMatches` (가장 단순) + 캐시
2. (PR-2) `getLeaderboard` aggregation + 단위 테스트 (5경기 fixture)
3. (PR-3) `getTeamInsights` aggregation (진영별 승률 + LCK 카드) + RiotMatch.raw join
4. (PR-4) `getMatchDetail` (게임별 풀 통계) + `getUserInternalHistory`
5. (PR-5) cache invalidate hook (match finished → prefix delete)
6. (PR-6) 프런트 `CommunityInternalStatsPage` 골격 + TeamInsightsGrid + Leaderboard 표
7. (PR-7) `InternalMatchList` 무한 스크롤 + `InternalMatchCard`
8. (PR-8) `InternalMatchDetailPage` (게임 탭 + 풀 통계 표 + objectives 바)
9. (PR-9) UserHistoryPage 5번째 탭 "내전" + `useUserInternalHistory` 분기
10. (PR-10) 컴포넌트 추출 (`FilterButton`, `RecentMatchCard`, `SummaryCard` → `components/history/`)
11. (PR-11) 운영 모니터링 (aggregation 응답 시간 / Garnet hit ratio / 캐시 invalidation 동작)
12. (Phase 후속) 페어 통계 (`pair-stats.util.ts` + 신규 엔드포인트)
## 추가 고려사항
### 확정 (사용자 결정 2026-04-27)
- 권한: 외부 공유 OK
- 데이터 소스: Match.result.games + RiotMatch.raw join (Garnet 1h TTL 캐시)
- 1차 스코프: 매치 목록 + 시즌/기간 필터 + 유저별 누적 leaderboard + 팀 인사이트 카드
- 내전 탭: 큐 그룹 5번째
### 권장 (운영 후 확인)
1. **최소 게임 수 임계** — `top KDA / best farm` 같은 누적 평균 카드는 1경기로 1위가 되는 변동성 있음. 기본 5경기 이상만 후보 (응답에 `minGamesThreshold` 노출 + 클라가 선택). 운영 후 조정.
2. **단일 게임 vs 누적 highlight 구분** — `mostKills` 는 단일 게임 최고치 vs 누적 합계 둘 다 의미 있음. 본 plan 은 `LeaderHighlight.isSingleGame: boolean` 으로 구분.
3. **외부 puuid 처리** — 토너먼트 코드 매칭이 잘못된 매치(외부 사용자가 우리 코드 사용)에서 외부 puuid 가 raw.info.participants 에 섞여 있을 수 있음. `userId === null` 인 행은 통계 제외 + match detail 표에는 회색 표시.
4. **소수점 자릿수 일관성** — winRate 정수, KDA/GPM/CS/min 소수 1자리, damageShare 정수 %.
5. **invalidate 비용** — `riot:communitystats:*:<cid>:*` scan 비용은 키 갯수에 비례. 한 커뮤니티에 시즌×기간×cursor 조합이 최대 수백개 정도라 OK. 단, scanIterator 동안 새 요청이 들어오면 race — 기본 atomic 보장 안 됨, 일관성 milestone 안에서 OK 로 봄.
6. **`Match.result.games` 가 비어있는 매치** — 결과 수집 워커가 아직 못 채운 in-progress 매치는 통계 제외. Plan §1 의 식별 기준에 명시됨.
7. **community-스코프 인덱스 hit** — `Match { communityId, status, scheduledAt }` 신규 인덱스 + `RiotMatch { matchId }` 기본 인덱스로 lookup. 100 매치 × 3게임 = 300 raw lookup → aggregate $lookup 한 번에 묶이므로 1 round trip.
8. **DDragon 의존** — 챔피언 이름은 클라가 manifest 로 풀이 (백엔드 응답엔 championId number 만). 일관성 100%.
### 추후 (Phase 후속)
- 페어 통계 (`pair-stats.util.ts` + `/pair-stats` 엔드포인트, 같은팀/상대팀 X 와 함께 시 승률)
- 사용자 head-to-head (두 사용자 직접 비교)
- 차트 시각화 (시즌 W-L 추세 그래프)
- 시즌 history dropdown 활용 (선행 plan 의 `Community.seasons[]`)
- MVP 자동 산정 (평점 산식 재사용)
- 운영자용 export (CSV/JSON 다운로드)
- 페어 통계 sortable 표 — UI 형태 (한 유저 선택 → 다른 유저 페어 / 모든 페어 매트릭스)
## Verification
### 백엔드
1. `apps/api` 단위 테스트:
```
pnpm --filter api test community-stats.service
```
- 5경기 fixture: aggregation 결과 (winRate / KDA / GPM 합산) 정확
- season 필터: 이전 시즌 매치 제외
- cache hit/miss: 두 번째 호출 aggregation 0회
- invalidate: match.status finished 전환 후 prefix delete 됐는지
2. 통합 테스트:
- 직접 호출 `curl /communities/<cid>/internal-stats/team-insights?seasonId=current`
- 응답에 `sideWinRate / topKda / mostKills / topTeamGpm / topKillParticipation / bestFarm` 모두 포함
- 매치 0건일 때 모든 highlight `null`, `sideWinRate { blue:0, red:0 }`
### 프런트
1. dev 서버:
```
pnpm --filter web dev
```
2. 브라우저 시나리오:
- `/communities/<cid>/internal-stats` 진입 → 시즌 셀렉터 / 팀 인사이트 6 카드 / leaderboard / 매치 카드 리스트 표시
- 시즌 셀렉터 변경 → URL query 반영 + 응답 변화
- 매치 카드 클릭 → `/communities/<cid>/internal-stats/match/<matchId>` 이동, 게임 탭 / 양 팀 풀 통계 표 / objectives 바 표시
- `/users/<userId>/history` 진입 → 큐 탭에 "내전" 5번째 보임. 클릭 시 랭크 필터 자동 숨김 + 내전 챔프 통계/매치 카드 표시
3. 외부 공유 검증: 인증 헤더 없이 위 URL 모두 접근 가능
4. Garnet 캐시 hit 확인: 두 번째 새로고침 시 응답 < 100ms (서버 로그)
### 운영
- aggregation 응답 시간 p95 < 500ms (100 매치 기준)
- Garnet 캐시 hit ratio > 70%
- 매치 finished 전환 후 invalidate 정상 동작 (캐시 키 scan 로그)