diff --git a/Legacy-Internal-Match-Import-플랜.md b/Legacy-Internal-Match-Import-플랜.md new file mode 100644 index 00000000..aa3dd57c --- /dev/null +++ b/Legacy-Internal-Match-Import-플랜.md @@ -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:` 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(); + + // 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:` 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:*::*` 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 통계 페이지에 자동 포함됨 diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts index 9e5770a7..415ea473 100644 --- a/apps/api/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -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, diff --git a/apps/api/src/modules/community-stats/community-stats-cache.service.ts b/apps/api/src/modules/community-stats/community-stats-cache.service.ts new file mode 100644 index 00000000..4d6abeb7 --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats-cache.service.ts @@ -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(key: string): Promise { + return this.garnetService.getJson(key); + } + + public set( + key: string, + value: unknown, + ttlSeconds = COMMUNITY_STATS_TTL_SECONDS, + ): Promise { + return this.garnetService.setJson(key, value, ttlSeconds); + } + + public setDetail(key: string, value: unknown): Promise { + return this.set(key, value, COMMUNITY_STATS_DETAIL_TTL_SECONDS); + } + + public async invalidateCommunity(communityId: string): Promise { + 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; + } +} diff --git a/apps/api/src/modules/community-stats/community-stats.controller.ts b/apps/api/src/modules/community-stats/community-stats.controller.ts new file mode 100644 index 00000000..e8d4ee69 --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.controller.ts @@ -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; + } +} diff --git a/apps/api/src/modules/community-stats/community-stats.module.ts b/apps/api/src/modules/community-stats/community-stats.module.ts new file mode 100644 index 00000000..c52af44c --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.module.ts @@ -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 {} diff --git a/apps/api/src/modules/community-stats/community-stats.service.ts b/apps/api/src/modules/community-stats/community-stats.service.ts new file mode 100644 index 00000000..c9e76511 --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.service.ts @@ -0,0 +1,1072 @@ +import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + CommunityDocument, + MatchDocument, + MatchGameResultParticipant, + RiotLane, + TeamSide, +} from '../global/database/schema'; +import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types'; +import type { HistorySeasonDto, RecentMatchView } from '../match-history/match-history.types'; +import { CommunityStatsCacheService } from './community-stats-cache.service'; +import type { + CommunityStatsFilters, + InternalMatchCardView, + InternalMatchDetailResponse, + InternalMatchListResponse, + LeaderboardChampionStats, + LeaderboardResponse, + LeaderboardRow, + LeaderHighlight, + TeamInsightsResponse, + UserInternalHistoryResponse, +} from './community-stats.types'; + +const DEFAULT_LIST_LIMIT = 20; +const MAX_LIST_LIMIT = 50; +const MAX_MATCH_SCAN = 300; +const MIN_HIGHLIGHT_GAMES = 5; + +interface CommunityStatsContext { + community: CommunityDocument; + season: HistorySeasonDto; + from: Date | null; + to: Date | null; +} + +interface InternalRecord { + matchId: string; + title: string; + scheduledAt: Date; + gameNumber: number; + riotMatchId: string; + gameCreation: number; + gameDuration: number; + userId: string; + summonerName: string; + profileIconId: number; + side: TeamSide; + championId: number; + championLevel: number; + teamPosition: string; + kills: number; + deaths: number; + assists: number; + win: boolean; + cs: number; + csPerMin: number; + gold: number; + gpm: number; + damageDealtToChampions: number; + damageTaken: number; + damageShare: number; + killParticipation: number; + visionScore: number; + controlWardsBought: number; + wardsPlaced: number; + wardsKilled: number; + items: number[]; + trinket: number; + summonerSpells: [number, number]; + perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + rating: number; +} + +interface InternalGameDetail { + gameNumber: number; + riotMatchId: string; + gameCreation: number; + gameDuration: number; + winnerSide: TeamSide; + teams: Array<{ + side: TeamSide; + win: boolean; + objectives: { baron: number; dragon: number; tower: number }; + participants: InternalRecord[]; + }>; +} + +interface BaseDataset { + season: HistorySeasonDto; + matches: InternalMatchCardView[]; + records: InternalRecord[]; + detailsByMatchId: Map; +} + +@Injectable() +export class CommunityStatsService { + constructor( + private readonly connectionService: ConnectionService, + private readonly cacheService: CommunityStatsCacheService, + ) {} + + public async getMatches(params: { + communityId: mongoose.Types.ObjectId; + filters: CommunityStatsFilters; + }): Promise { + const key = this.cacheKey('matches', params.communityId, params.filters); + const cached = await this.cacheService.get(key); + if (cached) return cached; + + const limit = this.clampLimit(params.filters.limit, DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT); + const dataset = await this.buildBaseDataset(params.communityId, params.filters); + const filtered = params.filters.championId + ? dataset.matches.filter((match) => + dataset.records.some( + (record) => + record.matchId === match.matchId && + record.championId === params.filters.championId, + ), + ) + : dataset.matches; + const cursor = params.filters.cursor; + const page = filtered + .filter((match) => !cursor || new Date(match.scheduledAt).getTime() < cursor) + .slice(0, limit + 1); + const visible = page.slice(0, limit); + const response: InternalMatchListResponse = { + matches: visible, + nextCursor: + page.length > limit + ? new Date(visible[visible.length - 1]?.scheduledAt ?? 0).getTime() + : null, + season: dataset.season, + }; + await this.cacheService.set(key, response); + return response; + } + + public async getLeaderboard(params: { + communityId: mongoose.Types.ObjectId; + filters: CommunityStatsFilters; + }): Promise { + const key = this.cacheKey('leaderboard', params.communityId, params.filters); + const cached = await this.cacheService.get(key); + if (cached) return cached; + + const dataset = await this.buildBaseDataset(params.communityId, params.filters); + const records = this.applyChampionFilter(dataset.records, params.filters); + const rows = this.buildLeaderboardRows(records); + const response = { rows, season: dataset.season }; + await this.cacheService.set(key, response); + return response; + } + + public async getTeamInsights(params: { + communityId: mongoose.Types.ObjectId; + filters: CommunityStatsFilters; + }): Promise { + const key = this.cacheKey('teamInsights', params.communityId, params.filters); + const cached = await this.cacheService.get(key); + if (cached) return cached; + + const dataset = await this.buildBaseDataset(params.communityId, params.filters); + const records = this.applyChampionFilter(dataset.records, params.filters); + const rows = this.buildLeaderboardRows(records); + const gameDetails = [...dataset.detailsByMatchId.values()].flat(); + const blueGames = gameDetails.length; + const redGames = gameDetails.length; + const blueWins = gameDetails.filter((game) => game.winnerSide === 'blue').length; + const redWins = gameDetails.filter((game) => game.winnerSide === 'red').length; + + const response: TeamInsightsResponse = { + season: dataset.season, + sideWinRate: { + blue: this.percent(blueWins, blueGames), + red: this.percent(redWins, redGames), + bluePicks: blueGames, + redPicks: redGames, + }, + topKda: this.toHighlight( + rows + .filter((row) => row.games >= MIN_HIGHLIGHT_GAMES) + .sort((left, right) => right.kda - left.kda)[0], + 'kda', + ), + mostKills: this.toHighlight( + rows.sort((left, right) => right.totalKills - left.totalKills)[0], + 'totalKills', + ), + topTeamGpm: this.toSingleGameHighlight( + records.sort((left, right) => right.gpm - left.gpm)[0], + 'gpm', + ), + topKillParticipation: this.toHighlight( + rows + .filter((row) => row.games >= MIN_HIGHLIGHT_GAMES) + .sort( + (left, right) => + right.avgKillParticipation - left.avgKillParticipation, + )[0], + 'avgKillParticipation', + ), + bestFarm: this.toHighlight( + rows + .filter((row) => row.games >= MIN_HIGHLIGHT_GAMES) + .sort((left, right) => right.avgCsPerMin - left.avgCsPerMin)[0], + 'avgCsPerMin', + ), + minGamesThreshold: MIN_HIGHLIGHT_GAMES, + }; + await this.cacheService.set(key, response); + return response; + } + + public async getMatchDetail(params: { + communityId: mongoose.Types.ObjectId; + matchId: mongoose.Types.ObjectId; + }): Promise { + const key = `riot:communitystats:matchDetail:${params.communityId.toString()}:${params.matchId.toString()}`; + const cached = await this.cacheService.get(key); + if (cached) return cached; + + const dataset = await this.buildBaseDataset(params.communityId, { + seasonId: 'all', + }); + const match = dataset.matches.find( + (item) => item.matchId === params.matchId.toString(), + ); + if (!match) throw new NotFoundException('Internal match not found.'); + const response: InternalMatchDetailResponse = { + match, + games: (dataset.detailsByMatchId.get(match.matchId) ?? []).map((game) => ({ + gameNumber: game.gameNumber, + riotMatchId: game.riotMatchId, + gameCreation: game.gameCreation, + gameDuration: game.gameDuration, + teams: game.teams.map((team) => ({ + side: team.side, + win: team.win, + objectives: team.objectives, + participants: team.participants.map((record) => ({ + userId: record.userId, + summonerName: record.summonerName, + side: record.side, + teamPosition: record.teamPosition, + championId: record.championId, + kills: record.kills, + deaths: record.deaths, + assists: record.assists, + cs: record.cs, + csPerMin: record.csPerMin, + gold: record.gold, + gpm: record.gpm, + damageDealtToChampions: record.damageDealtToChampions, + damageShare: record.damageShare, + killParticipation: record.killParticipation, + visionScore: record.visionScore, + items: record.items, + trinket: record.trinket, + summonerSpells: record.summonerSpells, + perks: record.perks, + win: record.win, + })), + })), + })), + }; + await this.cacheService.setDetail(key, response); + return response; + } + + public async getUserInternalHistory(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + filters: CommunityStatsFilters; + }): Promise { + const key = this.cacheKey( + `userInternal:${params.userId.toString()}`, + params.communityId, + params.filters, + ); + const cached = await this.cacheService.get(key); + if (cached) return cached; + + const dataset = await this.buildBaseDataset(params.communityId, params.filters); + const allUserRecords = dataset.records + .filter((record) => record.userId === params.userId.toString()) + .sort((left, right) => right.gameCreation - left.gameCreation); + const records = this.applyChampionFilter(allUserRecords, params.filters); + const limit = this.clampLimit(params.filters.limit, 30, 50); + const cursor = params.filters.cursor; + const page = records + .filter((record) => !cursor || record.gameCreation < cursor) + .slice(0, limit + 1); + const visible = page.slice(0, limit); + const response: UserInternalHistoryResponse = { + season: dataset.season, + championStats: this.buildUserChampionStats(allUserRecords, dataset.season), + summary: this.buildUserSummary(records, visible.length || limit), + matches: visible.map((record) => this.toRecentMatchView(record, dataset)), + nextCursor: + page.length > limit + ? visible[visible.length - 1]?.gameCreation ?? null + : null, + lastFetchedAt: records[0] ? new Date(records[0].gameCreation).toISOString() : null, + }; + await this.cacheService.set(key, response); + return response; + } + + public invalidateCommunity(communityId: mongoose.Types.ObjectId): Promise { + return this.cacheService.invalidateCommunity(communityId.toString()); + } + + private async buildBaseDataset( + communityId: mongoose.Types.ObjectId, + filters: CommunityStatsFilters, + ): Promise { + const context = await this.resolveContext(communityId, filters); + const MatchModel = await this.connectionService.getModel('match'); + const RiotMatchModel = await this.connectionService.getModel('riotMatch'); + const matches = await MatchModel.find({ + communityId, + status: { $in: ['finished', 'in-progress'] }, + 'result.games.0': { $exists: true }, + }) + .sort({ scheduledAt: -1 }) + .limit(MAX_MATCH_SCAN) + .exec(); + const riotMatchIds = [ + ...new Set( + matches.flatMap((match) => + (match.result?.games ?? []).map((game) => game.riotMatchId), + ), + ), + ]; + const riotDocs = await RiotMatchModel.find({ matchId: { $in: riotMatchIds } }) + .lean() + .exec(); + const rawByMatchId = new Map( + riotDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]), + ); + + const cards: InternalMatchCardView[] = []; + const records: InternalRecord[] = []; + const detailsByMatchId = new Map(); + + for (const match of matches) { + const games = (match.result?.games ?? []) + .filter((game) => this.isGameInRange(game.gameCreation, context)) + .sort((left, right) => left.gameNumber - right.gameNumber); + if (games.length === 0) continue; + cards.push(this.toMatchCard(match, games)); + + for (const game of games) { + const raw = rawByMatchId.get(game.riotMatchId); + const detail = raw + ? this.toGameDetail(match, game, raw) + : this.toFallbackGameDetail(match, game); + detailsByMatchId.set(match._id.toString(), [ + ...(detailsByMatchId.get(match._id.toString()) ?? []), + detail, + ]); + records.push(...detail.teams.flatMap((team) => team.participants)); + } + } + + return { + season: context.season, + matches: cards, + records, + detailsByMatchId, + }; + } + + private async resolveContext( + communityId: mongoose.Types.ObjectId, + filters: CommunityStatsFilters, + ): Promise { + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findById(communityId).exec(); + if (!community) throw new NotFoundException('Community not found.'); + const season = this.resolveSeason(community, filters.seasonId); + const from = + filters.from ? new Date(filters.from) : + season.startedAt ? new Date(season.startedAt) : + null; + const to = filters.to ? new Date(filters.to) : null; + if (from && Number.isNaN(from.getTime())) { + throw new BadRequestException('Invalid from date.'); + } + if (to && Number.isNaN(to.getTime())) { + throw new BadRequestException('Invalid to date.'); + } + return { community, season, from, to }; + } + + private resolveSeason( + community: CommunityDocument, + seasonId?: string, + ): HistorySeasonDto { + const seasons = this.resolveSeasons(community); + if (seasonId === 'all') { + return { id: 'all', label: '전체 시즌', startedAt: null, endedAt: null }; + } + if (seasonId && seasonId !== 'current') { + const selected = seasons.find((season) => season.id === seasonId); + if (!selected) throw new BadRequestException('Invalid seasonId.'); + return selected; + } + return ( + seasons.find((season) => !season.endedAt) ?? + seasons[0] ?? { + id: 'current', + label: '현재 시즌', + startedAt: community.seasonStartedAt?.toISOString() ?? null, + endedAt: null, + } + ); + } + + private resolveSeasons(community: CommunityDocument): HistorySeasonDto[] { + const configured = community.seasons?.map((season) => ({ + id: season.id, + label: season.label, + startedAt: season.startedAt.toISOString(), + endedAt: season.endedAt?.toISOString() ?? null, + })); + if (configured?.length) return configured; + return [ + { + id: 'current', + label: '현재 시즌', + startedAt: community.seasonStartedAt?.toISOString() ?? null, + endedAt: null, + }, + ]; + } + + private toMatchCard( + match: MatchDocument, + games: NonNullable['games'], + ): InternalMatchCardView { + const participantById = new Map( + match.participants.map((participant) => [ + participant.userId.toString(), + participant, + ]), + ); + return { + matchId: match._id.toString(), + title: match.title, + scheduledAt: match.scheduledAt.toISOString(), + status: match.status === 'finished' ? 'finished' : 'in-progress', + gameCount: match.gameCount, + blueScore: match.result?.blueScore ?? 0, + redScore: match.result?.redScore ?? 0, + winnerSide: match.result?.winnerSide, + games: games.map((game) => ({ + gameNumber: game.gameNumber, + riotMatchId: game.riotMatchId ?? null, + winnerSide: game.winnerSide ?? null, + gameDuration: game.gameDuration, + })), + teams: match.teams.map((team) => ({ + side: team.side, + name: team.name, + members: team.members.map((member) => { + const participant = participantById.get(member.userId.toString()); + return { + userId: member.userId.toString(), + summonerName: participant?.gameName ?? 'Unknown', + profileIconId: participant?.profileIconId ?? 0, + }; + }), + })), + }; + } + + private toGameDetail( + match: MatchDocument, + game: NonNullable['games'][number], + raw: RiotMatchDto, + ): InternalGameDetail { + const puuidByUserId = new Map( + match.participants + .filter((participant) => participant.puuid) + .map((participant) => [ + participant.userId.toString(), + participant.puuid as string, + ]), + ); + const rawByPuuid = new Map( + raw.info.participants.map((participant) => [participant.puuid, participant]), + ); + const rawTeamIdBySide = new Map(); + for (const participant of game.participants) { + const puuid = puuidByUserId.get(participant.userId.toString()); + const rawParticipant = puuid ? rawByPuuid.get(puuid) : undefined; + if (rawParticipant) rawTeamIdBySide.set(participant.side, rawParticipant.teamId); + } + + return { + gameNumber: game.gameNumber, + riotMatchId: game.riotMatchId, + gameCreation: game.gameCreation, + gameDuration: game.gameDuration, + winnerSide: game.winnerSide, + teams: (['blue', 'red'] as TeamSide[]).map((side) => { + const rawTeamId = rawTeamIdBySide.get(side); + const rawTeam = raw.info.teams.find((team) => team.teamId === rawTeamId); + const teamRawParticipants = raw.info.participants.filter( + (participant) => participant.teamId === rawTeamId, + ); + const teamKills = teamRawParticipants.reduce( + (sum, participant) => sum + participant.kills, + 0, + ); + const teamDamage = teamRawParticipants.reduce( + (sum, participant) => sum + participant.totalDamageDealtToChampions, + 0, + ); + return { + side, + win: game.winnerSide === side, + objectives: { + baron: rawTeam?.objectives?.baron?.kills ?? 0, + dragon: rawTeam?.objectives?.dragon?.kills ?? 0, + tower: rawTeam?.objectives?.tower?.kills ?? 0, + }, + participants: game.participants + .filter((participant) => participant.side === side) + .map((participant) => + this.toRecord({ + match, + game, + participant, + rawParticipant: rawByPuuid.get( + puuidByUserId.get(participant.userId.toString()) ?? '', + ), + teamKills, + teamDamage, + }), + ), + }; + }), + }; + } + + private toFallbackGameDetail( + match: MatchDocument, + game: NonNullable['games'][number], + ): InternalGameDetail { + return { + gameNumber: game.gameNumber, + riotMatchId: game.riotMatchId, + gameCreation: game.gameCreation, + gameDuration: game.gameDuration, + winnerSide: game.winnerSide, + teams: (['blue', 'red'] as TeamSide[]).map((side) => ({ + side, + win: game.winnerSide === side, + objectives: { baron: 0, dragon: 0, tower: 0 }, + participants: game.participants + .filter((participant) => participant.side === side) + .map((participant) => + this.toRecord({ match, game, participant, teamKills: 0, teamDamage: 0 }), + ), + })), + }; + } + + private toRecord(params: { + match: MatchDocument; + game: NonNullable['games'][number]; + participant: MatchGameResultParticipant; + rawParticipant?: RiotMatchParticipantDto; + teamKills: number; + teamDamage: number; + }): InternalRecord { + const { match, game, participant, rawParticipant, teamKills, teamDamage } = params; + const snapshot = match.participants.find((item) => + item.userId.equals(participant.userId), + ); + const minutes = Math.max( + (rawParticipant?.timePlayed ?? game.gameDuration) / 60, + 1, + ); + const cs = rawParticipant + ? rawParticipant.totalMinionsKilled + rawParticipant.neutralMinionsKilled + : 0; + const damage = rawParticipant?.totalDamageDealtToChampions ?? 0; + const killParticipation = this.percent( + participant.kills + participant.assists, + teamKills, + ); + const damageShare = this.percent(damage, teamDamage); + const rating = this.resolveRating({ + kills: participant.kills, + deaths: participant.deaths, + assists: participant.assists, + killParticipation, + csPerMin: this.average(cs, minutes), + damageShare, + visionPerMin: this.average(rawParticipant?.visionScore ?? 0, minutes), + }); + + return { + matchId: match._id.toString(), + title: match.title, + scheduledAt: match.scheduledAt, + gameNumber: game.gameNumber, + riotMatchId: game.riotMatchId, + gameCreation: game.gameCreation, + gameDuration: game.gameDuration, + userId: participant.userId.toString(), + summonerName: + snapshot?.gameName ?? + rawParticipant?.riotIdGameName ?? + rawParticipant?.summonerName ?? + 'Unknown', + profileIconId: snapshot?.profileIconId ?? 0, + side: participant.side, + championId: participant.championId, + championLevel: rawParticipant?.champLevel ?? 0, + teamPosition: + rawParticipant?.teamPosition || rawParticipant?.individualPosition || '', + kills: participant.kills, + deaths: participant.deaths, + assists: participant.assists, + win: participant.win, + cs, + csPerMin: this.average(cs, minutes), + gold: rawParticipant?.goldEarned ?? 0, + gpm: this.average(rawParticipant?.goldEarned ?? 0, minutes), + damageDealtToChampions: damage, + damageTaken: rawParticipant?.totalDamageTaken ?? 0, + damageShare, + killParticipation, + visionScore: rawParticipant?.visionScore ?? 0, + controlWardsBought: this.numberField(rawParticipant, 'visionWardsBoughtInGame'), + wardsPlaced: rawParticipant?.wardsPlaced ?? 0, + wardsKilled: rawParticipant?.wardsKilled ?? 0, + items: [ + rawParticipant?.item0 ?? 0, + rawParticipant?.item1 ?? 0, + rawParticipant?.item2 ?? 0, + rawParticipant?.item3 ?? 0, + rawParticipant?.item4 ?? 0, + rawParticipant?.item5 ?? 0, + ], + trinket: rawParticipant?.item6 ?? 0, + summonerSpells: [ + rawParticipant?.summoner1Id ?? 0, + rawParticipant?.summoner2Id ?? 0, + ], + perks: rawParticipant ? this.resolvePerks(rawParticipant) : {}, + rating, + }; + } + + private buildLeaderboardRows(records: InternalRecord[]): LeaderboardRow[] { + const byUser = new Map(); + for (const record of records) { + byUser.set(record.userId, [...(byUser.get(record.userId) ?? []), record]); + } + return [...byUser.entries()] + .map(([userId, rows]) => this.toLeaderboardRow(userId, rows)) + .sort((left, right) => right.games - left.games || right.winRate - left.winRate); + } + + private toLeaderboardRow(userId: string, records: InternalRecord[]): LeaderboardRow { + const first = records[0]; + const wins = records.filter((record) => record.win).length; + const kills = this.sum(records, 'kills'); + const deaths = this.sum(records, 'deaths'); + const assists = this.sum(records, 'assists'); + const byLane: LeaderboardRow['byLane'] = {}; + for (const lane of ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'] as RiotLane[]) { + const laneRecords = records.filter((record) => record.teamPosition === lane); + if (laneRecords.length === 0) continue; + byLane[lane] = { + games: laneRecords.length, + wins: laneRecords.filter((record) => record.win).length, + kda: this.kda( + this.sum(laneRecords, 'kills'), + this.sum(laneRecords, 'deaths'), + this.sum(laneRecords, 'assists'), + ), + }; + } + const championCounts = new Map(); + for (const record of records) { + const current = + championCounts.get(record.championId) ?? { games: 0, wins: 0 }; + current.games += 1; + current.wins += record.win ? 1 : 0; + championCounts.set(record.championId, current); + } + + return { + userId, + summonerName: first?.summonerName ?? 'Unknown', + profileIconId: first?.profileIconId ?? 0, + games: records.length, + wins, + losses: records.length - wins, + winRate: this.percent(wins, records.length), + totalKills: kills, + totalDeaths: deaths, + totalAssists: assists, + kda: this.kda(kills, deaths, assists), + avgGoldPerMin: this.average(this.sum(records, 'gpm'), records.length), + avgKillParticipation: this.average( + this.sum(records, 'killParticipation'), + records.length, + ), + avgCsPerMin: this.average(this.sum(records, 'csPerMin'), records.length), + avgDamageShare: this.average(this.sum(records, 'damageShare'), records.length), + avgVisionScore: this.average(this.sum(records, 'visionScore'), records.length), + byLane, + topChampions: [...championCounts.entries()] + .map(([championId, stat]) => ({ + championId, + games: stat.games, + winRate: this.percent(stat.wins, stat.games), + })) + .sort((left, right) => right.games - left.games || right.winRate - left.winRate) + .slice(0, 3), + }; + } + + private buildUserChampionStats( + records: InternalRecord[], + season: HistorySeasonDto, + ): LeaderboardChampionStats { + const byChampion = new Map(); + for (const record of records) { + byChampion.set(record.championId, [ + ...(byChampion.get(record.championId) ?? []), + record, + ]); + } + const champions = [...byChampion.entries()] + .map(([championId, rows]) => this.toChampionRow(championId, rows)) + .sort((left, right) => right.games - left.games || right.winRate - left.winRate); + const totals = this.toChampionRow(0, records); + return { + queueGroup: 'internal', + rank: 'all', + queueIds: [], + season, + lastFetchedAt: records[0] ? new Date(records[0].gameCreation).toISOString() : null, + champions, + totals, + }; + } + + private toChampionRow(championId: number, rows: InternalRecord[]) { + const wins = rows.filter((record) => record.win).length; + const kills = this.sum(rows, 'kills'); + const deaths = this.sum(rows, 'deaths'); + const assists = this.sum(rows, 'assists'); + const gameMinutes = rows.reduce( + (sum, record) => sum + Math.max(record.gameDuration / 60, 1), + 0, + ); + return { + championId, + games: rows.length, + wins, + losses: rows.length - wins, + winRate: this.percent(wins, rows.length), + avgKills: this.average(kills, rows.length), + avgDeaths: this.average(deaths, rows.length), + avgAssists: this.average(assists, rows.length), + kda: this.kda(kills, deaths, assists), + totalKills: kills, + totalDeaths: deaths, + totalAssists: assists, + doubleKills: 0, + tripleKills: 0, + quadraKills: 0, + pentaKills: 0, + avgCs: this.average(this.sum(rows, 'cs'), rows.length), + avgCsPerMin: this.average(this.sum(rows, 'cs'), gameMinutes), + }; + } + + private buildUserSummary( + records: InternalRecord[], + requestedLimit: number, + ): UserInternalHistoryResponse['summary'] { + const views = records.slice(0, requestedLimit); + const wins = views.filter((record) => record.win).length; + const kills = this.sum(views, 'kills'); + const deaths = this.sum(views, 'deaths'); + const assists = this.sum(views, 'assists'); + const best = views.reduce((bestRecord, record) => { + if (!bestRecord) return record; + return record.deaths === 0 || record.rating > bestRecord.rating + ? record + : bestRecord; + }, null); + + return { + windowSize: views.length, + winRate: this.percent(wins, views.length), + wins, + losses: views.length - wins, + streak: this.resolveStreak(views), + kda: this.kda(kills, deaths, assists), + avgKills: this.average(kills, views.length), + avgDeaths: this.average(deaths, views.length), + avgAssists: this.average(assists, views.length), + bestRating: best + ? { + rating: best.deaths === 0 ? 'Perfect' : best.rating, + kills: best.kills, + deaths: best.deaths, + assists: best.assists, + matchId: best.riotMatchId, + } + : null, + positionRates: this.resolvePositionRates(views), + topChampions: this.resolveTopChampions(views), + lastFetchedAt: views[0] ? new Date(views[0].gameCreation).toISOString() : null, + }; + } + + private toRecentMatchView(record: InternalRecord, dataset: BaseDataset): RecentMatchView { + const detail = dataset.detailsByMatchId + .get(record.matchId) + ?.find((game) => game.riotMatchId === record.riotMatchId); + return { + matchId: record.riotMatchId, + queueId: 0, + queueLabel: '내전', + gameCreation: record.gameCreation, + gameDuration: record.gameDuration, + win: record.win, + remake: false, + championId: record.championId, + championLevel: record.championLevel, + teamPosition: record.teamPosition, + kills: record.kills, + deaths: record.deaths, + assists: record.assists, + kda: this.kda(record.kills, record.deaths, record.assists), + rating: record.rating, + totalCs: record.cs, + csPerMin: record.csPerMin, + killParticipation: record.killParticipation, + visionScore: record.visionScore, + controlWardsBought: record.controlWardsBought, + wardsPlaced: record.wardsPlaced, + wardsKilled: record.wardsKilled, + damageDealtToChampions: record.damageDealtToChampions, + damageTaken: record.damageTaken, + goldEarned: record.gold, + items: record.items, + trinket: record.trinket, + summonerSpells: record.summonerSpells, + perks: record.perks, + teams: (detail?.teams ?? []).map((team) => ({ + side: team.side === 'blue' ? 100 : 200, + win: team.win, + objectives: team.objectives, + participants: team.participants.map((participant) => ({ + puuid: participant.userId, + gameName: participant.summonerName, + tagLine: '', + championId: participant.championId, + teamPosition: participant.teamPosition, + kills: participant.kills, + deaths: participant.deaths, + assists: participant.assists, + })), + })), + }; + } + + private applyChampionFilter( + records: InternalRecord[], + filters: CommunityStatsFilters, + ): InternalRecord[] { + if (!filters.championId) return records; + return records.filter((record) => record.championId === filters.championId); + } + + private isGameInRange( + gameCreation: number, + context: CommunityStatsContext, + ): boolean { + if (context.from && gameCreation < context.from.getTime()) return false; + if (context.to && gameCreation > context.to.getTime()) return false; + return true; + } + + private toHighlight( + row: LeaderboardRow | undefined, + field: keyof Pick< + LeaderboardRow, + 'kda' | 'totalKills' | 'avgKillParticipation' | 'avgCsPerMin' + >, + ): LeaderHighlight | null { + if (!row) return null; + return { + metric: Number(row[field]), + userId: row.userId, + summonerName: row.summonerName, + isSingleGame: false, + }; + } + + private toSingleGameHighlight( + record: InternalRecord | undefined, + field: keyof Pick, + ): LeaderHighlight | null { + if (!record) return null; + return { + metric: record[field], + userId: record.userId, + summonerName: record.summonerName, + championId: record.championId, + matchId: record.riotMatchId, + isSingleGame: true, + }; + } + + private resolveStreak( + records: InternalRecord[], + ): UserInternalHistoryResponse['summary']['streak'] { + if (records.length === 0) return null; + const firstWin = records[0].win; + let count = 0; + for (const record of records) { + if (record.win !== firstWin) break; + count += 1; + } + return { type: firstWin ? 'win' : 'loss', count }; + } + + private resolvePositionRates( + records: InternalRecord[], + ): Partial> { + const counts = new Map(); + for (const record of records) { + if (!record.teamPosition) continue; + counts.set(record.teamPosition, (counts.get(record.teamPosition) ?? 0) + 1); + } + return Object.fromEntries( + [...counts.entries()].map(([lane, count]) => [ + lane, + this.percent(count, records.length), + ]), + ) as Partial>; + } + + private resolveTopChampions(records: InternalRecord[]) { + const byChampion = new Map(); + for (const record of records) { + const current = + byChampion.get(record.championId) ?? { games: 0, wins: 0, rating: 0 }; + current.games += 1; + current.wins += record.win ? 1 : 0; + current.rating += record.rating; + byChampion.set(record.championId, current); + } + return [...byChampion.entries()] + .map(([championId, stat]) => ({ + championId, + games: stat.games, + winRate: this.percent(stat.wins, stat.games), + pickRate: this.percent(stat.games, records.length), + avgRating: this.average(stat.rating, stat.games), + })) + .sort((left, right) => right.games - left.games || right.winRate - left.winRate) + .slice(0, 3); + } + + private resolvePerks(participant: RiotMatchParticipantDto) { + const primary = participant.perks.styles.find( + (style) => style.description === 'primaryStyle', + ); + const sub = participant.perks.styles.find( + (style) => style.description === 'subStyle', + ); + return { + primaryStyle: primary?.style, + subStyle: sub?.style, + keystone: primary?.selections[0]?.perk, + }; + } + + private resolveRating(params: { + kills: number; + deaths: number; + assists: number; + killParticipation: number; + csPerMin: number; + damageShare: number; + visionPerMin: number; + }): number { + const kda = this.kda(params.kills, params.deaths, params.assists); + const score = + Math.min(kda / 6, 1) * 4 + + Math.min(params.killParticipation / 100, 1) * 2 + + Math.min(params.csPerMin / 9, 1) * 2 + + Math.min(params.damageShare / 35, 1) + + Math.min(params.visionPerMin / 2, 1); + return this.round(score); + } + + private cacheKey( + scope: string, + communityId: mongoose.Types.ObjectId, + filters: CommunityStatsFilters, + ): string { + return [ + 'riot:communitystats', + scope, + communityId.toString(), + filters.seasonId ?? 'current', + filters.from ?? '', + filters.to ?? '', + filters.championId ?? '', + filters.cursor ?? '', + filters.limit ?? '', + ].join(':'); + } + + private clampLimit(value: number | undefined, fallback: number, max: number): number { + if (!value || !Number.isFinite(value)) return fallback; + return Math.max(1, Math.min(Math.floor(value), max)); + } + + private sum( + records: InternalRecord[], + field: T, + ): number { + return records.reduce((total, record) => { + const value = record[field]; + return total + (typeof value === 'number' ? value : 0); + }, 0); + } + + private kda(kills: number, deaths: number, assists: number): number { + return deaths === 0 ? kills + assists : this.round((kills + assists) / deaths); + } + + private percent(value: number, total: number): number { + return total > 0 ? Math.round((value / total) * 100) : 0; + } + + private average(value: number, total: number): number { + return total > 0 ? this.round(value / total) : 0; + } + + private round(value: number): number { + return Math.round(value * 10) / 10; + } + + private numberField( + participant: RiotMatchParticipantDto | undefined, + key: string, + ): number { + const value = participant?.[key]; + return typeof value === 'number' && Number.isFinite(value) ? value : 0; + } +} diff --git a/apps/api/src/modules/community-stats/community-stats.types.ts b/apps/api/src/modules/community-stats/community-stats.types.ts new file mode 100644 index 00000000..4696f1cb --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.types.ts @@ -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>; + 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>; + 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]; +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.module.ts b/apps/api/src/modules/tournament-result/tournament-result.module.ts index bec4bd6b..b9281ad0 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.module.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.module.ts @@ -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], diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.ts b/apps/api/src/modules/tournament-result/tournament-result.service.ts index 5ee2a15f..2ce0be98 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.ts @@ -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; } diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 430041ad..1ebcf179 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -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() { } /> } /> } /> + } + /> + } + /> } diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts index b84c4e4e..b5d983e8 100644 --- a/apps/web/src/api/hooks.ts +++ b/apps/web/src/api/hooks.ts @@ -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 = {}, +) { + 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( + 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( + 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( + 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( + `/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( + 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), }); } diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index 47986dbf..28d5433a 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -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>; + 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'; diff --git a/apps/web/src/pages/CommunityInternalStatsPage.tsx b/apps/web/src/pages/CommunityInternalStatsPage.tsx new file mode 100644 index 00000000..65a84da6 --- /dev/null +++ b/apps/web/src/pages/CommunityInternalStatsPage.tsx @@ -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['data']; +}) { + const icon = championIconUrl(manifest, championId); + const name = championDisplayName(manifest, championId) ?? String(championId); + return ( + + + {icon ? : null} + + {name} + + ); +} + +function MatchCard({ + match, + manifest, +}: { + match: ApiInternalMatchCard; + manifest: ReturnType['data']; +}) { + return ( + +
+
+
+
+ {formatDateTime(match.scheduledAt)} +
+

