# 토너먼트 코드 풀 / 표시 플랜 > **대상**: 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)