This commit is contained in:
dahyeon committed 2026-04-27 14:04:04 -07:00
1 parent 7a43a667f1
commit c00545f281
21 files changed
+1920 -5

No files matched your search

+572
View File
@@ -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<string, unknown>; // 외부 서비스에서 받은 부가 정보
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<TournamentCode>(
{ /* ... */ },
{ 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<string, unknown>;
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') && (
<SideCard title="토너먼트 코드">
<TournamentCodeList slots={match.tournamentCodes} />
{isAdmin && <PoolStatsHint />} {/* §8.5 운영자에게만 잔여 표시 */}
</SideCard>
)}
```
`TournamentCodeList` 컴포넌트 — 1경기 / 2경기 / 3경기 식 row:
```tsx
function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) {
return (
<div className="space-y-2">
{slots.map((slot) => (
<TournamentCodeRow key={slot.gameNumber} slot={slot} />
))}
</div>
);
}
function TournamentCodeRow({ slot }: { slot: TournamentCodeSlotView }) {
return (
<div className="flex items-center gap-2">
<span className="text-[11px] font-bold text-base-content/40 w-12 shrink-0">
{slot.gameNumber}경기
</span>
{slot.code ? (
<TournamentCodeDisplay slot={slot} />
) : (
<span className="text-[11px] text-base-content/30">발급 대기 중…</span>
)}
</div>
);
}
```
`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:<matchId>` 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)
+2
View File
@@ -10,6 +10,7 @@ import { GlobalModule } from './modules/global/global.module';
import { MatchHistoryModule } from './modules/match-history/match-history.module'; import { MatchHistoryModule } from './modules/match-history/match-history.module';
import { MatchModule } from './modules/match/match.module'; import { MatchModule } from './modules/match/match.module';
import { RiotModule } from './modules/riot/riot.module'; import { RiotModule } from './modules/riot/riot.module';
import { TournamentCodeModule } from './modules/tournament-code/tournament-code.module';
import { UserModule } from './modules/user/user.module'; import { UserModule } from './modules/user/user.module';
@Module({ @Module({
@@ -24,6 +25,7 @@ import { UserModule } from './modules/user/user.module';
CommunityModule, CommunityModule,
MatchModule, MatchModule,
MatchHistoryModule, MatchHistoryModule,
TournamentCodeModule,
AuctionModule, AuctionModule,
UserModule, UserModule,
DakaoModule, DakaoModule,
@@ -1,11 +1,12 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { RiotModule } from '../riot/riot.module'; import { RiotModule } from '../riot/riot.module';
import { TournamentCodeModule } from '../tournament-code/tournament-code.module';
import { AuctionGateway } from './auction.gateway'; import { AuctionGateway } from './auction.gateway';
import { AuctionController } from './auction.controller'; import { AuctionController } from './auction.controller';
import { AuctionService } from './auction.service'; import { AuctionService } from './auction.service';
@Module({ @Module({
imports: [RiotModule], imports: [RiotModule, TournamentCodeModule],
controllers: [AuctionController], controllers: [AuctionController],
providers: [AuctionService, AuctionGateway], providers: [AuctionService, AuctionGateway],
exports: [AuctionService], exports: [AuctionService],
@@ -15,6 +15,7 @@ import {
TeamSide, TeamSide,
} from '../global/database/schema'; } from '../global/database/schema';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
const AUCTION_MAX_TEAM_SIZE = 5; const AUCTION_MAX_TEAM_SIZE = 5;
@@ -43,6 +44,7 @@ export class AuctionService {
constructor( constructor(
private readonly connectionService: ConnectionService, private readonly connectionService: ConnectionService,
private readonly enrichmentService: RiotAccountEnrichmentService, private readonly enrichmentService: RiotAccountEnrichmentService,
private readonly tournamentCodeService: TournamentCodeService,
) {} ) {}
public async start(params: StartAuctionParams): Promise<AuctionDocument> { public async start(params: StartAuctionParams): Promise<AuctionDocument> {
@@ -173,7 +175,9 @@ export class AuctionService {
}); });
match.status = 'team-built'; match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
await match.save(); await match.save();
await this.tournamentCodeService.reserveForMatch(match);
return auction; return auction;
} }
@@ -312,8 +316,11 @@ export class AuctionService {
await auction.deleteOne({ session }); await auction.deleteOne({ session });
if (match.status === 'team-built') { if (match.status === 'team-built') {
await this.tournamentCodeService.releaseFromMatch(match);
match.status = 'recruiting'; match.status = 'recruiting';
match.teams = []; match.teams = [];
match.tournamentCodeIds = [];
match.teamBuiltAt = undefined;
await match.save({ session }); await match.save({ session });
} }
await session.commitTransaction(); await session.commitTransaction();
@@ -393,7 +400,9 @@ export class AuctionService {
}; };
}); });
match.status = 'team-built'; match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
await match.save(); await match.save();
await this.tournamentCodeService.reserveForMatch(match);
} }
private resolveTeamName(side: TeamSide): string { private resolveTeamName(side: TeamSide): string {
@@ -35,6 +35,28 @@ export const TEAM_SIDES: TeamSide[] = ['blue', 'red'];
export type CommunityRole = 'owner' | 'admin' | 'member'; export type CommunityRole = 'owner' | 'admin' | 'member';
export const COMMUNITY_ROLES: 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 { export interface PositionPreference {
position: Position; position: Position;
priority: number; // 1 = 최우선, 숫자가 작을수록 높은 우선순위 priority: number; // 1 = 최우선, 숫자가 작을수록 높은 우선순위
@@ -215,6 +237,7 @@ export interface Community extends MongooseTimestamps {
riotRegion?: RiotRegionalRoute; riotRegion?: RiotRegionalRoute;
seasonStartedAt?: Date; seasonStartedAt?: Date;
seasons?: CommunitySeason[]; seasons?: CommunitySeason[];
matchGameCount?: number;
} }
export interface CommunitySeason { export interface CommunitySeason {
@@ -242,6 +265,30 @@ export interface RiotMatch extends MongooseTimestamps {
export type RiotMatchDocument = HydratedDocument<RiotMatch>; export type RiotMatchDocument = HydratedDocument<RiotMatch>;
// ===== TournamentCode (운영자가 미리 업로드한 토너먼트 코드 풀) =====
export interface TournamentCode extends MongooseTimestamps {
code: string;
region: RiotPlatformRoute;
mapType: TournamentMapType;
teamSize: number;
spectatorType: TournamentSpectatorType;
metadata?: Record<string, unknown>;
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<TournamentCode>;
// ===== Match (내전) ===== // ===== Match (내전) =====
export interface MatchParticipant { export interface MatchParticipant {
userId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId;
@@ -289,6 +336,9 @@ export interface Match extends MongooseTimestamps {
status: MatchStatus; status: MatchStatus;
scheduledAt: Date; scheduledAt: Date;
maxParticipants: number; maxParticipants: number;
gameCount: number;
tournamentCodeIds: mongoose.Types.ObjectId[];
teamBuiltAt?: Date;
hostUserId?: mongoose.Types.ObjectId; hostUserId?: mongoose.Types.ObjectId;
participants: MatchParticipant[]; participants: MatchParticipant[];
teams: MatchTeam[]; teams: MatchTeam[];
@@ -530,6 +580,7 @@ export const CommunitySchema = new Schema<Community>(
riotPlatform: { type: String }, riotPlatform: { type: String },
riotRegion: { type: String }, riotRegion: { type: String },
seasonStartedAt: { type: Date }, seasonStartedAt: { type: Date },
matchGameCount: { type: Number, required: false, default: 3 },
seasons: { seasons: {
type: [ type: [
new Schema<CommunitySeason>( new Schema<CommunitySeason>(
@@ -664,6 +715,59 @@ export const RiotMatchSchema = new Schema<RiotMatch>(
RiotMatchSchema.index({ participantPuuids: 1, gameCreation: -1 }); RiotMatchSchema.index({ participantPuuids: 1, gameCreation: -1 });
RiotMatchSchema.index({ participantPuuids: 1, queueId: 1, gameCreation: -1 }); RiotMatchSchema.index({ participantPuuids: 1, queueId: 1, gameCreation: -1 });
export const TournamentCodeSchema = new Schema<TournamentCode>(
{
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<MatchParticipant>( const MatchParticipantSubSchema = new Schema<MatchParticipant>(
{ {
userId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, userId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
@@ -738,6 +842,13 @@ export const MatchSchema = new Schema<Match>(
}, },
scheduledAt: { type: Date, required: true }, scheduledAt: { type: Date, required: true },
maxParticipants: { type: Number, required: true, default: 10 }, 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' }, hostUserId: { type: Schema.Types.ObjectId, ref: 'user' },
participants: { participants: {
type: [MatchParticipantSubSchema], type: [MatchParticipantSubSchema],
@@ -868,6 +979,11 @@ export const tournamentModelDefinitions: ModelDefinition[] = [
{ name: 'community', schema: CommunitySchema, schemaName: 'community' }, { name: 'community', schema: CommunitySchema, schemaName: 'community' },
{ name: 'user', schema: UserSchema, schemaName: 'user' }, { name: 'user', schema: UserSchema, schemaName: 'user' },
{ name: 'riotMatch', schema: RiotMatchSchema, schemaName: 'riotMatch' }, { name: 'riotMatch', schema: RiotMatchSchema, schemaName: 'riotMatch' },
{
name: 'tournamentCode',
schema: TournamentCodeSchema,
schemaName: 'tournamentCode',
},
{ name: 'match', schema: MatchSchema, schemaName: 'match' }, { name: 'match', schema: MatchSchema, schemaName: 'match' },
{ name: 'auction', schema: AuctionSchema, schemaName: 'auction' }, { name: 'auction', schema: AuctionSchema, schemaName: 'auction' },
]; ];
@@ -877,6 +993,7 @@ export interface TournamentModelTypes {
community: Community; community: Community;
user: User; user: User;
riotMatch: RiotMatch; riotMatch: RiotMatch;
tournamentCode: TournamentCode;
match: Match; match: Match;
auction: Auction; auction: Auction;
} }
@@ -59,6 +59,11 @@ export class CreateMatchDto {
@Min(2) @Min(2)
maxParticipants?: number; maxParticipants?: number;
@IsOptional()
@IsInt()
@Min(1)
gameCount?: number;
@IsOptional() @IsOptional()
@IsArray() @IsArray()
@IsString({ each: true }) @IsString({ each: true })
@@ -104,6 +109,11 @@ export class UpdateMatchDto {
@Min(2) @Min(2)
maxParticipants?: number; maxParticipants?: number;
@IsOptional()
@IsInt()
@Min(1)
gameCount?: number;
@IsOptional() @IsOptional()
@IsArray() @IsArray()
@IsString({ each: true }) @IsString({ each: true })
@@ -53,6 +53,7 @@ export class MatchController {
mapId: body.mapId ?? 11, mapId: body.mapId ?? 11,
scheduledAt: body.scheduledAt, scheduledAt: body.scheduledAt,
maxParticipants: body.maxParticipants ?? 10, maxParticipants: body.maxParticipants ?? 10,
gameCount: body.gameCount,
prizes: body.prizes ?? [], prizes: body.prizes ?? [],
notices: body.notices ?? [], notices: body.notices ?? [],
schedule: body.schedule ?? [], schedule: body.schedule ?? [],
@@ -87,7 +88,8 @@ export class MatchController {
public async getMatch( public async getMatch(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @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') @Patch(':matchId')
@@ -1,8 +1,10 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { TournamentCodeModule } from '../tournament-code/tournament-code.module';
import { MatchController } from './match.controller'; import { MatchController } from './match.controller';
import { MatchService } from './match.service'; import { MatchService } from './match.service';
@Module({ @Module({
imports: [TournamentCodeModule],
controllers: [MatchController], controllers: [MatchController],
providers: [MatchService], providers: [MatchService],
exports: [MatchService], exports: [MatchService],
+35 -1
View File
@@ -12,6 +12,8 @@ import {
PositionPreference, PositionPreference,
TierInfo, TierInfo,
} from '../global/database/schema'; } 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 { interface CreateMatchParams {
communityId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId;
@@ -41,12 +43,24 @@ interface JoinMatchParams {
@Injectable() @Injectable()
export class MatchService { export class MatchService {
constructor(private readonly connectionService: ConnectionService) {} constructor(
private readonly connectionService: ConnectionService,
private readonly tournamentCodeService: TournamentCodeService,
) {}
public async create(params: CreateMatchParams): Promise<MatchDocument> { public async create(params: CreateMatchParams): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match'); 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({ return MatchModel.create({
...params.data, ...params.data,
gameCount:
params.data.gameCount ??
community?.matchGameCount ??
DEFAULT_TOURNAMENT_GAME_COUNT,
communityId: params.communityId, communityId: params.communityId,
hostUserId: params.hostUserId, hostUserId: params.hostUserId,
}); });
@@ -76,6 +90,15 @@ export class MatchService {
return match; 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<MatchDocument> { public async update(params: UpdateMatchParams): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match'); const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(params.matchId); const match = await MatchModel.findById(params.matchId);
@@ -83,7 +106,17 @@ export class MatchService {
if (!match.communityId.equals(params.communityId)) { if (!match.communityId.equals(params.communityId)) {
throw new BadRequestException('Match does not belong to this community.'); throw new BadRequestException('Match does not belong to this community.');
} }
const previousStatus = match.status;
match.set(params.patch); 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(); await match.save();
return match; return match;
} }
@@ -98,6 +131,7 @@ export class MatchService {
if (!match.communityId.equals(params.communityId)) { if (!match.communityId.equals(params.communityId)) {
throw new BadRequestException('Match does not belong to this community.'); throw new BadRequestException('Match does not belong to this community.');
} }
await this.tournamentCodeService.releaseFromMatch(match);
await match.deleteOne(); await match.deleteOne();
} }
@@ -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;
@@ -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.');
}
}
}
@@ -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 {}
@@ -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
}`,
);
}
}
}
@@ -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<BulkUploadTournamentCodesResponse> {
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const invalid: BulkUploadTournamentCodesResponse['invalid'] = [];
const duplicates: string[] = [];
const valid: Array<
Omit<TournamentCode, 'createdAt' | 'updatedAt'> & {
uploadedBy: mongoose.Types.ObjectId;
}
> = [];
const seen = new Set<string>();
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<TournamentCodeDocument[]> {
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<TournamentCodeState, number>;
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<void> {
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<TournamentCodeDocument> {
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<MatchDocument> {
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<void> {
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<number> {
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<number> {
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<TournamentCodeSlotView[]> {
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();
}
}
@@ -0,0 +1,31 @@
import type {
TournamentCodeState,
TournamentSpectatorType,
} from '../global/database/schema';
export interface TournamentCodeUploadItem {
code: string;
expiresAt: string;
spectatorType?: TournamentSpectatorType;
metadata?: Record<string, unknown>;
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;
}
+5
View File
@@ -10,6 +10,7 @@ import LoginPage from './pages/Login';
import MatchDetailPage from './pages/MatchDetailPage'; import MatchDetailPage from './pages/MatchDetailPage';
import AuctionPage from './pages/AuctionPage'; import AuctionPage from './pages/AuctionPage';
import UserHistoryPage from './pages/UserHistoryPage'; import UserHistoryPage from './pages/UserHistoryPage';
import TournamentCodesPage from './pages/admin/TournamentCodesPage';
function MsalHeaderActions() { function MsalHeaderActions() {
const { accounts, instance } = useMsal(); const { accounts, instance } = useMsal();
@@ -71,6 +72,10 @@ function App() {
<Route path="/match/:id" element={<MatchDetailPage />} /> <Route path="/match/:id" element={<MatchDetailPage />} />
<Route path="/match/:id/auction" element={<AuctionPage />} /> <Route path="/match/:id/auction" element={<AuctionPage />} />
<Route path="/users/:userId/history" element={<UserHistoryPage />} /> <Route path="/users/:userId/history" element={<UserHistoryPage />} />
<Route
path="/admin/communities/:cid/tournament-codes"
element={<TournamentCodesPage />}
/>
</Routes> </Routes>
<DevAuthSwitcher /> <DevAuthSwitcher />
</div> </div>
+79
View File
@@ -16,6 +16,7 @@ import type {
ApiMatch, ApiMatch,
ApiRecentMatchesResponse, ApiRecentMatchesResponse,
ApiRecentSummaryResponse, ApiRecentSummaryResponse,
ApiTournamentCode,
ApiUserHistoryProfile, ApiUserHistoryProfile,
DdragonManifest, DdragonManifest,
MatchStatus, MatchStatus,
@@ -23,6 +24,11 @@ import type {
MeResponse, MeResponse,
RiotQueueGroup, RiotQueueGroup,
RiotRankFilter, RiotRankFilter,
TournamentCodeBulkUploadResponse,
TournamentCodeListResponse,
TournamentCodeState,
TournamentCodeStatsResponse,
TournamentCodeUploadItem,
} from './types'; } from './types';
const DDRAGON_MANIFEST_STALE_MS = 24 * 60 * 60 * 1000; 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<TournamentCodeStatsResponse>(
`/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<TournamentCodeListResponse>(
`/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<TournamentCodeBulkUploadResponse>(
`/communities/${communityId}/tournament-codes`,
{
method: 'POST',
body: JSON.stringify({ codes }),
},
),
});
}
export function useRestoreTournamentCode(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (codeId: string) =>
apiFetch<ApiTournamentCode>(
`/communities/${communityId}/tournament-codes/${codeId}/release`,
{ method: 'POST' },
),
});
}
export function useDeleteTournamentCode(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (codeId: string) =>
apiFetch<void>(`/communities/${communityId}/tournament-codes/${codeId}`, {
method: 'DELETE',
}),
});
}
export function useMe() { export function useMe() {
const authUserId = useAuthUserId(); const authUserId = useAuthUserId();
const { accounts, inProgress, instance } = useMsal(); const { accounts, inProgress, instance } = useMsal();
+5
View File
@@ -12,6 +12,7 @@ import type {
Position, Position,
RiotLane, RiotLane,
TeamSide, TeamSide,
TournamentCodeSlotView,
} from "./types"; } from "./types";
import { POSITION_ORDER, sideLabel } from "../lib/league"; import { POSITION_ORDER, sideLabel } from "../lib/league";
@@ -46,6 +47,8 @@ export interface MatchDetailView {
description: string; description: string;
map: string; map: string;
maxParticipants: number; maxParticipants: number;
gameCount: number;
tournamentCodes: TournamentCodeSlotView[];
joined: boolean; joined: boolean;
participants: ParticipantView[]; participants: ParticipantView[];
teams: TeamView[]; teams: TeamView[];
@@ -402,6 +405,8 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
description: match.description, description: match.description,
map: mapIdToLabel(match.mapId), map: mapIdToLabel(match.mapId),
maxParticipants: match.maxParticipants, maxParticipants: match.maxParticipants,
gameCount: match.gameCount ?? 3,
tournamentCodes: match.tournamentCodes ?? [],
joined: Boolean(match.joined), joined: Boolean(match.joined),
participants, participants,
teams, teams,
+71
View File
@@ -100,10 +100,28 @@ export interface ApiCommunity {
name: string; name: string;
description: string; description: string;
ownerUserId: string; ownerUserId: string;
matchGameCount?: number;
createdAt: string; createdAt: string;
updatedAt: 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 { export interface ApiMatchParticipant {
userId: string; userId: string;
puuid?: string; puuid?: string;
@@ -150,6 +168,8 @@ export interface ApiMatch {
status: MatchStatus; status: MatchStatus;
scheduledAt: string; scheduledAt: string;
maxParticipants: number; maxParticipants: number;
gameCount: number;
tournamentCodes?: TournamentCodeSlotView[];
hostUserId?: string; hostUserId?: string;
participants: ApiMatchParticipant[]; participants: ApiMatchParticipant[];
teams: ApiMatchTeam[]; teams: ApiMatchTeam[];
@@ -248,6 +268,57 @@ export interface DdragonManifest {
fetchedAt: string; 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<string, unknown>;
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<TournamentCodeState, number>;
expiringSoon: number;
available: number;
}
export interface TournamentCodeListResponse {
codes: ApiTournamentCode[];
}
export interface TournamentCodeUploadItem {
code: string;
expiresAt: string;
spectatorType?: TournamentSpectatorType;
metadata?: Record<string, unknown>;
source?: string;
notes?: string;
}
export interface TournamentCodeBulkUploadResponse {
inserted: number;
duplicates: string[];
invalid: Array<{ code: string; reason: string }>;
}
export type RiotQueueGroup = export type RiotQueueGroup =
| 'all' | 'all'
| 'summoners-rift' | 'summoners-rift'
+126 -2
View File
@@ -1,7 +1,13 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query'; import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Link, useNavigate, useParams } from 'react-router'; 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 { import {
buildDefaultPreferredPositions, buildDefaultPreferredPositions,
formatTierLabel, formatTierLabel,
@@ -15,7 +21,7 @@ import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config';
import { apiFetch, ApiError } from '../lib/api'; import { apiFetch, ApiError } from '../lib/api';
import { profileIconUrl } from '../lib/ddragon'; import { profileIconUrl } from '../lib/ddragon';
import { positionIcon, positionLabel } from '../lib/league'; 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 }) { function PosBadge({ pos, sub }: { pos: Position; sub?: boolean }) {
return ( 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 (
<div className="flex-1 min-w-0">
<div
className={`flex items-center gap-2 border px-2 py-1.5 ${
expired
? 'border-red-500/20 bg-red-500/8 text-red-400'
: used
? 'border-base-content/8 bg-base-content/5 text-base-content/35'
: 'border-primary/20 bg-primary/5 text-base-content'
}`}
>
<code className="font-mono text-[12px] font-bold truncate">
{expired ? '코드 만료' : slot.code}
</code>
{slot.code && !expired && (
<button
type="button"
className="ml-auto text-[10px] px-1.5 py-0.5 border border-base-content/10 text-base-content/45 hover:text-primary"
onClick={copyCode}
>
{copied ? '복사됨' : '복사'}
</button>
)}
</div>
<div
className={`mt-1 text-[10px] ${
expired || expiringSoon ? 'text-amber-500' : 'text-base-content/30'
}`}
>
{used
? '사용됨'
: expired
? '운영자에게 새 코드를 요청해주세요.'
: `만료: ${formatTournamentCodeExpiry(slot.expiresAt)}`}
</div>
</div>
);
}
function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) {
return (
<div className="space-y-2">
{slots.map((slot) => (
<div key={slot.gameNumber} className="flex items-start gap-2">
<span className="text-[11px] font-bold text-base-content/40 w-11 shrink-0 pt-1.5">
{slot.gameNumber}경기
</span>
{slot.code ? (
<TournamentCodeDisplay slot={slot} />
) : (
<span className="text-[11px] text-base-content/30 border border-dashed border-base-content/10 px-2 py-2 flex-1">
발급 대기 중... 운영자가 코드를 채우면 자동으로 붙습니다.
</span>
)}
</div>
))}
</div>
);
}
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 (
<div className="mt-3 border-t border-base-content/8 pt-3 text-[11px]">
<div className={available < 5 ? 'text-red-400' : 'text-base-content/35'}>
풀 잔여 {available}개
{expiringSoon > 0 ? ` · 만료 임박 ${expiringSoon}개` : ''}
</div>
<Link
to={`/admin/communities/${DEFAULT_COMMUNITY_ID}/tournament-codes`}
className="mt-1 inline-flex text-primary hover:underline"
>
코드 풀 관리
</Link>
</div>
);
}
export default function MatchDetailPage() { export default function MatchDetailPage() {
const { id } = useParams(); const { id } = useParams();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -623,6 +740,13 @@ export default function MatchDetailPage() {
</SideCard> </SideCard>
)} )}
{(match.status === 'team-built' || match.status === 'in-progress') && (
<SideCard title="토너먼트 코드">
<TournamentCodeList slots={match.tournamentCodes} />
<PoolStatsHint enabled={canManageAuction} />
</SideCard>
)}
{match.prizes.length > 0 && ( {match.prizes.length > 0 && (
<SideCard title="상품"> <SideCard title="상품">
<ul className="space-y-1.5"> <ul className="space-y-1.5">
@@ -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<TournamentCodeState | ''>('');
const [mode, setMode] = useState<'csv' | 'json'>('csv');
const [text, setText] = useState('');
const [message, setMessage] = useState<string | null>(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 (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<h1 className="text-lg font-bold">권한이 필요합니다</h1>
<p className="mt-2 text-sm text-base-content/40">
토너먼트 코드 풀은 owner/admin만 관리할 수 있습니다.
</p>
</main>
);
}
return (
<main className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
<Link
to="/"
className="inline-flex text-xs text-base-content/40 hover:text-base-content mb-5"
>
← 목록으로
</Link>
<div className="mb-6">
<h1 className="text-2xl font-black text-base-content">
토너먼트 코드 풀
</h1>
<p className="mt-1 text-sm text-base-content/45">
외부에서 생성한 코드를 업로드하고, 매치에 자동 할당되는 풀을 관리합니다.
</p>
</div>
<section className="grid sm:grid-cols-5 gap-3 mb-6">
{STATES.map((state) => (
<div key={state} className="border border-base-content/10 bg-base-100 p-4">
<div className="text-[10px] uppercase tracking-wider text-base-content/30">
{state}
</div>
<div className="mt-2 text-2xl font-black tabular-nums">
{counts?.[state] ?? 0}
</div>
</div>
))}
</section>
<section className="border border-base-content/10 bg-base-100 p-4 mb-6">
<div className="flex items-center justify-between gap-3 mb-3">
<h2 className="text-sm font-bold">Bulk 업로드</h2>
<div className="flex gap-1">
<button
type="button"
className={`px-3 py-1 text-xs border ${mode === 'csv' ? 'border-primary/40 text-primary bg-primary/5' : 'border-base-content/10 text-base-content/40'}`}
onClick={() => setMode('csv')}
>
간단 CSV
</button>
<button
type="button"
className={`px-3 py-1 text-xs border ${mode === 'json' ? 'border-primary/40 text-primary bg-primary/5' : 'border-base-content/10 text-base-content/40'}`}
onClick={() => setMode('json')}
>
확장 JSON
</button>
</div>
</div>
<textarea
value={text}
onChange={(event) => setText(event.target.value)}
rows={7}
placeholder={
mode === 'csv'
? 'KR-ABCD-1234,2026-05-30T18:00:00Z,메모'
: '[{"code":"KR-ABCD-1234","expiresAt":"2026-05-30T18:00:00Z","source":"external"}]'
}
className="w-full border border-base-content/10 bg-transparent p-3 text-xs font-mono focus:outline-none focus:border-primary/30"
/>
<div className="mt-3 flex items-center gap-3">
<button
type="button"
className="btn btn-primary btn-sm px-5 text-xs"
disabled={uploadMutation.isPending || !text.trim()}
onClick={handleUpload}
>
{uploadMutation.isPending ? '업로드 중...' : '업로드'}
</button>
{message && <span className="text-xs text-base-content/45">{message}</span>}
</div>
</section>
<section className="border border-base-content/10 bg-base-100 overflow-hidden">
<div className="px-4 py-3 border-b border-base-content/10 flex items-center justify-between gap-3">
<h2 className="text-sm font-bold">코드 목록</h2>
<select
value={stateFilter}
onChange={(event) => setStateFilter(event.target.value as TournamentCodeState | '')}
className="border border-base-content/10 bg-transparent px-2 py-1 text-xs"
>
<option value="">전체</option>
{STATES.map((state) => (
<option key={state} value={state}>
{state}
</option>
))}
</select>
</div>
<div className="overflow-x-auto">
<table className="w-full min-w-[900px] text-left">
<thead>
<tr className="bg-base-200/40 border-b border-base-content/10 text-[11px] uppercase tracking-wider text-base-content/35">
<th className="px-3 py-2">코드</th>
<th className="px-3 py-2">상태</th>
<th className="px-3 py-2">만료</th>
<th className="px-3 py-2">매치</th>
<th className="px-3 py-2">소스</th>
<th className="px-3 py-2 text-right">작업</th>
</tr>
</thead>
<tbody>
{codes.map((code) => (
<tr key={code._id} className="border-b border-base-content/5">
<td className="px-3 py-2 font-mono text-xs font-bold">
{code.code}
</td>
<td className="px-3 py-2 text-xs">{code.state}</td>
<td className="px-3 py-2 text-xs text-base-content/50">
{formatDate(code.expiresAt)}
</td>
<td className="px-3 py-2 text-xs text-base-content/50">
{code.matchId ? (
<Link to={`/match/${code.matchId}`} className="text-primary">
{code.matchId.slice(-6)} · {code.gameNumber}경기
</Link>
) : (
'-'
)}
</td>
<td className="px-3 py-2 text-xs text-base-content/50">
{code.source ?? '-'}
</td>
<td className="px-3 py-2">
<div className="flex justify-end gap-2">
{(code.state === 'released' || code.state === 'reserved') && (
<button
type="button"
className="text-[11px] px-2 py-1 border border-base-content/10 text-base-content/50 hover:text-primary"
onClick={() =>
restoreMutation.mutate(code._id, {
onSuccess: invalidate,
})
}
>
available 환원
</button>
)}
{code.state === 'available' && (
<button
type="button"
className="text-[11px] px-2 py-1 border border-red-500/20 text-red-400"
onClick={() =>
deleteMutation.mutate(code._id, {
onSuccess: invalidate,
})
}
>
폐기
</button>
)}
</div>
</td>
</tr>
))}
{codes.length === 0 && (
<tr>
<td
colSpan={6}
className="px-4 py-10 text-center text-sm text-base-content/35"
>
코드가 없습니다.
</td>
</tr>
)}
</tbody>
</table>
</div>
</section>
</main>
);
}