This commit is contained in:
dahyeon committed 2026-04-27 18:55:04 -07:00
1 parent 2250b6072e
commit 1bbfc901e8
17 files changed
+3471 -59

No files matched your search

+465
View File
@@ -0,0 +1,465 @@
# Legacy 내전 데이터 백필 (Import) 플랜
> **대상**: codex 가 이어서 작업 가능한 수준의 실행 플랜
> **레포**: `/Users/dahyeon/source/lolympus-tournament-support` (pnpm workspace)
> **작성 기준**: 2026-04-27
> **선행 작업**:
> - `Riot-최근경기-플랜.md` (RiotRateLimiterService, RiotMatch 영구 저장)
> - `Riot-소환사전적-플랜.md` (Redis Stream 작업 큐, leader election, ETA, deferUntil)
> - `Tournament-Result-수집-플랜.md` (Match.result.games 매핑 로직, team-mapping 유틸, advanceMatchIfReady)
> - `커뮤니티-내전-전적.md` / `stateful-stirring-moler.md` (커뮤니티 통계 페이지 — 본 plan 의 결과 데이터 소비처)
---
## 1. Context
본 시스템 도입 이전에 진행된 내전 매치는 우리 DB 에 없습니다. 그러나 Riot 은 `match-v5` raw 매치 데이터를 ~2년간 보관하므로, **커뮤니티 멤버 puuid 로 `type=tourney` 매치를 검색**해 backfill 할 수 있습니다.
목표:
- **2024-05-01 부터** 모든 커뮤니티 멤버의 토너먼트 코드 매치를 import 해 우리 `Match` 도큐먼트로 변환
- 임계값 휴리스틱은 사용하지 않음 — **검색된 모든 매치 import** (외부 토너먼트가 섞여도 OK)
- 추후 admin UI 에서 운영자가 잘못 들어온 매치를 직접 삭제 (사후 cleanup 정책)
- 1 match-v5 = 1 Match 도큐먼트 (시리즈 묶음 X)
- 야간/유휴 시간대 권장
선행 인프라가 갖춘 부분:
- `RiotMatchService.getMatchIdsByPuuid({type: 'tourney', startTime, ...})` 가 이미 동작
- `RiotMatch.raw` 영구 저장 + `participantPuuids` 인덱스
- Redis Stream 작업 큐 (`riot:queue:high/low`) + RiotRateLimiterService 글로벌 throttle
- `Tournament-Result-수집-플랜.md` 의 `team-mapping.util.ts` (puuid 합집합 다수결 → blue/red 매핑) 그대로 재사용
---
## 2. 결정사항 (사용자 결정 2026-04-27)
- **검색 시작일**: 2024-05-01 (UTC)
- **검색 종료일**: 멤버별 `isActivated=false` 면 `user.updatedAt`, 활성이면 현재
- **멤버별 startTime override**: `max(2024-05-01, user.createdAt)` 자동 채움. 운영자가 admin UI 에서 멤버별 수정 가능
- **임계값 필터 사용 X**: 검색된 모든 `type=tourney` 매치 import (외부 토너먼트도 포함)
- **시리즈 묶음 X**: 1 match-v5 = 1 Match 도큐먼트, `gameCount=1`
- **사후 cleanup**: admin UI 에서 legacy 매치 목록 보고 단일/bulk 삭제 가능
- **idempotent**: 같은 `riotMatchId` 두 번 import 안 됨
- **부하**: 야간 batch 권장. 운영자가 명시적으로 트리거
---
## 3. 데이터 모델 보강
### 3.1 Match 확장 (legacy 추적)
```ts
// schema.ts Match 추가
legacyImported?: boolean; // true 면 본 import 로 들어온 매치
legacyImportSource?: {
importedAt: Date;
importedBy: mongoose.Types.ObjectId; // 트리거한 admin userId
triggeringPuuid: string; // 어떤 멤버 검색으로 처음 발견됐는지 audit
jobId?: string;
};
// MatchSchema
legacyImported: { type: Boolean, default: false, index: true },
legacyImportSource: {
importedAt: { type: Date },
importedBy: { type: Schema.Types.ObjectId, ref: 'user' },
triggeringPuuid: { type: String },
jobId: { type: String },
}
```
### 3.2 RiotMatch unique 검사
이미 `RiotMatch.matchId` 가 unique 인덱스 (선행 plan 가정). 신규 import 시 이미 있으면 detail 재호출 skip.
### 3.3 Match `riotMatchId` 단위 unique
같은 match-v5 가 두 Match 도큐먼트로 들어오는 사고 방지:
- Mongo aggregation 단계에서 `result.games[].riotMatchId` 가 이미 다른 Match 에 존재하면 skip
- 또는 신규 sparse 인덱스: `Match.result.games.riotMatchId` (배열 인덱스, sparse)
```ts
MatchSchema.index({ 'result.games.riotMatchId': 1 }, { sparse: true, unique: false });
```
- unique 는 배열 element 단위로 보장하기 어려우니 application 레벨 검사 권장
### 3.4 신규 컬렉션 — `LegacyImportJob` (운영 추적)
```ts
export interface LegacyImportJob {
jobId: string;
communityId: mongoose.Types.ObjectId;
triggeredBy: mongoose.Types.ObjectId;
startedAt: Date;
completedAt?: Date;
state: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
// 입력 파라미터
windowStart: Date; // 기본 2024-05-01
windowEnd: Date;
memberOverrides: Array<{ // 운영자가 수정한 멤버별 윈도우
userId: mongoose.Types.ObjectId;
puuid: string;
startTime: Date;
endTime: Date;
}>;
// 진행 상황
totalMembers: number;
processedMembers: number;
totalDiscoveredMatchIds: number; // dedup 후
totalImportedMatches: number;
totalSkippedDuplicate: number;
totalErrors: number;
errors?: Array<{ puuid?: string; matchId?: string; reason: string; at: Date }>;
}
```
운영 가시성: admin UI 에서 import job 진행률 표시 + 실패 매치 재시도.
---
## 4. Import 흐름
### 4.1 트리거
```
admin UI → POST /communities/:cid/legacy-import
body: {
windowStart?: '2024-05-01T00:00:00Z',
windowEnd?: ISO,
memberOverrides?: [{ userId, startTime, endTime }, ...]
}
응답: { jobId, totalMembers, etaSeconds }
```
`@Roles('owner', 'admin')` 가드. 동시 동일 community 에 대한 job 1개로 제한 (Garnet `legacy-import:lock:<cid>` NX EX 6h).
### 4.2 sub-job 분할
선행 plan 의 작업 큐 패턴 그대로:
- parent job: `LegacyImportJob` 생성
- 멤버별 sub-job N개 enqueue → `riot:queue:low` (priority low — 사용자 갱신/prefetch 보다 뒤)
- payload:
```ts
{
kind: 'legacy-import-member',
parentJobId,
communityId,
userId,
puuid,
startTime, // epoch seconds
endTime,
triggeredBy,
}
```
### 4.3 worker — 멤버 1명 처리
```ts
async function processLegacyImportMember(job: LegacyImportMemberJob) {
let start = 0;
const collectedMatchIds = new Set<string>();
// 1. type=tourney list 페이지네이션 (count=100, region 'asia')
while (true) {
const ids = await matchService.getMatchIdsByPuuid(job.puuid, {
type: 'tourney',
startTime: Math.floor(job.startTime.getTime() / 1000),
endTime: Math.floor(job.endTime.getTime() / 1000),
start,
count: 100,
region: 'asia',
});
ids.forEach((id) => collectedMatchIds.add(id));
if (ids.length < 100) break;
start += 100;
// throttle 통과 — 별도 sleep 불필요
}
// 2. 각 matchId detail + Match 변환
for (const matchV5Id of collectedMatchIds) {
await importSingleMatch(matchV5Id, {
communityId: job.communityId,
triggeringPuuid: job.puuid,
importedBy: job.triggeredBy,
parentJobId: job.parentJobId,
});
}
await updateLegacyImportJobProgress(job.parentJobId, {
processedMembers: 1,
discovered: collectedMatchIds.size,
});
}
async function importSingleMatch(matchV5Id: string, ctx) {
// dedup: 이미 우리 Match 에 있는지
const existing = await MatchModel.findOne({ 'result.games.riotMatchId': matchV5Id });
if (existing) {
await incrementCounter('totalSkippedDuplicate');
return;
}
// RiotMatch raw 페치 (이미 있으면 cache hit)
const detail = await ensureRiotMatchPersisted(matchV5Id);
if (!detail.info.tournamentCode) return; // 안전: tourney 인데 코드 없는 비정상 케이스 skip
// 우리 멤버 매핑
const community = await CommunityModel.findById(ctx.communityId);
const userByPuuid = await buildUserByPuuidMap(ctx.communityId);
const teams100Puuids = detail.info.participants.filter((p) => p.teamId === 100).map((p) => p.puuid);
const teams200Puuids = detail.info.participants.filter((p) => p.teamId === 200).map((p) => p.puuid);
const team100MembersInOurs = teams100Puuids.filter((p) => userByPuuid.has(p)).length;
const team200MembersInOurs = teams200Puuids.filter((p) => userByPuuid.has(p)).length;
// 외부 매치(우리 멤버 0명) 는 import 하지 않음 — 검색 결과에 잘못 들어온 케이스 가드
if (team100MembersInOurs + team200MembersInOurs === 0) return;
// teamId → blue/red: 우리 멤버 더 많은 쪽이 blue (관습), 동수면 100=blue
const team100IsBlue = team100MembersInOurs >= team200MembersInOurs;
// Match 도큐먼트 생성
const match = await MatchModel.create({
communityId: ctx.communityId,
title: `[Legacy] ${formatDate(detail.info.gameCreation)}`,
description: 'Legacy import (자동 생성)',
mapId: detail.info.mapId ?? 11,
status: 'finished',
scheduledAt: new Date(detail.info.gameCreation),
teamBuiltAt: new Date(detail.info.gameCreation),
maxParticipants: 10,
gameCount: 1,
tournamentCodeIds: [], // legacy 라 우리 풀 코드 없음
participants: buildParticipantsSnapshot(detail, userByPuuid),
teams: buildTeams(detail, userByPuuid, team100IsBlue),
result: {
blueScore: 0,
redScore: 0,
games: [
buildGameResult(detail, userByPuuid, team100IsBlue, 1),
],
riotMatchIds: [matchV5Id],
},
legacyImported: true,
legacyImportSource: {
importedAt: new Date(),
importedBy: ctx.importedBy,
triggeringPuuid: ctx.triggeringPuuid,
jobId: ctx.parentJobId,
},
});
// result.winnerSide / blueScore / redScore 산정
const winnerSide = match.result!.games[0].winnerSide;
match.result!.blueScore = winnerSide === 'blue' ? 1 : 0;
match.result!.redScore = winnerSide === 'red' ? 1 : 0;
match.result!.winnerSide = winnerSide;
await match.save();
await incrementCounter('totalImportedMatches');
}
```
핵심 헬퍼:
- `ensureRiotMatchPersisted(matchV5Id)`: RiotMatch 컬렉션에 upsert. 이미 있으면 그대로 반환 (Riot API 호출 0회).
- `buildUserByPuuidMap(communityId)`: 커뮤니티 멤버 puuid → User 역인덱스 (in-memory cache, job 단위).
- `buildGameResult(detail, userByPuuid, team100IsBlue, gameNumber)`: 선행 plan `Tournament-Result-수집-플랜.md` `§4.4 computeGameResult` 함수 그대로 재사용. team mapping 만 override.
### 4.4 동시성 / dedup
- **멤버 sub-job 간 동시성**: 두 멤버가 같은 매치에 있으면 두 worker 가 같은 matchV5Id 를 동시에 처리하려고 함. `importSingleMatch` 진입 시 Garnet `legacy-import:match:<matchV5Id>` NX EX 60s 락. 이미 잡혔으면 skip.
- **재실행**: 같은 jobId 재실행 시 이미 처리된 멤버는 `LegacyImportJob.processedMembers` 기준 skip.
### 4.5 진행률 / ETA
- worker 가 sub-job 끝낼 때마다 `LegacyImportJob.processedMembers++`
- ETA: `(totalMembers - processedMembers) × avgMemberSeconds`
- avgMemberSeconds 기본 60 (멤버당 list 1~3 페이지 + detail 10~50건 가정), 실제 처리 시간으로 EWMA 갱신
- admin UI 가 5초 polling 으로 진행률 표시
### 4.6 cancel
- `POST /legacy-import-jobs/:jobId/cancel` (admin)
- `LegacyImportJob.state='cancelled'` 마킹 → worker 가 sub-job pickup 직후 state 확인 → cancelled 면 즉시 ack 후 skip
---
## 5. Admin UI
### 5.1 신규 페이지
`apps/web/src/pages/admin/LegacyImportPage.tsx`
- 라우트: `/admin/communities/:cid/legacy-import`
- `@Roles('owner', 'admin')` 가드 (useMe + role 분기)
#### 화면 구성
```
┌────────────────────────────────────────────┐
│ Legacy 내전 백필 │
├────────────────────────────────────────────┤
│ 검색 윈도우 │
│ 시작일 [2024-05-01 ▾] 종료일 [지금 ▾] │
├────────────────────────────────────────────┤
│ 멤버별 윈도우 (자동 채움 + 수정 가능) │
│ ┌──────────┬─────────────┬──────────┐ │
│ │ 멤버명 │ 시작일 │ 종료일 │ │
│ │ 홍길동 │ 2024-05-01 │ 지금 │ │
│ │ 이순신 │ 2024-08-15 │ 2025-12-31│ │
│ └──────────┴─────────────┴──────────┘ │
├────────────────────────────────────────────┤
│ [백필 시작] (확인 모달 → 예상 ETA 표시) │
├────────────────────────────────────────────┤
│ 진행 중인 작업 │
│ - jobId xxx: 23/100 멤버 처리 중... │
│ 발견 매치 142개 / import 89개 / 중복 53 │
├────────────────────────────────────────────┤
│ 과거 작업 (최근 10개) │
│ - jobId yyy: 완료, 100/100, import 412 │
└────────────────────────────────────────────┘
```
### 5.2 신규 페이지 — Legacy 매치 cleanup
`apps/web/src/pages/admin/LegacyMatchesPage.tsx`
- 라우트: `/admin/communities/:cid/legacy-matches`
- legacy 매치 목록 (`legacyImported=true` 필터) — 시간순 / 멤버 인원수 정렬
- 각 row: 매치 ID / 시간 / 우리 멤버 N명 / 외부 puuid 수 / 챔피언 미니 + **삭제 버튼**
- bulk select + 일괄 삭제
- 확인 모달 ("이 매치는 영구 삭제됩니다. RiotMatch raw 는 유지됩니다.")
### 5.3 신규 엔드포인트
| Method | Path | 권한 | 용도 |
|---|---|---|---|
| POST | `/communities/:cid/legacy-import` | `owner/admin` | import 트리거 |
| GET | `/communities/:cid/legacy-import-jobs` | `owner/admin` | job 목록 |
| GET | `/communities/:cid/legacy-import-jobs/:jobId` | `owner/admin` | job 상세 |
| POST | `/communities/:cid/legacy-import-jobs/:jobId/cancel` | `owner/admin` | 취소 |
| GET | `/communities/:cid/legacy-matches` | `owner/admin` | legacy 매치 목록 (페이지네이션) |
| DELETE | `/matches/:id` | `owner/admin` | 단일 매치 삭제 (legacy 외 일반 매치도 가능) |
| POST | `/communities/:cid/legacy-matches/bulk-delete` | `owner/admin` | bulk 삭제 |
`Match` 삭제 시 부수 효과:
- `tournamentCodeIds` 가 비어있으므로 풀 release 불필요
- `MatchHistoryCache` invalidate (`riot:communitystats:*:<cid>:*` prefix scan delete) — `community-stats.service` 의 invalidate 헬퍼 재사용
---
## 6. 변경 사항 (파일 단위)
### 6.1 백엔드
```
apps/api/src/modules/legacy-import/
legacy-import.module.ts
legacy-import.service.ts # enqueue + status + cancel
legacy-import.worker.ts # 작업 큐 dispatch (kind=legacy-import-member)
legacy-import.controller.ts
legacy-import.types.ts
match-builder.util.ts # buildParticipantsSnapshot / buildTeams / buildGameResult
```
수정:
- `apps/api/src/modules/global/database/schema.ts` — `Match.legacyImported`, `Match.legacyImportSource`, 신규 인덱스, `LegacyImportJob` 컬렉션 등록
- `apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts` — `kind === 'legacy-import-member'` dispatch 추가
- `apps/api/src/modules/match/match.service.ts` — `delete(matchId)` 메서드 + community-stats invalidate 호출
- `apps/api/src/modules/match/match.controller.ts` — `DELETE /matches/:id` 엔드포인트
- `apps/api/src/app.module.ts` — `LegacyImportModule` import
### 6.2 프런트
```
apps/web/src/pages/admin/LegacyImportPage.tsx
apps/web/src/pages/admin/LegacyMatchesPage.tsx
apps/web/src/components/admin/legacy/
MemberWindowTable.tsx # 멤버별 윈도우 수정 폼
LegacyImportJobProgress.tsx
LegacyMatchListRow.tsx
```
수정:
- `apps/web/src/App.tsx` — 2 신규 admin 라우트
- `apps/web/src/api/hooks.ts` — `useLegacyImportTrigger / useLegacyImportJobs / useLegacyMatches / useDeleteMatch`
- `apps/web/src/api/types.ts` — 응답 타입
---
## 7. 단위 테스트
- `legacy-import.service.spec.ts`
- parent job 생성 + 멤버별 sub-job N개 enqueue
- 동일 cid 동시 트리거 시 두 번째 거부 (Garnet 락)
- cancel 호출 시 state='cancelled', worker 가 다음 pickup 시 skip
- `legacy-import.worker.spec.ts`
- `importSingleMatch`: 이미 있는 riotMatchId → totalSkippedDuplicate++
- 외부 매치 (우리 멤버 0명) → import 안 됨 + 에러 카운트 X
- 우리 멤버 1명만 + 외부 9명 → 정상 import (휴리스틱 X 라 통과)
- team mapping: team100 우리 3명 vs team200 우리 0명 → team100=blue
- `match-builder.util.spec.ts`
- `buildGameResult` (Tournament-Result `computeGameResult` 재사용 검증)
- `buildTeams`: 우리 멤버 puuid → userId 매핑, 외부 puuid 는 teams 에서 제외
- `match.service.spec.ts`
- `delete(matchId)`: 매치 삭제 + cache invalidate 호출 확인
---
## 8. Rollout
1. (PR-1) `Match` 스키마 확장 (legacy 필드 + 인덱스) + `LegacyImportJob` 컬렉션 + 모델 등록
2. (PR-2) `match-builder.util.ts` (선행 plan `computeGameResult` 재사용 wrapping) + 단위 테스트
3. (PR-3) `LegacyImportService.enqueue / cancel / status` + parent job + sub-job 분할
4. (PR-4) `LegacyImportWorker` (worker dispatch + `importSingleMatch`) + 단위 테스트
5. (PR-5) `DELETE /matches/:id` 엔드포인트 + community-stats cache invalidate 통합
6. (PR-6) admin 트리거 페이지 (`LegacyImportPage`) — 윈도우 폼 + ETA 표시 + 진행률 polling
7. (PR-7) admin cleanup 페이지 (`LegacyMatchesPage`) — 매치 목록 + bulk 삭제
8. (PR-8) 운영 모니터링 (job 진행률 / 멤버당 처리 시간 / 외부 매치 비율 로그)
9. (Phase 후속) 자동 주기 재실행 (월 1회 등) — 1차에선 manual only
---
## 9. 추가 고려사항
### 확정 (사용자 결정 2026-04-27)
- **검색 시작일 2024-05-01**, 종료일 멤버 활성/비활성 따라 자동
- **멤버별 startTime override**: admin UI 에서 자동 채움 + 수정 가능
- **임계값 필터 X**: 검색된 모든 매치 import (외부 매치도 포함)
- **시리즈 묶음 X**: 1 match-v5 = 1 Match, gameCount=1
- **사후 cleanup**: admin UI 에서 단일/bulk 삭제
- **idempotent**: 같은 riotMatchId 두 번 import 안 됨
### 권장 (운영 후 확인)
1. **외부 매치 비율 로그** — `team100MembersInOurs + team200MembersInOurs` 별 분포를 import job 끝에 통계로 남기기. 운영자가 cleanup 우선순위 잡기 좋음.
2. **백필 매치의 title 컨벤션** — `[Legacy] 2024-08-15` 형식. 운영자가 cleanup 페이지에서 한눈에 식별.
3. **DELETE /matches/:id 가드** — `legacyImported=true` 외 일반 매치 삭제는 무서운 작업. 일반 매치 삭제 시 추가 확인 모달 또는 별도 엔드포인트로 분리.
4. **백필 매치의 participants snapshot** — `Match.participants[]` 는 보통 매치 신청 단계에서 채워지지만, legacy 라 신청 흐름이 없음. detail.info.participants 에서 우리 멤버만 추출해 채움. preferredPositions / tier 는 비움 (필수 아님 가정).
5. **mapId 결정** — `detail.info.mapId` 가 11(소협) 외 다른 값일 수 있음. 그대로 저장. 통계 페이지에서 mapId 필터로 분리 가능.
6. **시간대 권장** — admin UI 에 "야간 배치 권장" 안내 + 큐가 비어있는 시간대 표시 (Phase 후속).
7. **에러 매치 격리** — `LegacyImportJob.errors[]` 에 puuid+matchId+reason 보관. admin UI 에서 재시도 버튼.
8. **선행 plan 의 결과 수집 워커와의 충돌** — legacy import 가 만든 Match 는 `tournamentCodeIds=[]` 라 결과 수집 워커 (`maybeAdvanceMatch`) 가 트리거되지 않음. 자연 분리.
### 추후 (Phase 후속)
- 자동 주기 재실행 (월 1회 cron)
- 외부 매치 자동 분류 / 분리 (예: 멤버 ≥ 4명 = 우리 내전, < 4명 = 외부) 옵션 — UI 토글
- legacy 매치도 stateful-stirring-moler.md 의 community 통계 페이지에 자동 포함됨 (별도 분기 필요 없음 — `result.games[]` 형태가 같음)
---
## 10. Done 정의
- `Match.legacyImported` + `Match.legacyImportSource` + `LegacyImportJob` 컬렉션 + 인덱스 추가
- admin 이 `LegacyImportPage` 에서 윈도우/멤버 override 입력 후 트리거 → ETA 토스트 + 진행률 polling
- worker 가 멤버별 `type=tourney` list + detail 페치 → Match 도큐먼트 생성, `result.games[0]` 채워짐
- 같은 매치 두 번 import 안 됨 (Garnet 락 + Match application 검사)
- 우리 멤버 0명 매치는 자동 skip (외부 매치 가드)
- import job 진행률 / 발견 / import / 중복 / 에러 카운트 정확
- admin 이 `LegacyMatchesPage` 에서 잘못된 매치 단일/bulk 삭제 가능, 삭제 시 community-stats 캐시 invalidate
- 동일 cid 에 대한 동시 import 트리거 거부 (Garnet 락)
- cancel 동작
- Riot 429 0건 (글로벌 throttle 통과)
- 단위 테스트 통과
- legacy 매치가 `stateful-stirring-moler.md` 의 community 통계 페이지에 자동 포함됨
+2
View File
@@ -5,6 +5,7 @@ import { AppService } from './app.service';
import { AuctionModule } from './modules/auction/auction.module';
import { AuthModule } from './modules/auth/auth.module';
import { CommunityModule } from './modules/community/community.module';
import { CommunityStatsModule } from './modules/community-stats/community-stats.module';
import { DakaoModule } from './modules/dakao/dakao.module';
import { GlobalModule } from './modules/global/global.module';
import { MatchHistoryModule } from './modules/match-history/match-history.module';
@@ -24,6 +25,7 @@ import { UserModule } from './modules/user/user.module';
AuthModule,
RiotModule,
CommunityModule,
CommunityStatsModule,
MatchModule,
MatchHistoryModule,
TournamentCodeModule,
@@ -0,0 +1,59 @@
import { Injectable, Logger } from '@nestjs/common';
import { GarnetService } from '../global/garnet/garnet.service';
const COMMUNITY_STATS_TTL_SECONDS = 60 * 60;
const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60;
@Injectable()
export class CommunityStatsCacheService {
private readonly logger = new Logger(CommunityStatsCacheService.name);
constructor(private readonly garnetService: GarnetService) {}
public get<T>(key: string): Promise<T | null> {
return this.garnetService.getJson<T>(key);
}
public set(
key: string,
value: unknown,
ttlSeconds = COMMUNITY_STATS_TTL_SECONDS,
): Promise<void> {
return this.garnetService.setJson(key, value, ttlSeconds);
}
public setDetail(key: string, value: unknown): Promise<void> {
return this.set(key, value, COMMUNITY_STATS_DETAIL_TTL_SECONDS);
}
public async invalidateCommunity(communityId: string): Promise<number> {
const prefix = `riot:communitystats:`;
const match = `${prefix}*${communityId}*`;
const client = this.garnetService.raw();
let cursor = '0';
let deleted = 0;
do {
const reply = (await client.sendCommand([
'SCAN',
cursor,
'MATCH',
match,
'COUNT',
'100',
])) as [string, string[]];
cursor = reply[0];
const keys = reply[1] ?? [];
if (keys.length > 0) {
deleted += await client.del(keys);
}
} while (cursor !== '0');
if (deleted > 0) {
this.logger.debug(
`Invalidated ${deleted} community stats cache keys for ${communityId}.`,
);
}
return deleted;
}
}
@@ -0,0 +1,115 @@
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 { CommunityStatsService } from './community-stats.service';
import type { CommunityStatsFilters } from './community-stats.types';
@Controller('communities/:communityId')
export class CommunityStatsController {
constructor(private readonly communityStatsService: CommunityStatsService) {}
@Get('internal-stats/matches')
@AllowPublicAccess()
public getMatches(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Query('seasonId') seasonId?: string,
@Query('from') from?: string,
@Query('to') to?: string,
@Query('championId') championId?: string,
@Query('cursor') cursor?: string,
@Query('limit') limit?: string,
) {
return this.communityStatsService.getMatches({
communityId,
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }),
});
}
@Get('internal-stats/leaderboard')
@AllowPublicAccess()
public getLeaderboard(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Query('seasonId') seasonId?: string,
@Query('from') from?: string,
@Query('to') to?: string,
@Query('championId') championId?: string,
) {
return this.communityStatsService.getLeaderboard({
communityId,
filters: this.toFilters({ seasonId, from, to, championId }),
});
}
@Get('internal-stats/team-insights')
@AllowPublicAccess()
public getTeamInsights(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Query('seasonId') seasonId?: string,
@Query('from') from?: string,
@Query('to') to?: string,
@Query('championId') championId?: string,
) {
return this.communityStatsService.getTeamInsights({
communityId,
filters: this.toFilters({ seasonId, from, to, championId }),
});
}
@Get('internal-stats/match/:matchId')
@AllowPublicAccess()
public getMatchDetail(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
return this.communityStatsService.getMatchDetail({ communityId, matchId });
}
@Get('users/:userId/internal-history')
@AllowPublicAccess()
public getUserInternalHistory(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Query('seasonId') seasonId?: string,
@Query('from') from?: string,
@Query('to') to?: string,
@Query('championId') championId?: string,
@Query('cursor') cursor?: string,
@Query('limit') limit?: string,
) {
return this.communityStatsService.getUserInternalHistory({
communityId,
userId,
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }),
});
}
private toFilters(params: {
seasonId?: string;
from?: string;
to?: string;
championId?: string;
cursor?: string;
limit?: string;
}): CommunityStatsFilters {
return {
seasonId: params.seasonId,
from: params.from,
to: params.to,
championId: this.toNumber(params.championId),
cursor: this.toNumber(params.cursor),
limit: this.toNumber(params.limit),
};
}
private toNumber(value: string | undefined): number | undefined {
if (!value) return undefined;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : undefined;
}
}
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { CommunityStatsCacheService } from './community-stats-cache.service';
import { CommunityStatsController } from './community-stats.controller';
import { CommunityStatsService } from './community-stats.service';
@Module({
controllers: [CommunityStatsController],
providers: [CommunityStatsService, CommunityStatsCacheService],
exports: [CommunityStatsService],
})
export class CommunityStatsModule {}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,196 @@
import type { RiotLane, TeamSide } from '../global/database/schema';
import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types';
export interface CommunityStatsFilters {
seasonId?: string;
from?: string;
to?: string;
championId?: number;
cursor?: number;
limit?: number;
}
export interface InternalMatchListResponse {
matches: InternalMatchCardView[];
nextCursor: number | null;
season: HistorySeasonDto;
}
export interface InternalMatchCardView {
matchId: string;
title: string;
scheduledAt: string;
status: 'finished' | 'in-progress';
gameCount: number;
blueScore: number;
redScore: number;
winnerSide?: TeamSide;
games: Array<{
gameNumber: number;
riotMatchId: string | null;
winnerSide: TeamSide | null;
gameDuration: number;
}>;
teams: Array<{
side: TeamSide;
name: string;
members: Array<{
userId: string;
summonerName: string;
profileIconId: number;
}>;
}>;
}
export interface LeaderboardResponse {
rows: LeaderboardRow[];
season: HistorySeasonDto;
}
export 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 }>;
}
export interface LeaderHighlight {
metric: number;
userId: string;
summonerName: string;
championId?: number;
matchId?: string;
isSingleGame: boolean;
}
export interface TeamInsightsResponse {
season: HistorySeasonDto;
sideWinRate: {
blue: number;
red: number;
bluePicks: number;
redPicks: number;
};
topKda: LeaderHighlight | null;
mostKills: LeaderHighlight | null;
topTeamGpm: LeaderHighlight | null;
topKillParticipation: LeaderHighlight | null;
bestFarm: LeaderHighlight | null;
minGamesThreshold: number;
}
export interface InternalMatchDetailResponse {
match: InternalMatchCardView;
games: Array<{
gameNumber: number;
riotMatchId: string;
gameCreation: number;
gameDuration: number;
teams: Array<{
side: TeamSide;
win: boolean;
objectives: { baron: number; dragon: number; tower: number };
participants: Array<{
userId: string | null;
summonerName: string;
side: TeamSide;
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;
}>;
}>;
}>;
}
export interface UserInternalHistoryResponse {
season: HistorySeasonDto;
championStats: LeaderboardChampionStats;
summary: {
windowSize: number;
winRate: number;
wins: number;
losses: number;
streak: { type: 'win' | 'loss'; count: number } | null;
kda: number;
avgKills: number;
avgDeaths: number;
avgAssists: number;
bestRating: {
rating: number | 'Perfect';
kills: number;
deaths: number;
assists: number;
matchId: string;
} | null;
positionRates: Partial<Record<RiotLane, number>>;
topChampions: Array<{
championId: number;
games: number;
winRate: number;
pickRate: number;
avgRating: number;
}>;
lastFetchedAt: string | null;
};
matches: RecentMatchView[];
nextCursor: number | null;
lastFetchedAt: string | null;
}
export interface LeaderboardChampionStats {
queueGroup: 'internal';
rank: 'all';
queueIds: number[];
season: HistorySeasonDto;
lastFetchedAt: string | null;
champions: Array<{
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;
}>;
totals: LeaderboardChampionStats['champions'][number];
}
@@ -1,11 +1,12 @@
import { forwardRef, Module } from '@nestjs/common';
import { CommunityStatsModule } from '../community-stats/community-stats.module';
import { RiotJobQueueModule } from '../riot-job-queue/riot-job-queue.module';
import { RiotModule } from '../riot/riot.module';
import { TournamentResultController } from './tournament-result.controller';
import { TournamentResultService } from './tournament-result.service';
@Module({
imports: [RiotModule, forwardRef(() => RiotJobQueueModule)],
imports: [RiotModule, CommunityStatsModule, forwardRef(() => RiotJobQueueModule)],
controllers: [TournamentResultController],
providers: [TournamentResultService],
exports: [TournamentResultService],
@@ -5,6 +5,7 @@ import {
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service';
import type {
MatchDocument,
@@ -41,6 +42,7 @@ export class TournamentResultService {
private readonly connectionService: ConnectionService,
private readonly riotMatchService: RiotMatchService,
private readonly riotJobQueueService: RiotJobQueueService,
private readonly communityStatsService: CommunityStatsService,
) {}
public async scheduleInitialPoll(
@@ -256,6 +258,15 @@ export class TournamentResultService {
state: 'complete',
};
await match.save();
void this.communityStatsService
.invalidateCommunity(match.communityId)
.catch((error) => {
this.logger.warn(
`Failed to invalidate community stats cache for ${match.communityId.toString()}: ${
error instanceof Error ? error.message : error
}`,
);
});
return true;
}
+10
View File
@@ -10,6 +10,8 @@ import LoginPage from './pages/Login';
import MatchDetailPage from './pages/MatchDetailPage';
import AuctionPage from './pages/AuctionPage';
import UserHistoryPage from './pages/UserHistoryPage';
import CommunityInternalStatsPage from './pages/CommunityInternalStatsPage';
import InternalMatchDetailPage from './pages/InternalMatchDetailPage';
import TournamentCodesPage from './pages/admin/TournamentCodesPage';
function MsalHeaderActions() {
@@ -72,6 +74,14 @@ function App() {
<Route path="/match/:id" element={<MatchDetailPage />} />
<Route path="/match/:id/auction" element={<AuctionPage />} />
<Route path="/users/:userId/history" element={<UserHistoryPage />} />
<Route
path="/communities/:cid/internal-stats"
element={<CommunityInternalStatsPage />}
/>
<Route
path="/communities/:cid/internal-stats/match/:matchId"
element={<InternalMatchDetailPage />}
/>
<Route
path="/admin/communities/:cid/tournament-codes"
element={<TournamentCodesPage />}
+159 -3
View File
@@ -13,10 +13,15 @@ import type {
ApiChampionStatsResponse,
ApiCommunity,
ApiEnqueueRefreshResult,
ApiInternalMatchDetailResponse,
ApiInternalMatchListResponse,
ApiLeaderboardResponse,
ApiMatch,
ApiRecentMatchesResponse,
ApiRecentSummaryResponse,
ApiTeamInsightsResponse,
ApiTournamentCode,
ApiUserInternalHistoryResponse,
ApiUserHistoryProfile,
DdragonManifest,
MatchStatus,
@@ -45,6 +50,14 @@ export interface UserHistoryFilters {
championId?: number;
}
export interface CommunityInternalStatsFilters {
seasonId?: string;
from?: string;
to?: string;
championId?: number;
limit?: number;
}
function createMatchesPath(
communityId: string,
options: MatchesQueryOptions = {},
@@ -153,6 +166,7 @@ export function useChampionStats(
userId: string | undefined,
filters: UserHistoryFilters,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: [
@@ -168,7 +182,7 @@ export function useChampionStats(
createUserHistoryPath(communityId, userId ?? '', 'champion-stats', filters),
{ auth: 'none' },
),
enabled: Boolean(communityId && userId),
enabled: Boolean(communityId && userId && enabled),
});
}
@@ -176,6 +190,7 @@ export function useRecentSummary(
userId: string | undefined,
filters: UserHistoryFilters,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: [
@@ -192,7 +207,7 @@ export function useRecentSummary(
createUserHistoryPath(communityId, userId ?? '', 'recent-summary', filters),
{ auth: 'none' },
),
enabled: Boolean(communityId && userId),
enabled: Boolean(communityId && userId && enabled),
});
}
@@ -200,6 +215,7 @@ export function useRecentMatches(
userId: string | undefined,
filters: UserHistoryFilters,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useInfiniteQuery({
queryKey: [
@@ -221,7 +237,147 @@ export function useRecentMatches(
),
initialPageParam: null as number | null,
getNextPageParam: (lastPage) => lastPage.nextCursor,
enabled: Boolean(communityId && userId),
enabled: Boolean(communityId && userId && enabled),
});
}
function createCommunityInternalStatsPath(
communityId: string,
resource: string,
filters: CommunityInternalStatsFilters = {},
extra: Record<string, string | number | null | undefined> = {},
) {
const searchParams = new URLSearchParams();
if (filters.seasonId) searchParams.set('seasonId', filters.seasonId);
if (filters.from) searchParams.set('from', filters.from);
if (filters.to) searchParams.set('to', filters.to);
if (filters.championId) searchParams.set('championId', String(filters.championId));
if (filters.limit) searchParams.set('limit', String(filters.limit));
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}/internal-stats/${resource}${queryString ? `?${queryString}` : ''}`;
}
export function useCommunityInternalStatsMatches(
filters: CommunityInternalStatsFilters,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useInfiniteQuery({
queryKey: [
'community-internal-stats-matches',
communityId,
filters.seasonId ?? null,
filters.from ?? null,
filters.to ?? null,
filters.championId ?? null,
filters.limit ?? null,
],
queryFn: ({ pageParam }) =>
apiFetch<ApiInternalMatchListResponse>(
createCommunityInternalStatsPath(communityId, 'matches', filters, {
cursor: pageParam,
}),
{ auth: 'none' },
),
initialPageParam: null as number | null,
getNextPageParam: (lastPage) => lastPage.nextCursor,
enabled: Boolean(communityId && enabled),
});
}
export function useCommunityLeaderboard(
filters: CommunityInternalStatsFilters,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: [
'community-internal-stats-leaderboard',
communityId,
filters.seasonId ?? null,
filters.from ?? null,
filters.to ?? null,
filters.championId ?? null,
],
queryFn: () =>
apiFetch<ApiLeaderboardResponse>(
createCommunityInternalStatsPath(communityId, 'leaderboard', filters),
{ auth: 'none' },
),
enabled: Boolean(communityId && enabled),
});
}
export function useTeamInsights(
filters: CommunityInternalStatsFilters,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: [
'community-internal-stats-team-insights',
communityId,
filters.seasonId ?? null,
filters.from ?? null,
filters.to ?? null,
filters.championId ?? null,
],
queryFn: () =>
apiFetch<ApiTeamInsightsResponse>(
createCommunityInternalStatsPath(communityId, 'team-insights', filters),
{ auth: 'none' },
),
enabled: Boolean(communityId && enabled),
});
}
export function useInternalMatchDetail(
matchId: string | undefined,
communityId = DEFAULT_COMMUNITY_ID,
) {
return useQuery({
queryKey: ['community-internal-stats-match', communityId, matchId ?? null],
queryFn: () =>
apiFetch<ApiInternalMatchDetailResponse>(
`/communities/${communityId}/internal-stats/match/${matchId}`,
{ auth: 'none' },
),
enabled: Boolean(communityId && matchId),
retry: false,
});
}
export function useUserInternalHistory(
userId: string | undefined,
filters: UserHistoryFilters,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useInfiniteQuery({
queryKey: [
'user-internal-history',
communityId,
userId ?? null,
filters.seasonId ?? null,
filters.championId ?? null,
],
queryFn: ({ pageParam }) =>
apiFetch<ApiUserInternalHistoryResponse>(
createUserHistoryPath(communityId, userId ?? '', 'internal-history', filters, {
cursor: pageParam,
limit: 10,
}),
{ auth: 'none' },
),
initialPageParam: null as number | null,
getNextPageParam: (lastPage) => lastPage.nextCursor,
enabled: Boolean(communityId && userId && enabled),
});
}
+132 -1
View File
@@ -344,7 +344,8 @@ export type RiotQueueGroup =
| 'summoners-rift'
| 'aram'
| 'urf'
| 'arena';
| 'arena'
| 'internal';
export type RiotRankFilter = 'all' | 'solo' | 'flex' | 'normal';
export interface ApiHistorySeason {
@@ -482,6 +483,136 @@ export interface ApiRecentMatchesResponse {
season: ApiHistorySeason;
}
export interface ApiInternalMatchCard {
matchId: string;
title: string;
scheduledAt: string;
status: 'finished' | 'in-progress';
gameCount: number;
blueScore: number;
redScore: number;
winnerSide?: TeamSide;
games: Array<{
gameNumber: number;
riotMatchId: string | null;
winnerSide: TeamSide | null;
gameDuration: number;
}>;
teams: Array<{
side: TeamSide;
name: string;
members: Array<{
userId: string;
summonerName: string;
profileIconId: number;
}>;
}>;
}
export interface ApiInternalMatchListResponse {
matches: ApiInternalMatchCard[];
nextCursor: number | null;
season: ApiHistorySeason;
}
export interface ApiLeaderboardRow {
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 }>;
}
export interface ApiLeaderboardResponse {
rows: ApiLeaderboardRow[];
season: ApiHistorySeason;
}
export interface ApiLeaderHighlight {
metric: number;
userId: string;
summonerName: string;
championId?: number;
matchId?: string;
isSingleGame: boolean;
}
export interface ApiTeamInsightsResponse {
season: ApiHistorySeason;
sideWinRate: {
blue: number;
red: number;
bluePicks: number;
redPicks: number;
};
topKda: ApiLeaderHighlight | null;
mostKills: ApiLeaderHighlight | null;
topTeamGpm: ApiLeaderHighlight | null;
topKillParticipation: ApiLeaderHighlight | null;
bestFarm: ApiLeaderHighlight | null;
minGamesThreshold: number;
}
export interface ApiInternalMatchDetailResponse {
match: ApiInternalMatchCard;
games: Array<{
gameNumber: number;
riotMatchId: string;
gameCreation: number;
gameDuration: number;
teams: Array<{
side: TeamSide;
win: boolean;
objectives: { baron: number; dragon: number; tower: number };
participants: Array<{
userId: string | null;
summonerName: string;
side: TeamSide;
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;
}>;
}>;
}>;
}
export interface ApiUserInternalHistoryResponse {
season: ApiHistorySeason;
championStats: ApiChampionStatsResponse;
summary: ApiRecentSummaryResponse;
matches: ApiRecentMatchView[];
nextCursor: number | null;
lastFetchedAt: string | null;
}
export type ApiRiotJobPriority = 'high' | 'low';
export type ApiRiotJobState = 'queued' | 'processing' | 'completed' | 'failed';
@@ -0,0 +1,388 @@
import { Link, useSearchParams } from 'react-router';
import {
useCommunity,
useCommunityInternalStatsMatches,
useCommunityLeaderboard,
useDdragonManifest,
useTeamInsights,
} from '../api/hooks';
import type {
ApiInternalMatchCard,
ApiLeaderHighlight,
ApiLeaderboardRow,
TeamSide,
} from '../api/types';
import { DEFAULT_COMMUNITY_ID } from '../config';
import { championDisplayName, championIconUrl, profileIconUrl } from '../lib/ddragon';
function formatDateTime(value: string) {
return new Intl.DateTimeFormat('ko-KR', {
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(value));
}
function formatDuration(seconds: number) {
const minutes = Math.floor(seconds / 60);
const rest = seconds % 60;
return `${minutes}:${String(rest).padStart(2, '0')}`;
}
function sideLabel(side: TeamSide) {
return side === 'blue' ? '블루팀' : '레드팀';
}
function sideText(side: TeamSide) {
return side === 'blue' ? 'text-blue-400' : 'text-red-400';
}
function ratioClass(value: number) {
if (value >= 55) return 'text-blue-400';
if (value >= 50) return 'text-amber-400';
return 'text-base-content/45';
}
function ChampionChip({
championId,
manifest,
}: {
championId: number;
manifest: ReturnType<typeof useDdragonManifest>['data'];
}) {
const icon = championIconUrl(manifest, championId);
const name = championDisplayName(manifest, championId) ?? String(championId);
return (
<span className="inline-flex items-center gap-1.5">
<span className="w-5 h-5 bg-base-content/10 overflow-hidden">
{icon ? <img src={icon} alt="" className="w-full h-full object-cover" /> : null}
</span>
<span>{name}</span>
</span>
);
}
function MatchCard({
match,
manifest,
}: {
match: ApiInternalMatchCard;
manifest: ReturnType<typeof useDdragonManifest>['data'];
}) {
return (
<Link
to={`/communities/${DEFAULT_COMMUNITY_ID}/internal-stats/match/${match.matchId}`}
className="block group"
>
<article className="border border-base-content/10 bg-base-100 hover:border-primary/25 transition-colors">
<div className="p-4 grid lg:grid-cols-[1fr_auto_1fr] gap-4 items-center">
<div className="min-w-0">
<div className="text-[11px] text-base-content/35">
{formatDateTime(match.scheduledAt)}
</div>
<h3 className="mt-1 text-base font-black text-base-content truncate group-hover:text-primary">
{match.title}
</h3>
<div className="mt-2 flex flex-wrap gap-1.5">
{match.games.map((game) => (
<span
key={game.gameNumber}
className="inline-flex items-center gap-1 border border-base-content/10 px-2 py-1 text-[10px] text-base-content/45"
>
{game.gameNumber}경기
{game.winnerSide ? (
<span className={sideText(game.winnerSide)}>
{sideLabel(game.winnerSide)} 승
</span>
) : (
'대기'
)}
<span>{formatDuration(game.gameDuration)}</span>
</span>
))}
</div>
</div>
<div className="text-center px-8">
<div className="flex items-center justify-center gap-5">
<div className={match.winnerSide === 'blue' ? 'text-blue-400' : 'text-blue-400/30'}>
<div className="text-4xl font-black tabular-nums">{match.blueScore}</div>
<div className="text-[10px] font-bold uppercase tracking-wider">BLUE</div>
</div>
<div className="text-base-content/15 text-xs font-black">VS</div>
<div className={match.winnerSide === 'red' ? 'text-red-400' : 'text-red-400/30'}>
<div className="text-4xl font-black tabular-nums">{match.redScore}</div>
<div className="text-[10px] font-bold uppercase tracking-wider">RED</div>
</div>
</div>
</div>
<div className="grid sm:grid-cols-2 gap-2">
{match.teams.map((team) => (
<div
key={team.side}
className={`border ${team.side === 'blue' ? 'border-blue-500/15' : 'border-red-500/15'} p-2`}
>
<div className={`text-[10px] font-black uppercase tracking-wider ${sideText(team.side)}`}>
{team.name}
</div>
<div className="mt-2 space-y-1">
{team.members.slice(0, 5).map((member) => (
<div key={member.userId} className="flex items-center gap-1.5 min-w-0">
<span className="w-5 h-5 bg-base-content/10 overflow-hidden shrink-0">
<img
src={profileIconUrl(manifest, member.profileIconId)}
alt=""
className="w-full h-full object-cover"
loading="lazy"
/>
</span>
<span className="text-[11px] truncate text-base-content/65">
{member.summonerName}
</span>
</div>
))}
</div>
</div>
))}
</div>
</div>
</article>
</Link>
);
}
function HighlightCard({
title,
highlight,
suffix = '',
}: {
title: string;
highlight: ApiLeaderHighlight | null | undefined;
suffix?: string;
}) {
return (
<div className="border border-base-content/10 bg-base-100 p-4">
<div className="text-[10px] font-black uppercase tracking-wider text-base-content/30">
{title}
</div>
<div className="mt-2 text-xl font-black text-base-content tabular-nums">
{highlight ? `${highlight.metric}${suffix}` : '-'}
</div>
<div className="mt-1 text-[12px] text-base-content/45">
{highlight?.summonerName ?? '기록 없음'}
</div>
</div>
);
}
function LeaderboardTable({
rows,
manifest,
}: {
rows: ApiLeaderboardRow[];
manifest: ReturnType<typeof useDdragonManifest>['data'];
}) {
return (
<div className="border border-base-content/10 bg-base-100 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-left min-w-[920px]">
<thead>
<tr className="border-b border-base-content/10 bg-base-200/50 text-[11px] uppercase tracking-wider text-base-content/35">
<th className="px-3 py-2.5">#</th>
<th className="px-3 py-2.5">소환사</th>
<th className="px-3 py-2.5 text-center">승률</th>
<th className="px-3 py-2.5 text-center">게임</th>
<th className="px-3 py-2.5 text-center">KDA</th>
<th className="px-3 py-2.5 text-center">GPM</th>
<th className="px-3 py-2.5 text-center">킬관여</th>
<th className="px-3 py-2.5 text-center">분당 CS</th>
<th className="px-3 py-2.5">주 챔피언</th>
</tr>
</thead>
<tbody>
{rows.map((row, index) => (
<tr key={row.userId} className="border-b border-base-content/5 last:border-b-0">
<td className="px-3 py-2.5 text-[11px] text-base-content/30">
{index + 1}
</td>
<td className="px-3 py-2.5">
<Link
to={`/users/${row.userId}/history?queueGroup=internal`}
className="flex items-center gap-2 group"
>
<span className="w-7 h-7 bg-base-content/10 overflow-hidden">
<img
src={profileIconUrl(manifest, row.profileIconId)}
alt=""
className="w-full h-full object-cover"
loading="lazy"
/>
</span>
<span className="font-bold text-[13px] group-hover:text-primary">
{row.summonerName}
</span>
</Link>
</td>
<td className={`px-3 py-2.5 text-center text-[13px] font-black ${ratioClass(row.winRate)}`}>
{row.winRate}%
</td>
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
{row.games}
</td>
<td className="px-3 py-2.5 text-center text-[12px] font-bold tabular-nums">
{row.kda}
</td>
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
{row.avgGoldPerMin}
</td>
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
{row.avgKillParticipation}%
</td>
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
{row.avgCsPerMin}
</td>
<td className="px-3 py-2.5">
<div className="flex flex-wrap gap-2 text-[11px] text-base-content/55">
{row.topChampions.map((champion) => (
<ChampionChip
key={champion.championId}
championId={champion.championId}
manifest={manifest}
/>
))}
</div>
</td>
</tr>
))}
{rows.length === 0 && (
<tr>
<td colSpan={9} className="py-10 text-center text-sm text-base-content/35">
아직 집계할 내전 기록이 없습니다.
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
);
}
export default function CommunityInternalStatsPage() {
const [searchParams] = useSearchParams();
const championIdParam = Number(searchParams.get('championId'));
const championId =
Number.isFinite(championIdParam) && championIdParam > 0
? championIdParam
: undefined;
const filters = {
seasonId: searchParams.get('seasonId') ?? undefined,
championId,
limit: 12,
};
const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID);
const matchesQuery = useCommunityInternalStatsMatches(filters);
const leaderboardQuery = useCommunityLeaderboard(filters);
const insightsQuery = useTeamInsights(filters);
const { data: ddragon } = useDdragonManifest();
const matches = matchesQuery.data?.pages.flatMap((page) => page.matches) ?? [];
const season =
leaderboardQuery.data?.season ?? matchesQuery.data?.pages[0]?.season ?? null;
if (!DEFAULT_COMMUNITY_ID) {
return (
<main className="max-w-6xl mx-auto px-4 py-20 text-center text-sm text-amber-600">
`VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다.
</main>
);
}
return (
<main className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
<Link to="/" className="text-xs text-base-content/40 hover:text-base-content">
← 홈으로
</Link>
<section className="mt-5 mb-6 border border-base-content/10 bg-base-100 p-5">
<div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4">
<div>
<p className="text-[11px] font-black uppercase tracking-[0.24em] text-primary">
Community Records
</p>
<h1 className="mt-2 text-3xl font-black text-base-content">
{communityQuery.data?.name ?? '커뮤니티'} 내전 전적
</h1>
<p className="mt-2 text-sm text-base-content/45">
토너먼트 코드로 수집된 결과를 기준으로 매치, 선수 순위, 팀 인사이트를 보여줍니다.
</p>
</div>
<div className="border border-base-content/10 px-4 py-3 text-sm text-base-content/55">
<div className="text-[10px] uppercase tracking-wider text-base-content/30">
시즌
</div>
<div className="mt-1 font-bold">{season?.label ?? '현재 시즌'}</div>
</div>
</div>
</section>
<section className="grid sm:grid-cols-2 lg:grid-cols-5 gap-3 mb-6">
<HighlightCard title="최고 KDA" highlight={insightsQuery.data?.topKda} />
<HighlightCard title="누적 킬 1위" highlight={insightsQuery.data?.mostKills} />
<HighlightCard title="단일 경기 GPM" highlight={insightsQuery.data?.topTeamGpm} />
<HighlightCard title="킬 관여율" highlight={insightsQuery.data?.topKillParticipation} suffix="%" />
<HighlightCard title="분당 CS" highlight={insightsQuery.data?.bestFarm} />
</section>
<section className="mb-8">
<div className="flex items-center justify-between gap-3 mb-3">
<h2 className="text-sm font-black text-base-content">최근 내전</h2>
<div className="text-[11px] text-base-content/35">
블루 승률 {insightsQuery.data?.sideWinRate.blue ?? 0}% · 레드 승률{' '}
{insightsQuery.data?.sideWinRate.red ?? 0}%
</div>
</div>
{matchesQuery.isLoading ? (
<div className="border border-base-content/10 bg-base-100 px-4 py-12 text-center text-sm text-base-content/35">
내전 기록을 불러오는 중...
</div>
) : (
<div className="space-y-3">
{matches.map((match) => (
<MatchCard key={match.matchId} match={match} manifest={ddragon} />
))}
{matches.length === 0 && (
<div className="border border-base-content/10 bg-base-100 px-4 py-12 text-center text-sm text-base-content/35">
아직 수집된 내전 결과가 없습니다.
</div>
)}
</div>
)}
{matchesQuery.hasNextPage && (
<button
type="button"
className="mt-3 w-full border border-base-content/15 bg-base-100 py-3 text-sm font-bold text-base-content/60 hover:text-primary hover:border-primary/30 disabled:opacity-40"
disabled={matchesQuery.isFetchingNextPage}
onClick={() => matchesQuery.fetchNextPage()}
>
{matchesQuery.isFetchingNextPage ? '불러오는 중...' : '+ 더 보기'}
</button>
)}
</section>
<section>
<div className="flex items-center justify-between gap-3 mb-3">
<h2 className="text-sm font-black text-base-content">선수 순위</h2>
<div className="text-[11px] text-base-content/35">
포지션은 Riot Match의 라인 정보를 기준으로 합니다.
</div>
</div>
<LeaderboardTable
rows={leaderboardQuery.data?.rows ?? []}
manifest={ddragon}
/>
</section>
</main>
);
}
+11 -3
View File
@@ -88,9 +88,17 @@ export default function HomePage() {
return (
<main className="max-w-5xl mx-auto px-4 sm:px-6">
<section className="pt-8 pb-6">
<h2 className="text-xs font-bold text-base-content/40 uppercase tracking-widest mb-3">
다음 내전
</h2>
<div className="flex items-center justify-between gap-3 mb-3">
<h2 className="text-xs font-bold text-base-content/40 uppercase tracking-widest">
다음 내전
</h2>
<Link
to={`/communities/${DEFAULT_COMMUNITY_ID}/internal-stats`}
className="text-xs font-bold text-primary hover:underline"
>
내전 전적 보기
</Link>
</div>
{nextMatch ? (
<Link to={`/match/${nextMatch.id}`} className="block group">
@@ -0,0 +1,262 @@
import { Link, useParams } from 'react-router';
import { useDdragonManifest, useInternalMatchDetail } from '../api/hooks';
import type { ApiInternalMatchDetailResponse, TeamSide } from '../api/types';
import { DEFAULT_COMMUNITY_ID } from '../config';
import { championDisplayName, championIconUrl, itemIconUrl } from '../lib/ddragon';
import { LANE_LABELS } from '../lib/riot-history';
function formatDateTime(value: string | number) {
return new Intl.DateTimeFormat('ko-KR', {
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(value));
}
function formatDuration(seconds: number) {
const minutes = Math.floor(seconds / 60);
const rest = seconds % 60;
return `${minutes}:${String(rest).padStart(2, '0')}`;
}
function sideLabel(side: TeamSide) {
return side === 'blue' ? '블루팀' : '레드팀';
}
function sideClass(side: TeamSide) {
return side === 'blue' ? 'text-blue-400 border-blue-500/20' : 'text-red-400 border-red-500/20';
}
function ChampionCell({
championId,
manifest,
}: {
championId: number;
manifest: ReturnType<typeof useDdragonManifest>['data'];
}) {
const icon = championIconUrl(manifest, championId);
const name = championDisplayName(manifest, championId) ?? String(championId);
return (
<div className="flex items-center gap-2 min-w-0">
<span className="w-8 h-8 bg-base-content/10 overflow-hidden shrink-0">
{icon ? <img src={icon} alt="" className="w-full h-full object-cover" /> : null}
</span>
<span className="font-bold text-[13px] truncate">{name}</span>
</div>
);
}
function ItemStrip({
items,
trinket,
manifest,
}: {
items: number[];
trinket: number;
manifest: ReturnType<typeof useDdragonManifest>['data'];
}) {
return (
<div className="flex flex-wrap gap-1">
{[...items, trinket].map((itemId, index) => {
const icon = itemIconUrl(manifest, itemId);
return (
<span
key={`${itemId}-${index}`}
className="w-5 h-5 bg-base-content/10 border border-base-content/5 overflow-hidden"
>
{icon ? <img src={icon} alt="" className="w-full h-full object-cover" /> : null}
</span>
);
})}
</div>
);
}
function GamePanel({
game,
manifest,
}: {
game: ApiInternalMatchDetailResponse['games'][number];
manifest: ReturnType<typeof useDdragonManifest>['data'];
}) {
return (
<section className="border border-base-content/10 bg-base-100 overflow-hidden">
<div className="px-4 py-3 border-b border-base-content/10 bg-base-200/40 flex flex-wrap items-center justify-between gap-3">
<div>
<h2 className="text-sm font-black text-base-content">
{game.gameNumber}경기
</h2>
<p className="mt-1 text-[11px] text-base-content/35">
{formatDateTime(game.gameCreation)} · {formatDuration(game.gameDuration)} ·{' '}
<span className="font-mono">{game.riotMatchId}</span>
</p>
</div>
<div className="flex gap-2">
{game.teams.map((team) => (
<span
key={team.side}
className={`border px-2 py-1 text-[11px] font-black ${sideClass(team.side)} ${
team.win ? 'bg-base-content/5' : 'opacity-40'
}`}
>
{sideLabel(team.side)} {team.win ? '승' : '패'}
</span>
))}
</div>
</div>
{game.teams.map((team) => (
<div key={team.side} className="border-b border-base-content/8 last:border-b-0">
<div className={`px-4 py-2 text-[11px] font-black uppercase tracking-wider ${sideClass(team.side)}`}>
{sideLabel(team.side)} · 바론 {team.objectives.baron} · 드래곤{' '}
{team.objectives.dragon} · 타워 {team.objectives.tower}
</div>
<div className="overflow-x-auto">
<table className="w-full text-left min-w-[980px]">
<thead>
<tr className="bg-base-content/[0.02] text-[11px] text-base-content/35 uppercase tracking-wider">
<th className="px-3 py-2">소환사</th>
<th className="px-3 py-2">챔피언</th>
<th className="px-3 py-2 text-center">포지션</th>
<th className="px-3 py-2 text-center">K/D/A</th>
<th className="px-3 py-2 text-center">CS</th>
<th className="px-3 py-2 text-center">GPM</th>
<th className="px-3 py-2 text-center">킬관여</th>
<th className="px-3 py-2 text-center">피해비중</th>
<th className="px-3 py-2">아이템</th>
</tr>
</thead>
<tbody>
{team.participants.map((participant) => (
<tr
key={`${team.side}-${participant.userId}-${participant.championId}`}
className="border-t border-base-content/5"
>
<td className="px-3 py-2">
{participant.userId ? (
<Link
to={`/users/${participant.userId}/history?queueGroup=internal`}
className="font-bold text-[13px] hover:text-primary"
>
{participant.summonerName}
</Link>
) : (
<span className="font-bold text-[13px]">
{participant.summonerName}
</span>
)}
</td>
<td className="px-3 py-2">
<ChampionCell championId={participant.championId} manifest={manifest} />
</td>
<td className="px-3 py-2 text-center text-[12px]">
{LANE_LABELS[participant.teamPosition] ?? participant.teamPosition ?? '-'}
</td>
<td className="px-3 py-2 text-center text-[13px] font-black tabular-nums">
{participant.kills}
<span className="text-base-content/25"> / </span>
<span className="text-red-400">{participant.deaths}</span>
<span className="text-base-content/25"> / </span>
{participant.assists}
</td>
<td className="px-3 py-2 text-center text-[12px] tabular-nums">
{participant.cs} ({participant.csPerMin}/m)
</td>
<td className="px-3 py-2 text-center text-[12px] tabular-nums">
{participant.gpm}
</td>
<td className="px-3 py-2 text-center text-[12px] tabular-nums">
{participant.killParticipation}%
</td>
<td className="px-3 py-2 text-center text-[12px] tabular-nums">
{participant.damageShare}%
</td>
<td className="px-3 py-2">
<ItemStrip
items={participant.items}
trinket={participant.trinket}
manifest={manifest}
/>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
))}
</section>
);
}
export default function InternalMatchDetailPage() {
const { cid, matchId } = useParams();
const communityId = cid ?? DEFAULT_COMMUNITY_ID;
const detailQuery = useInternalMatchDetail(matchId, communityId);
const { data: ddragon } = useDdragonManifest();
const detail = detailQuery.data;
if (detailQuery.isLoading) {
return (
<main className="max-w-6xl mx-auto px-4 py-20 text-center text-sm text-base-content/40">
내전 상세 기록을 불러오는 중...
</main>
);
}
if (detailQuery.error || !detail) {
return (
<main className="max-w-6xl mx-auto px-4 py-20 text-center">
<h1 className="text-lg font-bold">내전 기록을 찾을 수 없습니다</h1>
<Link
to={`/communities/${communityId}/internal-stats`}
className="btn btn-ghost btn-sm mt-4"
>
내전 전적으로 돌아가기
</Link>
</main>
);
}
return (
<main className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
<Link
to={`/communities/${communityId}/internal-stats`}
className="text-xs text-base-content/40 hover:text-base-content"
>
← 내전 전적
</Link>
<section className="mt-5 mb-6 border border-base-content/10 bg-base-100 p-5">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h1 className="text-2xl font-black text-base-content">
{detail.match.title}
</h1>
<p className="mt-2 text-sm text-base-content/45">
{formatDateTime(detail.match.scheduledAt)} · {detail.match.gameCount}전제
</p>
</div>
<div className="flex items-center gap-6">
<div className={detail.match.winnerSide === 'blue' ? 'text-blue-400' : 'text-blue-400/30'}>
<div className="text-4xl font-black tabular-nums">{detail.match.blueScore}</div>
<div className="text-[10px] font-bold uppercase tracking-wider">BLUE</div>
</div>
<div className="text-base-content/15 text-xs font-black">VS</div>
<div className={detail.match.winnerSide === 'red' ? 'text-red-400' : 'text-red-400/30'}>
<div className="text-4xl font-black tabular-nums">{detail.match.redScore}</div>
<div className="text-[10px] font-bold uppercase tracking-wider">RED</div>
</div>
</div>
</div>
</section>
<div className="space-y-4">
{detail.games.map((game) => (
<GamePanel key={game.riotMatchId} game={game} manifest={ddragon} />
))}
</div>
</main>
);
}
+126 -51
View File
@@ -7,6 +7,7 @@ import {
useRecentMatches,
useRecentSummary,
useRefreshUserHistory,
useUserInternalHistory,
useUserHistoryProfile,
type UserHistoryFilters,
} from "../api/hooks";
@@ -495,7 +496,9 @@ export default function UserHistoryPage() {
const queueGroup: RiotQueueGroup = isRiotQueueGroup(queueGroupParam)
? queueGroupParam
: "summoners-rift";
const rank: RiotRankFilter = isRiotRankFilter(rankParam) ? rankParam : "all";
const isInternalQueue = queueGroup === "internal";
const rank: RiotRankFilter =
!isInternalQueue && isRiotRankFilter(rankParam) ? rankParam : "all";
const championIdParam = Number(searchParams.get("championId"));
const championId =
Number.isFinite(championIdParam) && championIdParam > 0
@@ -514,16 +517,30 @@ export default function UserHistoryPage() {
};
const { data: ddragon } = useDdragonManifest();
const profileQuery = useUserHistoryProfile(userId, DEFAULT_COMMUNITY_ID);
const standardHistoryEnabled = !isInternalQueue;
const championStatsQuery = useChampionStats(
userId,
aggregateFilters,
DEFAULT_COMMUNITY_ID,
standardHistoryEnabled,
);
const summaryQuery = useRecentSummary(
userId,
filters,
DEFAULT_COMMUNITY_ID,
standardHistoryEnabled,
);
const summaryQuery = useRecentSummary(userId, filters, DEFAULT_COMMUNITY_ID);
const recentMatchesQuery = useRecentMatches(
userId,
filters,
DEFAULT_COMMUNITY_ID,
standardHistoryEnabled,
);
const internalHistoryQuery = useUserInternalHistory(
userId,
filters,
DEFAULT_COMMUNITY_ID,
isInternalQueue,
);
const refreshMutation = useRefreshUserHistory(userId, DEFAULT_COMMUNITY_ID);
@@ -531,14 +548,32 @@ export default function UserHistoryPage() {
const primaryTier =
profile?.tiers.find((tier) => tier.queueType === "RANKED_SOLO_5x5") ??
profile?.tiers[0];
const matches =
recentMatchesQuery.data?.pages.flatMap((page) => page.matches) ?? [];
const internalPages = internalHistoryQuery.data?.pages ?? [];
const internalFirstPage = internalPages[0];
const summary = isInternalQueue ? internalFirstPage?.summary : summaryQuery.data;
const matches = isInternalQueue
? internalPages.flatMap((page) => page.matches)
: (recentMatchesQuery.data?.pages.flatMap((page) => page.matches) ?? []);
const historyLastFetchedAt = isInternalQueue
? internalFirstPage?.lastFetchedAt
: recentMatchesQuery.data?.pages[0]?.lastFetchedAt;
const matchesLoading = isInternalQueue
? internalHistoryQuery.isLoading
: recentMatchesQuery.isLoading;
const hasNextPage = isInternalQueue
? internalHistoryQuery.hasNextPage
: recentMatchesQuery.hasNextPage;
const isFetchingNextPage = isInternalQueue
? internalHistoryQuery.isFetchingNextPage
: recentMatchesQuery.isFetchingNextPage;
const selectedChampionName = championId
? (championDisplayName(ddragon, championId) ?? String(championId))
: null;
const visibleChampionRows = useMemo(() => {
const rows = championStatsQuery.data?.champions ?? [];
const rows = isInternalQueue
? (internalFirstPage?.championStats.champions ?? [])
: (championStatsQuery.data?.champions ?? []);
const keyword = championSearch.trim().toLowerCase();
return rows
.filter((row) => {
@@ -549,10 +584,17 @@ export default function UserHistoryPage() {
return displayName.toLowerCase().includes(keyword);
})
.sort((left, right) => right[sortKey] - left[sortKey]);
}, [championSearch, championStatsQuery.data?.champions, ddragon, sortKey]);
}, [
championSearch,
championStatsQuery.data?.champions,
ddragon,
internalFirstPage?.championStats.champions,
isInternalQueue,
sortKey,
]);
const refreshSocket = useRiotRefreshSocket({
puuid: profile?.puuid,
puuid: isInternalQueue ? undefined : profile?.puuid,
parentJobId: refreshResult?.parentJobId,
onEvent: (event: ApiRiotRefreshEvent) => {
if (!profile || event.puuid !== profile.puuid) return;
@@ -600,11 +642,24 @@ export default function UserHistoryPage() {
queryClient.invalidateQueries({
queryKey: ["user-recent-matches", DEFAULT_COMMUNITY_ID, userId ?? null],
}),
queryClient.invalidateQueries({
queryKey: ["user-internal-history", DEFAULT_COMMUNITY_ID, userId ?? null],
}),
]);
}
function handleRefresh() {
if (!userId) return;
if (isInternalQueue) {
setRefreshResult(null);
setRefreshNotice(
"내전 기록은 토너먼트 결과 수집 데이터를 다시 조회합니다. Riot API 갱신 큐는 사용하지 않습니다.",
);
void queryClient.invalidateQueries({
queryKey: ["user-internal-history", DEFAULT_COMMUNITY_ID, userId ?? null],
});
return;
}
refreshMutation.mutate(
{ queueGroups: [queueGroup], priority: "high" },
{
@@ -699,10 +754,19 @@ export default function UserHistoryPage() {
</div>
<div className="border border-dashed border-base-content/10 px-3 py-2 text-[11px] text-base-content/35 sm:text-right space-y-2">
<div>
{/* 이 페이지는 저장된 경기 DB만 조회합니다. */}
<br />
{/* Riot API 갱신은 버튼 클릭 시 큐에서 처리합니다. */}
아래 버튼을 누르면 기록이 갱신됩니다.
{isInternalQueue ? (
<>
{/* 내전 탭은 토너먼트 결과 DB를 조회합니다. */}
Riot API 갱신 없이 수집된 내전 결과를 다시 불러옵니다.
</>
) : (
<>
{/* 이 페이지는 저장된 경기 DB만 조회합니다. */}
<br />
{/* Riot API 갱신은 버튼 클릭 시 큐에서 처리합니다. */}
아래 버튼을 누르면 기록이 갱신됩니다.
</>
)}
</div>
<button
type="button"
@@ -710,11 +774,17 @@ export default function UserHistoryPage() {
disabled={refreshMutation.isPending || !userId}
onClick={handleRefresh}
>
{refreshMutation.isPending ? "요청 중..." : "정보 갱신"}
{isInternalQueue
? "내전 기록 다시 불러오기"
: refreshMutation.isPending
? "요청 중..."
: "정보 갱신"}
</button>
<div className="text-[10px] text-base-content/25">
갱신 소켓: {refreshSocket.connectionStatus}
</div>
{!isInternalQueue && (
<div className="text-[10px] text-base-content/25">
갱신 소켓: {refreshSocket.connectionStatus}
</div>
)}
</div>
</div>
{(refreshNotice || refreshSocket.error) && (
@@ -739,19 +809,25 @@ export default function UserHistoryPage() {
))}
</div>
<div className="flex flex-wrap items-center justify-between gap-3 px-3 py-2">
<div className="flex flex-wrap">
{RANK_FILTER_TABS.map((tab) => (
<FilterButton
key={tab.value}
active={rank === tab.value}
onClick={() =>
updateSearch({ rank: tab.value, championId: null })
}
>
{tab.label}
</FilterButton>
))}
</div>
{!isInternalQueue ? (
<div className="flex flex-wrap">
{RANK_FILTER_TABS.map((tab) => (
<FilterButton
key={tab.value}
active={rank === tab.value}
onClick={() =>
updateSearch({ rank: tab.value, championId: null })
}
>
{tab.label}
</FilterButton>
))}
</div>
) : (
<div className="px-3 py-2 text-[11px] text-base-content/40">
내전 탭은 토너먼트 코드 결과 수집 데이터를 기준으로 집계합니다.
</div>
)}
{selectedChampionName && (
<button
type="button"
@@ -781,33 +857,33 @@ export default function UserHistoryPage() {
<section className="mb-6">
<h2 className="text-sm font-bold text-base-content mb-3">
최근 {summaryQuery.data?.windowSize ?? 20}게임 전적 요약
최근 {summary?.windowSize ?? 20}게임 전적 요약
</h2>
<div className="grid sm:grid-cols-2 lg:grid-cols-5 gap-3">
<SummaryCard
label="승률"
value={`${summaryQuery.data?.winRate ?? 0}%`}
sub={`${summaryQuery.data?.wins ?? 0}승 ${summaryQuery.data?.losses ?? 0}패`}
value={`${summary?.winRate ?? 0}%`}
sub={`${summary?.wins ?? 0}승 ${summary?.losses ?? 0}패`}
/>
<SummaryCard
label="KDA"
value={summaryQuery.data?.kda ?? 0}
sub={`${summaryQuery.data?.avgKills ?? 0} / ${summaryQuery.data?.avgDeaths ?? 0} / ${summaryQuery.data?.avgAssists ?? 0}`}
value={summary?.kda ?? 0}
sub={`${summary?.avgKills ?? 0} / ${summary?.avgDeaths ?? 0} / ${summary?.avgAssists ?? 0}`}
/>
<SummaryCard
label="최고 평점"
value={summaryQuery.data?.bestRating?.rating ?? "-"}
value={summary?.bestRating?.rating ?? "-"}
sub={
summaryQuery.data?.bestRating
? `${summaryQuery.data.bestRating.kills}/${summaryQuery.data.bestRating.deaths}/${summaryQuery.data.bestRating.assists}`
summary?.bestRating
? `${summary.bestRating.kills}/${summary.bestRating.deaths}/${summary.bestRating.assists}`
: "기록 없음"
}
/>
<SummaryCard
label="연승/연패"
value={
summaryQuery.data?.streak
? `${summaryQuery.data.streak.count}${summaryQuery.data.streak.type === "win" ? "연승" : "연패"}`
summary?.streak
? `${summary.streak.count}${summary.streak.type === "win" ? "연승" : "연패"}`
: "-"
}
sub="가장 최근 경기 기준"
@@ -817,7 +893,7 @@ export default function UserHistoryPage() {
자주 플레이한 챔피언
</div>
<div className="mt-3 flex items-center gap-3">
{(summaryQuery.data?.topChampions ?? []).map((champion) => (
{(summary?.topChampions ?? []).map((champion) => (
<button
type="button"
key={champion.championId}
@@ -835,7 +911,7 @@ export default function UserHistoryPage() {
</div>
</button>
))}
{(summaryQuery.data?.topChampions ?? []).length === 0 && (
{(summary?.topChampions ?? []).length === 0 && (
<span className="text-[11px] text-base-content/25">
기록 없음
</span>
@@ -890,14 +966,11 @@ export default function UserHistoryPage() {
<div className="flex items-center justify-between gap-3 mb-3">
<h2 className="text-sm font-bold text-base-content">매치 히스토리</h2>
<span className="text-[11px] text-base-content/35">
최근 저장:{" "}
{formatLastFetched(
recentMatchesQuery.data?.pages[0]?.lastFetchedAt,
)}
최근 저장: {formatLastFetched(historyLastFetchedAt)}
</span>
</div>
{recentMatchesQuery.isLoading ? (
{matchesLoading ? (
<div className="border border-base-content/10 bg-base-100 px-4 py-10 text-center text-sm text-base-content/35">
최근 경기를 불러오는 중...
</div>
@@ -917,16 +990,18 @@ export default function UserHistoryPage() {
</div>
)}
{recentMatchesQuery.hasNextPage && (
{hasNextPage && (
<button
type="button"
className="mt-3 w-full border border-base-content/15 bg-base-100 py-3 text-sm font-bold text-base-content/60 hover:border-primary/30 hover:text-primary disabled:opacity-40"
disabled={recentMatchesQuery.isFetchingNextPage}
onClick={() => recentMatchesQuery.fetchNextPage()}
disabled={isFetchingNextPage}
onClick={() =>
isInternalQueue
? internalHistoryQuery.fetchNextPage()
: recentMatchesQuery.fetchNextPage()
}
>
{recentMatchesQuery.isFetchingNextPage
? "불러오는 중..."
: "+ 더 보기"}
{isFetchingNextPage ? "불러오는 중..." : "+ 더 보기"}
</button>
)}
</section>
+450
View File
@@ -0,0 +1,450 @@
# 커뮤니티 내전 전적 / 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 로그)