+ {match.title} +

+
+ {match.games.map((game) => ( + + {game.gameNumber}경기 + {game.winnerSide ? ( + + {sideLabel(game.winnerSide)} 승 + + ) : ( + '대기' + )} + {formatDuration(game.gameDuration)} + + ))} +
+
+ +
+
+
+
{match.blueScore}
+
BLUE
+
+
VS
+
+
{match.redScore}
+
RED
+
+
+
+ +
+ {match.teams.map((team) => ( +
+
+ {team.name} +
+
+ {team.members.slice(0, 5).map((member) => ( +
+ + + + + {member.summonerName} + +
+ ))} +
+
+ ))} +
+
+
+ + ); +} + +function HighlightCard({ + title, + highlight, + suffix = '', +}: { + title: string; + highlight: ApiLeaderHighlight | null | undefined; + suffix?: string; +}) { + return ( +
+
+ {title} +
+
+ {highlight ? `${highlight.metric}${suffix}` : '-'} +
+
+ {highlight?.summonerName ?? '기록 없음'} +
+
+ ); +} + +function LeaderboardTable({ + rows, + manifest, +}: { + rows: ApiLeaderboardRow[]; + manifest: ReturnType['data']; +}) { + return ( +
+
+ + + + + + + + + + + + + + + + {rows.map((row, index) => ( + + + + + + + + + + + + ))} + {rows.length === 0 && ( + + + + )} + +
#소환사승률게임KDAGPM킬관여분당 CS주 챔피언
+ {index + 1} + + + + + + + {row.summonerName} + + + + {row.winRate}% + + {row.games} + + {row.kda} + + {row.avgGoldPerMin} + + {row.avgKillParticipation}% + + {row.avgCsPerMin} + +
+ {row.topChampions.map((champion) => ( + + ))} +
+
+ 아직 집계할 내전 기록이 없습니다. +
+
+
+ ); +} + +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 ( +
+ `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. +
+ ); + } + + return ( +
+ + ← 홈으로 + + +
+
+
+

+ Community Records +

+

+ {communityQuery.data?.name ?? '커뮤니티'} 내전 전적 +

+

+ 토너먼트 코드로 수집된 결과를 기준으로 매치, 선수 순위, 팀 인사이트를 보여줍니다. +

+
+
+
+ 시즌 +
+
{season?.label ?? '현재 시즌'}
+
+
+
+ +
+ + + + + +
+ +
+
+

최근 내전

+
+ 블루 승률 {insightsQuery.data?.sideWinRate.blue ?? 0}% · 레드 승률{' '} + {insightsQuery.data?.sideWinRate.red ?? 0}% +
+
+ {matchesQuery.isLoading ? ( +
+ 내전 기록을 불러오는 중... +
+ ) : ( +
+ {matches.map((match) => ( + + ))} + {matches.length === 0 && ( +
+ 아직 수집된 내전 결과가 없습니다. +
+ )} +
+ )} + {matchesQuery.hasNextPage && ( + + )} +
+ +
+
+

선수 순위

+
+ 포지션은 Riot Match의 라인 정보를 기준으로 합니다. +
+
+ +
+
+ ); +} diff --git a/apps/web/src/pages/HomePage.tsx b/apps/web/src/pages/HomePage.tsx index cec7e7cf..5b2737b5 100644 --- a/apps/web/src/pages/HomePage.tsx +++ b/apps/web/src/pages/HomePage.tsx @@ -88,9 +88,17 @@ export default function HomePage() { return (
-

- 다음 내전 -

+
+

+ 다음 내전 +

+ + 내전 전적 보기 + +
{nextMatch ? ( diff --git a/apps/web/src/pages/InternalMatchDetailPage.tsx b/apps/web/src/pages/InternalMatchDetailPage.tsx new file mode 100644 index 00000000..86197eac --- /dev/null +++ b/apps/web/src/pages/InternalMatchDetailPage.tsx @@ -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['data']; +}) { + const icon = championIconUrl(manifest, championId); + const name = championDisplayName(manifest, championId) ?? String(championId); + return ( +
+ + {icon ? : null} + + {name} +
+ ); +} + +function ItemStrip({ + items, + trinket, + manifest, +}: { + items: number[]; + trinket: number; + manifest: ReturnType['data']; +}) { + return ( +
+ {[...items, trinket].map((itemId, index) => { + const icon = itemIconUrl(manifest, itemId); + return ( + + {icon ? : null} + + ); + })} +
+ ); +} + +function GamePanel({ + game, + manifest, +}: { + game: ApiInternalMatchDetailResponse['games'][number]; + manifest: ReturnType['data']; +}) { + return ( +
+
+
+

+ {game.gameNumber}경기 +

+

+ {formatDateTime(game.gameCreation)} · {formatDuration(game.gameDuration)} ·{' '} + {game.riotMatchId} +

+
+
+ {game.teams.map((team) => ( + + {sideLabel(team.side)} {team.win ? '승' : '패'} + + ))} +
+
+ + {game.teams.map((team) => ( +
+
+ {sideLabel(team.side)} · 바론 {team.objectives.baron} · 드래곤{' '} + {team.objectives.dragon} · 타워 {team.objectives.tower} +
+
+ + + + + + + + + + + + + + + + {team.participants.map((participant) => ( + + + + + + + + + + + + ))} + +
소환사챔피언포지션K/D/ACSGPM킬관여피해비중아이템
+ {participant.userId ? ( + + {participant.summonerName} + + ) : ( + + {participant.summonerName} + + )} + + + + {LANE_LABELS[participant.teamPosition] ?? participant.teamPosition ?? '-'} + + {participant.kills} + / + {participant.deaths} + / + {participant.assists} + + {participant.cs} ({participant.csPerMin}/m) + + {participant.gpm} + + {participant.killParticipation}% + + {participant.damageShare}% + + +
+
+
+ ))} +
+ ); +} + +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 ( +
+ 내전 상세 기록을 불러오는 중... +
+ ); + } + + if (detailQuery.error || !detail) { + return ( +
+

내전 기록을 찾을 수 없습니다

+ + 내전 전적으로 돌아가기 + +
+ ); + } + + return ( +
+ + ← 내전 전적 + + +
+
+
+

+ {detail.match.title} +

+

+ {formatDateTime(detail.match.scheduledAt)} · {detail.match.gameCount}전제 +

+
+
+
+
{detail.match.blueScore}
+
BLUE
+
+
VS
+
+
{detail.match.redScore}
+
RED
+
+
+
+
+ +
+ {detail.games.map((game) => ( + + ))} +
+
+ ); +} diff --git a/apps/web/src/pages/UserHistoryPage.tsx b/apps/web/src/pages/UserHistoryPage.tsx index 02b29c70..e71addae 100644 --- a/apps/web/src/pages/UserHistoryPage.tsx +++ b/apps/web/src/pages/UserHistoryPage.tsx @@ -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() {
- {/* 이 페이지는 저장된 경기 DB만 조회합니다. */} -
- {/* Riot API 갱신은 버튼 클릭 시 큐에서 처리합니다. */} - 아래 버튼을 누르면 기록이 갱신됩니다. + {isInternalQueue ? ( + <> + {/* 내전 탭은 토너먼트 결과 DB를 조회합니다. */} + Riot API 갱신 없이 수집된 내전 결과를 다시 불러옵니다. + + ) : ( + <> + {/* 이 페이지는 저장된 경기 DB만 조회합니다. */} +
+ {/* Riot API 갱신은 버튼 클릭 시 큐에서 처리합니다. */} + 아래 버튼을 누르면 기록이 갱신됩니다. + + )}
-
- 갱신 소켓: {refreshSocket.connectionStatus} -
+ {!isInternalQueue && ( +
+ 갱신 소켓: {refreshSocket.connectionStatus} +
+ )}
{(refreshNotice || refreshSocket.error) && ( @@ -739,19 +809,25 @@ export default function UserHistoryPage() { ))}
-
- {RANK_FILTER_TABS.map((tab) => ( - - updateSearch({ rank: tab.value, championId: null }) - } - > - {tab.label} - - ))} -
+ {!isInternalQueue ? ( +
+ {RANK_FILTER_TABS.map((tab) => ( + + updateSearch({ rank: tab.value, championId: null }) + } + > + {tab.label} + + ))} +
+ ) : ( +
+ 내전 탭은 토너먼트 코드 결과 수집 데이터를 기준으로 집계합니다. +
+ )} {selectedChampionName && ( ))} - {(summaryQuery.data?.topChampions ?? []).length === 0 && ( + {(summary?.topChampions ?? []).length === 0 && ( 기록 없음 @@ -890,14 +966,11 @@ export default function UserHistoryPage() {

매치 히스토리

- 최근 저장:{" "} - {formatLastFetched( - recentMatchesQuery.data?.pages[0]?.lastFetchedAt, - )} + 최근 저장: {formatLastFetched(historyLastFetchedAt)}
- {recentMatchesQuery.isLoading ? ( + {matchesLoading ? (
최근 경기를 불러오는 중...
@@ -917,16 +990,18 @@ export default function UserHistoryPage() {
)} - {recentMatchesQuery.hasNextPage && ( + {hasNextPage && ( )}
diff --git a/커뮤니티-내전-전적.md b/커뮤니티-내전-전적.md new file mode 100644 index 00000000..8290d5b7 --- /dev/null +++ b/커뮤니티-내전-전적.md @@ -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: , + 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::...`) +- `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|&from=&to=&championId=` + +#### 응답 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 + >; + 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::::: # 1h +riot:communitystats:leaderboard:::: # 1h +riot:communitystats:teamInsights:::: # 1h +riot:communitystats:matchDetail: # 24h (불변) +riot:userInternalStats::::: # 1h +``` + +매치가 새로 finished 될 때 invalidate: `community-stats.service` 가 `match.service` 의 finished 전환 직후 cache prefix delete (`riot:communitystats:*::*`). 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 +} /> +} /> +``` + +`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:*::*` 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//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//internal-stats` 진입 → 시즌 셀렉터 / 팀 인사이트 6 카드 / leaderboard / 매치 카드 리스트 표시 + - 시즌 셀렉터 변경 → URL query 반영 + 응답 변화 + - 매치 카드 클릭 → `/communities//internal-stats/match/` 이동, 게임 탭 / 양 팀 풀 통계 표 / objectives 바 표시 + - `/users//history` 진입 → 큐 탭에 "내전" 5번째 보임. 클릭 시 랭크 필터 자동 숨김 + 내전 챔프 통계/매치 카드 표시 +3. 외부 공유 검증: 인증 헤더 없이 위 URL 모두 접근 가능 +4. Garnet 캐시 hit 확인: 두 번째 새로고침 시 응답 < 100ms (서버 로그) + +### 운영 + +- aggregation 응답 시간 p95 < 500ms (100 매치 기준) +- Garnet 캐시 hit ratio > 70% +- 매치 finished 전환 후 invalidate 정상 동작 (캐시 키 scan 로그)