diff --git a/Tournament-Code-플랜.md b/Tournament-Code-플랜.md new file mode 100644 index 00000000..44df1196 --- /dev/null +++ b/Tournament-Code-플랜.md @@ -0,0 +1,572 @@ +# 토너먼트 코드 풀 / 표시 플랜 + +> **대상**: codex 가 이어서 작업 가능한 수준의 실행 플랜 +> **레포**: `/Users/dahyeon/source/lolympus-tournament-support` (pnpm workspace) +> **작성 기준**: 2026-04-27 + +--- + +## 1. Context + +내전이 `team-built` 상태가 되면 5명씩 게임에 입장할 수 있도록 **토너먼트 코드** 1개를 매치에 발급해 표시해야 합니다. + +**제약** — Riot Tournament-Stub-V5 사용 권한 없음. 우회: + +1. 외부 서비스(별도 운영) 가 토너먼트 코드를 미리 수십~수백 개 생성. +2. 운영자가 그 코드를 우리 Admin UI 에 **수동 업로드** → 풀에 적재. +3. 매치가 `team-built` 으로 전환되는 순간 풀에서 atomic pop → 매치에 attach. +4. (Phase 후속) 게임 끝난 후 `match-v5` detail 의 `info.tournamentCode` 필드로 우리 코드와 매칭해 매치 결과 수집. + +본 plan 은 1~3 까지. 4 는 §5.E 에 자리만. + +--- + +## 2. 결정사항 (사용자 결정 2026-04-27) + +- **적재**: 운영자 수동 업로드 → Admin UI 필수 +- **카테고리**: 5v5 소환사 협곡 단일 (`mapType=SUMMONERS_RIFT`, `teamSize=5`) +- **화이트리스트**: 사용 안 함 (`allowedSummonerIds` 미지정) +- **만료**: `expiresAt` 보관 + pop 쿼리에 검사 (24h 안전 마진) +- **Tournament API**: 사용 불가. 단순 표시만. +- **결과 수집**: Phase 후속 — 일반 match-v5 응답의 `info.tournamentCode` 매칭으로 우회 +- **잔여 알림**: 미구현. 운영자 수동 확인. +- **권한**: 코드 자체는 누구나 볼 수 있음. **풀 잔여 통계는 admin 만**. +- **풀 비었을 때**: placeholder 표시 + 운영자가 채우면 자동 attach +- **데이터 모델**: 별도 `TournamentCode` 컬렉션 + **`Match.tournamentCodeIds[]` 1:N join** +- **다게임 구조**: 한 내전 = N 경기 (1경기/2경기/3경기 …). `team-built` 진입 시 N개 코드 atomic 발급 +- **표시 범위**: `team-built` + `in-progress` 모두 표시. `finished` 에서만 SideCard 숨김 +- **코드 형식 검증**: 정규식 통과한 코드만 적재 (`/^[A-Z0-9-]{8,}$/i` 1차) +- **bulk 업로드 2모드**: 간단(textarea CSV) + 확장(JSON 붙여넣기) + +--- + +## 3. 데이터 모델 + +### 3.1 TournamentCode (신규 컬렉션) + +```ts +// apps/api/src/modules/global/database/schema.ts + +export type TournamentCodeState = + | 'available' // 풀에 대기 중 + | 'reserved' // 매치에 할당됨, 아직 게임 시작 전 + | 'used' // 게임 시작/종료 — 회수 불가 + | 'expired' // expiresAt 경과 (cron 으로 마킹) + | 'released'; // 매치 취소로 풀 복귀 (재할당 가능) + +export interface TournamentCode extends MongooseTimestamps { + code: string; // unique, Riot 형식 (정규식 검증) + region: RiotPlatformRoute; // 기본 'kr' + mapType: 'SUMMONERS_RIFT'; + teamSize: number; // 5 고정 + spectatorType: 'NONE' | 'LOBBYONLY' | 'ALL'; + metadata?: Record; // 외부 서비스에서 받은 부가 정보 + expiresAt: Date; // 운영자 입력 필수 + + state: TournamentCodeState; + + // 할당 추적 + matchId?: mongoose.Types.ObjectId; // reserved/used 시 채워짐 + gameNumber?: number; // 1-based, 한 매치 안에서 몇 번째 경기인지 + reservedAt?: Date; + usedAt?: Date; // 게임 시작 webhook 또는 결과 수집 시 + releasedAt?: Date; + riotMatchId?: string; // 결과 수집 시 매칭된 match-v5 id (Phase 후속) + + // 운영 추적 + uploadedBy: mongoose.Types.ObjectId; // userId + uploadedAt: Date; + source?: string; // 외부 서비스 식별자 (옵션) + notes?: string; +} + +export const TournamentCodeSchema = new Schema( + { /* ... */ }, + { timestamps: true, collection: 'tournament_code' }, +); + +TournamentCodeSchema.index({ code: 1 }, { unique: true }); +TournamentCodeSchema.index({ state: 1, expiresAt: 1 }); // pop 쿼리 +TournamentCodeSchema.index({ matchId: 1, gameNumber: 1 }); // join lookup + 정렬 +TournamentCodeSchema.index({ state: 1, uploadedAt: -1 }); // admin 목록 +TournamentCodeSchema.index({ riotMatchId: 1 }, { sparse: true }); // 결과 수집 reverse lookup +``` + +> 모델 등록: `connection.service.ts` 의 `getModel<'tournamentCode'>` 추가. + +#### 3.1.1 코드 형식 정규식 검증 + +`/^[A-Z0-9-]{8,}$/i` (영숫자 + 하이픈, 최소 8자). bulk 업로드/수동 추가 시 통과 못 한 코드는 응답의 `invalid` 배열에 포함, DB 적재 X. 정규식은 `tournament-code.constants.ts` 에 상수로 분리. + +### 3.2 Match 확장 + +```ts +// schema.ts Match 추가 +gameCount: number; // 한 내전의 경기 수 (default 3, community 설정에서 snapshot) +tournamentCodeIds: mongoose.Types.ObjectId[]; // gameNumber 순서 보장 (length ≤ gameCount) + +// MatchSchema +gameCount: { type: Number, required: true, default: 3 }, +tournamentCodeIds: { + type: [{ type: Schema.Types.ObjectId, ref: 'tournamentCode' }], + default: [], +} +``` + +#### 3.2.1 Community 확장 (게임 수 기본값) + +```ts +// Community +matchGameCount?: number; // default 3, 매치 생성 시 snapshot +``` + +매치 생성 시 `match.gameCount = community.matchGameCount ?? 3`. 매치별 override 도 매치 생성 폼에서 가능. + +#### 3.2.2 API 응답 구조 + +```ts +// /matches/:id 응답 +{ + ...match, + tournamentCodes: [ + { gameNumber: 1, code: 'KR-...', expiresAt: '...', state: 'reserved', riotMatchId: null }, + { gameNumber: 2, code: 'KR-...', expiresAt: '...', state: 'reserved', riotMatchId: null }, + { gameNumber: 3, code: null, expiresAt: null, state: 'pending', riotMatchId: null }, // 풀 부족분 + ], +} +``` + +`gameCount` 만큼 슬롯이 항상 차 있음. 풀 부족 시 코드 자리는 `code: null, state: 'pending'` placeholder. 추후 풀 보충 시 자동 attach. + +--- + +## 4. Lifecycle / 트리거 지점 + +``` +upload (admin) atomic pop game start (Phase 후속) + │ │ │ +[available] ─────→ [reserved] ───────────────→ [used] + │ + │ match cancel / re-recruit + └──────────→ [released] ──→ [available] (재할당 가능) + +[any state] ──── expiresAt < now ────→ [expired] (cron daily) +``` + +### 4.1 reserve (`team-built` 전환) — N개 atomic 발급 + +- `auction.service.ts:175` (마지막 멤버 배정), `:395` (admin 강제 전환) 두 곳에서 `match.status = 'team-built'` 직후 호출. + +```ts +// TournamentCodeService.reserveForMatch(match): 부족분만 보충하는 idempotent 함수 +const need = match.gameCount - match.tournamentCodeIds.length; +if (need <= 0) return; + +const startGameNumber = match.tournamentCodeIds.length + 1; +const reservedIds: mongoose.Types.ObjectId[] = []; + +for (let i = 0; i < need; i++) { + const code = await TournamentCodeModel.findOneAndUpdate( + { + state: 'available', + region: 'kr', + mapType: 'SUMMONERS_RIFT', + teamSize: 5, + expiresAt: { $gt: new Date(Date.now() + 24 * 60 * 60 * 1000) }, // 24h 안전 마진 + }, + { + $set: { + state: 'reserved', + matchId: match._id, + gameNumber: startGameNumber + i, + reservedAt: new Date(), + }, + }, + { sort: { expiresAt: 1 }, new: true }, // 만료 임박순 소비 + ); + if (!code) break; // 풀 고갈 — 부분 발급으로 종료 + reservedIds.push(code._id); +} + +if (reservedIds.length > 0) { + match.tournamentCodeIds.push(...reservedIds); + await match.save(); +} +``` + +- 각 호출이 atomic findOneAndUpdate → 두 매치가 같은 코드 받지 않음. +- 부족분만 채우는 idempotent 라 `pendingMatches` cron 에서 재호출해도 안전. + +### 4.2 release (`team-built` → `recruiting` 회귀) + +- `auction.service.ts:314-315` 의 회귀 흐름에서 호출. +- match cancel/삭제 시에도 호출. + +```ts +// TournamentCodeService.releaseFromMatch(match) +await TournamentCodeModel.updateMany( + { _id: { $in: match.tournamentCodeIds }, state: 'reserved' }, + { $set: { state: 'released', releasedAt: new Date() }, $unset: { matchId: 1, gameNumber: 1 } }, +); +match.tournamentCodeIds = []; +await match.save(); +``` + +`used` 상태(이미 게임 시작) 코드는 release 대상에서 제외. `released` 는 admin UI 환원 버튼에서만 `available` 로 돌아옴 (audit 보존). + +### 4.3 expired 마킹 (cron) + +```ts +@Cron('0 0 * * * *', { timeZone: 'Asia/Seoul' }) // 매시 정각 +async markExpired() { + await TournamentCodeModel.updateMany( + { state: { $in: ['available', 'reserved', 'released'] }, expiresAt: { $lte: new Date() } }, + { $set: { state: 'expired' } }, + ); +} +``` + +`reserved` 였는데 만료되면 → `expired`. 매치 표시는 "코드 만료됨" placeholder. (희박한 케이스 — 운영자가 매치 시작 직전 코드 안 채웠을 때만) + +### 4.4 placeholder 자동 채우기 (풀 부족분 보충) + +- `team-built` / `in-progress` 인 매치 중 `tournamentCodeIds.length < gameCount` 인 매치 검색 → `reserveForMatch` 재호출 (부족분만 채움). +- **트리거 두 곳**: + 1. **admin 업로드 controller 안에서 직접 실행** — 즉시성 보장 + 2. **cron `@Cron('*/30 * * * * *')`** — 안전망 (30초 간격) + +```ts +// TournamentCodeScheduler.attachPending +const pendingMatches = await MatchModel.find({ + status: { $in: ['team-built', 'in-progress'] }, + $expr: { $lt: [{ $size: '$tournamentCodeIds' }, '$gameCount'] }, +}); +for (const match of pendingMatches) await codeService.reserveForMatch(match); +``` + +--- + +## 5. 변경 사항 + +### 5.1 백엔드 + +#### 신규 모듈 `apps/api/src/modules/tournament-code/` + +``` +tournament-code.module.ts +tournament-code.service.ts # reserveForMatch / releaseFromMatch / markExpired / bulkUpload / list / delete +tournament-code.controller.ts # admin endpoints +tournament-code.scheduler.ts # 만료 cron + 자동 attach cron +tournament-code.types.ts +``` + +#### 엔드포인트 + +| Method | Path | 권한 | 용도 | +|---|---|---|---| +| POST | `/communities/:cid/tournament-codes` | `@Roles('owner','admin')` | bulk 업로드 | +| GET | `/communities/:cid/tournament-codes` | `@Roles('owner','admin')` | 목록 (state/expiresAt 필터) | +| GET | `/communities/:cid/tournament-codes/stats` | `@Roles('owner','admin')` | 풀 잔여 통계 (state 별 카운트 + 만료 임박 카운트) | +| DELETE | `/communities/:cid/tournament-codes/:id` | `@Roles('owner','admin')` | 폐기 (state=available 만) | +| POST | `/communities/:cid/tournament-codes/:id/release` | `@Roles('owner','admin')` | reserved/released → available 수동 환원 | + +bulk 업로드 body: +```ts +interface BulkUploadRequest { + codes: Array<{ + code: string; // 공백 trim + expiresAt: string; // ISO + spectatorType?: 'NONE' | 'LOBBYONLY' | 'ALL'; // 기본 'ALL' + metadata?: Record; + source?: string; + notes?: string; + }>; +} +``` + +응답: +```ts +interface BulkUploadResponse { + inserted: number; + duplicates: string[]; // 이미 존재하는 code (skipped) + invalid: Array<{ code: string; reason: string }>; +} +``` + +#### 매치 응답에 join + +`match.service.ts` 의 `serializeMatch` (또는 mapper) 에서 `tournamentCodeIds` 를 `populate` 또는 `$lookup` 으로 풀어 `gameNumber` 정렬 + 부족분은 placeholder 슬롯으로 채워서 응답: + +```ts +function buildTournamentCodeSlots( + match: Match, + codes: TournamentCode[], +): TournamentCodeSlotView[] { + const byNumber = new Map(codes.map((c) => [c.gameNumber!, c])); + return Array.from({ length: match.gameCount }, (_, i) => { + const gameNumber = i + 1; + const code = byNumber.get(gameNumber); + return code + ? { + gameNumber, + code: code.code, + expiresAt: code.expiresAt.toISOString(), + state: code.state, // 'reserved' | 'used' | 'expired' + riotMatchId: code.riotMatchId ?? null, + } + : { gameNumber, code: null, expiresAt: null, state: 'pending', riotMatchId: null }; + }); +} +``` + +#### auction.service 통합 + +- `:175`, `:395` 직후 `tournamentCodeService.reserveForMatch(match)` 호출. +- `:314-315` 직전 `tournamentCodeService.releaseFromMatch(match)` 호출. + +### 5.2 프런트 + +#### 매치 상세 우측 SideCard 추가 + +`apps/web/src/pages/MatchDetailPage.tsx` `611~654` 일정/상품/안내사항 SideCard 들 아래에: + +```tsx +{match.status !== 'finished' && + (match.status === 'team-built' || match.status === 'in-progress') && ( + + + {isAdmin && } {/* §8.5 운영자에게만 잔여 표시 */} + + )} +``` + +`TournamentCodeList` 컴포넌트 — 1경기 / 2경기 / 3경기 식 row: + +```tsx +function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) { + return ( +
+ {slots.map((slot) => ( + + ))} +
+ ); +} + +function TournamentCodeRow({ slot }: { slot: TournamentCodeSlotView }) { + return ( +
+ + {slot.gameNumber}경기 + + {slot.code ? ( + + ) : ( + 발급 대기 중… + )} +
+ ); +} +``` + +`TournamentCodeDisplay`: +- 모노스페이스 코드 + 카피 버튼 (clipboard) + 카피 토스트 ("복사했어요. 게임 클라이언트의 토너먼트 코드 입력란에 붙여 넣으세요") +- 만료 시각 ("만료: 4월 30일 18:00") +- 만료 24h 이내면 amber 경고 +- `state === 'expired'` → "코드 만료. 운영자에게 문의해 주세요." +- `state === 'used'` → 회색 + "사용됨" 라벨 (다음 경기 코드만 강조) +- `riotMatchId` 있으면 hover 시 매치 ID 툴팁 (Phase 후속 결과 수집 후) + +#### types.ts + +```ts +export type TournamentCodeSlotState = 'reserved' | 'used' | 'expired' | 'pending'; + +export interface TournamentCodeSlotView { + gameNumber: number; + code: string | null; + expiresAt: string | null; + state: TournamentCodeSlotState; + riotMatchId: string | null; +} + +export interface ApiMatch { + // ... + gameCount: number; + tournamentCodes: TournamentCodeSlotView[]; // 항상 length === gameCount +} +``` + +#### Admin 페이지 신규 + +`apps/web/src/pages/admin/TournamentCodesPage.tsx`: +- 라우트: `/admin/communities/:cid/tournament-codes` +- 권한 가드: `useMe` 의 `currentUser.role === 'owner' | 'admin'` 아니면 redirect +- 섹션: + 1. **잔여 현황 카드**: state 별 카운트 (available / reserved / used / expired) + 만료 임박 7일 이내 카운트 + 2. **bulk 업로드 — 2모드 탭**: + - **간단**: textarea, 줄당 `code,expiresAt(ISO)` (CSV 1줄). 예: `KR-ABCD-1234,2026-05-30T18:00:00Z` + - **확장**: JSON 붙여넣기 (`{spectatorType, metadata, source, notes}` 추가 가능) + - 정규식 통과한 코드만 적재, invalid/duplicate 결과 응답 표시 + 3. **목록 테이블**: state 필터 / expiresAt 정렬 / 매치 ID 링크 (`gameNumber` 함께) / 폐기·환원 버튼 +- 폴링: React Query `refetchInterval: 30s` + +#### SideCard 안의 운영자 잔여 안내 (§8.5) + +`PoolStatsHint` 컴포넌트: +- `useMe` 로 admin/owner 판별 +- 별도 호출 `GET /communities/:cid/tournament-codes/stats` (다음 §) +- 표시: "풀 잔여 12개 (만료 임박 3개)" — 5개 미만이면 빨강 +- admin 페이지로 가는 inline link + +#### 매치 상세 클릭 트리거 — 변경 없음 + +기본 `MatchDetailPage` 안에서 자동 표시. 외부 공유 OK 정책 그대로. + +### 5.3 매치 cancel/삭제 시 release + +- `match.service.ts` 의 매치 삭제/취소 흐름에 `releaseFromMatch` 호출. +- match status 가 `team-built` → `in-progress` 로 전환되면 **코드 자체는 그대로 reserved 유지**. 게임이 끝나는 시점(Phase 후속 결과 수집)에 `reserved → used` 전환. +- `in-progress` 상태에서도 SideCard 표시 유지 (다음 경기 코드 보여주기 위함). + +--- + +## 6. 결과 수집 우회 (Phase 후속 — 본 plan 자리만) + +토너먼트 API 못 쓰니까 게임이 끝났는지 알 방법이 없습니다. **`match-v5 by-puuid` 의 `type=tourney` 필터** 를 활용해 호출량/정확도를 끌어올리는 우회 흐름: + +### 6.1 호출 패턴 — `type=tourney` + `startTime` window + +``` +GET /lol/match/v5/matches/by-puuid/{puuid}/ids + ?type=tourney + &startTime={teamBuiltAtEpochSeconds - 60} // 안전 마진 60초 + &endTime={now} + &start=0 + &count=100 +``` + +- `type=tourney` 로 **토너먼트 코드로 만들어진 매치만** 필터 → 일반/랭크 매치 제외, payload·detail call 모두 절감. +- `startTime` = 매치가 `team-built` 으로 전환된 epoch seconds (안전 마진 60초). `Match.teamBuiltAt: Date` 신규 필드 필요. +- `endTime` = 폴링 시점. +- `start/count` 페이지네이션은 1차 100 으로 충분 (BO3/BO5 라도 한 매치는 최대 5게임). +- `RiotMatchService.getMatchIdsByPuuid` 가 이미 `type: 'tourney'` 를 지원함 (`riot.types.ts:29`, `riot-match.service.ts:21~26`) — 신규 클라이언트 코드 불필요. + +### 6.2 매핑 흐름 + +1. 매치가 `team-built` 으로 전환되는 시점에 `Match.teamBuiltAt = now` snapshot. +2. **결과 수집 작업 큐** (선행 plan 의 Riot 작업 큐 high stream 재사용) 에 `riot.tournament-result.poll.match` job enqueue. payload: `{matchId, puuids: [캡틴 2명], teamBuiltAtEpoch}`. +3. worker: + ```ts + for (const puuid of puuids) { + const ids = await matchService.getMatchIdsByPuuid(puuid, { + type: 'tourney', + startTime: teamBuiltAtEpoch - 60, + count: 100, + region: 'asia', + }); + for (const matchV5Id of ids) { + const detail = await matchService.getMatch(matchV5Id); + const tCode = detail.info.tournamentCode; + if (!tCode) continue; + const code = await TournamentCodeModel.findOneAndUpdate( + { code: tCode, matchId: match._id, state: 'reserved' }, + { $set: { state: 'used', usedAt: new Date(detail.info.gameCreation), riotMatchId: matchV5Id } }, + { new: true }, + ); + if (code) await maybeAdvanceMatch(match); // 모든 슬롯 used 면 finished 전환 + } + } + ``` +4. **재폴링 정책**: 결과를 모두 못 찾았으면 5분 후 재 enqueue (예: 첫 polling 후 1시간 동안 5분 간격 재시도, 그 후 1시간 간격으로 24시간까지). 24h 내 못 찾으면 `state = 'expired'` 마킹 + 운영자 알림 자리. +5. **dedup**: 매치당 jobId 단일 (`riot:tourney-poll:dedup:` Garnet NX). 한 매치는 한 polling 체인. + +### 6.3 finished 전환 + +```ts +async function maybeAdvanceMatch(match: Match) { + const codes = await TournamentCodeModel.find({ matchId: match._id }).sort({ gameNumber: 1 }); + if (codes.length < match.gameCount) return; + if (!codes.every((c) => c.state === 'used' && c.riotMatchId)) return; + + match.status = 'finished'; + match.result = match.result ?? defaultResult(); + match.result.riotMatchIds = codes.map((c) => c.riotMatchId!); + // 승패/스코어는 별도 결과 집계 단계 (이번 PR 범위 외) + await match.save(); +} +``` + +### 6.4 본 plan 에서 미리 준비할 것 + +- `Match.teamBuiltAt: Date` 필드 추가 (PR-1 에서 같이) — 결과 수집 시 `startTime` 으로 사용. +- `TournamentCode.riotMatchId` 필드 + sparse 인덱스 (이미 §3.1). +- `gameNumber` 로 어느 경기 결과인지 매핑 가능 (운영자가 코드를 1경기/2경기 순서대로 발급한 가정). +- `RiotMatchService.getMatchIdsByPuuid` 의 `type: 'tourney'` 지원 확인 완료. + +### 6.5 폴링 대상 puuid 선택 + +- 기본: **양 팀 캡틴 puuid 2명만** 폴링 → 최소 호출. +- 캡틴이 게임에 입장 안 한 케이스 (드물지만 가능) 대비: 24h 안에 결과 못 찾으면 **모든 참가자 puuid** (10명) 로 확장 retry. +- 한 매치당 최악 호출량: 2 puuid × 100ids list + 매치당 detail call 5게임 = ~12 calls. 매치 1개 finished 까지 ≤ 24h. + +### 6.6 결과 수집 모듈 자체는 별도 PR (`Tournament-Result-수집-플랜.md` 후속). + +--- + +## 7. Rollout + +1. (PR-1) `TournamentCode` 컬렉션 + Match `gameCount`/`tournamentCodeIds[]`/`teamBuiltAt` + Community `matchGameCount` + 모델 등록 + 인덱스 (riotMatchId sparse 포함) +2. (PR-2) `TournamentCodeService.reserveForMatch (idempotent N개 발급) / releaseFromMatch / bulkUpload (정규식 검증) / list / stats` + 단위 테스트 (atomic pop concurrency, 부분 발급, 정규식 reject) +3. (PR-3) auction.service 통합 (reserve/release 두 트리거) + 매치 생성 시 `gameCount` snapshot + `team-built` 전환 시 `teamBuiltAt` snapshot +4. (PR-4) 매치 응답에 `tournamentCodes[]` slot 빌더 + types 확장 (gameCount + slot view) +5. (PR-5) `TournamentCodeScheduler` (만료 cron 매시 + 부족분 자동 attach cron 30초) +6. (PR-6) 매치 상세 SideCard — `TournamentCodeList` (1경기/2경기/3경기 row) + 카피 토스트 + 만료 경고. status guard: `team-built` ∪ `in-progress` +7. (PR-7) Admin 페이지 `TournamentCodesPage` — 잔여 현황 + 2모드 bulk 업로드 + 목록 + 환원/폐기 +8. (PR-8) SideCard `PoolStatsHint` (admin/owner 만 표시, /stats 엔드포인트 호출) +9. (PR-9) 매치 cancel/삭제 흐름에 release 통합 +10. (Phase 후속) 결과 수집 폴링 모듈 (`info.tournamentCode` 매칭) + +--- + +## 8. 추가 고려사항 + +### 확정 (사용자 결정 2026-04-27) + +본 plan §2 의 모든 결정사항. 추가 항목: + +1. **정규식 검증** (`/^[A-Z0-9-]{8,}$/i`) — bulk 업로드 시 invalid 응답에 포함, DB 적재 X. +2. **만료 안전 마진 24h** — pop 쿼리에 `expiresAt > now + 24h`. admin 페이지에서 임박 코드 amber 표시. +3. **bulk 업로드 2모드** — 간단(textarea CSV) + 확장(JSON 붙여넣기). +4. **표시 범위**: `team-built` + `in-progress` 모두 표시 (1경기/2경기/3경기 식). `finished` 에서만 사라짐. +5. **풀 잔여 통계**: admin/owner 에게만 SideCard 안에 inline 표시 + admin 페이지 카드. +6. **자동 attach 트리거**: admin 업로드 controller 안 + cron 30초 둘 다. +7. **재할당 audit**: `released → available` 은 admin 환원 버튼만. 자동 환원 cron 두지 않음. +8. **카피 토스트**: 코드 카피 시 "복사했어요. 게임 클라이언트의 토너먼트 코드 입력란에 붙여 넣으세요". + +### 추후 (Phase 후속) + +- 결과 수집 폴링 모듈 (§6) — `info.tournamentCode` 매칭으로 `riotMatchId` 채움 + `state=used` +- 잔여 알림 (dakao bot 또는 discord webhook) +- 풀 자동 보충 (외부 서비스 webhook / API key 인증) +- 토너먼트 API 권한 받으면 본 plan 의 풀 메커니즘은 그대로 두고 코드 생성 자동화만 추가 + +--- + +## 9. Done 정의 + +- `TournamentCode` 컬렉션 생성 + 인덱스 5개 등록 (riotMatchId sparse 포함) +- `Match.gameCount` + `Match.tournamentCodeIds[]` 추가, `Community.matchGameCount` 자리 +- 운영자가 admin 페이지에서 2모드 (CSV/JSON) bulk 업로드, 정규식 통과한 코드만 적재 +- 매치가 `team-built` 으로 전환 → 매치에 `gameCount` 만큼 코드 atomic N개 발급 (만료 임박순, gameNumber 1..N), 동시 두 매치 같은 코드 받지 않음 +- 풀 부족 시 부분 발급 → 부족 슬롯은 `state: 'pending'` placeholder 로 응답 +- `team-built` → `recruiting` 회귀 시 reserved 코드 모두 release → admin 환원 버튼으로 available 로 복귀 +- MatchDetailPage 우측 SideCard 에 `team-built` ∪ `in-progress` 일 때 1경기/2경기/3경기 row 표시. `finished` 에서 사라짐 +- admin/owner 에게는 SideCard 안에 풀 잔여 inline 표시 ("풀 잔여 12개 (만료 임박 3개)") +- 풀이 비었던 슬롯은 admin 이 새 코드 업로드하면 30초 안에 자동 attach +- 만료 임박 24h 이내 코드는 pop 쿼리에서 제외, admin 페이지 amber +- 만료된 코드는 매시 cron 으로 state=expired 마킹 +- 매치 응답 (`/matches/:id`) 에 `tournamentCodes: TournamentCodeSlotView[]` (length === gameCount) 포함 +- `match-v5` 응답의 `info.tournamentCode` 파싱이 이미 가능함을 확인 + `TournamentCode.riotMatchId` 필드/인덱스 자리 마련 + `Match.teamBuiltAt` 자리 마련 (Phase 후속 결과 수집의 `startTime` 으로 사용) +- `RiotMatchService.getMatchIdsByPuuid` 가 `type: 'tourney'` 지원 확인됨 (Phase 후속에서 그대로 호출) +- 단위 테스트 통과 (atomic N개 pop / 부분 발급 / 정규식 reject / 만료 필터 / release / bulk 중복 skip) diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts index fe01b00c..2b2fc17e 100644 --- a/apps/api/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -10,6 +10,7 @@ import { GlobalModule } from './modules/global/global.module'; import { MatchHistoryModule } from './modules/match-history/match-history.module'; import { MatchModule } from './modules/match/match.module'; import { RiotModule } from './modules/riot/riot.module'; +import { TournamentCodeModule } from './modules/tournament-code/tournament-code.module'; import { UserModule } from './modules/user/user.module'; @Module({ @@ -24,6 +25,7 @@ import { UserModule } from './modules/user/user.module'; CommunityModule, MatchModule, MatchHistoryModule, + TournamentCodeModule, AuctionModule, UserModule, DakaoModule, diff --git a/apps/api/src/modules/auction/auction.module.ts b/apps/api/src/modules/auction/auction.module.ts index 4a165890..d440e927 100644 --- a/apps/api/src/modules/auction/auction.module.ts +++ b/apps/api/src/modules/auction/auction.module.ts @@ -1,11 +1,12 @@ import { Module } from '@nestjs/common'; import { RiotModule } from '../riot/riot.module'; +import { TournamentCodeModule } from '../tournament-code/tournament-code.module'; import { AuctionGateway } from './auction.gateway'; import { AuctionController } from './auction.controller'; import { AuctionService } from './auction.service'; @Module({ - imports: [RiotModule], + imports: [RiotModule, TournamentCodeModule], controllers: [AuctionController], providers: [AuctionService, AuctionGateway], exports: [AuctionService], diff --git a/apps/api/src/modules/auction/auction.service.ts b/apps/api/src/modules/auction/auction.service.ts index e8c5122c..e46d90dc 100644 --- a/apps/api/src/modules/auction/auction.service.ts +++ b/apps/api/src/modules/auction/auction.service.ts @@ -15,6 +15,7 @@ import { TeamSide, } from '../global/database/schema'; import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; +import { TournamentCodeService } from '../tournament-code/tournament-code.service'; const AUCTION_MAX_TEAM_SIZE = 5; @@ -43,6 +44,7 @@ export class AuctionService { constructor( private readonly connectionService: ConnectionService, private readonly enrichmentService: RiotAccountEnrichmentService, + private readonly tournamentCodeService: TournamentCodeService, ) {} public async start(params: StartAuctionParams): Promise { @@ -173,7 +175,9 @@ export class AuctionService { }); match.status = 'team-built'; + match.teamBuiltAt = match.teamBuiltAt ?? new Date(); await match.save(); + await this.tournamentCodeService.reserveForMatch(match); return auction; } @@ -312,8 +316,11 @@ export class AuctionService { await auction.deleteOne({ session }); if (match.status === 'team-built') { + await this.tournamentCodeService.releaseFromMatch(match); match.status = 'recruiting'; match.teams = []; + match.tournamentCodeIds = []; + match.teamBuiltAt = undefined; await match.save({ session }); } await session.commitTransaction(); @@ -393,7 +400,9 @@ export class AuctionService { }; }); match.status = 'team-built'; + match.teamBuiltAt = match.teamBuiltAt ?? new Date(); await match.save(); + await this.tournamentCodeService.reserveForMatch(match); } private resolveTeamName(side: TeamSide): string { diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index 4b05a2fa..22e30430 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -35,6 +35,28 @@ export const TEAM_SIDES: TeamSide[] = ['blue', 'red']; export type CommunityRole = 'owner' | 'admin' | 'member'; export const COMMUNITY_ROLES: CommunityRole[] = ['owner', 'admin', 'member']; +export type TournamentCodeState = + | 'available' + | 'reserved' + | 'used' + | 'expired' + | 'released'; +export const TOURNAMENT_CODE_STATES: TournamentCodeState[] = [ + 'available', + 'reserved', + 'used', + 'expired', + 'released', +]; +export type TournamentMapType = 'SUMMONERS_RIFT'; +export const TOURNAMENT_MAP_TYPES: TournamentMapType[] = ['SUMMONERS_RIFT']; +export type TournamentSpectatorType = 'NONE' | 'LOBBYONLY' | 'ALL'; +export const TOURNAMENT_SPECTATOR_TYPES: TournamentSpectatorType[] = [ + 'NONE', + 'LOBBYONLY', + 'ALL', +]; + export interface PositionPreference { position: Position; priority: number; // 1 = 최우선, 숫자가 작을수록 높은 우선순위 @@ -215,6 +237,7 @@ export interface Community extends MongooseTimestamps { riotRegion?: RiotRegionalRoute; seasonStartedAt?: Date; seasons?: CommunitySeason[]; + matchGameCount?: number; } export interface CommunitySeason { @@ -242,6 +265,30 @@ export interface RiotMatch extends MongooseTimestamps { export type RiotMatchDocument = HydratedDocument; +// ===== TournamentCode (운영자가 미리 업로드한 토너먼트 코드 풀) ===== +export interface TournamentCode extends MongooseTimestamps { + code: string; + region: RiotPlatformRoute; + mapType: TournamentMapType; + teamSize: number; + spectatorType: TournamentSpectatorType; + metadata?: Record; + expiresAt: Date; + state: TournamentCodeState; + matchId?: mongoose.Types.ObjectId; + gameNumber?: number; + reservedAt?: Date; + usedAt?: Date; + releasedAt?: Date; + riotMatchId?: string; + uploadedBy: mongoose.Types.ObjectId; + uploadedAt: Date; + source?: string; + notes?: string; +} + +export type TournamentCodeDocument = HydratedDocument; + // ===== Match (내전) ===== export interface MatchParticipant { userId: mongoose.Types.ObjectId; @@ -289,6 +336,9 @@ export interface Match extends MongooseTimestamps { status: MatchStatus; scheduledAt: Date; maxParticipants: number; + gameCount: number; + tournamentCodeIds: mongoose.Types.ObjectId[]; + teamBuiltAt?: Date; hostUserId?: mongoose.Types.ObjectId; participants: MatchParticipant[]; teams: MatchTeam[]; @@ -530,6 +580,7 @@ export const CommunitySchema = new Schema( riotPlatform: { type: String }, riotRegion: { type: String }, seasonStartedAt: { type: Date }, + matchGameCount: { type: Number, required: false, default: 3 }, seasons: { type: [ new Schema( @@ -664,6 +715,59 @@ export const RiotMatchSchema = new Schema( RiotMatchSchema.index({ participantPuuids: 1, gameCreation: -1 }); RiotMatchSchema.index({ participantPuuids: 1, queueId: 1, gameCreation: -1 }); +export const TournamentCodeSchema = new Schema( + { + code: { + type: String, + required: true, + trim: true, + uppercase: true, + }, + region: { type: String, required: true, default: 'kr' }, + mapType: { + type: String, + enum: TOURNAMENT_MAP_TYPES, + required: true, + default: 'SUMMONERS_RIFT', + }, + teamSize: { type: Number, required: true, default: 5 }, + spectatorType: { + type: String, + enum: TOURNAMENT_SPECTATOR_TYPES, + required: true, + default: 'ALL', + }, + metadata: { type: Schema.Types.Mixed }, + expiresAt: { type: Date, required: true }, + state: { + type: String, + enum: TOURNAMENT_CODE_STATES, + required: true, + default: 'available', + }, + matchId: { type: Schema.Types.ObjectId, ref: 'match' }, + gameNumber: { type: Number }, + reservedAt: { type: Date }, + usedAt: { type: Date }, + releasedAt: { type: Date }, + riotMatchId: { type: String }, + uploadedBy: { type: Schema.Types.ObjectId, ref: 'user', required: true }, + uploadedAt: { type: Date, required: true, default: Date.now }, + source: { type: String }, + notes: { type: String }, + }, + { + timestamps: true, + collection: 'tournament_code', + }, +); + +TournamentCodeSchema.index({ code: 1 }, { unique: true }); +TournamentCodeSchema.index({ state: 1, expiresAt: 1 }); +TournamentCodeSchema.index({ matchId: 1, gameNumber: 1 }); +TournamentCodeSchema.index({ state: 1, uploadedAt: -1 }); +TournamentCodeSchema.index({ riotMatchId: 1 }, { sparse: true }); + const MatchParticipantSubSchema = new Schema( { userId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, @@ -738,6 +842,13 @@ export const MatchSchema = new Schema( }, scheduledAt: { type: Date, required: true }, maxParticipants: { type: Number, required: true, default: 10 }, + gameCount: { type: Number, required: true, default: 3 }, + tournamentCodeIds: { + type: [{ type: Schema.Types.ObjectId, ref: 'tournamentCode' }], + required: true, + default: [], + }, + teamBuiltAt: { type: Date }, hostUserId: { type: Schema.Types.ObjectId, ref: 'user' }, participants: { type: [MatchParticipantSubSchema], @@ -868,6 +979,11 @@ export const tournamentModelDefinitions: ModelDefinition[] = [ { name: 'community', schema: CommunitySchema, schemaName: 'community' }, { name: 'user', schema: UserSchema, schemaName: 'user' }, { name: 'riotMatch', schema: RiotMatchSchema, schemaName: 'riotMatch' }, + { + name: 'tournamentCode', + schema: TournamentCodeSchema, + schemaName: 'tournamentCode', + }, { name: 'match', schema: MatchSchema, schemaName: 'match' }, { name: 'auction', schema: AuctionSchema, schemaName: 'auction' }, ]; @@ -877,6 +993,7 @@ export interface TournamentModelTypes { community: Community; user: User; riotMatch: RiotMatch; + tournamentCode: TournamentCode; match: Match; auction: Auction; } diff --git a/apps/api/src/modules/match/dto/create-match.dto.ts b/apps/api/src/modules/match/dto/create-match.dto.ts index 611b1e2e..63989d96 100644 --- a/apps/api/src/modules/match/dto/create-match.dto.ts +++ b/apps/api/src/modules/match/dto/create-match.dto.ts @@ -59,6 +59,11 @@ export class CreateMatchDto { @Min(2) maxParticipants?: number; + @IsOptional() + @IsInt() + @Min(1) + gameCount?: number; + @IsOptional() @IsArray() @IsString({ each: true }) @@ -104,6 +109,11 @@ export class UpdateMatchDto { @Min(2) maxParticipants?: number; + @IsOptional() + @IsInt() + @Min(1) + gameCount?: number; + @IsOptional() @IsArray() @IsString({ each: true }) diff --git a/apps/api/src/modules/match/match.controller.ts b/apps/api/src/modules/match/match.controller.ts index 505501e4..d3c71af0 100644 --- a/apps/api/src/modules/match/match.controller.ts +++ b/apps/api/src/modules/match/match.controller.ts @@ -53,6 +53,7 @@ export class MatchController { mapId: body.mapId ?? 11, scheduledAt: body.scheduledAt, maxParticipants: body.maxParticipants ?? 10, + gameCount: body.gameCount, prizes: body.prizes ?? [], notices: body.notices ?? [], schedule: body.schedule ?? [], @@ -87,7 +88,8 @@ export class MatchController { public async getMatch( @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, ) { - return this.matchService.getById(matchId); + const match = await this.matchService.getById(matchId); + return this.matchService.serialize(match); } @Patch(':matchId') diff --git a/apps/api/src/modules/match/match.module.ts b/apps/api/src/modules/match/match.module.ts index 6ead6da7..e458b7cd 100644 --- a/apps/api/src/modules/match/match.module.ts +++ b/apps/api/src/modules/match/match.module.ts @@ -1,8 +1,10 @@ import { Module } from '@nestjs/common'; +import { TournamentCodeModule } from '../tournament-code/tournament-code.module'; import { MatchController } from './match.controller'; import { MatchService } from './match.service'; @Module({ + imports: [TournamentCodeModule], controllers: [MatchController], providers: [MatchService], exports: [MatchService], diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index cb77f8bd..4283d82b 100644 --- a/apps/api/src/modules/match/match.service.ts +++ b/apps/api/src/modules/match/match.service.ts @@ -12,6 +12,8 @@ import { PositionPreference, TierInfo, } from '../global/database/schema'; +import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants'; +import { TournamentCodeService } from '../tournament-code/tournament-code.service'; interface CreateMatchParams { communityId: mongoose.Types.ObjectId; @@ -41,12 +43,24 @@ interface JoinMatchParams { @Injectable() export class MatchService { - constructor(private readonly connectionService: ConnectionService) {} + constructor( + private readonly connectionService: ConnectionService, + private readonly tournamentCodeService: TournamentCodeService, + ) {} public async create(params: CreateMatchParams): Promise { const MatchModel = await this.connectionService.getModel('match'); + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findById(params.communityId) + .select({ matchGameCount: 1 }) + .lean() + .exec(); return MatchModel.create({ ...params.data, + gameCount: + params.data.gameCount ?? + community?.matchGameCount ?? + DEFAULT_TOURNAMENT_GAME_COUNT, communityId: params.communityId, hostUserId: params.hostUserId, }); @@ -76,6 +90,15 @@ export class MatchService { return match; } + public async serialize(match: MatchDocument) { + const obj = match.toObject(); + return { + ...obj, + gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT, + tournamentCodes: await this.tournamentCodeService.buildSlots(match), + }; + } + public async update(params: UpdateMatchParams): Promise { const MatchModel = await this.connectionService.getModel('match'); const match = await MatchModel.findById(params.matchId); @@ -83,7 +106,17 @@ export class MatchService { if (!match.communityId.equals(params.communityId)) { throw new BadRequestException('Match does not belong to this community.'); } + const previousStatus = match.status; match.set(params.patch); + if ( + previousStatus !== 'recruiting' && + match.status === 'recruiting' && + match.tournamentCodeIds.length > 0 + ) { + await this.tournamentCodeService.releaseFromMatch(match); + match.tournamentCodeIds = []; + match.teamBuiltAt = undefined; + } await match.save(); return match; } @@ -98,6 +131,7 @@ export class MatchService { if (!match.communityId.equals(params.communityId)) { throw new BadRequestException('Match does not belong to this community.'); } + await this.tournamentCodeService.releaseFromMatch(match); await match.deleteOne(); } diff --git a/apps/api/src/modules/tournament-code/tournament-code.constants.ts b/apps/api/src/modules/tournament-code/tournament-code.constants.ts new file mode 100644 index 00000000..ee4da598 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.constants.ts @@ -0,0 +1,4 @@ +export const TOURNAMENT_CODE_PATTERN = /^[A-Z0-9-]{8,}$/i; +export const TOURNAMENT_CODE_EXPIRY_MARGIN_MS = 24 * 60 * 60 * 1000; +export const TOURNAMENT_CODE_EXPIRING_SOON_MS = 7 * 24 * 60 * 60 * 1000; +export const DEFAULT_TOURNAMENT_GAME_COUNT = 3; diff --git a/apps/api/src/modules/tournament-code/tournament-code.controller.ts b/apps/api/src/modules/tournament-code/tournament-code.controller.ts new file mode 100644 index 00000000..cd28cd47 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.controller.ts @@ -0,0 +1,105 @@ +import { + BadRequestException, + Body, + Controller, + Delete, + Get, + HttpCode, + HttpStatus, + Param, + Post, + Query, + UseGuards, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { Roles } from '../auth/roles.decorator'; +import { RolesGuard } from '../auth/roles.guard'; +import { ParseObjectIdPipe } from '../common/parse-object-id.pipe'; +import type { + TournamentCodeState, + UserDocument, +} from '../global/database/schema'; +import { TournamentCodeService } from './tournament-code.service'; +import type { BulkUploadTournamentCodesRequest } from './tournament-code.types'; + +@Controller('communities/:communityId/tournament-codes') +@Roles('owner', 'admin') +@UseGuards(RolesGuard) +export class TournamentCodeController { + constructor(private readonly tournamentCodeService: TournamentCodeService) {} + + @Post() + public async bulkUpload( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Body() body: BulkUploadTournamentCodesRequest, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.tournamentCodeService.bulkUpload({ + communityId, + uploadedBy: currentUser._id, + codes: body.codes ?? [], + }); + } + + @Get() + public async list( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Query('state') state?: TournamentCodeState, + @Query('limit') limit?: string, + ) { + this.assertSameCommunity(currentUser, communityId); + return { + codes: await this.tournamentCodeService.list({ + state, + limit: limit ? Number(limit) : undefined, + }), + }; + } + + @Get('stats') + public async stats( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.tournamentCodeService.stats(); + } + + @Post(':id/release') + public async restore( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('id', ParseObjectIdPipe) id: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.tournamentCodeService.restoreToAvailable(id); + } + + @Delete(':id') + @HttpCode(HttpStatus.NO_CONTENT) + public async discard( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('id', ParseObjectIdPipe) id: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + await this.tournamentCodeService.discardAvailable(id); + } + + private assertSameCommunity( + user: UserDocument, + communityId: mongoose.Types.ObjectId, + ): void { + if (!user.communityId.equals(communityId)) { + throw new BadRequestException('Different community.'); + } + } +} diff --git a/apps/api/src/modules/tournament-code/tournament-code.module.ts b/apps/api/src/modules/tournament-code/tournament-code.module.ts new file mode 100644 index 00000000..f41cc726 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { TournamentCodeController } from './tournament-code.controller'; +import { TournamentCodeScheduler } from './tournament-code.scheduler'; +import { TournamentCodeService } from './tournament-code.service'; + +@Module({ + controllers: [TournamentCodeController], + providers: [TournamentCodeService, TournamentCodeScheduler], + exports: [TournamentCodeService], +}) +export class TournamentCodeModule {} diff --git a/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts b/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts new file mode 100644 index 00000000..9f73d297 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts @@ -0,0 +1,57 @@ +import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; +import { TournamentCodeService } from './tournament-code.service'; + +@Injectable() +export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(TournamentCodeScheduler.name); + private attachTimer?: NodeJS.Timeout; + private expireTimer?: NodeJS.Timeout; + + constructor(private readonly tournamentCodeService: TournamentCodeService) {} + + public onModuleInit() { + this.attachTimer = setInterval(() => { + void this.attachPending(); + }, 30_000); + this.expireTimer = setInterval(() => { + void this.markExpired(); + }, 60 * 60 * 1000); + this.attachTimer.unref?.(); + this.expireTimer.unref?.(); + + void this.attachPending(); + void this.markExpired(); + } + + public onModuleDestroy() { + if (this.attachTimer) clearInterval(this.attachTimer); + if (this.expireTimer) clearInterval(this.expireTimer); + } + + private async attachPending() { + try { + const touched = await this.tournamentCodeService.attachPendingMatches(); + if (touched > 0) { + this.logger.debug(`Attached tournament codes for ${touched} matches.`); + } + } catch (error) { + this.logger.warn( + `Failed to attach pending tournament codes: ${ + error instanceof Error ? error.message : error + }`, + ); + } + } + + private async markExpired() { + try { + await this.tournamentCodeService.markExpired(); + } catch (error) { + this.logger.warn( + `Failed to mark expired tournament codes: ${ + error instanceof Error ? error.message : error + }`, + ); + } + } +} diff --git a/apps/api/src/modules/tournament-code/tournament-code.service.ts b/apps/api/src/modules/tournament-code/tournament-code.service.ts new file mode 100644 index 00000000..56370ed3 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.service.ts @@ -0,0 +1,363 @@ +import { + BadRequestException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + MatchDocument, + TournamentCode, + TournamentCodeDocument, + TournamentCodeState, + TournamentSpectatorType, +} from '../global/database/schema'; +import { + DEFAULT_TOURNAMENT_GAME_COUNT, + TOURNAMENT_CODE_EXPIRING_SOON_MS, + TOURNAMENT_CODE_EXPIRY_MARGIN_MS, + TOURNAMENT_CODE_PATTERN, +} from './tournament-code.constants'; +import type { + BulkUploadTournamentCodesResponse, + TournamentCodeSlotView, + TournamentCodeUploadItem, +} from './tournament-code.types'; + +const DEFAULT_REGION = 'kr'; +const DEFAULT_SPECTATOR_TYPE: TournamentSpectatorType = 'ALL'; + +@Injectable() +export class TournamentCodeService { + constructor(private readonly connectionService: ConnectionService) {} + + public async bulkUpload(params: { + communityId: mongoose.Types.ObjectId; + uploadedBy: mongoose.Types.ObjectId; + codes: TournamentCodeUploadItem[]; + }): Promise { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const invalid: BulkUploadTournamentCodesResponse['invalid'] = []; + const duplicates: string[] = []; + const valid: Array< + Omit & { + uploadedBy: mongoose.Types.ObjectId; + } + > = []; + const seen = new Set(); + + for (const item of params.codes) { + const code = this.normalizeCode(item.code); + if (!code) { + invalid.push({ code: item.code ?? '', reason: 'empty-code' }); + continue; + } + if (!TOURNAMENT_CODE_PATTERN.test(code)) { + invalid.push({ code, reason: 'invalid-format' }); + continue; + } + if (seen.has(code)) { + duplicates.push(code); + continue; + } + seen.add(code); + + const expiresAt = new Date(item.expiresAt); + if (Number.isNaN(expiresAt.getTime())) { + invalid.push({ code, reason: 'invalid-expiresAt' }); + continue; + } + if (expiresAt <= new Date()) { + invalid.push({ code, reason: 'expired-expiresAt' }); + continue; + } + + valid.push({ + code, + region: DEFAULT_REGION, + mapType: 'SUMMONERS_RIFT', + teamSize: 5, + spectatorType: item.spectatorType ?? DEFAULT_SPECTATOR_TYPE, + metadata: item.metadata, + expiresAt, + state: 'available', + uploadedBy: params.uploadedBy, + uploadedAt: new Date(), + source: item.source, + notes: item.notes, + }); + } + + if (valid.length === 0) { + return { inserted: 0, duplicates, invalid }; + } + + const existing = await TournamentCodeModel.find({ + code: { $in: valid.map((item) => item.code) }, + }) + .select({ code: 1 }) + .lean() + .exec(); + const existingCodes = new Set(existing.map((item) => item.code)); + duplicates.push(...existing.map((item) => item.code)); + + const insertable = valid.filter((item) => !existingCodes.has(item.code)); + if (insertable.length > 0) { + await TournamentCodeModel.insertMany(insertable, { ordered: false }); + } + + await this.attachPendingMatches(params.communityId); + + return { + inserted: insertable.length, + duplicates: [...new Set(duplicates)], + invalid, + }; + } + + public async list(params: { + state?: TournamentCodeState; + limit?: number; + }): Promise { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const filter: { state?: TournamentCodeState } = {}; + if (params.state) filter.state = params.state; + return TournamentCodeModel.find(filter) + .sort({ expiresAt: 1, uploadedAt: -1 }) + .limit(Math.min(params.limit ?? 100, 300)) + .exec(); + } + + public async stats(): Promise<{ + byState: Record; + expiringSoon: number; + available: number; + }> { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const states: TournamentCodeState[] = [ + 'available', + 'reserved', + 'used', + 'expired', + 'released', + ]; + const counts = await TournamentCodeModel.aggregate<{ + _id: TournamentCodeState; + count: number; + }>([{ $group: { _id: '$state', count: { $sum: 1 } } }]).exec(); + const byState = Object.fromEntries(states.map((state) => [state, 0])) as Record< + TournamentCodeState, + number + >; + for (const entry of counts) byState[entry._id] = entry.count; + + const expiringSoon = await TournamentCodeModel.countDocuments({ + state: 'available', + expiresAt: { + $gt: new Date(), + $lte: new Date(Date.now() + TOURNAMENT_CODE_EXPIRING_SOON_MS), + }, + }); + + return { byState, expiringSoon, available: byState.available }; + } + + public async discardAvailable(id: mongoose.Types.ObjectId): Promise { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const result = await TournamentCodeModel.deleteOne({ + _id: id, + state: 'available', + }).exec(); + if (result.deletedCount === 0) { + throw new BadRequestException('Only available tournament codes can be deleted.'); + } + } + + public async restoreToAvailable( + id: mongoose.Types.ObjectId, + ): Promise { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const MatchModel = await this.connectionService.getModel('match'); + const code = await TournamentCodeModel.findById(id); + if (!code) throw new NotFoundException('Tournament code not found.'); + if (code.state !== 'released' && code.state !== 'reserved') { + throw new BadRequestException( + 'Only released or reserved tournament codes can be restored.', + ); + } + const previousMatchId = code.matchId; + code.state = 'available'; + code.matchId = undefined; + code.gameNumber = undefined; + code.reservedAt = undefined; + code.releasedAt = undefined; + await code.save(); + if (previousMatchId) { + await MatchModel.updateOne( + { _id: previousMatchId }, + { $pull: { tournamentCodeIds: code._id } }, + ).exec(); + await this.attachPendingMatches(); + } + return code; + } + + public async reserveForMatch( + matchOrId: MatchDocument | mongoose.Types.ObjectId, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const match = + matchOrId instanceof mongoose.Types.ObjectId + ? await MatchModel.findById(matchOrId) + : await MatchModel.findById(matchOrId._id); + if (!match) throw new NotFoundException('Match not found.'); + + match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; + const need = match.gameCount - match.tournamentCodeIds.length; + if (need <= 0) return match; + + const reservedIds: mongoose.Types.ObjectId[] = []; + const startGameNumber = match.tournamentCodeIds.length + 1; + const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS); + + for (let index = 0; index < need; index += 1) { + const code = await TournamentCodeModel.findOneAndUpdate( + { + state: 'available', + region: DEFAULT_REGION, + mapType: 'SUMMONERS_RIFT', + teamSize: 5, + expiresAt: { $gt: expiresAfter }, + }, + { + $set: { + state: 'reserved', + matchId: match._id, + gameNumber: startGameNumber + index, + reservedAt: new Date(), + }, + $unset: { releasedAt: 1 }, + }, + { sort: { expiresAt: 1 }, new: true }, + ).exec(); + if (!code) break; + reservedIds.push(code._id); + } + + if (reservedIds.length > 0) { + match.tournamentCodeIds.push(...reservedIds); + await match.save(); + } + return match; + } + + public async releaseFromMatch( + matchOrId: MatchDocument | mongoose.Types.ObjectId, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const match = + matchOrId instanceof mongoose.Types.ObjectId + ? await MatchModel.findById(matchOrId) + : await MatchModel.findById(matchOrId._id); + if (!match) return; + if (match.tournamentCodeIds.length === 0) return; + + await TournamentCodeModel.updateMany( + { _id: { $in: match.tournamentCodeIds }, state: 'reserved' }, + { + $set: { state: 'released', releasedAt: new Date() }, + $unset: { matchId: 1, gameNumber: 1, reservedAt: 1 }, + }, + ).exec(); + + match.tournamentCodeIds = []; + await match.save(); + } + + public async markExpired(): Promise { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const result = await TournamentCodeModel.updateMany( + { + state: { $in: ['available', 'reserved', 'released'] }, + expiresAt: { $lte: new Date() }, + }, + { $set: { state: 'expired' } }, + ).exec(); + return result.modifiedCount; + } + + public async attachPendingMatches( + communityId?: mongoose.Types.ObjectId, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const filter: { + status: { $in: string[] }; + communityId?: mongoose.Types.ObjectId; + } = { + status: { $in: ['team-built', 'in-progress'] }, + }; + if (communityId) filter.communityId = communityId; + + const matches = await MatchModel.find(filter).exec(); + let touched = 0; + for (const match of matches) { + if ((match.tournamentCodeIds?.length ?? 0) >= (match.gameCount || 0)) { + continue; + } + await this.reserveForMatch(match); + touched += 1; + } + return touched; + } + + public async buildSlots(match: MatchDocument): Promise { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; + const ids = match.tournamentCodeIds ?? []; + const codes = + ids.length > 0 + ? await TournamentCodeModel.find({ _id: { $in: ids } }).exec() + : []; + const byGameNumber = new Map( + codes + .filter((code) => typeof code.gameNumber === 'number') + .map((code) => [code.gameNumber as number, code]), + ); + + return Array.from({ length: gameCount }, (_, index) => { + const gameNumber = index + 1; + const code = byGameNumber.get(gameNumber); + if (!code) { + return { + gameNumber, + code: null, + expiresAt: null, + state: 'pending', + riotMatchId: null, + }; + } + return { + gameNumber, + code: code.code, + expiresAt: code.expiresAt.toISOString(), + state: code.state, + riotMatchId: code.riotMatchId ?? null, + }; + }); + } + + private normalizeCode(code: string | undefined): string { + return (code ?? '').trim().toUpperCase(); + } +} diff --git a/apps/api/src/modules/tournament-code/tournament-code.types.ts b/apps/api/src/modules/tournament-code/tournament-code.types.ts new file mode 100644 index 00000000..c841da3f --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.types.ts @@ -0,0 +1,31 @@ +import type { + TournamentCodeState, + TournamentSpectatorType, +} from '../global/database/schema'; + +export interface TournamentCodeUploadItem { + code: string; + expiresAt: string; + spectatorType?: TournamentSpectatorType; + metadata?: Record; + source?: string; + notes?: string; +} + +export interface BulkUploadTournamentCodesRequest { + codes: TournamentCodeUploadItem[]; +} + +export interface BulkUploadTournamentCodesResponse { + inserted: number; + duplicates: string[]; + invalid: Array<{ code: string; reason: string }>; +} + +export interface TournamentCodeSlotView { + gameNumber: number; + code: string | null; + expiresAt: string | null; + state: TournamentCodeState | 'pending'; + riotMatchId: string | null; +} diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index f01cfd1e..430041ad 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -10,6 +10,7 @@ import LoginPage from './pages/Login'; import MatchDetailPage from './pages/MatchDetailPage'; import AuctionPage from './pages/AuctionPage'; import UserHistoryPage from './pages/UserHistoryPage'; +import TournamentCodesPage from './pages/admin/TournamentCodesPage'; function MsalHeaderActions() { const { accounts, instance } = useMsal(); @@ -71,6 +72,10 @@ function App() { } /> } /> } /> + } + /> diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts index 1286c0d6..2344a6ae 100644 --- a/apps/web/src/api/hooks.ts +++ b/apps/web/src/api/hooks.ts @@ -16,6 +16,7 @@ import type { ApiMatch, ApiRecentMatchesResponse, ApiRecentSummaryResponse, + ApiTournamentCode, ApiUserHistoryProfile, DdragonManifest, MatchStatus, @@ -23,6 +24,11 @@ import type { MeResponse, RiotQueueGroup, RiotRankFilter, + TournamentCodeBulkUploadResponse, + TournamentCodeListResponse, + TournamentCodeState, + TournamentCodeStatsResponse, + TournamentCodeUploadItem, } from './types'; const DDRAGON_MANIFEST_STALE_MS = 24 * 60 * 60 * 1000; @@ -253,6 +259,79 @@ export function useDdragonManifest(locale = 'ko_KR') { }); } +export function useTournamentCodeStats( + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: ['tournament-code-stats', communityId], + queryFn: () => + apiFetch( + `/communities/${communityId}/tournament-codes/stats`, + ), + enabled: Boolean(communityId && enabled), + refetchInterval: enabled ? 30_000 : false, + retry: false, + }); +} + +export function useTournamentCodes( + options: { state?: TournamentCodeState; limit?: number }, + communityId = DEFAULT_COMMUNITY_ID, +) { + return useQuery({ + queryKey: [ + 'tournament-codes', + communityId, + options.state ?? null, + options.limit ?? null, + ], + queryFn: () => { + const searchParams = new URLSearchParams(); + if (options.state) searchParams.set('state', options.state); + if (options.limit) searchParams.set('limit', String(options.limit)); + const queryString = searchParams.toString(); + return apiFetch( + `/communities/${communityId}/tournament-codes${queryString ? `?${queryString}` : ''}`, + ); + }, + enabled: Boolean(communityId), + refetchInterval: 30_000, + }); +} + +export function useBulkUploadTournamentCodes(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (codes: TournamentCodeUploadItem[]) => + apiFetch( + `/communities/${communityId}/tournament-codes`, + { + method: 'POST', + body: JSON.stringify({ codes }), + }, + ), + }); +} + +export function useRestoreTournamentCode(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (codeId: string) => + apiFetch( + `/communities/${communityId}/tournament-codes/${codeId}/release`, + { method: 'POST' }, + ), + }); +} + +export function useDeleteTournamentCode(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (codeId: string) => + apiFetch(`/communities/${communityId}/tournament-codes/${codeId}`, { + method: 'DELETE', + }), + }); +} + export function useMe() { const authUserId = useAuthUserId(); const { accounts, inProgress, instance } = useMsal(); diff --git a/apps/web/src/api/mappers.ts b/apps/web/src/api/mappers.ts index bf0931e1..09f87377 100644 --- a/apps/web/src/api/mappers.ts +++ b/apps/web/src/api/mappers.ts @@ -12,6 +12,7 @@ import type { Position, RiotLane, TeamSide, + TournamentCodeSlotView, } from "./types"; import { POSITION_ORDER, sideLabel } from "../lib/league"; @@ -46,6 +47,8 @@ export interface MatchDetailView { description: string; map: string; maxParticipants: number; + gameCount: number; + tournamentCodes: TournamentCodeSlotView[]; joined: boolean; participants: ParticipantView[]; teams: TeamView[]; @@ -402,6 +405,8 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { description: match.description, map: mapIdToLabel(match.mapId), maxParticipants: match.maxParticipants, + gameCount: match.gameCount ?? 3, + tournamentCodes: match.tournamentCodes ?? [], joined: Boolean(match.joined), participants, teams, diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index abeedf42..aa461060 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -100,10 +100,28 @@ export interface ApiCommunity { name: string; description: string; ownerUserId: string; + matchGameCount?: number; createdAt: string; updatedAt: string; } +export type TournamentCodeState = + | 'available' + | 'reserved' + | 'used' + | 'expired' + | 'released'; + +export type TournamentCodeSlotState = TournamentCodeState | 'pending'; + +export interface TournamentCodeSlotView { + gameNumber: number; + code: string | null; + expiresAt: string | null; + state: TournamentCodeSlotState; + riotMatchId: string | null; +} + export interface ApiMatchParticipant { userId: string; puuid?: string; @@ -150,6 +168,8 @@ export interface ApiMatch { status: MatchStatus; scheduledAt: string; maxParticipants: number; + gameCount: number; + tournamentCodes?: TournamentCodeSlotView[]; hostUserId?: string; participants: ApiMatchParticipant[]; teams: ApiMatchTeam[]; @@ -248,6 +268,57 @@ export interface DdragonManifest { fetchedAt: string; } +export type TournamentSpectatorType = 'NONE' | 'LOBBYONLY' | 'ALL'; + +export interface ApiTournamentCode { + _id: string; + code: string; + region: string; + mapType: 'SUMMONERS_RIFT'; + teamSize: number; + spectatorType: TournamentSpectatorType; + metadata?: Record; + expiresAt: string; + state: TournamentCodeState; + matchId?: string; + gameNumber?: number; + reservedAt?: string; + usedAt?: string; + releasedAt?: string; + riotMatchId?: string; + uploadedBy: string; + uploadedAt: string; + source?: string; + notes?: string; + createdAt: string; + updatedAt: string; +} + +export interface TournamentCodeStatsResponse { + byState: Record; + expiringSoon: number; + available: number; +} + +export interface TournamentCodeListResponse { + codes: ApiTournamentCode[]; +} + +export interface TournamentCodeUploadItem { + code: string; + expiresAt: string; + spectatorType?: TournamentSpectatorType; + metadata?: Record; + source?: string; + notes?: string; +} + +export interface TournamentCodeBulkUploadResponse { + inserted: number; + duplicates: string[]; + invalid: Array<{ code: string; reason: string }>; +} + export type RiotQueueGroup = | 'all' | 'summoners-rift' diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index 69e30246..aa303d1f 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -1,7 +1,13 @@ import { useEffect, useState } from 'react'; import { useMutation, useQueryClient } from '@tanstack/react-query'; import { Link, useNavigate, useParams } from 'react-router'; -import { useAuction, useDdragonManifest, useMatch, useMe } from '../api/hooks'; +import { + useAuction, + useDdragonManifest, + useMatch, + useMe, + useTournamentCodeStats, +} from '../api/hooks'; import { buildDefaultPreferredPositions, formatTierLabel, @@ -15,7 +21,7 @@ import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config'; import { apiFetch, ApiError } from '../lib/api'; import { profileIconUrl } from '../lib/ddragon'; import { positionIcon, positionLabel } from '../lib/league'; -import type { Position } from '../api/types'; +import type { Position, TournamentCodeSlotView } from '../api/types'; function PosBadge({ pos, sub }: { pos: Position; sub?: boolean }) { return ( @@ -279,6 +285,117 @@ function SideCard({ ); } +function formatTournamentCodeExpiry(value: string | null) { + if (!value) return null; + return new Intl.DateTimeFormat('ko-KR', { + month: 'long', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + }).format(new Date(value)); +} + +function isExpiringSoon(value: string | null) { + if (!value) return false; + const expiresAt = new Date(value).getTime(); + return expiresAt - Date.now() <= 24 * 60 * 60 * 1000; +} + +function TournamentCodeDisplay({ slot }: { slot: TournamentCodeSlotView }) { + const [copied, setCopied] = useState(false); + const expired = slot.state === 'expired'; + const used = slot.state === 'used'; + const expiringSoon = isExpiringSoon(slot.expiresAt); + + async function copyCode() { + if (!slot.code) return; + await navigator.clipboard.writeText(slot.code); + setCopied(true); + window.setTimeout(() => setCopied(false), 1600); + } + + return ( +
+
+ + {expired ? '코드 만료' : slot.code} + + {slot.code && !expired && ( + + )} +
+
+ {used + ? '사용됨' + : expired + ? '운영자에게 새 코드를 요청해주세요.' + : `만료: ${formatTournamentCodeExpiry(slot.expiresAt)}`} +
+
+ ); +} + +function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) { + return ( +
+ {slots.map((slot) => ( +
+ + {slot.gameNumber}경기 + + {slot.code ? ( + + ) : ( + + 발급 대기 중... 운영자가 코드를 채우면 자동으로 붙습니다. + + )} +
+ ))} +
+ ); +} + +function PoolStatsHint({ enabled }: { enabled: boolean }) { + const statsQuery = useTournamentCodeStats(DEFAULT_COMMUNITY_ID, enabled); + if (!enabled) return null; + const available = statsQuery.data?.available ?? 0; + const expiringSoon = statsQuery.data?.expiringSoon ?? 0; + + return ( +
+
+ 풀 잔여 {available}개 + {expiringSoon > 0 ? ` · 만료 임박 ${expiringSoon}개` : ''} +
+ + 코드 풀 관리 + +
+ ); +} + export default function MatchDetailPage() { const { id } = useParams(); const navigate = useNavigate(); @@ -623,6 +740,13 @@ export default function MatchDetailPage() { )} + {(match.status === 'team-built' || match.status === 'in-progress') && ( + + + + + )} + {match.prizes.length > 0 && (
    diff --git a/apps/web/src/pages/admin/TournamentCodesPage.tsx b/apps/web/src/pages/admin/TournamentCodesPage.tsx new file mode 100644 index 00000000..3fa1b6f2 --- /dev/null +++ b/apps/web/src/pages/admin/TournamentCodesPage.tsx @@ -0,0 +1,311 @@ +import { useMemo, useState } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { Link, useParams } from 'react-router'; +import { + useBulkUploadTournamentCodes, + useDeleteTournamentCode, + useMe, + useRestoreTournamentCode, + useTournamentCodes, + useTournamentCodeStats, +} from '../../api/hooks'; +import type { + TournamentCodeState, + TournamentCodeUploadItem, +} from '../../api/types'; +import { DEFAULT_COMMUNITY_ID } from '../../config'; + +const STATES: TournamentCodeState[] = [ + 'available', + 'reserved', + 'released', + 'used', + 'expired', +]; + +function formatDate(value: string | undefined) { + if (!value) return '-'; + return new Intl.DateTimeFormat('ko-KR', { + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + }).format(new Date(value)); +} + +function parseCsv(text: string): TournamentCodeUploadItem[] { + return text + .split(/\r?\n/u) + .map((line) => line.trim()) + .filter(Boolean) + .map((line) => { + const [code, expiresAt, notes] = line.split(',').map((part) => part.trim()); + return { code, expiresAt, notes }; + }); +} + +function parseJson(text: string): TournamentCodeUploadItem[] { + const parsed = JSON.parse(text) as unknown; + if (Array.isArray(parsed)) return parsed as TournamentCodeUploadItem[]; + if ( + typeof parsed === 'object' && + parsed !== null && + 'codes' in parsed && + Array.isArray((parsed as { codes: unknown }).codes) + ) { + return (parsed as { codes: TournamentCodeUploadItem[] }).codes; + } + throw new Error('JSON은 배열 또는 { codes: [...] } 형태여야 합니다.'); +} + +export default function TournamentCodesPage() { + const { cid } = useParams(); + const communityId = cid ?? DEFAULT_COMMUNITY_ID; + const queryClient = useQueryClient(); + const meQuery = useMe(); + const [stateFilter, setStateFilter] = useState(''); + const [mode, setMode] = useState<'csv' | 'json'>('csv'); + const [text, setText] = useState(''); + const [message, setMessage] = useState(null); + const currentUser = + meQuery.data?.memberships.find( + (membership) => membership.community?._id === communityId, + )?.user ?? null; + const canManage = currentUser?.role === 'owner' || currentUser?.role === 'admin'; + const statsQuery = useTournamentCodeStats(communityId, canManage); + const listQuery = useTournamentCodes( + { state: stateFilter || undefined, limit: 200 }, + communityId, + ); + const uploadMutation = useBulkUploadTournamentCodes(communityId); + const restoreMutation = useRestoreTournamentCode(communityId); + const deleteMutation = useDeleteTournamentCode(communityId); + + const counts = statsQuery.data?.byState; + const codes = useMemo( + () => listQuery.data?.codes ?? [], + [listQuery.data?.codes], + ); + + async function invalidate() { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: ['tournament-code-stats', communityId], + }), + queryClient.invalidateQueries({ + queryKey: ['tournament-codes', communityId], + }), + queryClient.invalidateQueries({ + queryKey: ['matches', communityId], + }), + ]); + } + + function handleUpload() { + setMessage(null); + let payload: TournamentCodeUploadItem[]; + try { + payload = mode === 'csv' ? parseCsv(text) : parseJson(text); + } catch (error) { + setMessage(error instanceof Error ? error.message : '입력 파싱 실패'); + return; + } + + uploadMutation.mutate(payload, { + onSuccess: async (result) => { + await invalidate(); + setMessage( + `업로드 완료: ${result.inserted}개 추가, 중복 ${result.duplicates.length}개, invalid ${result.invalid.length}개`, + ); + }, + onError: (error) => { + setMessage(error instanceof Error ? error.message : '업로드 실패'); + }, + }); + } + + if (!canManage) { + return ( +
    +

    권한이 필요합니다

    +

    + 토너먼트 코드 풀은 owner/admin만 관리할 수 있습니다. +

    +
    + ); + } + + return ( +
    + + ← 목록으로 + +
    +

    + 토너먼트 코드 풀 +

    +

    + 외부에서 생성한 코드를 업로드하고, 매치에 자동 할당되는 풀을 관리합니다. +

    +
    + +
    + {STATES.map((state) => ( +
    +
    + {state} +
    +
    + {counts?.[state] ?? 0} +
    +
    + ))} +
    + +
    +
    +

    Bulk 업로드

    +
    + + +
    +
    +