diff --git a/Frontend-Backend-통합-플랜.md b/Frontend-Backend-통합-플랜.md new file mode 100644 index 00000000..25ea3ff8 --- /dev/null +++ b/Frontend-Backend-통합-플랜.md @@ -0,0 +1,433 @@ +# Frontend ↔ Backend 통합 플랜 (Lolympus Tournament Support) + +> **대상**: codex에 이어서 작업 가능한 수준의 실행 플랜 +> **레포**: `/Users/dahyeon/source/lolympus-tournament-support` (pnpm workspace) +> **작성 기준**: 2026-04-24 + +--- + +## 1. Context + +`apps/web`(React 19 + Vite + React Router 7)은 현재 `src/mock.ts`와 `src/auction-mock.ts`의 하드코딩된 더미 데이터로만 화면을 그립니다. 경매 페이지는 `setInterval` 기반 클라이언트 사이드 시뮬레이터(`createMockAuction()`)로 동작합니다. + +`apps/api`(NestJS 11 + Mongoose 9)는 Community/User/Match/Auction 스키마와 CRUD 엔드포인트, RBAC 가드(`@Roles`), 글로벌 `ValidationPipe`, `X-Auth-User-Id` 헤더 기반 임시 인증까지 구축되어 있습니다. 하지만 **경매 실시간 푸시(WebSocket) 미구현, CORS 미설정, `MatchParticipant` 스냅샷에 티어 정보 없음, `/me` 같은 편의 엔드포인트 없음**이 통합의 걸림돌입니다. + +### 이번 작업의 목표 + +1. 경매 페이지가 서버 주도 타이머·상태로 10명 관전 + 2명 입찰을 실시간 동기화하도록 **WebSocket 게이트웨이**를 API에 추가 +2. 프론트엔드의 모든 mock import를 제거하고 **API 클라이언트 + React Query + Socket.IO 클라이언트**로 교체 +3. 초기 MVP는 **단일 기본 커뮤니티** 전제 (env `VITE_DEFAULT_COMMUNITY_ID`) +4. **로그인 UI는 이번 범위에서 제외**. admin 기능은 개발자용 "User ID 수동 입력" 위젯으로 임시 처리 +5. `MatchParticipant` 스냅샷에 `tier` 필드 추가 (참여 시점의 primary RiotAccount tier를 복사) + +### 비목표 (이번 작업에 포함하지 않음) + +- 카카오/디스코드 OAuth 로그인 플로우 +- 다중 커뮤니티 전환 UI +- Riot API 실시간 동기화 UI (기존 `RiotAccountService`는 그대로 둠) +- 매치 결과 기록 UI (`MatchResult`) +- 포스트-경매 Riot 토너먼트 코드 발급 + +--- + +## 2. 현재 상태 정리 (실사 결과) + +### 2.1 백엔드에 이미 있는 것 + +| 영역 | 파일 | 상태 | +| ----------------------------------------------- | ------------------------------------------------ | ----------- | +| Community CRUD + owner 트랜잭션 | `apps/api/src/modules/community/*` | ✅ | +| Match CRUD + 참여(join) | `apps/api/src/modules/match/*` | ✅ | +| Auction 시작/입찰/낙찰/다음/리셋 | `apps/api/src/modules/auction/*` | ✅ (HTTP만) | +| 스키마 (Community/User/Match/Auction/RiotMatch) | `apps/api/src/modules/global/database/schema.ts` | ✅ | +| `@Roles` + `RolesGuard` + `CurrentUser` | `apps/api/src/modules/auth/*` | ✅ | +| 글로벌 `ValidationPipe` | `apps/api/src/main.ts` | ✅ | + +### 2.2 백엔드에 없는 것 (이번에 추가) + +1. **CORS** — Vite dev는 `http://localhost:5173`, API는 `http://localhost:3000`. `app.enableCors()` 필요 +2. **WebSocket (Socket.IO) 게이트웨이** — auction 상태 푸시 + 클라이언트 입찰 수신 +3. **서버 주도 타이머** — 현재 auction 문서에 `maxTimerSeconds`만 있음. 입찰 시 갱신되는 `currentDeadline: Date` 필드 + 만료 자동 `markSold` 스케줄러 필요 +4. **`MatchParticipant.tier`** — 참여 시 primary RiotAccount의 primary queue tier(solo 5x5)를 snapshot으로 복사 +5. **`GET /me`** — 현재 `X-Auth-User-Id` 헤더의 User 반환 (헤더 없으면 `null`). 프론트에서 admin 기능 가시성 판단용 +6. **`GET /communities/:communityId`** — 프론트 헤더에 커뮤니티 이름 표시용 +7. `mapId: number` → 프론트 라벨 매핑 유틸(프론트 쪽). 백엔드는 그대로 + +### 2.3 프론트엔드에 없는 것 (이번에 추가) + +1. API 클라이언트 (`src/lib/api.ts`) — fetch 래퍼, `X-Auth-User-Id` 주입 +2. `@tanstack/react-query` + `QueryClientProvider` +3. `socket.io-client` + `useAuctionSocket` 훅 +4. `src/config.ts` — `VITE_API_BASE_URL`, `VITE_DEFAULT_COMMUNITY_ID`, localStorage `X-Auth-User-Id` 관리 +5. 백엔드 스키마에 대응하는 **프론트 타입** (`src/api/types.ts`) +6. 백엔드 `Match`/`Auction` → 프론트 `MatchDetail`/`AuctionState` **매핑 함수** (`src/api/mappers.ts`) +7. 개발자용 "User ID 주입" 토글 UI (admin 기능 테스트용, 프로덕션 빌드에선 숨김) + +### 2.4 데이터 모델 차이 요약 + +| 프론트 모델 | 백엔드 모델 | 매핑 전략 | +| --------------------------------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------ | +| `MatchDetail.date`/`time` (한국어 string) | `Match.scheduledAt: Date` | 프론트에서 `Intl.DateTimeFormat('ko-KR')`로 포맷 | +| `MatchDetail.map: string` ("소환사의 협곡") | `Match.mapId: number` (11) | 프론트 `mapIdToLabel` 유틸 | +| `Participant.tier: {previousSeason, current, peak}` | 추가 필요: `MatchParticipant.tier` 스냅샷 | 백엔드에 필드 추가 후 프론트가 그대로 읽음 (프론트 `TierInfo`는 백엔드 원본 형태로 리팩터) | +| `Team.participants[].assignedPosition` | `MatchTeam.members[].assignedPosition` | 프론트가 `match.participants`와 `match.teams`를 조합해서 표시 | +| `AuctionPlayer.tier` (단일) | `AuctionPlayerSnapshot.tiers: TierInfo[]` | 프론트에서 `queueType === 'RANKED_SOLO_5x5'` 필터 후 대표 선택 | +| `AuctionPlayer.masteries[].championName` | `ChampionMasteryEntry.championName` (optional) | 프론트가 fallback 처리 | +| `AuctionState.timer` (초, 카운트다운) | 서버 `currentDeadline: Date` | 프론트가 `deadline - now`로 매 틱 계산 | + +--- + +## 3. 실행 계획 + +> 단계는 독립적이지 않고 순차 진행 권장. Phase 0 → 1 → 2 → 3 순서. + +### Phase 0 — 백엔드 선행 보강 (`apps/api`) + +#### 0.1 CORS 활성화 + +**파일**: `apps/api/src/main.ts` + +```ts +app.enableCors({ + origin: process.env.WEB_ORIGIN?.split(",") ?? ["http://localhost:5173"], + credentials: true, + allowedHeaders: ["Content-Type", "X-Auth-User-Id"], +}); +``` + +프로덕션용 origin은 `project.env`의 `WEB_ORIGIN`으로 주입. + +#### 0.2 `MatchParticipant.tier` 스냅샷 필드 추가 + +**파일**: `apps/api/src/modules/global/database/schema.ts` + +- `MatchParticipant` interface + sub-schema에 `tier?: TierInfo` 추가 (optional — Riot 계정이 없는 유저도 참여 가능해야 하면) +- `MatchService.join()` (`apps/api/src/modules/match/match.service.ts` 라인 93~)에서 `primaryRiot.tiers.find(t => t.queueType === 'RANKED_SOLO_5x5') ?? primaryRiot.tiers[0]`를 복사 +- 기존 데이터 마이그레이션 없이 optional이라 호환성 유지 + +#### 0.3 `/me` + `/communities/:id` 편의 엔드포인트 + +**신규 파일**: `apps/api/src/modules/user/user.controller.ts`, `user.module.ts` + +```ts +@Controller("me") +class MeController { + @Get() + me(@CurrentUser() user: UserDocument | undefined) { + return user ? { user } : { user: null }; + } +} +``` + +**Community 쪽** (`community.controller.ts`): + +```ts +@Get(':communityId') +async getCommunity(@Param('communityId', ParseObjectIdPipe) id) { + return this.communityService.getById(id); // 서비스에 메서드 추가 +} +``` + +#### 0.4 Auction WebSocket 게이트웨이 (핵심) + +**의존성 설치**: `pnpm --filter api add @nestjs/websockets @nestjs/platform-socket.io socket.io` + +**신규 파일**: `apps/api/src/modules/auction/auction.gateway.ts` + +네임스페이스·룸 구조: + +- 네임스페이스: `/auction` +- 룸 이름: `matchId` 문자열 + +이벤트 스펙: +| 방향 | 이벤트 | payload | +| --- | --- | --- | +| server→client | `state` | `AuctionDocument` (직렬화) | +| server→client | `tick` | `{ deadline: string, serverTime: string }` | +| server→client | `error` | `{ message: string }` | +| client→server | `join` | `{ matchId: string }` | +| client→server | `bid` | `{ side, amount, bidderUserId? }` | +| client→server | `open-bidding` | `{}` | +| client→server | `sold` | `{ assignedPosition? }` | +| client→server | `next` | `{}` | + +구현 포인트: + +- `handleConnection`/`handleDisconnect`에서 Socket.IO의 rooms 표준 사용 +- 클라이언트 `join` 시 해당 matchId 룸에 입장 + 현재 `state` 푸시 +- 입찰/낙찰/다음 이벤트는 **기존 `AuctionService` 메서드 재사용**. 결과 상태를 해당 룸에 브로드캐스트 +- `AuctionService`가 phase 전이 시마다 `deadline: Date` 계산해서 Auction 문서에 저장 (`AuctionSchema`에 `currentDeadline?: Date` 추가) +- 타이머 만료 자동 처리는 **Phase 0에선 생략**하고, 클라이언트가 deadline 지나면 "시간 종료" 표시만. 자동 `markSold`는 후속 작업 (`SchedulerRegistry` + `setTimeout` 필요). 트러스트 전제라 팀장이 수동 sold 하면 충분. + +**AuthMiddleware는 socket.io 연결에 적용되지 않음**: 게이트웨이 자체에서 `@ConnectedSocket()`의 handshake headers 또는 auth payload에서 `x-auth-user-id`를 읽어 옵션으로 취급. 권한 필요한 이벤트(`open-bidding`, `sold`, `next`)는 일단 무검증 유지 (트러스트 전제). `bid`만 payload의 `bidderUserId`를 검증해서 해당 팀의 `captainUserId`와 일치하는지 정도 체크하면 고의 방해 방지 최소선은 만족. + +#### 0.5 `AuctionSchema.currentDeadline` 추가 + +**파일**: `apps/api/src/modules/global/database/schema.ts` + +- interface `Auction`에 `currentDeadline?: Date` +- Schema 필드 추가 +- `AuctionService.openBidding()`과 `placeBid()`에서 `new Date(Date.now() + auction.maxTimerSeconds * 1000)`로 갱신 + - `placeBid` 시엔 `Math.max(5, remainingSeconds)` 보장 (기존 프론트 mock 로직과 동일: 최소 5초) +- `markSold` / `next` 시엔 `undefined`로 리셋 + +#### 0.6 AppModule 등록 + +**파일**: `apps/api/src/app.module.ts` + +- `UserModule` import +- `AuctionModule`에서 게이트웨이 providers 등록 (`AuctionGateway` + `AuctionService`는 그대로) + +#### 0.7 검증 (Phase 0 종료 시) + +```bash +cd apps/api +./node_modules/.bin/tsc --noEmit +pnpm start:dev +``` + +- `curl -H "X-Auth-User-Id: " http://localhost:3000/me`로 `/me` 확인 +- socket.io 클라이언트(또는 `wscat`)로 `ws://localhost:3000/auction` 연결 + `join` 이벤트 → `state` 수신 확인 + +--- + +### Phase 1 — 프론트엔드 인프라 구축 (`apps/web`) + +#### 1.1 의존성 설치 + +```bash +pnpm --filter web add @tanstack/react-query socket.io-client +pnpm --filter web add -D @tanstack/react-query-devtools +``` + +#### 1.2 환경 변수 + +**신규 파일**: `apps/web/.env.development` (기존 있으면 추가) + +``` +VITE_API_BASE_URL=http://localhost:3000 +VITE_DEFAULT_COMMUNITY_ID= +``` + +**신규 파일**: `apps/web/src/config.ts` + +- `API_BASE_URL`, `DEFAULT_COMMUNITY_ID` export +- `getAuthUserId()` / `setAuthUserId(id | null)` (localStorage `lolympus.authUserId`) + +#### 1.3 API 클라이언트 + +**신규 파일**: `apps/web/src/lib/api.ts` + +- `apiFetch(path, init?)`: 베이스 URL 붙이고, `X-Auth-User-Id` 자동 주입, JSON 파싱, 4xx/5xx는 `ApiError` throw +- 응답 타입은 제네릭 + +#### 1.4 타입 정의 (백엔드 미러) + +**신규 파일**: `apps/web/src/api/types.ts` + +- `Position`, `TeamSide`, `MatchStatus`, `AuctionPhase` 같은 유니온은 복붙 +- `TierInfo`, `ChampionMasteryEntry`, `RiotRecentStatsSummary` 등 sub-type +- `ApiCommunity`, `ApiUser`, `ApiMatch`, `ApiAuction` — 응답 형태 그대로 +- `_id: string` (ObjectId 직렬화), `createdAt/updatedAt: string` (ISO) + +> 타입 중복은 MVP에선 감수. 나중에 `packages/shared-types` 생성 고려. + +#### 1.5 매핑 레이어 + +**신규 파일**: `apps/web/src/api/mappers.ts` + +- `mapApiMatchToMatchDetail(match: ApiMatch): MatchDetail` +- `mapApiAuctionToAuctionState(auction: ApiAuction, serverNow?: Date): AuctionState` +- `mapIdToLabel(mapId: number): string` — `11 → '소환사의 협곡'`, `12 → '칼바람 나락'`, ... +- `formatKoreanDate(date: Date): { date, time }` +- `selectPrimaryTier(tiers: TierInfo[]): TierInfo | undefined` + +> 기존 `apps/web/src/mock.ts`의 `MatchDetail`/`Participant` 타입은 유지한 채로 매퍼가 채움. 이후 Phase 2에서 점진 삭제. + +#### 1.6 React Query 설정 + +**파일 수정**: `apps/web/src/main.tsx` + +- `QueryClientProvider`로 감싸기 +- staleTime 10s, cacheTime 5min 기본값 + +#### 1.7 Socket 훅 + +**신규 파일**: `apps/web/src/api/useAuctionSocket.ts` + +- `useAuctionSocket(matchId: string)` 훅 +- 내부: `useEffect`로 `io(API_BASE_URL + '/auction', { auth: { 'x-auth-user-id': getAuthUserId() } })` +- `join` emit 후 `state`/`tick`/`error` 이벤트 구독 +- state는 `useState`로 저장, 반환: `{ state, placeBid, openBidding, markSold, next, connectionStatus }` + +#### 1.8 개발자용 User 주입 위젯 + +**신규 파일**: `apps/web/src/components/DevAuthSwitcher.tsx` + +- 우하단 플로팅 패널. input + "Set"/"Clear" 버튼. localStorage 값 표시 +- `import.meta.env.DEV`일 때만 렌더 + +--- + +### Phase 2 — 페이지 교체 (`apps/web`) + +#### 2.1 HomePage + +**파일**: `apps/web/src/pages/HomePage.tsx` + +- mock import 제거 +- `useQuery(['matches', communityId, 'upcoming'])` → `GET /communities/:id/matches?status=recruiting&limit=20` +- `useQuery(['matches', communityId, 'finished'])` → `GET /communities/:id/matches?status=finished&limit=10` +- "다음 내전"은 upcoming의 첫 요소 +- 각 카드는 `mapApiMatchToMatchDetail`의 축약 버전으로 + +#### 2.2 MatchDetailPage + +**파일**: `apps/web/src/pages/MatchDetailPage.tsx` + +- `useQuery(['match', matchId])` → `GET /communities/:id/matches/:matchId` +- `mapApiMatchToMatchDetail()` 적용 +- 참가자 티어는 `participant.tier` 직접 사용 (백엔드 snapshot) +- "경매 시작" 버튼은 `/me` 결과의 role이 admin/owner일 때만 보여주기 (admin 전용) + +#### 2.3 AuctionPage + +**파일**: `apps/web/src/pages/AuctionPage.tsx` + +- `createMockAuction` import 제거 +- 초기 상태: `useQuery(['auction', matchId])` → `GET /communities/:id/matches/:matchId/auction` +- 이후: `useAuctionSocket(matchId)`로 실시간 갱신 +- 타이머: `state.currentDeadline`과 `Date.now()` 차이로 클라이언트 카운트다운 +- "입찰" 버튼: `placeBid({side, amount})` 호출 (내부적으로 socket emit) +- "공개"/"낙찰"/"다음" 버튼(팀장용): socket emit — 페이지에 세 버튼 노출 (트러스트 전제) +- **localStorage에 자기가 어느 팀장인지 저장하는 토글** 추가 (dev 편의) + +#### 2.4 mock 파일 제거 + +- `apps/web/src/mock.ts` — Position/TierInfo/Participant 같은 타입만 `src/api/types.ts`로 흡수 후 삭제 +- `apps/web/src/auction-mock.ts` — 전부 삭제 +- `apps/web/src/auction-types.ts` — 프론트 전용 파생 타입만 남기고 백엔드 응답 타입은 `api/types.ts`로 + +--- + +### Phase 3 — E2E 검증 및 시드 + +#### 3.1 시드 데이터 생성 스크립트 + +**신규 파일**: `apps/api/src/seed.ts` (또는 ad-hoc) + +- `CommunityService.createCommunityWithOwner({ name: 'Dev Community', owner: { kakaoTalkNickname: 'DevOwner' } })` +- 참가자 유저 10명 생성 (Riot 계정 더미 + tiers 채움 — 기존 mock 데이터를 DB로 이식) +- 매치 3개 (recruiting 1, team-built 1, finished 1) +- 반환된 `communityId`를 `.env.development`에 복사 + +실행: + +```bash +pnpm --filter api exec ts-node src/seed.ts +``` + +#### 3.2 통합 smoke test + +1. `pnpm --filter api start:dev` +2. `pnpm --filter web dev` +3. 브라우저에서 `http://localhost:5173`: + - HomePage에 시드 매치 3개 표시되는지 + - MatchDetailPage에서 참가자 티어 정보 렌더링되는지 + - DevAuthSwitcher로 owner User ID 주입 → 경매 시작 버튼 보이는지 + - AuctionPage 두 탭 열어서 한쪽 입찰 시 다른 쪽 실시간 반영되는지 +4. `tsc --noEmit`과 `pnpm --filter web build` 무오류 확인 + +--- + +## 4. 파일별 수정/신규 체크리스트 + +### `apps/api` 수정 + +- [ ] `src/main.ts` — CORS +- [ ] `src/modules/global/database/schema.ts` — `MatchParticipant.tier?`, `Auction.currentDeadline?` +- [ ] `src/modules/match/match.service.ts::join` — tier 스냅샷 복사 +- [ ] `src/modules/auction/auction.service.ts` — `openBidding`/`placeBid`에서 `currentDeadline` 갱신, `markSold`/`next`에서 리셋 +- [ ] `src/modules/community/community.controller.ts` + `community.service.ts` — `getById` + `GET /communities/:id` +- [ ] `src/app.module.ts` — `UserModule`, `AuctionGateway` provider 등록 + +### `apps/api` 신규 + +- [ ] `src/modules/user/user.module.ts` +- [ ] `src/modules/user/user.controller.ts` (`GET /me`) +- [ ] `src/modules/auction/auction.gateway.ts` +- [ ] `src/seed.ts` (선택) + +### `apps/web` 수정 + +- [ ] `src/main.tsx` — `QueryClientProvider` +- [ ] `src/App.tsx` — DevAuthSwitcher 마운트 +- [ ] `src/pages/HomePage.tsx` — react-query 연동 +- [ ] `src/pages/MatchDetailPage.tsx` — react-query 연동 +- [ ] `src/pages/AuctionPage.tsx` — socket 훅 연동 + +### `apps/web` 신규 + +- [ ] `.env.development` +- [ ] `src/config.ts` +- [ ] `src/lib/api.ts` +- [ ] `src/api/types.ts` +- [ ] `src/api/mappers.ts` +- [ ] `src/api/useAuctionSocket.ts` +- [ ] `src/api/hooks.ts` (선택 — `useMatches`, `useMatch`, `useAuction`, `useMe`) +- [ ] `src/components/DevAuthSwitcher.tsx` + +### `apps/web` 삭제 + +- [ ] `src/mock.ts` (타입은 `src/api/types.ts`로 흡수 후) +- [ ] `src/auction-mock.ts` + +--- + +## 5. 재사용할 기존 유틸 + +| 용도 | 위치 | 재사용 포인트 | +| ---------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------- | +| ObjectId 파라미터 파싱 | `apps/api/src/modules/common/parse-object-id.pipe.ts` | 새 엔드포인트(`getCommunity`, `me`)에도 적용 | +| 트랜잭션 세션 생성 | `apps/api/src/modules/global/database/connection.service.ts::createSession` | `AuctionGateway`에서 원자적 상태 전이가 필요한 경우 | +| `@CurrentUser()` | `apps/api/src/modules/auth/current-user.decorator.ts` | `/me`에서 그대로 사용 | +| Role 매핑 | `apps/api/src/modules/auth/permissions.ts::roleHasPermission` | 프론트에 권한 표시 JSON 내려줄 때 참고 | +| 포지션 라벨/아이콘 | `apps/web/src/assets/position/*` + `mock.ts`의 `positionLabel`/`positionIcon` | `src/api/mappers.ts`로 이동 | + +--- + +## 6. 위험 요소 & 주의사항 + +1. **Socket.IO 인증 미적용**: MVP에선 WebSocket 연결에 인증을 강제하지 않음. 고의 방해 시나리오 대비는 `bid` 이벤트의 `bidderUserId`가 해당 팀 `captainUserId`와 일치하는지만 체크. 프로덕션 전환 전에 JWT 핸드셰이크로 교체. +2. **타이머 만료 자동 sold 미구현**: 팀장이 수동으로 "낙찰" 누르는 흐름. 이게 불편하면 후속 작업으로 `SchedulerRegistry` 타이머 추가. +3. **Mongoose `HydratedDocument` 직렬화**: `JSON.stringify`는 `toJSON`을 거치지만 `_id`가 ObjectId 객체로 나올 수 있음. 엔드포인트에서 `.lean()` 또는 `toObject({ versionKey: false })` 적용 고려 — 또는 프론트에서 `String(_id)` 처리. +4. **프론트 타입 중복**: `apps/web/src/api/types.ts`가 백엔드 스키마와 갈라질 수 있음. Phase 3 이후 `packages/shared-types` 워크스페이스로 승격 권장. +5. **시드 데이터의 communityId 동기화**: `.env.development`에 하드코딩되므로 재시드 시 값 바뀜. `seed.ts` 마지막에 `.env.development`를 갱신하도록 하면 편함. +6. **`forbidNonWhitelisted: true`**: DTO에 없는 필드는 400. 프론트 요청 페이로드 구성 시 주의. +7. **Riot 계정 없는 유저 참여**: `MatchService.join`은 현재 `primaryRiot` 없어도 `undefined`로 저장. `tier` 필드도 optional로 유지해야 기존 흐름 유지. + +--- + +## 7. 검증 체크리스트 (최종) + +- [ ] `pnpm --filter api run build` 무오류 +- [ ] `pnpm --filter web run build` 무오류 +- [ ] `curl -i http://localhost:3000/me` → `{user: null}`, 헤더 넣으면 user 객체 +- [ ] `curl http://localhost:3000/communities//matches` → 시드 매치 목록 +- [ ] 브라우저 HomePage 렌더 OK +- [ ] MatchDetailPage에 티어 표시 OK +- [ ] AuctionPage 두 탭 open → 한쪽 bid 하면 다른 쪽 `state` 이벤트로 즉시 갱신 +- [ ] DevAuthSwitcher로 owner ID 주입 시에만 "경매 시작" 버튼 노출 +- [ ] 비 admin 상태에선 admin 엔드포인트 호출 시 401/403 응답이 UI에 에러 토스트로 노출 + +--- + +## 8. 작업 순서 (codex 핸드오프용) + +1. **Phase 0** (백엔드 보강) — 스키마 변경 → 서비스 갱신 → 게이트웨이 → CORS/ME. 빌드 확인. +2. **Phase 1** (프론트 인프라) — deps 설치 → config/api/types/mappers → QueryClientProvider. +3. **Phase 3의 3.1 시드** 먼저 돌려서 `communityId` 확보 → `.env.development` 업데이트. +4. **Phase 2** (페이지 교체) — HomePage → MatchDetailPage → AuctionPage 순서. +5. **Phase 3의 3.2** E2E 스모크 테스트. + +각 Phase 종료마다 `tsc --noEmit`으로 타입 검증, 필요시 `pnpm lint` 실행. diff --git a/apps/api/package.json b/apps/api/package.json index 1fd256f6..1a4adafb 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -8,6 +8,7 @@ "scripts": { "build": "nest build", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", + "seed:dev": "ts-node src/seed.ts", "start:dev": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'dev'); \"./start.ps1\"\"", "start:test": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'test'); \"./start.ps1\"\"", "start:prod": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'prod'); \"./start.ps1\"\"", @@ -27,13 +28,16 @@ "@nestjs/config": "^4.0.4", "@nestjs/core": "^11.0.1", "@nestjs/platform-express": "^11.0.1", + "@nestjs/platform-socket.io": "^11.1.19", "@nestjs/swagger": "^11.2.7", + "@nestjs/websockets": "^11.1.19", "class-transformer": "^0.5.1", "class-validator": "^0.15.1", "mongoose": "^9.4.1", "nats": "^2.29.3", "reflect-metadata": "^0.2.2", "rxjs": "^7.8.1", + "socket.io": "^4.8.3", "temporal-polyfill": "^0.3.2" }, "devDependencies": { diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts index fed6dbfb..7c24c83a 100644 --- a/apps/api/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -8,6 +8,7 @@ import { CommunityModule } from './modules/community/community.module'; import { GlobalModule } from './modules/global/global.module'; import { MatchModule } from './modules/match/match.module'; import { RiotModule } from './modules/riot/riot.module'; +import { UserModule } from './modules/user/user.module'; @Module({ imports: [ @@ -21,6 +22,7 @@ import { RiotModule } from './modules/riot/riot.module'; CommunityModule, MatchModule, AuctionModule, + UserModule, ], controllers: [AppController], providers: [AppService], diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index 9cef9d3f..3dcdb436 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -6,6 +6,17 @@ async function bootstrap() { const app = await NestFactory.create(AppModule, { rawBody: true, }); + + const isDev = process.env.NODE_ENV === 'dev'; + const webOrigins = process.env.WEB_ORIGIN?.split(',').map((origin) => + origin.trim(), + ) ?? ['http://localhost:5173', 'http://126.dahyeon.us:5173']; + + app.enableCors({ + origin: isDev ? true : webOrigins, + credentials: true, + allowedHeaders: ['Content-Type', 'X-Auth-User-Id'], + }); app.useGlobalPipes( new ValidationPipe({ whitelist: true, diff --git a/apps/api/src/modules/auction/auction.gateway.ts b/apps/api/src/modules/auction/auction.gateway.ts new file mode 100644 index 00000000..f283287e --- /dev/null +++ b/apps/api/src/modules/auction/auction.gateway.ts @@ -0,0 +1,247 @@ +import { Logger } from '@nestjs/common'; +import { + ConnectedSocket, + MessageBody, + OnGatewayConnection, + OnGatewayDisconnect, + SubscribeMessage, + WebSocketGateway, + WebSocketServer, +} from '@nestjs/websockets'; +import mongoose from 'mongoose'; +import { Namespace, Socket } from 'socket.io'; +import type { AuctionDocument, Position, TeamSide } from '../global/database/schema'; +import { AuctionService } from './auction.service'; + +interface JoinAuctionPayload { + matchId: string; +} + +interface BidPayload { + side: TeamSide; + amount: number; + bidderUserId?: string; +} + +interface SoldPayload { + assignedPosition?: Position; +} + +@WebSocketGateway({ + namespace: '/auction', + cors: { + origin: true, + credentials: true, + allowedHeaders: ['Content-Type', 'X-Auth-User-Id'], + }, +}) +export class AuctionGateway + implements OnGatewayConnection, OnGatewayDisconnect +{ + @WebSocketServer() + private server!: Namespace; + + private readonly logger = new Logger(AuctionGateway.name); + private readonly roomTimers = new Map(); + + constructor(private readonly auctionService: AuctionService) {} + + public handleConnection(socket: Socket) { + this.logger.debug(`Auction client connected: ${socket.id}`); + } + + public handleDisconnect(socket: Socket) { + const matchId = this.getSocketMatchId(socket); + if (!matchId) return; + this.maybeClearRoomTimer(matchId); + } + + @SubscribeMessage('join') + public async handleJoin( + @ConnectedSocket() socket: Socket, + @MessageBody() payload: JoinAuctionPayload, + ) { + if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) { + this.emitError(socket, 'Invalid matchId.'); + return; + } + + await socket.join(payload.matchId); + socket.data.matchId = payload.matchId; + + try { + const auction = await this.auctionService.getByMatchId( + new mongoose.Types.ObjectId(payload.matchId), + ); + this.broadcastState(payload.matchId, auction); + } catch (error) { + this.emitKnownError(socket, error); + } + } + + @SubscribeMessage('bid') + public async handleBid( + @ConnectedSocket() socket: Socket, + @MessageBody() payload: BidPayload, + ) { + const matchId = this.requireJoinedMatchId(socket); + if (!matchId) return; + + const bidderUserId = this.resolveBidderUserId(socket, payload?.bidderUserId); + if (payload?.bidderUserId && !bidderUserId) { + this.emitError(socket, 'Invalid bidderUserId.'); + return; + } + + try { + const auction = await this.auctionService.placeBid({ + matchId: new mongoose.Types.ObjectId(matchId), + side: payload.side, + amount: payload.amount, + bidderUserId, + }); + this.broadcastState(matchId, auction); + } catch (error) { + this.emitKnownError(socket, error); + } + } + + @SubscribeMessage('open-bidding') + public async handleOpenBidding(@ConnectedSocket() socket: Socket) { + const matchId = this.requireJoinedMatchId(socket); + if (!matchId) return; + + try { + const auction = await this.auctionService.openBidding( + new mongoose.Types.ObjectId(matchId), + ); + this.broadcastState(matchId, auction); + } catch (error) { + this.emitKnownError(socket, error); + } + } + + @SubscribeMessage('sold') + public async handleSold( + @ConnectedSocket() socket: Socket, + @MessageBody() payload: SoldPayload, + ) { + const matchId = this.requireJoinedMatchId(socket); + if (!matchId) return; + + try { + const auction = await this.auctionService.markSold({ + matchId: new mongoose.Types.ObjectId(matchId), + assignedPosition: payload?.assignedPosition, + }); + this.broadcastState(matchId, auction); + } catch (error) { + this.emitKnownError(socket, error); + } + } + + @SubscribeMessage('next') + public async handleNext(@ConnectedSocket() socket: Socket) { + const matchId = this.requireJoinedMatchId(socket); + if (!matchId) return; + + try { + const auction = await this.auctionService.next( + new mongoose.Types.ObjectId(matchId), + ); + this.broadcastState(matchId, auction); + } catch (error) { + this.emitKnownError(socket, error); + } + } + + private requireJoinedMatchId(socket: Socket): string | null { + const matchId = this.getSocketMatchId(socket); + if (!matchId) { + this.emitError(socket, 'Join a match room before sending events.'); + return null; + } + return matchId; + } + + private getSocketMatchId(socket: Socket): string | undefined { + return typeof socket.data.matchId === 'string' ? socket.data.matchId : undefined; + } + + private resolveBidderUserId( + socket: Socket, + payloadBidderUserId?: string, + ): mongoose.Types.ObjectId | undefined { + const candidate = + payloadBidderUserId ?? this.readHandshakeUserId(socket); + if (!candidate || !mongoose.isValidObjectId(candidate)) { + return undefined; + } + return new mongoose.Types.ObjectId(candidate); + } + + private readHandshakeUserId(socket: Socket): string | undefined { + const authUserId = socket.handshake.auth['x-auth-user-id']; + if (typeof authUserId === 'string') return authUserId; + + const header = socket.handshake.headers['x-auth-user-id']; + return Array.isArray(header) ? header[0] : header; + } + + private broadcastState(matchId: string, auction: AuctionDocument) { + this.server.to(matchId).emit('state', this.serializeAuction(auction)); + this.syncRoomTimer(matchId, auction); + } + + private syncRoomTimer(matchId: string, auction: AuctionDocument) { + this.clearRoomTimer(matchId); + if (!auction.currentDeadline) return; + + const deadline = auction.currentDeadline; + const deadlineIso = deadline.toISOString(); + this.server.to(matchId).emit('tick', { + deadline: deadlineIso, + serverTime: new Date().toISOString(), + }); + + const timer = setInterval(() => { + this.server.to(matchId).emit('tick', { + deadline: deadlineIso, + serverTime: new Date().toISOString(), + }); + + if (Date.now() >= deadline.getTime()) { + this.clearRoomTimer(matchId); + } + }, 1000); + + this.roomTimers.set(matchId, timer); + } + + private maybeClearRoomTimer(matchId: string) { + const room = this.server.adapter.rooms.get(matchId); + if (room && room.size > 0) return; + this.clearRoomTimer(matchId); + } + + private clearRoomTimer(matchId: string) { + const timer = this.roomTimers.get(matchId); + if (!timer) return; + clearInterval(timer); + this.roomTimers.delete(matchId); + } + + private emitKnownError(socket: Socket, error: unknown) { + const message = + error instanceof Error ? error.message : 'Unexpected auction gateway error.'; + this.emitError(socket, message); + } + + private emitError(socket: Socket, message: string) { + socket.emit('error', { message }); + } + + private serializeAuction(auction: AuctionDocument) { + return JSON.parse(JSON.stringify(auction)); + } +} diff --git a/apps/api/src/modules/auction/auction.module.ts b/apps/api/src/modules/auction/auction.module.ts index 82e38f62..dece1703 100644 --- a/apps/api/src/modules/auction/auction.module.ts +++ b/apps/api/src/modules/auction/auction.module.ts @@ -1,10 +1,11 @@ import { Module } from '@nestjs/common'; +import { AuctionGateway } from './auction.gateway'; import { AuctionController } from './auction.controller'; import { AuctionService } from './auction.service'; @Module({ controllers: [AuctionController], - providers: [AuctionService], + providers: [AuctionService, AuctionGateway], exports: [AuctionService], }) export class AuctionModule {} diff --git a/apps/api/src/modules/auction/auction.service.ts b/apps/api/src/modules/auction/auction.service.ts index 20f2e568..4b91320b 100644 --- a/apps/api/src/modules/auction/auction.service.ts +++ b/apps/api/src/modules/auction/auction.service.ts @@ -148,6 +148,7 @@ export class AuctionService { auction.phase = 'bidding'; auction.currentBid = 0; auction.currentBidder = undefined; + auction.currentDeadline = this.createDeadline(auction.maxTimerSeconds); await auction.save(); return auction; } @@ -165,9 +166,18 @@ export class AuctionService { if (params.amount > team.points) { throw new BadRequestException('Bid exceeds team points.'); } + if ( + params.bidderUserId && + !team.captainUserId.equals(params.bidderUserId) + ) { + throw new BadRequestException('Bidder is not the captain of this team.'); + } auction.currentBid = params.amount; auction.currentBidder = params.side; + auction.currentDeadline = this.createDeadline( + this.resolveBidExtensionSeconds(auction), + ); auction.bids.push({ side: params.side, amount: params.amount, @@ -200,6 +210,7 @@ export class AuctionService { }); team.points -= auction.currentBid; auction.phase = 'sold'; + auction.currentDeadline = undefined; await auction.save(); return auction; } @@ -221,6 +232,7 @@ export class AuctionService { auction.currentBid = 0; auction.currentBidder = undefined; } + auction.currentDeadline = undefined; await auction.save(); return auction; } @@ -262,4 +274,19 @@ export class AuctionService { await session.endSession(); } } + + private createDeadline(secondsFromNow: number): Date { + return new Date(Date.now() + secondsFromNow * 1000); + } + + private resolveBidExtensionSeconds(auction: AuctionDocument): number { + if (!auction.currentDeadline) { + return auction.maxTimerSeconds; + } + + const remainingSeconds = Math.ceil( + (auction.currentDeadline.getTime() - Date.now()) / 1000, + ); + return Math.max(5, remainingSeconds); + } } diff --git a/apps/api/src/modules/community/community.controller.ts b/apps/api/src/modules/community/community.controller.ts index 3b5d0095..4d1205f9 100644 --- a/apps/api/src/modules/community/community.controller.ts +++ b/apps/api/src/modules/community/community.controller.ts @@ -2,6 +2,7 @@ import { Body, Controller, ForbiddenException, + Get, Param, Patch, Post, @@ -26,6 +27,14 @@ export class CommunityController { return this.communityService.createCommunityWithOwner(body); } + @Get(':communityId') + public async getCommunity( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + ) { + return this.communityService.getById(communityId); + } + @Patch(':communityId/members/:userId/promote') @Roles('owner') @UseGuards(RolesGuard) diff --git a/apps/api/src/modules/community/community.service.ts b/apps/api/src/modules/community/community.service.ts index eb1a5c79..03568c4b 100644 --- a/apps/api/src/modules/community/community.service.ts +++ b/apps/api/src/modules/community/community.service.ts @@ -26,6 +26,15 @@ export interface CreateCommunityInput { export class CommunityService { constructor(private readonly connectionService: ConnectionService) {} + public async getById( + communityId: mongoose.Types.ObjectId, + ): Promise { + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findById(communityId).exec(); + if (!community) throw new NotFoundException('Community not found.'); + return community; + } + public async createCommunityWithOwner(input: CreateCommunityInput): Promise<{ community: CommunityDocument; owner: UserDocument; diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index b65872e0..2c2912f6 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -169,6 +169,7 @@ export interface MatchParticipant { gameName?: string; tagLine?: string; profileIconId?: number; + tier?: TierInfo; preferredPositions: PositionPreference[]; joinedAt: Date; } @@ -262,6 +263,7 @@ export interface Auction extends MongooseTimestamps { currentBid: number; currentBidder?: TeamSide; maxTimerSeconds: number; + currentDeadline?: Date; initialPoints: number; startedAt?: Date; completedAt?: Date; @@ -481,6 +483,7 @@ const MatchParticipantSubSchema = new Schema( gameName: { type: String }, tagLine: { type: String }, profileIconId: { type: Number }, + tier: { type: TierInfoSubSchema }, preferredPositions: { type: [PositionPreferenceSubSchema], required: true, @@ -661,6 +664,7 @@ export const AuctionSchema = new Schema( currentBid: { type: Number, required: true, default: 0 }, currentBidder: { type: String, enum: TEAM_SIDES, required: false }, maxTimerSeconds: { type: Number, required: true, default: 30 }, + currentDeadline: { type: Date, required: false }, initialPoints: { type: Number, required: true, default: 1000 }, startedAt: { type: Date, required: false }, completedAt: { type: Date, required: false }, diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index 20a0a20c..64fe8e8b 100644 --- a/apps/api/src/modules/match/match.service.ts +++ b/apps/api/src/modules/match/match.service.ts @@ -10,6 +10,7 @@ import { MatchDocument, MatchStatus, PositionPreference, + TierInfo, } from '../global/database/schema'; interface CreateMatchParams { @@ -51,7 +52,10 @@ export class MatchService { public async list(query: ListMatchesQuery): Promise { const MatchModel = await this.connectionService.getModel('match'); - const filter: mongoose.FilterQuery = { + const filter: { + communityId: mongoose.Types.ObjectId; + status?: MatchStatus; + } = { communityId: query.communityId, }; if (query.status) filter.status = query.status; @@ -123,16 +127,34 @@ export class MatchService { } const primaryRiot = user.riotAccounts.find((a) => a.isPrimary); + const primaryTier = this.selectParticipantTier(primaryRiot?.tiers ?? []); match.participants.push({ userId: user._id, puuid: primaryRiot?.puuid, gameName: primaryRiot?.gameName, tagLine: primaryRiot?.tagLine, profileIconId: primaryRiot?.profileIconId, + tier: primaryTier, preferredPositions: params.preferredPositions, joinedAt: new Date(), }); await match.save(); return match; } + + private selectParticipantTier(tiers: TierInfo[]): TierInfo | undefined { + const tier = + tiers.find((entry) => entry.queueType === 'RANKED_SOLO_5x5') ?? tiers[0]; + if (!tier) return undefined; + + return { + queueType: tier.queueType, + tier: tier.tier, + rank: tier.rank, + leaguePoints: tier.leaguePoints, + wins: tier.wins, + losses: tier.losses, + fetchedAt: tier.fetchedAt, + }; + } } diff --git a/apps/api/src/modules/riot/riot-webhook.controller.spec.ts b/apps/api/src/modules/riot/riot-webhook.controller.spec.ts index b72287fb..78bbd913 100644 --- a/apps/api/src/modules/riot/riot-webhook.controller.spec.ts +++ b/apps/api/src/modules/riot/riot-webhook.controller.spec.ts @@ -37,7 +37,7 @@ describe('RiotWebhookController', () => { eventType: 'MATCH_FINISHED', }, rawBody: Buffer.from('{"eventType":"MATCH_FINISHED"}', 'utf8'), - } as RiotWebhookRequest; + } as unknown as RiotWebhookRequest; const response = controller.captureTournamentWebhook(request); diff --git a/apps/api/src/modules/user/user.controller.ts b/apps/api/src/modules/user/user.controller.ts new file mode 100644 index 00000000..a5761d46 --- /dev/null +++ b/apps/api/src/modules/user/user.controller.ts @@ -0,0 +1,11 @@ +import { Controller, Get } from '@nestjs/common'; +import { CurrentUser } from '../auth/current-user.decorator'; +import type { UserDocument } from '../global/database/schema'; + +@Controller('me') +export class UserController { + @Get() + public me(@CurrentUser() user: UserDocument | undefined) { + return { user: user ?? null }; + } +} diff --git a/apps/api/src/modules/user/user.module.ts b/apps/api/src/modules/user/user.module.ts new file mode 100644 index 00000000..84a4b78a --- /dev/null +++ b/apps/api/src/modules/user/user.module.ts @@ -0,0 +1,7 @@ +import { Module } from '@nestjs/common'; +import { UserController } from './user.controller'; + +@Module({ + controllers: [UserController], +}) +export class UserModule {} diff --git a/apps/api/src/seed.ts b/apps/api/src/seed.ts new file mode 100644 index 00000000..38e12b63 --- /dev/null +++ b/apps/api/src/seed.ts @@ -0,0 +1,913 @@ +import 'reflect-metadata'; +import { Module } from '@nestjs/common'; +import { ConfigModule } from '@nestjs/config'; +import { NestFactory } from '@nestjs/core'; +import mongoose from 'mongoose'; +import { readFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { ConnectionService } from './modules/global/database/connection.service'; +import type { + ChampionMasteryEntry, + MatchParticipant, + MatchTeam, + Position, + PositionPreference, + RiotRecentStatsSummary, + TierInfo, +} from './modules/global/database/schema'; +import { SecretModule } from './modules/global/secret/secret.module'; + +process.env.NODE_ENV ??= 'dev'; + +async function loadMachineEnvFile() { + const homeDir = process.env.HOME ?? process.env.USERPROFILE; + if (!homeDir) return; + + const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt'); + + try { + const file = await readFile(machineEnvFile, 'utf8'); + for (const rawLine of file.split(/\r?\n/)) { + const line = rawLine.trim(); + if (!line || line.startsWith('#')) continue; + + const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/); + if (!matched) continue; + + const [, key, rawValue] = matched; + const value = rawValue.replace(/^["']|["']$/g, ''); + process.env[key] = value; + } + } catch { + // start.ps1도 파일이 없으면 그냥 지나간다. + } +} + +@Module({ + imports: [ + ConfigModule.forRoot({ + isGlobal: true, + envFilePath: [ + resolve(__dirname, '../../project.env'), + resolve(process.cwd(), 'apps/project.env'), + resolve(process.cwd(), 'project.env'), + ], + }), + SecretModule, + ], + providers: [ConnectionService], +}) +class SeedModule {} + +type SeedPlayer = { + key: string; + gameName: string; + tagLine: string; + kakaoTalkNickname: string; + profileIconId: number; + main: Position; + sub: Position; + tier: { + tier: string; + rank: string; + leaguePoints: number; + wins: number; + losses: number; + }; + flex?: { + tier: string; + rank: string; + leaguePoints: number; + wins: number; + losses: number; + }; + masteries: ChampionMasteryEntry[]; + recentStatsSummary: RiotRecentStatsSummary; +}; + +const DEV_COMMUNITY_NAME = '[DEV] Lolympus Test Community'; +const DEV_COMMUNITY_DESCRIPTION = + 'Frontend/Backend 통합 검증용으로 생성된 개발 커뮤니티입니다.'; + +const NOW = new Date(); + +const PLAYER_SEEDS: SeedPlayer[] = [ + { + key: 'priri', + gameName: '프리리', + tagLine: 'KR1', + kakaoTalkNickname: '프리리', + profileIconId: 588, + main: 'MID', + sub: 'ADC', + tier: { + tier: 'DIAMOND', + rank: 'IV', + leaguePoints: 37, + wins: 66, + losses: 58, + }, + flex: { + tier: 'EMERALD', + rank: 'I', + leaguePoints: 54, + wins: 31, + losses: 22, + }, + masteries: [ + { championId: 'Syndra', championName: '신드라', level: 7, points: 124300 }, + { championId: 'Ahri', championName: '아리', level: 7, points: 98200 }, + { championId: 'Orianna', championName: '오리아나', level: 6, points: 63400 }, + ], + recentStatsSummary: { + games: 24, + wins: 14, + losses: 10, + avgKills: 7.8, + avgDeaths: 4.2, + avgAssists: 6.7, + avgCs: 188, + mostPlayedChampionIds: ['Syndra', 'Ahri', 'Orianna'], + }, + }, + { + key: 'hobul', + gameName: '호호불어먹어요', + tagLine: '0000', + kakaoTalkNickname: '호호불', + profileIconId: 7015, + main: 'JGL', + sub: 'TOP', + tier: { + tier: 'PLATINUM', + rank: 'II', + leaguePoints: 73, + wins: 54, + losses: 49, + }, + flex: { + tier: 'EMERALD', + rank: 'III', + leaguePoints: 22, + wins: 14, + losses: 10, + }, + masteries: [ + { championId: 'Viego', championName: '비에고', level: 7, points: 138200 }, + { championId: 'LeeSin', championName: '리신', level: 6, points: 88700 }, + { championId: 'Nidalee', championName: '니달리', level: 6, points: 64100 }, + ], + recentStatsSummary: { + games: 28, + wins: 15, + losses: 13, + avgKills: 5.9, + avgDeaths: 4.9, + avgAssists: 9.1, + avgCs: 151, + mostPlayedChampionIds: ['Viego', 'LeeSin', 'Nidalee'], + }, + }, + { + key: 'soda', + gameName: '소다', + tagLine: 'KR1', + kakaoTalkNickname: '소다', + profileIconId: 5186, + main: 'TOP', + sub: 'MID', + tier: { + tier: 'EMERALD', + rank: 'I', + leaguePoints: 18, + wins: 49, + losses: 41, + }, + flex: { + tier: 'PLATINUM', + rank: 'I', + leaguePoints: 64, + wins: 20, + losses: 14, + }, + masteries: [ + { championId: 'Jax', championName: '잭스', level: 7, points: 112400 }, + { championId: 'Camille', championName: '카밀', level: 6, points: 76500 }, + { championId: 'Gwen', championName: '그웬', level: 6, points: 58700 }, + ], + recentStatsSummary: { + games: 21, + wins: 11, + losses: 10, + avgKills: 5.4, + avgDeaths: 4.6, + avgAssists: 5.2, + avgCs: 201, + mostPlayedChampionIds: ['Jax', 'Camille', 'Gwen'], + }, + }, + { + key: 'inghoba', + gameName: '잉호바', + tagLine: 'KR1', + kakaoTalkNickname: '잉호바', + profileIconId: 7050, + main: 'SUP', + sub: 'MID', + tier: { + tier: 'DIAMOND', + rank: 'III', + leaguePoints: 41, + wins: 72, + losses: 60, + }, + flex: { + tier: 'MASTER', + rank: '', + leaguePoints: 121, + wins: 19, + losses: 11, + }, + masteries: [ + { championId: 'Thresh', championName: '쓰레쉬', level: 7, points: 187300 }, + { championId: 'Nautilus', championName: '노틸러스', level: 7, points: 144800 }, + { championId: 'Rakan', championName: '라칸', level: 6, points: 65300 }, + ], + recentStatsSummary: { + games: 32, + wins: 19, + losses: 13, + avgKills: 2.5, + avgDeaths: 4.3, + avgAssists: 14.8, + avgCs: 34, + mostPlayedChampionIds: ['Thresh', 'Nautilus', 'Rakan'], + }, + }, + { + key: 'tabkey', + gameName: '잉호바탭키도둑', + tagLine: 'Tab', + kakaoTalkNickname: '탭키도둑', + profileIconId: 5231, + main: 'ADC', + sub: 'SUP', + tier: { + tier: 'PLATINUM', + rank: 'I', + leaguePoints: 47, + wins: 61, + losses: 56, + }, + flex: { + tier: 'EMERALD', + rank: 'IV', + leaguePoints: 28, + wins: 22, + losses: 20, + }, + masteries: [ + { championId: 'Jinx', championName: '징크스', level: 7, points: 166100 }, + { championId: 'KaiSa', championName: '카이사', level: 7, points: 139400 }, + { championId: 'Ezreal', championName: '이즈리얼', level: 6, points: 90100 }, + ], + recentStatsSummary: { + games: 29, + wins: 16, + losses: 13, + avgKills: 8.4, + avgDeaths: 4.8, + avgAssists: 6.1, + avgCs: 213, + mostPlayedChampionIds: ['Jinx', 'KaiSa', 'Ezreal'], + }, + }, + { + key: 'osu', + gameName: 'osu', + tagLine: 'KR1', + kakaoTalkNickname: 'osu', + profileIconId: 7091, + main: 'MID', + sub: 'JGL', + tier: { + tier: 'EMERALD', + rank: 'III', + leaguePoints: 59, + wins: 58, + losses: 50, + }, + flex: { + tier: 'MASTER', + rank: '', + leaguePoints: 74, + wins: 12, + losses: 8, + }, + masteries: [ + { championId: 'Viktor', championName: '빅토르', level: 7, points: 172900 }, + { championId: 'Hwei', championName: '흐웨이', level: 6, points: 94400 }, + { championId: 'Taliyah', championName: '탈리야', level: 6, points: 55300 }, + ], + recentStatsSummary: { + games: 25, + wins: 13, + losses: 12, + avgKills: 6.3, + avgDeaths: 5.2, + avgAssists: 7.7, + avgCs: 198, + mostPlayedChampionIds: ['Viktor', 'Hwei', 'Taliyah'], + }, + }, + { + key: 'icequeen', + gameName: 'IceQueen', + tagLine: 'KR1', + kakaoTalkNickname: '아이스퀸', + profileIconId: 5102, + main: 'ADC', + sub: 'MID', + tier: { + tier: 'DIAMOND', + rank: 'II', + leaguePoints: 63, + wins: 67, + losses: 52, + }, + flex: { + tier: 'MASTER', + rank: '', + leaguePoints: 34, + wins: 11, + losses: 9, + }, + masteries: [ + { championId: 'Xayah', championName: '자야', level: 7, points: 154800 }, + { championId: 'Zeri', championName: '제리', level: 7, points: 141900 }, + { championId: 'Ashe', championName: '애쉬', level: 6, points: 59800 }, + ], + recentStatsSummary: { + games: 31, + wins: 18, + losses: 13, + avgKills: 7.7, + avgDeaths: 4.4, + avgAssists: 7.2, + avgCs: 226, + mostPlayedChampionIds: ['Xayah', 'Zeri', 'Ashe'], + }, + }, + { + key: 'jungler123', + gameName: '정글러123', + tagLine: 'KR3', + kakaoTalkNickname: '정글러123', + profileIconId: 4789, + main: 'JGL', + sub: 'SUP', + tier: { + tier: 'PLATINUM', + rank: 'III', + leaguePoints: 15, + wins: 43, + losses: 42, + }, + flex: { + tier: 'GOLD', + rank: 'I', + leaguePoints: 87, + wins: 18, + losses: 16, + }, + masteries: [ + { championId: 'LeeSin', championName: '리신', level: 7, points: 201300 }, + { championId: 'Viego', championName: '비에고', level: 6, points: 87600 }, + { championId: 'Rengar', championName: '렝가', level: 6, points: 65400 }, + ], + recentStatsSummary: { + games: 38, + wins: 18, + losses: 20, + avgKills: 5.4, + avgDeaths: 5.8, + avgAssists: 8.1, + avgCs: 142, + mostPlayedChampionIds: ['LeeSin', 'Viego', 'Rengar'], + }, + }, + { + key: 'topsol', + gameName: '탑솔장인', + tagLine: 'KR1', + kakaoTalkNickname: '탑솔장인', + profileIconId: 5450, + main: 'TOP', + sub: 'JGL', + tier: { + tier: 'EMERALD', + rank: 'II', + leaguePoints: 46, + wins: 57, + losses: 44, + }, + flex: { + tier: 'PLATINUM', + rank: 'II', + leaguePoints: 34, + wins: 21, + losses: 19, + }, + masteries: [ + { championId: 'Jax', championName: '잭스', level: 7, points: 145600 }, + { championId: 'Yorick', championName: '요릭', level: 7, points: 112400 }, + { championId: 'Nasus', championName: '나서스', level: 6, points: 89300 }, + ], + recentStatsSummary: { + games: 47, + wins: 27, + losses: 20, + avgKills: 5.6, + avgDeaths: 3.9, + avgAssists: 4.1, + avgCs: 201, + mostPlayedChampionIds: ['Jax', 'Yorick', 'Nasus'], + }, + }, + { + key: 'supporter', + gameName: '서폿장인', + tagLine: '0001', + kakaoTalkNickname: '서폿장인', + profileIconId: 4900, + main: 'SUP', + sub: 'ADC', + tier: { + tier: 'DIAMOND', + rank: 'IV', + leaguePoints: 9, + wins: 64, + losses: 61, + }, + flex: { + tier: 'DIAMOND', + rank: 'III', + leaguePoints: 25, + wins: 17, + losses: 14, + }, + masteries: [ + { championId: 'Yuumi', championName: '유미', level: 7, points: 198700 }, + { championId: 'Sona', championName: '소나', level: 7, points: 145200 }, + { championId: 'Nami', championName: '나미', level: 6, points: 92100 }, + ], + recentStatsSummary: { + games: 52, + wins: 30, + losses: 22, + avgKills: 1.8, + avgDeaths: 4.2, + avgAssists: 16.3, + avgCs: 25, + mostPlayedChampionIds: ['Yuumi', 'Sona', 'Nami'], + }, + }, +]; + +function createPreferences(main: Position, sub: Position): PositionPreference[] { + const rest = (['TOP', 'JGL', 'MID', 'ADC', 'SUP'] as Position[]).filter( + (position) => position !== main && position !== sub, + ); + + return [ + { position: main, priority: 1 }, + { position: sub, priority: 2 }, + ...rest.map((position, index) => ({ + position, + priority: index + 3, + })), + ]; +} + +function createTier( + queueType: string, + tier: string, + rank: string, + leaguePoints: number, + wins: number, + losses: number, +): TierInfo { + return { + queueType, + tier, + rank: rank || 'I', + leaguePoints, + wins, + losses, + fetchedAt: NOW, + }; +} + +function selectPrimaryTier(tiers: TierInfo[]) { + return tiers.find((tier) => tier.queueType === 'RANKED_SOLO_5x5') ?? tiers[0]; +} + +function createRiotAccount(player: SeedPlayer) { + const tiers = [ + createTier( + 'RANKED_SOLO_5x5', + player.tier.tier, + player.tier.rank, + player.tier.leaguePoints, + player.tier.wins, + player.tier.losses, + ), + ]; + + if (player.flex) { + tiers.push( + createTier( + 'RANKED_FLEX_SR', + player.flex.tier, + player.flex.rank, + player.flex.leaguePoints, + player.flex.wins, + player.flex.losses, + ), + ); + } + + return { + puuid: `dev-seed-${player.key}-puuid`, + gameName: player.gameName, + tagLine: player.tagLine, + profileIconId: player.profileIconId, + revisionDate: Date.now(), + summonerLevel: 200, + isPrimary: true, + tiers, + tierHistory: [], + matchIds: [], + recentStatsSummary: player.recentStatsSummary, + recentStatsFetchedAt: NOW, + championMasteries: player.masteries, + championMasteriesFetchedAt: NOW, + championRecords: {}, + championRecordsFetchedAt: NOW, + createdAt: NOW, + updatedAt: NOW, + }; +} + +function createStaffRiotAccount(key: string, gameName: string, tagLine: string) { + return { + puuid: `dev-seed-${key}-puuid`, + gameName, + tagLine, + profileIconId: 29, + revisionDate: Date.now(), + summonerLevel: 120, + isPrimary: true, + tiers: [createTier('RANKED_SOLO_5x5', 'GOLD', 'I', 75, 24, 19)], + tierHistory: [], + matchIds: [], + recentStatsSummary: { + games: 12, + wins: 7, + losses: 5, + avgKills: 5.1, + avgDeaths: 4.3, + avgAssists: 7.4, + avgCs: 167, + mostPlayedChampionIds: ['Orianna', 'JarvanIV'], + }, + recentStatsFetchedAt: NOW, + championMasteries: [ + { championId: 'Orianna', championName: '오리아나', level: 5, points: 18300 }, + { championId: 'JarvanIV', championName: '자르반 4세', level: 5, points: 12600 }, + ], + championMasteriesFetchedAt: NOW, + championRecords: {}, + championRecordsFetchedAt: NOW, + createdAt: NOW, + updatedAt: NOW, + }; +} + +function toMatchParticipant(user: { + _id: mongoose.Types.ObjectId; + riotAccounts: Array<{ + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + tiers: TierInfo[]; + }>; + preferredPositions: PositionPreference[]; +}): MatchParticipant { + const primary = user.riotAccounts[0]; + + return { + userId: user._id, + puuid: primary?.puuid, + gameName: primary?.gameName, + tagLine: primary?.tagLine, + profileIconId: primary?.profileIconId, + tier: primary ? selectPrimaryTier(primary.tiers) : undefined, + preferredPositions: user.preferredPositions, + joinedAt: NOW, + }; +} + +async function main() { + await loadMachineEnvFile(); + + const app = await NestFactory.createApplicationContext(SeedModule, { + logger: ['error', 'warn', 'log'], + }); + + try { + const connectionService = app.get(ConnectionService); + const CommunityModel = await connectionService.getModel('community'); + const UserModel = await connectionService.getModel('user'); + const MatchModel = await connectionService.getModel('match'); + const AuctionModel = await connectionService.getModel('auction'); + + const existingCommunity = await CommunityModel.findOne({ + name: DEV_COMMUNITY_NAME, + }).exec(); + + if (existingCommunity) { + const existingMatches = await MatchModel.find({ + communityId: existingCommunity._id, + }) + .select('_id') + .lean() + .exec(); + + const matchIds = existingMatches.map((match) => match._id); + if (matchIds.length > 0) { + await AuctionModel.deleteMany({ matchId: { $in: matchIds } }).exec(); + } + + await MatchModel.deleteMany({ communityId: existingCommunity._id }).exec(); + await UserModel.deleteMany({ communityId: existingCommunity._id }).exec(); + await CommunityModel.deleteOne({ _id: existingCommunity._id }).exec(); + } + + const communityId = new mongoose.Types.ObjectId(); + const ownerUserId = new mongoose.Types.ObjectId(); + const adminUserId = new mongoose.Types.ObjectId(); + + await CommunityModel.create({ + _id: communityId, + name: DEV_COMMUNITY_NAME, + description: DEV_COMMUNITY_DESCRIPTION, + ownerUserId, + }); + + const owner = { + _id: ownerUserId, + communityId, + role: 'owner' as const, + kakaoTalkId: 'dev-owner', + kakaoTalkNickname: 'DevOwner', + discordId: 'dev-owner-discord', + discordNickname: 'DevOwner', + riotAccounts: [createStaffRiotAccount('owner', 'DevOwner', 'KR1')], + preferredPositions: createPreferences('MID', 'SUP'), + isActivated: true, + }; + + const admin = { + _id: adminUserId, + communityId, + role: 'admin' as const, + kakaoTalkId: 'dev-admin', + kakaoTalkNickname: 'DevAdmin', + discordId: 'dev-admin-discord', + discordNickname: 'DevAdmin', + riotAccounts: [createStaffRiotAccount('admin', 'DevAdmin', 'KR1')], + preferredPositions: createPreferences('JGL', 'MID'), + isActivated: true, + }; + + const players = PLAYER_SEEDS.map((player) => ({ + _id: new mongoose.Types.ObjectId(), + communityId, + role: 'member' as const, + kakaoTalkId: `seed-${player.key}`, + kakaoTalkNickname: player.kakaoTalkNickname, + discordId: `seed-${player.key}-discord`, + discordNickname: player.gameName, + riotAccounts: [createRiotAccount(player)], + preferredPositions: createPreferences(player.main, player.sub), + isActivated: true, + })); + + await UserModel.insertMany([owner, admin, ...players], { ordered: true }); + + const recruitingPlayers = players.slice(0, 6); + const auctionPlayers = players; + const finishedBlue = [ + { user: players[0], assignedPosition: 'MID' as const, cost: 0 }, + { user: players[2], assignedPosition: 'TOP' as const, cost: 320 }, + { user: players[4], assignedPosition: 'ADC' as const, cost: 280 }, + { user: players[7], assignedPosition: 'JGL' as const, cost: 190 }, + { user: players[9], assignedPosition: 'SUP' as const, cost: 210 }, + ]; + const finishedRed = [ + { user: players[1], assignedPosition: 'JGL' as const, cost: 0 }, + { user: players[3], assignedPosition: 'SUP' as const, cost: 240 }, + { user: players[5], assignedPosition: 'MID' as const, cost: 250 }, + { user: players[6], assignedPosition: 'ADC' as const, cost: 300 }, + { user: players[8], assignedPosition: 'TOP' as const, cost: 220 }, + ]; + + const recruitingMatchId = new mongoose.Types.ObjectId(); + const auctionMatchId = new mongoose.Types.ObjectId(); + const finishedMatchId = new mongoose.Types.ObjectId(); + + await MatchModel.insertMany([ + { + _id: recruitingMatchId, + communityId, + hostUserId: ownerUserId, + title: '쌀먹 내전', + description: '통합 테스트용 모집 중 매치입니다.', + mapId: 11, + status: 'recruiting', + scheduledAt: new Date('2026-04-27T12:00:00.000Z'), + maxParticipants: 10, + participants: recruitingPlayers.map(toMatchParticipant), + teams: [], + prizes: ['5명 추첨 커피', 'MVP: 스킨 선물'], + notices: [ + '시작 10분 전까지 커스텀 방에 입장해주세요.', + '개발용 시드 데이터입니다.', + ], + schedule: [ + { time: '20:50', label: '로비 오픈' }, + { time: '21:00', label: '내전 시작' }, + ], + }, + { + _id: auctionMatchId, + communityId, + hostUserId: ownerUserId, + title: '롤림푸스 경매 테스트 매치', + description: 'Socket.IO 경매 페이지 검증용으로 생성된 매치입니다.', + mapId: 11, + status: 'team-built', + scheduledAt: new Date('2026-04-26T11:00:00.000Z'), + maxParticipants: 10, + participants: auctionPlayers.map(toMatchParticipant), + teams: [ + { + side: 'blue', + name: '블루팀', + captainUserId: players[0]._id, + members: [ + { + userId: players[0]._id, + assignedPosition: 'MID', + cost: 0, + }, + ], + }, + { + side: 'red', + name: '레드팀', + captainUserId: players[1]._id, + members: [ + { + userId: players[1]._id, + assignedPosition: 'JGL', + cost: 0, + }, + ], + }, + ], + prizes: ['우승팀 햄버거 세트'], + notices: ['현재 경매 진행 중인 테스트 매치입니다.'], + schedule: [ + { time: '19:30', label: '디스코드 집합' }, + { time: '19:45', label: '경매 시작' }, + ], + }, + { + _id: finishedMatchId, + communityId, + hostUserId: ownerUserId, + title: '시즌 4 준결승', + description: '완료된 매치 UI 확인용 더미 경기 결과입니다.', + mapId: 11, + status: 'finished', + scheduledAt: new Date('2026-04-20T11:00:00.000Z'), + maxParticipants: 10, + participants: players.map(toMatchParticipant), + teams: [ + { + side: 'blue', + name: '블루팀', + captainUserId: players[0]._id, + members: finishedBlue.map((member) => ({ + userId: member.user._id, + assignedPosition: member.assignedPosition, + cost: member.cost, + })), + }, + { + side: 'red', + name: '레드팀', + captainUserId: players[1]._id, + members: finishedRed.map((member) => ({ + userId: member.user._id, + assignedPosition: member.assignedPosition, + cost: member.cost, + })), + }, + ], + result: { + winnerSide: 'blue', + blueScore: 2, + redScore: 1, + mvpUserId: players[0]._id, + riotMatchIds: ['KR_DEV_0001', 'KR_DEV_0002', 'KR_DEV_0003'], + }, + prizes: ['1등 팀: RP 10,000 지급', 'MVP: 프리리'], + notices: [], + schedule: [], + }, + ]); + + const auctionOrder = auctionPlayers.slice(2).map((player) => { + const primary = player.riotAccounts[0]; + + return { + userId: player._id, + puuid: primary.puuid, + gameName: primary.gameName, + tagLine: primary.tagLine, + profileIconId: primary.profileIconId, + preferredPositions: player.preferredPositions, + tiers: primary.tiers, + masteries: primary.championMasteries, + recentStatsSummary: primary.recentStatsSummary, + }; + }); + + await AuctionModel.create({ + matchId: auctionMatchId, + phase: 'presenting', + teams: [ + { + side: 'blue', + captainUserId: players[0]._id, + points: 1000, + members: [], + }, + { + side: 'red', + captainUserId: players[1]._id, + points: 1000, + members: [], + }, + ], + order: auctionOrder, + currentIndex: 0, + bids: [], + currentBid: 0, + maxTimerSeconds: 30, + initialPoints: 1000, + startedAt: NOW, + }); + + const summary = { + communityId: communityId.toString(), + ownerUserId: ownerUserId.toString(), + adminUserId: adminUserId.toString(), + recruitingMatchId: recruitingMatchId.toString(), + auctionMatchId: auctionMatchId.toString(), + finishedMatchId: finishedMatchId.toString(), + playerUserIds: players.map((player) => ({ + userId: player._id.toString(), + gameName: player.riotAccounts[0].gameName, + })), + }; + + console.log('\n[seed:dev] Dev seed completed.\n'); + console.log(JSON.stringify(summary, null, 2)); + console.log( + `\napps/web/.env.development 에 아래 값을 넣으면 됩니다:\nVITE_DEFAULT_COMMUNITY_ID=${summary.communityId}\n`, + ); + } finally { + await app.close(); + } +} + +void main().catch((error: unknown) => { + console.error('\n[seed:dev] Failed to seed database.\n'); + console.error(error); + process.exitCode = 1; +}); diff --git a/apps/web/.env.development b/apps/web/.env.development new file mode 100644 index 00000000..1c53bb26 --- /dev/null +++ b/apps/web/.env.development @@ -0,0 +1,2 @@ +VITE_API_BASE_URL=http://126.dahyeon.us:3000 +VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1 diff --git a/apps/web/package.json b/apps/web/package.json index 33113e09..c7dc8268 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -10,9 +10,11 @@ "preview": "vite preview" }, "dependencies": { + "@tanstack/react-query": "^5.100.1", "react": "^19.2.4", "react-dom": "^19.2.4", - "react-router": "^7.14.0" + "react-router": "^7.14.0", + "socket.io-client": "^4.8.3" }, "devDependencies": { "@eslint/js": "^9.39.4", diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 2fd91571..c076e820 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -1,21 +1,35 @@ -import { BrowserRouter, Routes, Route } from "react-router"; -import HomePage from "./pages/HomePage"; -import MatchDetailPage from "./pages/MatchDetailPage"; -import AuctionPage from "./pages/AuctionPage"; +import { BrowserRouter, Link, Route, Routes } from 'react-router'; +import DevAuthSwitcher from './components/DevAuthSwitcher'; +import { DEFAULT_COMMUNITY_ID } from './config'; +import { useCommunity } from './api/hooks'; +import HomePage from './pages/HomePage'; +import MatchDetailPage from './pages/MatchDetailPage'; +import AuctionPage from './pages/AuctionPage'; function App() { + const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID); + const communityLabel = communityQuery.data?.name ?? 'LOLYMPUS'; + return (
- {/* Navbar */} @@ -24,6 +38,7 @@ function App() { } /> } /> +
); diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts new file mode 100644 index 00000000..92ddeabe --- /dev/null +++ b/apps/web/src/api/hooks.ts @@ -0,0 +1,85 @@ +import { useQuery } from '@tanstack/react-query'; +import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config'; +import { apiFetch } from '../lib/api'; +import type { + ApiAuction, + ApiCommunity, + ApiMatch, + MatchStatus, + MatchesResponse, + MeResponse, +} from './types'; + +interface MatchesQueryOptions { + status?: MatchStatus; + limit?: number; +} + +function createMatchesPath( + communityId: string, + options: MatchesQueryOptions = {}, +) { + const searchParams = new URLSearchParams(); + if (options.status) searchParams.set('status', options.status); + if (options.limit) searchParams.set('limit', String(options.limit)); + + const queryString = searchParams.toString(); + return `/communities/${communityId}/matches${queryString ? `?${queryString}` : ''}`; +} + +export function useCommunity(communityId = DEFAULT_COMMUNITY_ID) { + return useQuery({ + queryKey: ['community', communityId], + queryFn: () => apiFetch(`/communities/${communityId}`), + enabled: Boolean(communityId), + }); +} + +export function useMatches( + options: MatchesQueryOptions, + communityId = DEFAULT_COMMUNITY_ID, +) { + return useQuery({ + queryKey: ['matches', communityId, options.status ?? null, options.limit ?? null], + queryFn: async () => { + const response = await apiFetch( + createMatchesPath(communityId, options), + ); + return response.matches; + }, + enabled: Boolean(communityId), + }); +} + +export function useMatch(matchId: string | undefined, communityId = DEFAULT_COMMUNITY_ID) { + return useQuery({ + queryKey: ['match', communityId, matchId ?? null], + queryFn: () => + apiFetch(`/communities/${communityId}/matches/${matchId}`), + enabled: Boolean(communityId && matchId), + retry: false, + }); +} + +export function useAuction( + matchId: string | undefined, + communityId = DEFAULT_COMMUNITY_ID, +) { + return useQuery({ + queryKey: ['auction', communityId, matchId ?? null], + queryFn: () => + apiFetch(`/communities/${communityId}/matches/${matchId}/auction`), + enabled: Boolean(communityId && matchId), + retry: false, + }); +} + +export function useMe() { + const authUserId = useAuthUserId(); + + return useQuery({ + queryKey: ['me', authUserId], + queryFn: () => apiFetch('/me'), + retry: false, + }); +} diff --git a/apps/web/src/api/mappers.ts b/apps/web/src/api/mappers.ts new file mode 100644 index 00000000..b9f572ec --- /dev/null +++ b/apps/web/src/api/mappers.ts @@ -0,0 +1,448 @@ +import type { + ApiAuction, + ApiAuctionPlayerSnapshot, + ApiAuctionTeam, + ApiMatch, + ApiMatchParticipant, + ApiPositionPreference, + ApiTierInfo, + MatchStatus, + Position, + TeamSide, +} from './types'; +import { POSITION_ORDER, sideLabel } from '../lib/league'; + +export interface ParticipantView { + id: string; + userId: string; + summonerName: string; + tag: string; + tier?: ApiTierInfo; + mainPosition: Position; + subPosition: Position; + profileIconId: number; +} + +export interface TeamParticipantView extends ParticipantView { + assignedPosition: Position; + cost?: number; +} + +export interface TeamView { + side: TeamSide; + name: string; + participants: TeamParticipantView[]; +} + +export interface MatchDetailView { + id: string; + title: string; + date: string; + time: string; + status: MatchStatus; + description: string; + map: string; + maxParticipants: number; + joined: boolean; + participants: ParticipantView[]; + teams: TeamView[]; + result?: { + winner: string; + blueScore: number; + redScore: number; + }; + prizes: string[]; + notices: string[]; + schedule: { time: string; label: string }[]; +} + +export interface AuctionPlayerView extends ParticipantView { + masteries: { + championName: string; + championId: string; + level: number; + points: number; + }[]; + recentStats: { + games: number; + wins: number; + losses: number; + kda: { + kills: number; + deaths: number; + assists: number; + }; + avgCs: number; + }; +} + +export interface AuctionTeamView { + side: TeamSide; + captainUserId: string; + captainName: string; + points: number; + members: (AuctionPlayerView & { + assignedPosition: Position; + cost: number; + })[]; +} + +export interface AuctionStateView { + matchId: string; + phase: ApiAuction['phase']; + teams: [AuctionTeamView, AuctionTeamView]; + currentPlayer: AuctionPlayerView | null; + currentPlayerIndex: number; + totalPlayers: number; + auctionOrder: AuctionPlayerView[]; + bids: { + side: TeamSide; + amount: number; + timestamp: string; + }[]; + currentBid: number; + currentBidder: TeamSide | null; + timer: number; + maxTimer: number; + deadline?: string; +} + +const MAP_LABELS: Record = { + 11: '소환사의 협곡', + 12: '칼바람 나락', + 21: '소환사의 협곡', + 22: '전략적 팀 전투', +}; + +const TIER_NAMES: Record = { + IRON: '아이언', + BRONZE: '브론즈', + SILVER: '실버', + GOLD: '골드', + PLATINUM: '플래티넘', + EMERALD: '에메랄드', + DIAMOND: '다이아', + MASTER: '마스터', + GRANDMASTER: '그랜드마스터', + CHALLENGER: '챌린저', +}; + +function sortPreferredPositions(preferredPositions: ApiPositionPreference[]) { + return [...preferredPositions].sort((left, right) => left.priority - right.priority); +} + +function resolveMainAndSubPosition(preferredPositions: ApiPositionPreference[]) { + const sorted = sortPreferredPositions(preferredPositions); + return { + mainPosition: sorted[0]?.position ?? 'MID', + subPosition: sorted[1]?.position ?? sorted[0]?.position ?? 'MID', + }; +} + +function mapMatchParticipantToView( + participant: ApiMatchParticipant, +): ParticipantView { + const { mainPosition, subPosition } = resolveMainAndSubPosition( + participant.preferredPositions, + ); + + return { + id: participant.userId, + userId: participant.userId, + summonerName: participant.gameName ?? '알 수 없음', + tag: participant.tagLine ?? '----', + tier: participant.tier, + mainPosition, + subPosition, + profileIconId: participant.profileIconId ?? 0, + }; +} + +function mapAuctionPlayerToView( + player: ApiAuctionPlayerSnapshot, +): AuctionPlayerView { + const { mainPosition, subPosition } = resolveMainAndSubPosition( + player.preferredPositions, + ); + + return { + id: player.userId, + userId: player.userId, + summonerName: player.gameName, + tag: player.tagLine, + tier: selectPrimaryTier(player.tiers), + mainPosition, + subPosition, + profileIconId: player.profileIconId, + masteries: player.masteries.slice(0, 3).map((mastery) => ({ + championName: mastery.championName ?? mastery.championId, + championId: mastery.championId, + level: mastery.level, + points: mastery.points, + })), + recentStats: { + games: player.recentStatsSummary?.games ?? 0, + wins: player.recentStatsSummary?.wins ?? 0, + losses: player.recentStatsSummary?.losses ?? 0, + kda: { + kills: player.recentStatsSummary?.avgKills ?? 0, + deaths: player.recentStatsSummary?.avgDeaths ?? 0, + assists: player.recentStatsSummary?.avgAssists ?? 0, + }, + avgCs: Math.round(player.recentStatsSummary?.avgCs ?? 0), + }, + }; +} + +function createFallbackParticipant(userId: string): ParticipantView { + return { + id: userId, + userId, + summonerName: `User ${userId.slice(-4)}`, + tag: '----', + mainPosition: 'MID', + subPosition: 'MID', + profileIconId: 0, + }; +} + +function mapAuctionTeamToView( + team: ApiAuctionTeam, + playerLookup: Map, + participantLookup: Map, +): AuctionTeamView { + return { + side: team.side, + captainUserId: team.captainUserId, + captainName: + participantLookup.get(team.captainUserId)?.summonerName ?? + `User ${team.captainUserId.slice(-4)}`, + points: team.points, + members: team.members.map((member) => { + const participant = participantLookup.get(member.userId); + const player = + playerLookup.get(member.userId) ?? + (participant + ? { + ...participant, + masteries: [], + recentStats: { + games: 0, + wins: 0, + losses: 0, + kda: { kills: 0, deaths: 0, assists: 0 }, + avgCs: 0, + }, + } + : { + ...createFallbackParticipant(member.userId), + masteries: [], + recentStats: { + games: 0, + wins: 0, + losses: 0, + kda: { kills: 0, deaths: 0, assists: 0 }, + avgCs: 0, + }, + }); + + return { + ...player, + assignedPosition: member.assignedPosition, + cost: member.cost, + }; + }), + }; +} + +export function mapIdToLabel(mapId: number) { + return MAP_LABELS[mapId] ?? `맵 #${mapId}`; +} + +export function formatKoreanDate(dateLike: string | Date) { + const date = new Date(dateLike); + + return { + date: new Intl.DateTimeFormat('ko-KR', { + year: 'numeric', + month: 'long', + day: 'numeric', + weekday: 'short', + }).format(date), + time: new Intl.DateTimeFormat('ko-KR', { + hour: 'numeric', + minute: '2-digit', + }).format(date), + }; +} + +export function selectPrimaryTier(tiers: ApiTierInfo[]) { + return tiers.find((tier) => tier.queueType === 'RANKED_SOLO_5x5') ?? tiers[0]; +} + +export function formatTierLabel(tier?: ApiTierInfo) { + if (!tier) return '미등록'; + + const tierName = TIER_NAMES[tier.tier] ?? tier.tier; + const highTier = ['MASTER', 'GRANDMASTER', 'CHALLENGER'].includes(tier.tier); + + if (highTier && tier.leaguePoints > 0) { + return `${tierName} ${tier.leaguePoints}LP`; + } + + return tier.rank ? `${tierName} ${tier.rank}` : tierName; +} + +export function getTierColorToken(tier?: ApiTierInfo) { + switch (tier?.tier) { + case 'CHALLENGER': + return 'text-amber-400'; + case 'GRANDMASTER': + return 'text-red-400'; + case 'MASTER': + return 'text-fuchsia-400'; + case 'DIAMOND': + return 'text-cyan-400'; + case 'EMERALD': + return 'text-emerald-400'; + case 'PLATINUM': + return 'text-teal-300'; + case 'GOLD': + return 'text-yellow-400'; + case 'SILVER': + return 'text-gray-300'; + case 'BRONZE': + return 'text-amber-700'; + case 'IRON': + return 'text-stone-400'; + default: + return 'text-base-content/50'; + } +} + +export function buildDefaultPreferredPositions() { + return POSITION_ORDER.map((position, index) => ({ + position, + priority: index + 1, + })); +} + +export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { + const formattedDate = formatKoreanDate(match.scheduledAt); + const participants = match.participants.map(mapMatchParticipantToView); + const participantLookup = new Map( + participants.map((participant) => [participant.userId, participant]), + ); + + const teams = match.teams.map((team) => ({ + side: team.side, + name: team.name || sideLabel(team.side), + participants: team.members.map((member) => { + const participant = + participantLookup.get(member.userId) ?? createFallbackParticipant(member.userId); + + return { + ...participant, + assignedPosition: member.assignedPosition, + cost: member.cost, + }; + }), + })); + + const winnerTeam = match.result + ? teams.find((team) => team.side === match.result?.winnerSide) + : undefined; + + return { + id: match._id, + title: match.title, + date: formattedDate.date, + time: formattedDate.time, + status: match.status, + description: match.description, + map: mapIdToLabel(match.mapId), + maxParticipants: match.maxParticipants, + joined: Boolean(match.joined), + participants, + teams, + result: match.result + ? { + winner: winnerTeam?.name ?? sideLabel(match.result.winnerSide), + blueScore: match.result.blueScore, + redScore: match.result.redScore, + } + : undefined, + prizes: match.prizes, + notices: match.notices, + schedule: match.schedule, + }; +} + +export function mapApiAuctionToAuctionState( + auction: ApiAuction, + match: ApiMatch, + now = new Date(), +): AuctionStateView { + const participantLookup = new Map( + match.participants + .map(mapMatchParticipantToView) + .map((participant) => [participant.userId, participant]), + ); + const auctionOrder = auction.order.map(mapAuctionPlayerToView); + const auctionPlayerLookup = new Map( + auctionOrder.map((player) => [player.userId, player]), + ); + const blueTeam = + auction.teams.find((team) => team.side === 'blue') ?? + ({ + side: 'blue', + captainUserId: '', + points: 0, + members: [], + } satisfies ApiAuctionTeam); + const redTeam = + auction.teams.find((team) => team.side === 'red') ?? + ({ + side: 'red', + captainUserId: '', + points: 0, + members: [], + } satisfies ApiAuctionTeam); + + const totalPlayers = auctionOrder.length; + const currentPlayer = + auction.phase === 'complete' + ? null + : auctionPlayerLookup.get(auction.order[auction.currentIndex]?.userId ?? '') ?? null; + const currentPlayerIndex = + auction.phase === 'complete' ? totalPlayers : auction.currentIndex; + const timer = auction.currentDeadline + ? Math.max( + 0, + Math.ceil((new Date(auction.currentDeadline).getTime() - now.getTime()) / 1000), + ) + : 0; + + return { + matchId: auction.matchId, + phase: auction.phase, + teams: [ + mapAuctionTeamToView(blueTeam, auctionPlayerLookup, participantLookup), + mapAuctionTeamToView(redTeam, auctionPlayerLookup, participantLookup), + ], + currentPlayer, + currentPlayerIndex, + totalPlayers, + auctionOrder, + bids: auction.bids.map((bid) => ({ + side: bid.side, + amount: bid.amount, + timestamp: bid.timestamp, + })), + currentBid: auction.currentBid, + currentBidder: auction.currentBidder ?? null, + timer, + maxTimer: auction.maxTimerSeconds, + deadline: auction.currentDeadline, + }; +} diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts new file mode 100644 index 00000000..6a596ecd --- /dev/null +++ b/apps/web/src/api/types.ts @@ -0,0 +1,207 @@ +export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP'; +export type TeamSide = 'blue' | 'red'; +export type MatchStatus = + | 'recruiting' + | 'team-built' + | 'in-progress' + | 'finished'; +export type AuctionPhase = + | 'waiting' + | 'presenting' + | 'bidding' + | 'sold' + | 'complete'; +export type CommunityRole = 'owner' | 'admin' | 'member'; + +export interface ApiPositionPreference { + position: Position; + priority: number; +} + +export interface ApiTierInfo { + queueType: string; + tier: string; + rank: string; + leaguePoints: number; + wins: number; + losses: number; + fetchedAt: string; +} + +export interface ApiChampionMasteryEntry { + championId: string; + championName?: string; + level: number; + points: number; +} + +export interface ApiRiotRecentStatsSummary { + games: number; + wins: number; + losses: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + avgCs: number; + mostPlayedChampionIds: string[]; + extras?: Record; +} + +export interface ApiRiotAccount { + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + revisionDate: number; + summonerLevel: number; + isPrimary: boolean; + tiers: ApiTierInfo[]; + tierHistory: unknown[]; + matchIds: string[]; + championMasteries: ApiChampionMasteryEntry[]; + championRecords: Record>; + recentStatsSummary?: ApiRiotRecentStatsSummary; + createdAt: string; + updatedAt: string; +} + +export interface ApiUser { + _id: string; + communityId: string; + role: CommunityRole; + kakaoTalkId?: string; + kakaoTalkNickname?: string; + discordId?: string; + discordNickname?: string; + riotAccounts: ApiRiotAccount[]; + preferredPositions: ApiPositionPreference[]; + isActivated: boolean; + createdAt: string; + updatedAt: string; +} + +export interface ApiCommunity { + _id: string; + name: string; + description: string; + ownerUserId: string; + createdAt: string; + updatedAt: string; +} + +export interface ApiMatchParticipant { + userId: string; + puuid?: string; + gameName?: string; + tagLine?: string; + profileIconId?: number; + tier?: ApiTierInfo; + preferredPositions: ApiPositionPreference[]; + joinedAt: string; +} + +export interface ApiMatchTeamMember { + userId: string; + assignedPosition: Position; + cost?: number; +} + +export interface ApiMatchTeam { + side: TeamSide; + name: string; + captainUserId?: string; + members: ApiMatchTeamMember[]; +} + +export interface ApiMatchResult { + winnerSide: TeamSide; + blueScore: number; + redScore: number; + mvpUserId?: string; + riotMatchIds: string[]; +} + +export interface ApiMatchScheduleItem { + time: string; + label: string; +} + +export interface ApiMatch { + _id: string; + communityId: string; + title: string; + description: string; + mapId: number; + status: MatchStatus; + scheduledAt: string; + maxParticipants: number; + hostUserId?: string; + participants: ApiMatchParticipant[]; + teams: ApiMatchTeam[]; + result?: ApiMatchResult; + prizes: string[]; + notices: string[]; + schedule: ApiMatchScheduleItem[]; + joined?: boolean; + createdAt: string; + updatedAt: string; +} + +export interface ApiAuctionPlayerSnapshot { + userId: string; + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + preferredPositions: ApiPositionPreference[]; + tiers: ApiTierInfo[]; + masteries: ApiChampionMasteryEntry[]; + recentStatsSummary?: ApiRiotRecentStatsSummary; +} + +export interface ApiAuctionTeamMember { + userId: string; + assignedPosition: Position; + cost: number; +} + +export interface ApiAuctionTeam { + side: TeamSide; + captainUserId: string; + points: number; + members: ApiAuctionTeamMember[]; +} + +export interface ApiAuctionBid { + side: TeamSide; + amount: number; + bidderUserId: string; + timestamp: string; +} + +export interface ApiAuction { + _id: string; + matchId: string; + phase: AuctionPhase; + teams: ApiAuctionTeam[]; + order: ApiAuctionPlayerSnapshot[]; + currentIndex: number; + bids: ApiAuctionBid[]; + currentBid: number; + currentBidder?: TeamSide; + maxTimerSeconds: number; + currentDeadline?: string; + initialPoints: number; + startedAt?: string; + completedAt?: string; + createdAt: string; + updatedAt: string; +} + +export interface MeResponse { + user: ApiUser | null; +} + +export interface MatchesResponse { + matches: ApiMatch[]; +} diff --git a/apps/web/src/api/useAuctionSocket.ts b/apps/web/src/api/useAuctionSocket.ts new file mode 100644 index 00000000..f2fd610c --- /dev/null +++ b/apps/web/src/api/useAuctionSocket.ts @@ -0,0 +1,104 @@ +import { useEffect, useRef, useState } from 'react'; +import { io, type Socket } from 'socket.io-client'; +import { API_BASE_URL, useAuthUserId } from '../config'; +import type { ApiAuction, Position, TeamSide } from './types'; + +type ConnectionStatus = + | 'idle' + | 'connecting' + | 'connected' + | 'disconnected' + | 'error'; + +interface BidPayload { + side: TeamSide; + amount: number; + bidderUserId?: string; +} + +export function useAuctionSocket(matchId: string | undefined) { + const authUserId = useAuthUserId(); + const socketRef = useRef(null); + const [auction, setAuction] = useState(null); + const [connectionStatus, setConnectionStatus] = + useState('idle'); + const [error, setError] = useState(null); + + useEffect(() => { + if (!matchId) { + setAuction(null); + setConnectionStatus('idle'); + return; + } + + const socket = io(`${API_BASE_URL}/auction`, { + transports: ['websocket'], + auth: authUserId ? { 'x-auth-user-id': authUserId } : {}, + }); + + socketRef.current = socket; + setConnectionStatus('connecting'); + setError(null); + + socket.on('connect', () => { + setConnectionStatus('connected'); + socket.emit('join', { matchId }); + }); + + socket.on('disconnect', () => { + setConnectionStatus('disconnected'); + }); + + socket.on('state', (nextAuction: ApiAuction) => { + setAuction(nextAuction); + setError(null); + }); + + socket.on('error', (payload: { message?: string }) => { + setConnectionStatus('error'); + setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.'); + }); + + return () => { + socket.removeAllListeners(); + socket.disconnect(); + socketRef.current = null; + setConnectionStatus('idle'); + }; + }, [authUserId, matchId]); + + function emit(eventName: string, payload?: unknown) { + const socket = socketRef.current; + if (!socket || !socket.connected) { + setError('소켓이 아직 연결되지 않았습니다.'); + return; + } + + setError(null); + + if (payload === undefined) { + socket.emit(eventName); + return; + } + + socket.emit(eventName, payload); + } + + return { + auction, + connectionStatus, + error, + placeBid(payload: BidPayload) { + emit('bid', payload); + }, + openBidding() { + emit('open-bidding', {}); + }, + markSold(assignedPosition?: Position) { + emit('sold', assignedPosition ? { assignedPosition } : {}); + }, + next() { + emit('next', {}); + }, + }; +} diff --git a/apps/web/src/auction-mock.ts b/apps/web/src/auction-mock.ts deleted file mode 100644 index 6c7f3b1d..00000000 --- a/apps/web/src/auction-mock.ts +++ /dev/null @@ -1,427 +0,0 @@ -import type { AuctionPlayer, AuctionState, AuctionTeam } from "./auction-types"; - -const auctionPlayers: AuctionPlayer[] = [ - { - id: 3, - summonerName: "프리리", - tag: "0000", - tier: { - previousSeason: "플래티넘 I", - current: "에메랄드 I", - peak: "에메랄드 I", - }, - mainPosition: "TOP", - subPosition: "MID", - profileIconId: 588, - masteries: [ - { - championName: "신드라", - championId: "Syndra", - level: 7, - points: 124300, - }, - { - championName: "아리", - championId: "Ahri", - level: 7, - points: 98200, - }, - { - championName: "르블랑", - championId: "Leblanc", - level: 6, - points: 45100, - }, - ], - recentStats: { - games: 20, - wins: 13, - losses: 7, - kda: { kills: 8.2, deaths: 7.0, assists: 7.8 }, - avgCs: 178, - }, - }, - { - id: 6, - summonerName: "면정학", - tag: "1234", - tier: { - previousSeason: "플래티넘 III", - current: "에메랄드 III", - peak: "에메랄드 III", - }, - mainPosition: "MID", - subPosition: "ADC", - profileIconId: 6207, - masteries: [ - { - championName: "오리아나", - championId: "Orianna", - level: 7, - points: 312500, - }, - { - championName: "신드라", - championId: "Syndra", - level: 7, - points: 156800, - }, - { championName: "빅토르", championId: "Viktor", level: 6, points: 67200 }, - ], - recentStats: { - games: 20, - wins: 9, - losses: 11, - kda: { kills: 5.4, deaths: 7.3, assists: 7.9 }, - avgCs: 195, - }, - }, - { - id: 5, - summonerName: "던던", - tag: "KR1", - tier: { - previousSeason: "마스터 47LP", - current: "다이아몬드 II", - peak: "마스터 6LP", - }, - mainPosition: "MID", - subPosition: "SUP", - profileIconId: 7036, - masteries: [ - { championName: "조이", championId: "Zoe", level: 7, points: 189400 }, - { - championName: "제라스", - championId: "Xerath", - level: 7, - points: 134200, - }, - { - championName: "흐웨이", - championId: "Hwei", - level: 6, - points: 78900, - }, - ], - recentStats: { - games: 15, - wins: 5, - losses: 10, - kda: { kills: 6.1, deaths: 5.1, assists: 6.0 }, - avgCs: 212, - }, - }, - { - id: 8, - summonerName: "정글러123", - tag: "KR3", - tier: { - previousSeason: "골드 I", - current: "플래티넘 III", - peak: "플래티넘 III", - }, - mainPosition: "JGL", - subPosition: "SUP", - profileIconId: 4789, - masteries: [ - { championName: "리신", championId: "LeeSin", level: 7, points: 201300 }, - { championName: "비에고", championId: "Viego", level: 6, points: 87600 }, - { championName: "렝가", championId: "Rengar", level: 6, points: 65400 }, - ], - recentStats: { - games: 38, - wins: 18, - losses: 20, - kda: { kills: 5.4, deaths: 5.8, assists: 8.1 }, - avgCs: 142, - }, - }, - { - id: 9, - summonerName: "탑솔장인", - tag: "KR1", - tier: { - previousSeason: "에메랄드 IV", - current: "에메랄드 II", - peak: "에메랄드 I", - }, - mainPosition: "TOP", - subPosition: "JGL", - profileIconId: 5450, - masteries: [ - { championName: "잭스", championId: "Jax", level: 7, points: 145600 }, - { championName: "요릭", championId: "Yorick", level: 7, points: 112400 }, - { championName: "나서스", championId: "Nasus", level: 6, points: 89300 }, - ], - recentStats: { - games: 47, - wins: 27, - losses: 20, - kda: { kills: 5.6, deaths: 3.9, assists: 4.1 }, - avgCs: 201, - }, - }, - { - id: 4, - summonerName: "요들마스터", - tag: "KR2", - tier: { - previousSeason: "다이아 II", - current: "다이아 III", - peak: "다이아 I", - }, - mainPosition: "SUP", - subPosition: "MID", - profileIconId: 4951, - masteries: [ - { - championName: "쓰레쉬", - championId: "Thresh", - level: 7, - points: 267800, - }, - { - championName: "노틸러스", - championId: "Nautilus", - level: 7, - points: 134500, - }, - { championName: "룰루", championId: "Lulu", level: 6, points: 78900 }, - ], - recentStats: { - games: 61, - wins: 36, - losses: 25, - kda: { kills: 2.1, deaths: 3.8, assists: 14.2 }, - avgCs: 32, - }, - }, - { - id: 10, - summonerName: "서폿장인", - tag: "0001", - tier: { - previousSeason: "다이아 III", - current: "다이아 IV", - peak: "다이아 II", - }, - mainPosition: "SUP", - subPosition: "ADC", - profileIconId: 4900, - masteries: [ - { championName: "유미", championId: "Yuumi", level: 7, points: 198700 }, - { championName: "소나", championId: "Sona", level: 7, points: 145200 }, - { championName: "나미", championId: "Nami", level: 6, points: 92100 }, - ], - recentStats: { - games: 52, - wins: 30, - losses: 22, - kda: { kills: 1.8, deaths: 4.2, assists: 16.3 }, - avgCs: 25, - }, - }, - { - id: 2, - summonerName: "Shadow Wolf", - tag: "KR1", - tier: { - previousSeason: "다이아 IV", - current: "플래티넘 II", - peak: "다이아 II", - }, - mainPosition: "JGL", - subPosition: "TOP", - profileIconId: 4834, - masteries: [ - { - championName: "니달리", - championId: "Nidalee", - level: 7, - points: 178900, - }, - { championName: "엘리스", championId: "Elise", level: 7, points: 134500 }, - { - championName: "그레이브즈", - championId: "Graves", - level: 6, - points: 67800, - }, - ], - recentStats: { - games: 44, - wins: 22, - losses: 22, - kda: { kills: 6.5, deaths: 4.7, assists: 7.8 }, - avgCs: 156, - }, - }, -]; - -function createInitialState(): AuctionState { - const blueTeam: AuctionTeam = { - side: "blue", - captainName: "프리리", - points: 1000, - members: [], - }; - const redTeam: AuctionTeam = { - side: "red", - captainName: "IceQueen", - points: 1000, - members: [], - }; - - return { - matchId: 1, - phase: "waiting", - teams: [blueTeam, redTeam], - currentPlayer: null, - currentPlayerIndex: -1, - totalPlayers: auctionPlayers.length, - auctionOrder: auctionPlayers, - bids: [], - currentBid: 0, - currentBidder: null, - timer: 0, - maxTimer: 15, - }; -} - -// Mock WebSocket - 경매 시뮬레이션 -export function createMockAuction(onUpdate: (state: AuctionState) => void) { - let state = createInitialState(); - let timerInterval: ReturnType | null = null; - let isRunning = false; - - function emit() { - onUpdate({ - ...state, - teams: [{ ...state.teams[0] }, { ...state.teams[1] }], - }); - } - - function clearTimer() { - if (timerInterval) { - clearInterval(timerInterval); - timerInterval = null; - } - } - - function startBidTimer() { - clearTimer(); - state.timer = state.maxTimer; - emit(); - - timerInterval = setInterval(() => { - state.timer--; - emit(); - if (state.timer <= 0) { - clearTimer(); - handleTimerEnd(); - } - }, 1000); - } - - function handleTimerEnd() { - if (state.currentBidder && state.currentPlayer) { - // 낙찰 - const teamIdx = state.currentBidder === "blue" ? 0 : 1; - state.teams[teamIdx].points -= state.currentBid; - state.teams[teamIdx].members.push({ - ...state.currentPlayer, - cost: state.currentBid, - assignedPosition: state.currentPlayer.mainPosition, - }); - state.phase = "sold"; - emit(); - - // 다음 선수로 - setTimeout(() => { - if (!isRunning) return; - nextPlayer(); - }, 2000); - } else { - // 유찰 → 최소 가격으로 랜덤 팀에 배정 - if (state.currentPlayer) { - const randomSide = Math.random() > 0.5 ? 0 : 1; - const minCost = 50; - state.teams[randomSide].points -= minCost; - state.teams[randomSide].members.push({ - ...state.currentPlayer, - cost: minCost, - assignedPosition: state.currentPlayer.mainPosition, - }); - state.phase = "sold"; - state.currentBid = minCost; - state.currentBidder = randomSide === 0 ? "blue" : "red"; - emit(); - - setTimeout(() => { - if (!isRunning) return; - nextPlayer(); - }, 2000); - } - } - } - - function nextPlayer() { - const nextIdx = state.currentPlayerIndex + 1; - if (nextIdx >= state.auctionOrder.length) { - state.phase = "complete"; - state.currentPlayer = null; - emit(); - return; - } - - state.currentPlayerIndex = nextIdx; - state.currentPlayer = state.auctionOrder[nextIdx]; - state.bids = []; - state.currentBid = 0; - state.currentBidder = null; - state.phase = "presenting"; - emit(); - - // 2초 뒤 입찰 시작 - setTimeout(() => { - if (!isRunning) return; - state.phase = "bidding"; - startBidTimer(); - }, 2500); - } - - return { - start() { - isRunning = true; - state.phase = "waiting"; - emit(); - setTimeout(() => { - if (!isRunning) return; - nextPlayer(); - }, 1500); - }, - - bid(side: "blue" | "red", amount: number) { - if (state.phase !== "bidding") return; - const teamIdx = side === "blue" ? 0 : 1; - if (amount <= state.currentBid) return; - if (amount > state.teams[teamIdx].points) return; - - state.currentBid = amount; - state.currentBidder = side; - state.bids.push({ side, amount, timestamp: Date.now() }); - // 입찰 시 타이머 리셋 (최소 5초) - if (state.timer < 5) { - state.timer = 5; - } - emit(); - }, - - destroy() { - isRunning = false; - clearTimer(); - }, - - getState: () => state, - }; -} diff --git a/apps/web/src/auction-types.ts b/apps/web/src/auction-types.ts deleted file mode 100644 index 6caa5ded..00000000 --- a/apps/web/src/auction-types.ts +++ /dev/null @@ -1,69 +0,0 @@ -import type { Participant, Position } from "./mock"; - -export interface ChampionMastery { - championName: string; - championId: string; - level: number; - points: number; -} - -export interface RecentStats { - games: number; - wins: number; - losses: number; - kda: { kills: number; deaths: number; assists: number }; - avgCs: number; -} - -export interface AuctionPlayer extends Participant { - masteries: ChampionMastery[]; - recentStats: RecentStats; -} - -export interface AuctionTeam { - side: "blue" | "red"; - captainName: string; - points: number; - members: (AuctionPlayer & { cost: number; assignedPosition: Position })[]; -} - -export type AuctionPhase = - | "waiting" - | "presenting" - | "bidding" - | "sold" - | "complete"; - -export interface BidEntry { - side: "blue" | "red"; - amount: number; - timestamp: number; -} - -export interface AuctionState { - matchId: number; - phase: AuctionPhase; - teams: [AuctionTeam, AuctionTeam]; - currentPlayer: AuctionPlayer | null; - currentPlayerIndex: number; - totalPlayers: number; - auctionOrder: AuctionPlayer[]; - bids: BidEntry[]; - currentBid: number; - currentBidder: "blue" | "red" | null; - timer: number; - maxTimer: number; -} - -// WebSocket message types (서버 → 클라이언트) -export type ServerMessage = - | { type: "auction:init"; state: AuctionState } - | { type: "auction:present"; player: AuctionPlayer; index: number } - | { type: "auction:bid"; side: "blue" | "red"; amount: number } - | { type: "auction:timer"; remaining: number } - | { type: "auction:sold"; side: "blue" | "red"; player: AuctionPlayer; cost: number } - | { type: "auction:complete"; teams: [AuctionTeam, AuctionTeam] }; - -// WebSocket message types (클라이언트 → 서버) -export type ClientMessage = - | { type: "bid"; amount: number }; diff --git a/apps/web/src/components/DevAuthSwitcher.tsx b/apps/web/src/components/DevAuthSwitcher.tsx new file mode 100644 index 00000000..29f25143 --- /dev/null +++ b/apps/web/src/components/DevAuthSwitcher.tsx @@ -0,0 +1,58 @@ +import { useEffect, useState } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { setAuthUserId, useAuthUserId } from '../config'; + +export default function DevAuthSwitcher() { + const authUserId = useAuthUserId(); + const queryClient = useQueryClient(); + const [inputValue, setInputValue] = useState(authUserId ?? ''); + + useEffect(() => { + setInputValue(authUserId ?? ''); + }, [authUserId]); + + if (!import.meta.env.DEV) { + return null; + } + + function updateAuthUserId(nextValue: string | null) { + setAuthUserId(nextValue); + void queryClient.invalidateQueries(); + } + + return ( +
+
+ Dev Auth +
+
+ X-Auth-User-Id +
+ setInputValue(event.target.value)} + placeholder="Mongo User ID" + className="mt-1 w-full border border-base-content/10 bg-transparent px-2 py-2 text-xs text-base-content focus:outline-none focus:border-primary/30" + /> +
+ + +
+
+ 현재값: {authUserId ?? '없음'} +
+
+ ); +} diff --git a/apps/web/src/config.ts b/apps/web/src/config.ts new file mode 100644 index 00000000..f7b66c49 --- /dev/null +++ b/apps/web/src/config.ts @@ -0,0 +1,90 @@ +import { useSyncExternalStore } from 'react'; + +export type DevCaptainSide = 'spectator' | 'blue' | 'red'; + +const AUTH_USER_ID_STORAGE_KEY = 'lolympus.authUserId'; +const DEV_CAPTAIN_SIDE_STORAGE_KEY = 'lolympus.devCaptainSide'; +const AUTH_USER_CHANGED_EVENT = 'lolympus:auth-user-changed'; +const CAPTAIN_SIDE_CHANGED_EVENT = 'lolympus:captain-side-changed'; + +export const API_BASE_URL = ( + import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:3000' +).replace(/\/$/, ''); + +export const DEFAULT_COMMUNITY_ID = ( + import.meta.env.VITE_DEFAULT_COMMUNITY_ID ?? '' +).trim(); + +function dispatchWindowEvent(eventName: string) { + if (typeof window === 'undefined') return; + window.dispatchEvent(new Event(eventName)); +} + +function subscribeToWindowChanges(eventName: string, callback: () => void) { + if (typeof window === 'undefined') { + return () => undefined; + } + + const handleChange = () => callback(); + window.addEventListener(eventName, handleChange); + window.addEventListener('storage', handleChange); + + return () => { + window.removeEventListener(eventName, handleChange); + window.removeEventListener('storage', handleChange); + }; +} + +export function getAuthUserId(): string | null { + if (typeof window === 'undefined') return null; + const value = window.localStorage.getItem(AUTH_USER_ID_STORAGE_KEY)?.trim(); + return value ? value : null; +} + +export function setAuthUserId(userId: string | null) { + if (typeof window === 'undefined') return; + + if (!userId?.trim()) { + window.localStorage.removeItem(AUTH_USER_ID_STORAGE_KEY); + } else { + window.localStorage.setItem(AUTH_USER_ID_STORAGE_KEY, userId.trim()); + } + + dispatchWindowEvent(AUTH_USER_CHANGED_EVENT); +} + +export function getDevCaptainSide(): DevCaptainSide { + if (typeof window === 'undefined') return 'spectator'; + + const value = window.localStorage.getItem( + DEV_CAPTAIN_SIDE_STORAGE_KEY, + ) as DevCaptainSide | null; + + if (value === 'blue' || value === 'red' || value === 'spectator') { + return value; + } + + return 'spectator'; +} + +export function setDevCaptainSide(side: DevCaptainSide) { + if (typeof window === 'undefined') return; + window.localStorage.setItem(DEV_CAPTAIN_SIDE_STORAGE_KEY, side); + dispatchWindowEvent(CAPTAIN_SIDE_CHANGED_EVENT); +} + +export function useAuthUserId(): string | null { + return useSyncExternalStore( + (callback) => subscribeToWindowChanges(AUTH_USER_CHANGED_EVENT, callback), + getAuthUserId, + () => null, + ); +} + +export function useDevCaptainSide(): DevCaptainSide { + return useSyncExternalStore( + (callback) => subscribeToWindowChanges(CAPTAIN_SIDE_CHANGED_EVENT, callback), + getDevCaptainSide, + () => 'spectator', + ); +} diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index bef5202a..c2975e03 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -1,10 +1,23 @@ -import { StrictMode } from 'react' -import { createRoot } from 'react-dom/client' -import './index.css' -import App from './App.tsx' +import { StrictMode } from 'react'; +import { createRoot } from 'react-dom/client'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import './index.css'; +import App from './App.tsx'; + +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + staleTime: 10 * 1000, + gcTime: 5 * 60 * 1000, + refetchOnWindowFocus: false, + }, + }, +}); createRoot(document.getElementById('root')!).render( - + + + , -) +); diff --git a/apps/web/src/mock.ts b/apps/web/src/mock.ts deleted file mode 100644 index ebea74e1..00000000 --- a/apps/web/src/mock.ts +++ /dev/null @@ -1,404 +0,0 @@ -// LoL 포지션 -export type Position = "TOP" | "JGL" | "MID" | "ADC" | "SUP"; - -export type MatchStatus = "recruiting" | "team-built" | "finished"; - -export interface TierInfo { - previousSeason: string; - current: string; - peak: string; -} - -export interface Participant { - id: number; - summonerName: string; - tag: string; - tier: TierInfo; - mainPosition: Position; - subPosition: Position; - profileIconId: number; -} - -export interface Team { - name: string; - participants: (Participant & { assignedPosition: Position })[]; -} - -export interface MatchDetail { - id: number; - title: string; - date: string; - time: string; - status: MatchStatus; - description: string; - map: string; - maxParticipants: number; - participants: Participant[]; - teams?: [Team, Team]; - result?: { winner: string; blueScore: number; redScore: number }; - prizes?: string[]; - notices?: string[]; - schedule?: { time: string; label: string }[]; -} - -export const positionLabel: Record = { - TOP: "탑", - JGL: "정글", - MID: "미드", - ADC: "원딜", - SUP: "서폿", -}; - -import posTop from "./assets/position/Top_icon.png"; -import posJgl from "./assets/position/Jungle_icon.png"; -import posMid from "./assets/position/Middle_icon.png"; -import posAdc from "./assets/position/Bottom_icon.png"; -import posSup from "./assets/position/Support_icon.png"; - -export const positionIcon: Record = { - TOP: posTop, - JGL: posJgl, - MID: posMid, - ADC: posAdc, - SUP: posSup, -}; - -const participants: Participant[] = [ - { - id: 1, - summonerName: "프리리", - tag: "KR1", - tier: { - previousSeason: "플래티넘 I", - current: "다이아 IV", - peak: "다이아 IV", - }, - mainPosition: "MID", - subPosition: "ADC", - profileIconId: 588, - }, - { - id: 2, - summonerName: "호호불어먹어요", - tag: "0000", - tier: { - previousSeason: "다이아 IV", - current: "플래티넘 II", - peak: "다이아 IV", - }, - mainPosition: "JGL", - subPosition: "TOP", - profileIconId: 7015, - }, - { - id: 3, - summonerName: "소다", - tag: "KR1", - tier: { - previousSeason: "플래티넘 I", - current: "에메랄드 I", - peak: "에메랄드 I", - }, - mainPosition: "TOP", - subPosition: "MID", - profileIconId: 5186, - }, - { - id: 4, - summonerName: "잉호바", - tag: "KR1", - tier: { - previousSeason: "다이아 II", - current: "다이아 III", - peak: "마스터 200LP", - }, - mainPosition: "SUP", - subPosition: "MID", - profileIconId: 7050, - }, - { - id: 5, - summonerName: "잉호바탭키도둑", - tag: "Tab", - tier: { - previousSeason: "에메랄드 II", - current: "플래티넘 I", - peak: "에메랄드 I", - }, - mainPosition: "ADC", - subPosition: "SUP", - profileIconId: 5231, - }, - { - id: 6, - summonerName: "osu", - tag: "KR1", - tier: { - previousSeason: "플래티넘 III", - current: "에메랄드 III", - peak: "마스터 200LP", - }, - mainPosition: "MID", - subPosition: "JGL", - profileIconId: 7091, - }, - { - id: 7, - summonerName: "IceQueen", - tag: "KR1", - tier: { - previousSeason: "다이아 I", - current: "다이아 II", - peak: "마스터 50LP", - }, - mainPosition: "ADC", - subPosition: "MID", - profileIconId: 5102, - }, - { - id: 8, - summonerName: "정글러123", - tag: "KR3", - tier: { - previousSeason: "골드 I", - current: "플래티넘 III", - peak: "플래티넘 III", - }, - mainPosition: "JGL", - subPosition: "SUP", - profileIconId: 4789, - }, - { - id: 9, - summonerName: "탑솔장인", - tag: "KR1", - tier: { - previousSeason: "에메랄드 IV", - current: "에메랄드 II", - peak: "에메랄드 I", - }, - mainPosition: "TOP", - subPosition: "JGL", - profileIconId: 5450, - }, - { - id: 10, - summonerName: "서폿장인", - tag: "0001", - tier: { - previousSeason: "다이아 III", - current: "다이아 IV", - peak: "다이아 II", - }, - mainPosition: "SUP", - subPosition: "ADC", - profileIconId: 4900, - }, -]; - -// 내전 1: 팀빌딩 전 (모집 중) -export const match_recruiting: MatchDetail = { - id: 2, - title: "쌀먹 내전", - date: "2026년 4월 19일 (일)", - time: "오후 3시", - status: "recruiting", - description: "JEIFF님의 후원으로 개최되는 쌀먹 내전. 많관부~", - map: "소환사의 협곡", - maxParticipants: 10, - participants: participants.slice(0, 6), - prizes: ["5명 추첨 커피", "MVP: 스킨 선물"], - notices: [ - "시작 10분 전까지 커스텀 방에 입장해주세요.", - "무단 불참 시 다음 내전 참여가 제한될 수 있습니다.", - "게임 중 과도한 욕설은 자제해주세요.", - ], - schedule: [ - { time: "21:45", label: "로비 오픈" }, - { time: "21:50", label: "경매 시작" }, - { time: "22:00", label: "게임 시작" }, - { time: "~24:00", label: "예상 종료" }, - ], -}; - -// 내전 2: 팀빌딩 완료, 게임 시작 전 -export const match_teamBuilt: MatchDetail = { - id: 1, - title: "롤림푸스 멸망전 시즌 4 결승전", - date: "2026년 4월 18일 (토)", - time: "오후 8시", - status: "team-built", - description: "시즌 4 최종 결승전입니다. ABC팀 VS DEF팀으로 진행됩니다.", - map: "소환사의 협곡", - maxParticipants: 10, - participants, - teams: [ - { - name: "블루팀", - participants: [ - { ...participants[0], assignedPosition: "MID" }, - { ...participants[1], assignedPosition: "JGL" }, - { ...participants[2], assignedPosition: "TOP" }, - { ...participants[4], assignedPosition: "ADC" }, - { ...participants[9], assignedPosition: "SUP" }, - ], - }, - { - name: "레드팀", - participants: [ - { ...participants[6], assignedPosition: "ADC" }, - { ...participants[5], assignedPosition: "MID" }, - { ...participants[8], assignedPosition: "TOP" }, - { ...participants[7], assignedPosition: "JGL" }, - { ...participants[3], assignedPosition: "SUP" }, - ], - }, - ], - prizes: ["승리 팀: 햄버거 세트", "패배 팀: 컴포즈커피 아메리카노"], - notices: [ - "결승전은 3판 2선으로 진행됩니다.", - "시작 15분 전까지 디스코드 음성채널에 입장해주세요.", - "경기 중 감정 표현과 도발 모션은 금지입니다.", - ], - schedule: [ - { time: "19:30", label: "디스코드 집합" }, - { time: "19:45", label: "팀빌딩 확인" }, - { time: "20:00", label: "1세트 시작" }, - { time: "20:40", label: "2세트 시작 (예상)" }, - { time: "21:20", label: "3세트 시작 (필요시)" }, - ], -}; - -// 내전 3: 게임 종료 -export const match_finished: MatchDetail = { - id: 101, - title: "시즌 4 준결승", - date: "2026년 4월 11일 (금)", - time: "오후 8시", - status: "finished", - description: "시즌 4 준결승전입니다.", - map: "소환사의 협곡", - maxParticipants: 10, - participants, - teams: [ - { - name: "블루팀", - participants: [ - { ...participants[0], assignedPosition: "MID" }, - { ...participants[1], assignedPosition: "JGL" }, - { ...participants[2], assignedPosition: "TOP" }, - { ...participants[4], assignedPosition: "ADC" }, - { ...participants[9], assignedPosition: "SUP" }, - ], - }, - { - name: "레드팀", - participants: [ - { ...participants[6], assignedPosition: "ADC" }, - { ...participants[5], assignedPosition: "MID" }, - { ...participants[8], assignedPosition: "TOP" }, - { ...participants[7], assignedPosition: "JGL" }, - { ...participants[3], assignedPosition: "SUP" }, - ], - }, - ], - result: { winner: "블루팀", blueScore: 2, redScore: 1 }, - prizes: ["1등 팀: RP 10,000 지급", "MVP: 프리리 (MID)"], - notices: [], - schedule: [], -}; - -// 메인 페이지용 -export const nextMatchSummary = { - id: match_teamBuilt.id, - title: match_teamBuilt.title, - date: match_teamBuilt.date, - time: match_teamBuilt.time, - participants: match_teamBuilt.participants.length, - maxParticipants: match_teamBuilt.maxParticipants, - status: "모집 완료", - description: match_teamBuilt.description, - map: match_teamBuilt.map, -}; - -export const upcomingMatches = [ - { - id: match_recruiting.id, - title: match_recruiting.title, - date: match_recruiting.date, - time: match_recruiting.time, - participants: match_recruiting.participants.length, - maxParticipants: match_recruiting.maxParticipants, - status: "모집 중", - map: match_recruiting.map, - }, - { - id: 3, - title: "칼바람 나락 내전", - date: "2026년 4월 25일 (토)", - time: "오후 7시", - participants: 2, - maxParticipants: 10, - status: "모집 중", - map: "칼바람 나락", - }, - { - id: 4, - title: "롤림푸스 시즌 5 개막전", - date: "2026년 5월 2일 (토)", - time: "오후 8시", - participants: 0, - maxParticipants: 10, - status: "예정", - map: "소환사의 협곡", - }, -]; - -export const pastMatches = [ - { - id: 101, - title: "시즌 4 준결승", - date: "2026년 4월 11일", - participants: 10, - result: "블루팀 승리", - map: "소환사의 협곡", - }, - { - id: 102, - title: "평일 내전", - date: "2026년 4월 9일", - participants: 10, - result: "레드팀 승리", - map: "소환사의 협곡", - }, - { - id: 103, - title: "칼바람 나락 내전", - date: "2026년 4월 5일", - participants: 10, - result: "-", - map: "칼바람 나락", - }, - { - id: 104, - title: "시즌 4 8강", - date: "2026년 4월 4일", - participants: 10, - result: "블루팀 승리", - map: "소환사의 협곡", - }, - { - id: 105, - title: "주말 내전", - date: "2026년 3월 29일", - participants: 10, - result: "레드팀 승리", - map: "소환사의 협곡", - }, -]; - -export function getMatchById(id: number): MatchDetail | undefined { - return [match_recruiting, match_teamBuilt, match_finished].find( - (m) => m.id === id, - ); -} diff --git a/apps/web/src/pages/AuctionPage.tsx b/apps/web/src/pages/AuctionPage.tsx index fb5d13fd..3998a9d7 100644 --- a/apps/web/src/pages/AuctionPage.tsx +++ b/apps/web/src/pages/AuctionPage.tsx @@ -1,89 +1,72 @@ -import { useEffect, useRef, useState } from "react"; -import { useParams, Link } from "react-router"; -import { createMockAuction } from "../auction-mock"; -import type { - AuctionState, - AuctionPlayer, - AuctionTeam, -} from "../auction-types"; -import { positionIcon, positionLabel, type Position } from "../mock"; +import { useEffect, useRef, useState } from 'react'; +import { Link, useParams } from 'react-router'; +import { useAuction, useMatch, useMe } from '../api/hooks'; +import { + formatTierLabel, + getTierColorToken, + mapApiAuctionToAuctionState, + type AuctionStateView, +} from '../api/mappers'; +import { useAuctionSocket } from '../api/useAuctionSocket'; +import { DEFAULT_COMMUNITY_ID, setDevCaptainSide, useDevCaptainSide } from '../config'; +import { ApiError } from '../lib/api'; +import { positionIcon, positionLabel } from '../lib/league'; +import type { Position } from '../api/types'; -// -- 티어 색상 -- -function tierColor(tier: string): string { - if (tier.startsWith("챌린저")) return "text-amber-400"; - if (tier.startsWith("그랜드마스터")) return "text-red-400"; - if (tier.startsWith("마스터")) return "text-purple-400"; - if (tier.startsWith("다이아")) return "text-cyan-400"; - if (tier.startsWith("에메랄드")) return "text-emerald-400"; - if (tier.startsWith("플래티넘")) return "text-teal-300"; - if (tier.startsWith("골드")) return "text-yellow-400"; - if (tier.startsWith("실버")) return "text-gray-300"; - return "text-amber-700"; -} - -function formatPoints(n: number): string { - return n.toLocaleString(); +function formatPoints(value: number) { + return value.toLocaleString(); } function PosBadge({ pos }: { pos: Position }) { return ( - + {positionLabel[pos]} ); } -// -- 타이머 바 -- function TimerBar({ timer, maxTimer }: { timer: number; maxTimer: number }) { - const pct = (timer / maxTimer) * 100; + const pct = maxTimer > 0 ? (timer / maxTimer) * 100 : 0; const urgent = timer <= 5; + return (
); } -// -- 팀 패널 -- function TeamPanel({ team, isActive, isLeft, }: { - team: AuctionTeam; + team: AuctionStateView['teams'][number]; isActive: boolean; isLeft: boolean; }) { const borderColor = - team.side === "blue" ? "border-blue-500/25" : "border-red-500/25"; - const accentBar = team.side === "blue" ? "bg-blue-500" : "bg-red-500"; - const sideColor = team.side === "blue" ? "text-blue-400" : "text-red-400"; - const headerBg = team.side === "blue" ? "bg-blue-500/8" : "bg-red-500/8"; + team.side === 'blue' ? 'border-blue-500/25' : 'border-red-500/25'; + const accentBar = team.side === 'blue' ? 'bg-blue-500' : 'bg-red-500'; + const sideColor = team.side === 'blue' ? 'text-blue-400' : 'text-red-400'; + const headerBg = team.side === 'blue' ? 'bg-blue-500/8' : 'bg-red-500/8'; return (
- - {/* 헤더 */}
- - {team.side === "blue" ? "블루팀" : "레드팀"} + + {team.side === 'blue' ? '블루팀' : '레드팀'} 팀장: {team.captainName} @@ -95,18 +78,17 @@ function TeamPanel({
- {/* 멤버 목록 */}
{team.members.length === 0 ? (
아직 멤버가 없습니다
) : ( - team.members.map((m) => ( -
+ team.members.map((member) => ( +
- {m.summonerName} + {member.summonerName}
- + - {m.cost} + {member.cost}
)) )} - {/* 빈 슬롯 */} - {Array.from({ length: 4 - team.members.length }).map((_, i) => ( + {Array.from({ length: Math.max(0, 4 - team.members.length) }).map((_, index) => (
@@ -140,18 +121,14 @@ function TeamPanel({ ); } -// -- 현재 경매 선수 카드 -- function PlayerSpotlight({ - player, - phase, - currentBid, - currentBidder, + state, }: { - player: AuctionPlayer; - phase: AuctionState["phase"]; - currentBid: number; - currentBidder: "blue" | "red" | null; + state: AuctionStateView; }) { + const player = state.currentPlayer; + if (!player) return null; + const winRate = player.recentStats.games > 0 ? Math.round((player.recentStats.wins / player.recentStats.games) * 100) @@ -162,11 +139,10 @@ function PlayerSpotlight({ (player.recentStats.kda.kills + player.recentStats.kda.assists) / player.recentStats.kda.deaths ).toFixed(2) - : "Perfect"; + : 'Perfect'; return (
- {/* 선수 프로필 */}
@@ -185,19 +161,8 @@ function PlayerSpotlight({ #{player.tag}
-
- - {player.tier.previousSeason} - - → - - {player.tier.current} - - - ({player.tier.peak}) - +
+ {formatTierLabel(player.tier)}
@@ -206,7 +171,7 @@ function PlayerSpotlight({ src={positionIcon[player.subPosition]} alt="" className="w-3.5 h-3.5 object-contain inline" - />{" "} + />{' '} {positionLabel[player.subPosition]}
@@ -214,38 +179,41 @@ function PlayerSpotlight({
- {/* 스탯 그리드 */}
- {/* 숙련도 */}

숙련도 높은 챔피언

- {player.masteries.map((m) => ( -
-
- {m.championName} -
-
-
- {m.championName} + {player.masteries.length > 0 ? ( + player.masteries.map((mastery) => ( +
+
+ {mastery.championName}
-
- Lv.{m.level} · {(m.points / 1000).toFixed(0)}K +
+
+ {mastery.championName} +
+
+ Lv.{mastery.level} · {(mastery.points / 1000).toFixed(0)}K +
+ )) + ) : ( +
+ 숙련도 데이터가 없습니다.
- ))} + )}
- {/* 최근 전적 */}

최근 솔로랭크 @@ -254,7 +222,7 @@ function PlayerSpotlight({
승률 = 55 ? "text-blue-400" : winRate >= 50 ? "text-base-content" : "text-red-400"}`} + className={`text-sm font-bold tabular-nums ${winRate >= 55 ? 'text-blue-400' : winRate >= 50 ? 'text-base-content' : 'text-red-400'}`} > {winRate}% @@ -262,12 +230,8 @@ function PlayerSpotlight({
전적 - - {player.recentStats.wins}W - {" "} - - {player.recentStats.losses}L - + {player.recentStats.wins}W{' '} + {player.recentStats.losses}L
@@ -276,7 +240,7 @@ function PlayerSpotlight({ {player.recentStats.kda.kills}/{player.recentStats.kda.deaths}/ {player.recentStats.kda.assists} = 3 ? "text-emerald-400" : "text-base-content/50"}`} + className={`ml-1 font-bold ${Number(kdaRatio) >= 3 ? 'text-emerald-400' : 'text-base-content/50'}`} > ({kdaRatio}) @@ -292,23 +256,22 @@ function PlayerSpotlight({
- {/* 현재 입찰 상태 */} - {(phase === "bidding" || phase === "sold") && ( + {(state.phase === 'bidding' || state.phase === 'sold') && (
- {phase === "sold" ? "낙찰가" : "현재 입찰가"} + {state.phase === 'sold' ? '낙찰가' : '현재 입찰가'}
- {currentBidder && ( + {state.currentBidder && ( - {currentBidder === "blue" ? "블루" : "레드"} + {state.currentBidder === 'blue' ? '블루' : '레드'} )} - {currentBid > 0 ? formatPoints(currentBid) : "—"} + {state.currentBid > 0 ? formatPoints(state.currentBid) : '—'}
@@ -318,80 +281,86 @@ function PlayerSpotlight({ ); } -// -- 입찰 컨트롤 -- function BidControls({ state, + captainSide, onBid, }: { - state: AuctionState; - onBid: (side: "blue" | "red", amount: number) => void; + state: AuctionStateView; + captainSide: 'spectator' | 'blue' | 'red'; + onBid: (side: 'blue' | 'red', amount: number) => void; }) { const [bidAmount, setBidAmount] = useState(100); const minBid = state.currentBid + 10; + const activeTeam = + captainSide === 'blue' + ? state.teams[0] + : captainSide === 'red' + ? state.teams[1] + : null; useEffect(() => { setBidAmount(Math.max(minBid, Math.ceil(minBid / 10) * 10)); - }, [state.currentBid]); + }, [state.currentBid, minBid]); - if (state.phase !== "bidding") return null; + if (state.phase !== 'bidding') return null; + + if (!activeTeam) { + return ( +
+ 관전자 모드입니다. 우측 상단에서 조작자 역할을 선택하면 입찰할 수 있습니다. +
+ ); + } const presets = [50, 100, 150, 200, 300, 500]; return (
- {presets.map((p) => ( + {presets.map((preset) => ( ))} - setBidAmount(Math.max(minBid, Number(e.target.value))) + onChange={(event) => + setBidAmount(Math.max(minBid, Number(event.target.value))) } min={minBid} - className="w-20 text-xs px-2 py-1 border border-base-content/10 bg-transparent text-base-content tabular-nums text-right focus:outline-none focus:border-primary/30" + className="w-24 text-xs px-2 py-1 border border-base-content/10 bg-transparent text-base-content tabular-nums text-right focus:outline-none focus:border-primary/30" />
-
- - -
+
); } -// -- 입찰 로그 -- -function BidLog({ bids }: { bids: AuctionState["bids"] }) { +function BidLog({ bids }: { bids: AuctionStateView['bids'] }) { const endRef = useRef(null); + useEffect(() => { - endRef.current?.scrollIntoView({ behavior: "smooth" }); + endRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [bids.length]); if (bids.length === 0) return null; @@ -404,16 +373,16 @@ function BidLog({ bids }: { bids: AuctionState["bids"] }) {
- {bids.map((b, i) => ( -
+ {bids.map((bid, index) => ( +
- {b.side === "blue" ? "블루" : "레드"} + {bid.side === 'blue' ? '블루' : '레드'} → - {formatPoints(b.amount)}P + {formatPoints(bid.amount)}P
))} @@ -423,47 +392,89 @@ function BidLog({ bids }: { bids: AuctionState["bids"] }) { ); } -// -- 메인 -- export default function AuctionPage() { const { id } = useParams(); - const [state, setState] = useState(null); - const auctionRef = useRef | null>(null); + const meQuery = useMe(); + const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); + const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID); + const socket = useAuctionSocket(id); + const captainSide = useDevCaptainSide(); + const [now, setNow] = useState(() => Date.now()); + const [assignedPosition, setAssignedPosition] = useState('MID'); useEffect(() => { - const auction = createMockAuction((newState) => { - setState({ ...newState }); - }); - auctionRef.current = auction; - auction.start(); + const timer = window.setInterval(() => setNow(Date.now()), 1000); + return () => window.clearInterval(timer); + }, []); - return () => { - auction.destroy(); - }; - }, [id]); + const liveAuction = socket.auction ?? auctionQuery.data ?? null; + const auctionState = + liveAuction && matchQuery.data + ? mapApiAuctionToAuctionState(liveAuction, matchQuery.data, new Date(now)) + : null; - if (!state) { + useEffect(() => { + if (auctionState?.currentPlayer) { + setAssignedPosition(auctionState.currentPlayer.mainPosition); + } + }, [auctionState?.currentPlayer?.id]); + + if (!DEFAULT_COMMUNITY_ID) { return (
- 연결 중... + + `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. +
); } - const handleBid = (side: "blue" | "red", amount: number) => { - auctionRef.current?.bid(side, amount); - }; + if (matchQuery.isLoading || (auctionQuery.isLoading && !socket.auction)) { + return ( +
+ 경매를 연결하는 중... +
+ ); + } - const phaseLabel: Record = { - waiting: "경매 준비 중...", - presenting: "다음 선수 등장", - bidding: "입찰 진행 중", - sold: "낙찰!", - complete: "경매 완료", + if (auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404 && !socket.auction) { + return ( +
+

경매가 아직 시작되지 않았습니다

+ + 내전 상세로 돌아가기 + +
+ ); + } + + if (!auctionState || !matchQuery.data) { + return ( +
+ + 경매 상태를 불러오지 못했습니다. + +
+ ); + } + + const canManageAuction = + import.meta.env.DEV || + meQuery.data?.user?.role === 'owner' || + meQuery.data?.user?.role === 'admin'; + const phaseLabel: Record = { + waiting: '경매 준비 중...', + presenting: '다음 선수 등장', + bidding: '입찰 진행 중', + sold: '낙찰!', + complete: '경매 완료', }; + const errorMessage = + socket.error ?? + (auctionQuery.error instanceof Error ? auctionQuery.error.message : null); return (
- {/* 뒤로가기 */} - {/* 경매 헤더 */} -
+ {errorMessage && ( +
+ {errorMessage} +
+ )} + +

경매 팀빌딩

- {state.currentPlayerIndex + 1} / {state.totalPlayers} 선수 + {Math.min(auctionState.currentPlayerIndex + 1, Math.max(auctionState.totalPlayers, 1))} /{' '} + {auctionState.totalPlayers} 선수

-
- - {phaseLabel[state.phase]} - - {state.phase === "bidding" && ( +
+
- {state.timer}s + {phaseLabel[auctionState.phase]} - )} + {auctionState.phase === 'bidding' && ( + + {auctionState.timer}s + + )} +
+
+ 소켓: {socket.connectionStatus} + {import.meta.env.DEV && ( + + )} +
- {/* 타이머 바 */} - {state.phase === "bidding" && ( - + {auctionState.phase === 'bidding' && ( + )} - {/* 메인 3컬럼 */}
- {/* 블루팀 */}
- {/* 중앙: 선수 카드 */}
- {state.phase === "waiting" && ( -
-
- 경매가 곧 시작됩니다... -
-
- )} - - {state.phase === "complete" && ( + {auctionState.phase === 'complete' ? (
경매 완료 @@ -558,44 +581,85 @@ export default function AuctionPage() { 결과 확인
- )} + ) : ( + <> + - {state.currentPlayer && - (state.phase === "presenting" || - state.phase === "bidding" || - state.phase === "sold") && ( - <> - + {auctionState.phase === 'sold' && auctionState.currentBidder && ( +
+ {auctionState.currentBidder === 'blue' ? '블루팀' : '레드팀'} 낙찰 + {' '}— {formatPoints(auctionState.currentBid)}P +
+ )} - {state.phase === "sold" && state.currentBidder && ( -
- {state.currentBidder === "blue" ? "블루팀" : "레드팀"} 낙찰 - — {formatPoints(state.currentBid)}P + socket.placeBid({ side, amount })} + /> + + + {canManageAuction && ( +
+
+ Auction Controls
- )} - - - - - )} + {auctionState.phase === 'presenting' && ( + + )} + {auctionState.phase === 'bidding' && ( +
+ + +
+ )} + {auctionState.phase === 'sold' && ( + + )} +
+ )} + + )}
- {/* 레드팀 */}
diff --git a/apps/web/src/pages/HomePage.tsx b/apps/web/src/pages/HomePage.tsx index bb3b8705..25538298 100644 --- a/apps/web/src/pages/HomePage.tsx +++ b/apps/web/src/pages/HomePage.tsx @@ -1,19 +1,19 @@ -import { Link } from "react-router"; -import { - nextMatchSummary, - upcomingMatches, - pastMatches, -} from "../mock"; +import { Link } from 'react-router'; +import { mapApiMatchToMatchDetail } from '../api/mappers'; +import { useMatches } from '../api/hooks'; +import { DEFAULT_COMMUNITY_ID } from '../config'; function StatusBadge({ status }: { status: string }) { const styles: Record = { - "모집 중": "bg-green-500/15 text-green-500 border-green-500/20", - "모집 완료": "bg-amber-500/15 text-amber-500 border-amber-500/20", - 예정: "bg-blue-500/15 text-blue-400 border-blue-500/20", + 모집중: 'bg-green-500/15 text-green-500 border-green-500/20', + 팀빌딩: 'bg-amber-500/15 text-amber-500 border-amber-500/20', + 진행중: 'bg-blue-500/15 text-blue-400 border-blue-500/20', + 종료: 'bg-base-content/8 text-base-content/40 border-base-content/10', }; + return ( {status} @@ -28,88 +28,146 @@ function MapBadge({ map }: { map: string }) { ); } +function getStatusLabel(status: string) { + switch (status) { + case 'recruiting': + return '모집중'; + case 'team-built': + return '팀빌딩'; + case 'in-progress': + return '진행중'; + case 'finished': + return '종료'; + default: + return status; + } +} + export default function HomePage() { + const upcomingMatchesQuery = useMatches({ limit: 20 }, DEFAULT_COMMUNITY_ID); + const finishedMatchesQuery = useMatches( + { status: 'finished', limit: 10 }, + DEFAULT_COMMUNITY_ID, + ); + + if (!DEFAULT_COMMUNITY_ID) { + return ( +
+
+ `apps/web/.env.development`의 `VITE_DEFAULT_COMMUNITY_ID`를 먼저 설정해주세요. +
+
+ ); + } + + if (upcomingMatchesQuery.isLoading || finishedMatchesQuery.isLoading) { + return ( +
+ 매치 목록을 불러오는 중... +
+ ); + } + + if (upcomingMatchesQuery.error || finishedMatchesQuery.error) { + return ( +
+ + 매치 목록을 불러오지 못했습니다. + +
+ ); + } + + const upcomingMatches = + upcomingMatchesQuery.data?.map(mapApiMatchToMatchDetail) ?? []; + const finishedMatches = + finishedMatchesQuery.data?.map(mapApiMatchToMatchDetail) ?? []; + const nextMatch = upcomingMatches[0]; + const upcomingCards = nextMatch ? upcomingMatches.slice(1) : upcomingMatches; + return (
- {/* 다음 내전 (Hero) */}

다음 내전

- -
-
-
-
-
-

- {nextMatchSummary.title} -

- + + {nextMatch ? ( + +
+
+
+
+
+

+ {nextMatch.title} +

+ +
+

+ {nextMatch.description} +

+
+ {nextMatch.date} {nextMatch.time} + | + + {nextMatch.participants.length}/{nextMatch.maxParticipants}명 + + | + +
-

- {nextMatchSummary.description} -

-
- - - {nextMatchSummary.date} {nextMatchSummary.time} +
+ + 상세 보기 - | - - - {nextMatchSummary.participants}/{nextMatchSummary.maxParticipants}명 - - | -
-
- - 상세 보기 - -
+ + ) : ( +
+ 아직 등록된 내전이 없습니다.
- + )}
- {/* 예정된 내전 */}

예정된 내전

- {upcomingMatches.map((match) => ( - -
-
-

- {match.title} -

- -
-
-
- - {match.date} {match.time} + {upcomingCards.length > 0 ? ( + upcomingCards.map((match) => ( + +
+
+

+ {match.title} +

+
-
- - {match.participants}/{match.maxParticipants}명 +
+
{match.date} {match.time}
+
+ {match.participants.length}/{match.maxParticipants}명 +
+
+
+
-
- -
-
- - ))} + + )) + ) : ( +
+ 예정된 추가 매치가 없습니다. +
+ )}
- {/* 지난 내전 기록 */}

지난 내전 기록 @@ -126,33 +184,44 @@ export default function HomePage() { - {pastMatches.map((match) => ( - - - {match.date} - - - - {match.title} - - - - - - - {match.participants}명 - - - {match.result} + {finishedMatches.length > 0 ? ( + finishedMatches.map((match) => ( + + + {match.date} + + + + {match.title} + + + + + + + {match.participants.length}명 + + + {match.result ? `${match.result.winner} 승리` : '-'} + + + )) + ) : ( + + + 아직 종료된 내전 기록이 없습니다. - ))} + )}

diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index 5ef42e0a..54e8b089 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -1,23 +1,28 @@ -import { useParams, Link } from "react-router"; +import { useEffect, useState } from 'react'; +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { Link, useNavigate, useParams } from 'react-router'; +import { useAuction, useMatch, useMe } from '../api/hooks'; import { - getMatchById, - positionLabel, - positionIcon, - type MatchDetail, - type Participant, - type Position, - type Team, - type TierInfo, -} from "../mock"; + buildDefaultPreferredPositions, + formatTierLabel, + getTierColorToken, + mapApiMatchToMatchDetail, + type MatchDetailView, + type ParticipantView, + type TeamView, +} from '../api/mappers'; +import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config'; +import { apiFetch, ApiError } from '../lib/api'; +import { positionIcon, positionLabel } from '../lib/league'; +import type { Position } from '../api/types'; -// -- 포지션 배지 -- function PosBadge({ pos, sub }: { pos: Position; sub?: boolean }) { return ( + 티어 정보 없음 +
+ ); + } -// -- 티어 셀 (전시즌 / 현재 / 최고) -- -function TierCell({ tier }: { tier: TierInfo }) { return (
- {tier.previousSeason} - → - - {tier.current} - - - ({tier.peak}) + + {formatTierLabel(participant.tier)} + {participant.tier.leaguePoints > 0 && ( + + {participant.tier.leaguePoints}LP + + )}
); } -// -- 상태 배지 -- -function statusBadge(status: MatchDetail["status"]) { +function statusBadge(status: MatchDetailView['status']) { switch (status) { - case "recruiting": + case 'recruiting': return { - label: "모집 중", - cls: "bg-green-500/15 text-green-500 border-green-500/20", + label: '모집 중', + cls: 'bg-green-500/15 text-green-500 border-green-500/20', }; - case "team-built": + case 'team-built': return { - label: "팀빌딩 완료", - cls: "bg-amber-500/15 text-amber-500 border-amber-500/20", + label: '팀빌딩 완료', + cls: 'bg-amber-500/15 text-amber-500 border-amber-500/20', }; - case "finished": + case 'in-progress': return { - label: "종료", - cls: "bg-base-content/8 text-base-content/40 border-base-content/10", + label: '진행 중', + cls: 'bg-blue-500/15 text-blue-400 border-blue-500/20', + }; + case 'finished': + return { + label: '종료', + cls: 'bg-base-content/8 text-base-content/40 border-base-content/10', }; } } -// -- 참가자 행 -- function ParticipantRow({ - p, + participant, index, assignedPos, }: { - p: Participant; + participant: ParticipantView; index: number; assignedPos?: Position; }) { @@ -99,7 +101,7 @@ function ParticipantRow({
- {p.summonerName} + {participant.summonerName} - #{p.tag} + #{participant.tag}
- + {assignedPos ? ( @@ -125,10 +127,10 @@ function ParticipantRow({ ) : ( <> - + - + )} @@ -136,58 +138,90 @@ function ParticipantRow({ ); } -// -- 참가자 테이블 (팀빌딩 전) -- -function ParticipantTable({ participants }: { participants: Participant[] }) { +function ParticipantTable({ + participants, + maxParticipants, + joined, + canJoin, + onJoin, + isJoining, +}: { + participants: ParticipantView[]; + maxParticipants: number; + joined: boolean; + canJoin: boolean; + onJoin: () => void; + isJoining: boolean; +}) { return ( -
- - - - - - - - - - - - {participants.map((p, i) => ( - - ))} - -
#소환사전 시즌 → 현재 (최고)주 포지션부 포지션
+
+
+

+ 참가자 ({participants.length}/{maxParticipants}) +

+ +
+
+ + + + + + + + + + + + {participants.map((participant, index) => ( + + ))} + +
#소환사현재 티어주 포지션부 포지션
+
+ {participants.length < maxParticipants && ( +
+ + {maxParticipants - participants.length}자리 남음 + +
+ )}
); } -// -- 팀 카드 (팀빌딩 후) -- function TeamCard({ team, - side, isWinner, }: { - team: Team; - side: "blue" | "red"; + team: TeamView; isWinner?: boolean; }) { const borderColor = - side === "blue" ? "border-blue-500/25" : "border-red-500/25"; - const headerBg = side === "blue" ? "bg-blue-500/8" : "bg-red-500/8"; - const sideColor = side === "blue" ? "text-blue-400" : "text-red-400"; - const accentBar = side === "blue" ? "bg-blue-500" : "bg-red-500"; + team.side === 'blue' ? 'border-blue-500/25' : 'border-red-500/25'; + const headerBg = team.side === 'blue' ? 'bg-blue-500/8' : 'bg-red-500/8'; + const sideColor = team.side === 'blue' ? 'text-blue-400' : 'text-red-400'; + const accentBar = team.side === 'blue' ? 'bg-blue-500' : 'bg-red-500'; return ( -
+
- + {team.name} {isWinner && ( @@ -202,17 +236,17 @@ function TeamCard({ # 소환사 - 전 시즌 → 현재 (최고) + 현재 티어 포지션 - {team.participants.map((p, i) => ( + {team.participants.map((participant, index) => ( ))} @@ -221,7 +255,6 @@ function TeamCard({ ); } -// -- 사이드바 카드 -- function SideCard({ title, children, @@ -241,12 +274,95 @@ function SideCard({ ); } -// -- 메인 -- export default function MatchDetailPage() { const { id } = useParams(); - const match = getMatchById(Number(id)); + const navigate = useNavigate(); + const queryClient = useQueryClient(); + const authUserId = useAuthUserId(); + const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); + const meQuery = useMe(); + const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID); + const [blueCaptainUserId, setBlueCaptainUserId] = useState(''); + const [redCaptainUserId, setRedCaptainUserId] = useState(''); - if (!match) { + const joinMatchMutation = useMutation({ + mutationFn: () => + apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants`, { + method: 'POST', + body: JSON.stringify({ + preferredPositions: + meQuery.data?.user?.preferredPositions.length + ? meQuery.data.user.preferredPositions.slice(0, 5) + : buildDefaultPreferredPositions(), + }), + }), + onSuccess: async () => { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: ['match', DEFAULT_COMMUNITY_ID, id ?? null], + }), + queryClient.invalidateQueries({ + queryKey: ['matches', DEFAULT_COMMUNITY_ID], + }), + ]); + }, + }); + + const startAuctionMutation = useMutation({ + mutationFn: () => + apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/auction`, { + method: 'POST', + body: JSON.stringify({ + captains: [ + { side: 'blue', userId: blueCaptainUserId }, + { side: 'red', userId: redCaptainUserId }, + ], + initialPoints: 1000, + maxTimerSeconds: 30, + }), + }), + onSuccess: async () => { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: ['match', DEFAULT_COMMUNITY_ID, id ?? null], + }), + queryClient.invalidateQueries({ + queryKey: ['auction', DEFAULT_COMMUNITY_ID, id ?? null], + }), + ]); + navigate(`/match/${id}/auction`); + }, + }); + + useEffect(() => { + const participants = matchQuery.data?.participants ?? []; + if (!blueCaptainUserId && participants[0]) { + setBlueCaptainUserId(participants[0].userId); + } + if (!redCaptainUserId && participants[1]) { + setRedCaptainUserId(participants[1].userId); + } + }, [blueCaptainUserId, redCaptainUserId, matchQuery.data?.participants]); + + if (!DEFAULT_COMMUNITY_ID) { + return ( +
+ + `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. + +
+ ); + } + + if (matchQuery.isLoading) { + return ( +
+ 매치 정보를 불러오는 중... +
+ ); + } + + if (matchQuery.error || !matchQuery.data) { return (

내전을 찾을 수 없습니다

@@ -257,11 +373,24 @@ export default function MatchDetailPage() { ); } + const match = mapApiMatchToMatchDetail(matchQuery.data); const si = statusBadge(match.status); + const canManageAuction = + meQuery.data?.user?.role === 'owner' || meQuery.data?.user?.role === 'admin'; + const auctionNotStarted = + auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404; + const showAuctionLink = Boolean(auctionQuery.data); + const canStartAuction = + canManageAuction && + match.status === 'recruiting' && + matchQuery.data.participants.length >= 2 && + auctionNotStarted && + blueCaptainUserId && + redCaptainUserId && + blueCaptainUserId !== redCaptainUserId; return (
- {/* 뒤로가기 */} - {/* 헤더 */}

@@ -295,43 +423,11 @@ export default function MatchDetailPage() { {si.label}

-

- {match.description} -

+

{match.description}

- - - - - {match.date} {match.time} - + {match.date} {match.time} | - - - - + {match.participants.length}/{match.maxParticipants}명 | @@ -341,12 +437,23 @@ export default function MatchDetailPage() {
- {/* 결과 배너 (종료된 경우) */} - {match.status === "finished" && match.result && ( + {joinMatchMutation.error instanceof Error && ( +
+ {joinMatchMutation.error.message} +
+ )} + + {startAuctionMutation.error instanceof Error && ( +
+ {startAuctionMutation.error.message} +
+ )} + + {match.status === 'finished' && match.result && (
{match.result.blueScore} @@ -359,7 +466,7 @@ export default function MatchDetailPage() { VS
{match.result.redScore} @@ -376,70 +483,131 @@ export default function MatchDetailPage() { )}
- {/* 좌측: 참가자 / 팀 */} -
- {match.status === "recruiting" ? ( -
-
-

- 참가자 ({match.participants.length}/{match.maxParticipants}) -

- -
- - {match.participants.length < match.maxParticipants && ( -
- - {match.maxParticipants - match.participants.length}자리 남음 - +
+ {match.status === 'recruiting' ? ( + <> + joinMatchMutation.mutate()} + isJoining={joinMatchMutation.isPending} + /> + + {canManageAuction && ( +
+
+

+ 경매 시작 +

+

+ 두 팀장을 선택하면 경매를 시작할 수 있습니다. +

+
+ + {showAuctionLink ? ( + + 경매 페이지 열기 + + ) : ( +
+ + +
+ + {!authUserId && ( + + Dev Auth에 owner/admin User ID를 먼저 입력해주세요. + + )} +
+
+ )}
)} -
+ ) : (
- {match.teams?.map((team, i) => ( + {match.teams.map((team) => ( ))} + {showAuctionLink && ( +
+ + 경매 페이지 열기 + +
+ )}
)}
- {/* 우측: 사이드바 */}
- {/* 일정 */} - {match.schedule && match.schedule.length > 0 && ( + {match.schedule.length > 0 && (
    - {match.schedule.map((s, i) => ( -
  • + {match.schedule.map((item, index) => ( +
  • - {s.time} + {item.time} - {s.label} + {item.label}
  • ))}
)} - {/* 상품 */} - {match.prizes && match.prizes.length > 0 && ( + {match.prizes.length > 0 && (
    - {match.prizes.map((prize, i) => ( + {match.prizes.map((prize, index) => (
  • ▸ @@ -450,13 +618,12 @@ export default function MatchDetailPage() { )} - {/* 안내사항 */} - {match.notices && match.notices.length > 0 && ( + {match.notices.length > 0 && (
      - {match.notices.map((notice, i) => ( + {match.notices.map((notice, index) => (
    • • diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 4ff4f8fe..828a1bc1 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -5,4 +5,8 @@ import tailwindcss from "@tailwindcss/vite"; // https://vite.dev/config/ export default defineConfig({ plugins: [react(), tailwindcss()], + server: { + host: "0.0.0.0", + allowedHosts: ["126.dahyeon.us"], + }, }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f20da3a9..2a70695f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -22,13 +22,19 @@ importers: version: 4.0.4(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(rxjs@7.8.2) '@nestjs/core': specifier: ^11.0.1 - version: 11.1.18(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@11.1.18)(reflect-metadata@0.2.2)(rxjs@7.8.2) + version: 11.1.18(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@11.1.18)(@nestjs/websockets@11.1.19)(reflect-metadata@0.2.2)(rxjs@7.8.2) '@nestjs/platform-express': specifier: ^11.0.1 version: 11.1.18(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.18) + '@nestjs/platform-socket.io': + specifier: ^11.1.19 + version: 11.1.19(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/websockets@11.1.19)(rxjs@7.8.2) '@nestjs/swagger': specifier: ^11.2.7 version: 11.2.7(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.18)(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2) + '@nestjs/websockets': + specifier: ^11.1.19 + version: 11.1.19(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.18)(@nestjs/platform-socket.io@11.1.19)(reflect-metadata@0.2.2)(rxjs@7.8.2) class-transformer: specifier: ^0.5.1 version: 0.5.1 @@ -47,6 +53,9 @@ importers: rxjs: specifier: ^7.8.1 version: 7.8.2 + socket.io: + specifier: ^4.8.3 + version: 4.8.3 temporal-polyfill: specifier: ^0.3.2 version: 0.3.2 @@ -123,6 +132,9 @@ importers: apps/web: dependencies: + '@tanstack/react-query': + specifier: ^5.100.1 + version: 5.100.1(react@19.2.5) react: specifier: ^19.2.4 version: 19.2.5 @@ -132,6 +144,9 @@ importers: react-router: specifier: ^7.14.0 version: 7.14.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + socket.io-client: + specifier: ^4.8.3 + version: 4.8.3 devDependencies: '@eslint/js': specifier: ^9.39.4 @@ -931,6 +946,13 @@ packages: '@nestjs/common': ^11.0.0 '@nestjs/core': ^11.0.0 + '@nestjs/platform-socket.io@11.1.19': + resolution: {integrity: sha512-gu1nPIEaP5Qjjg/Cl8wXyvwGpdZGzgbtK4KcH65YRAA+GTKUkIHb4BNpLJ27Ymq/wqLJKNEbCjajfzD0BEjMGA==} + peerDependencies: + '@nestjs/common': ^11.0.0 + '@nestjs/websockets': ^11.0.0 + rxjs: ^7.1.0 + '@nestjs/schematics@11.0.10': resolution: {integrity: sha512-q9lr0wGwgBHLarD4uno3XiW4JX60WPlg2VTgbqPHl/6bT4u1IEEzj+q9Tad3bVnqL5mlDF3vrZ2tj+x13CJpmw==} peerDependencies: @@ -966,6 +988,18 @@ packages: '@nestjs/platform-express': optional: true + '@nestjs/websockets@11.1.19': + resolution: {integrity: sha512-2qo8jtIwwwgkqAI1BtnJ02EaFLrRkKA39eYXS8IhZCHilhBHCWdjnJ5cLcFq4oF+s+KZ7LcLGD/3stxJy8ijzg==} + peerDependencies: + '@nestjs/common': ^11.0.0 + '@nestjs/core': ^11.0.0 + '@nestjs/platform-socket.io': ^11.0.0 + reflect-metadata: ^0.1.12 || ^0.2.0 + rxjs: ^7.1.0 + peerDependenciesMeta: + '@nestjs/platform-socket.io': + optional: true + '@noble/hashes@1.8.0': resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==} engines: {node: ^14.21.3 || >=16} @@ -1264,6 +1298,9 @@ packages: resolution: {integrity: sha512-O/IEdcCUKkubz60tFbGA7ceITTAJsty+lBjNoorP4Z6XRqaFb/OjQjZODophEcuq68nKm6/0r+6/lLQ+XVpk8g==} engines: {node: '>=18.0.0'} + '@socket.io/component-emitter@3.1.2': + resolution: {integrity: sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==} + '@tailwindcss/node@4.2.2': resolution: {integrity: sha512-pXS+wJ2gZpVXqFaUEjojq7jzMpTGf8rU6ipJz5ovJV6PUGmlJ+jvIwGrzdHdQ80Sg+wmQxUFuoW1UAAwHNEdFA==} @@ -1354,6 +1391,14 @@ packages: peerDependencies: vite: ^5.2.0 || ^6 || ^7 || ^8 + '@tanstack/query-core@5.100.1': + resolution: {integrity: sha512-awvQhOO/2TrSCHE5LKKsXcvvj6WSBncwEcMFCB/ez0Qs0b17iyyivoGArNV3HFfXryZwCpnb/olsaBBKrIbtSw==} + + '@tanstack/react-query@5.100.1': + resolution: {integrity: sha512-UgWRLhQKprC37SsO6y1zRabOqDmM2gsdTNPbqTT35yl7kOOhwXU4nyfOiGHXPwoEFJV1IpSk85hjIFjNFWVpzw==} + peerDependencies: + react: ^18 || ^19 + '@tokenizer/inflate@0.4.1': resolution: {integrity: sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==} engines: {node: '>=18'} @@ -1397,6 +1442,9 @@ packages: '@types/cookiejar@2.1.5': resolution: {integrity: sha512-he+DHOWReW0nghN24E1WUqM0efK4kI9oTqDm6XmK8ZPe2djZ90BSNdGnIyCLzCPw7/pogPlGbzI2wHGGmi4O/Q==} + '@types/cors@2.8.19': + resolution: {integrity: sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==} + '@types/eslint-scope@3.7.7': resolution: {integrity: sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==} @@ -1474,6 +1522,9 @@ packages: '@types/whatwg-url@13.0.0': resolution: {integrity: sha512-N8WXpbE6Wgri7KUSvrmQcqrMllKZ9uxkYWMt+mCSGwNc0Hsw9VQTW7ApqI4XNrx6/SaM2QQJCzMPDEXE058s+Q==} + '@types/ws@8.18.1': + resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==} + '@types/yargs-parser@21.0.3': resolution: {integrity: sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==} @@ -1701,6 +1752,10 @@ packages: '@xtuc/long@4.2.2': resolution: {integrity: sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==} + accepts@1.3.8: + resolution: {integrity: sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==} + engines: {node: '>= 0.6'} + accepts@2.0.0: resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==} engines: {node: '>= 0.6'} @@ -1852,6 +1907,10 @@ packages: base64-js@1.5.1: resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} + base64id@2.0.0: + resolution: {integrity: sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==} + engines: {node: ^4.5.0 || >= 5.9} + baseline-browser-mapping@2.10.17: resolution: {integrity: sha512-HdrkN8eVG2CXxeifv/VdJ4A4RSra1DTW8dc/hdxzhGHN8QePs6gKaWM9pHPcpCoxYZJuOZ8drHmbdpLHjCYjLA==} engines: {node: '>=6.0.0'} @@ -2174,6 +2233,17 @@ packages: resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==} engines: {node: '>= 0.8'} + engine.io-client@6.6.4: + resolution: {integrity: sha512-+kjUJnZGwzewFDw951CDWcwj35vMNf2fcj7xQWOctq1F2i1jkDdVvdFG9kM/BEChymCH36KgjnW0NsL58JYRxw==} + + engine.io-parser@5.2.3: + resolution: {integrity: sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==} + engines: {node: '>=10.0.0'} + + engine.io@6.6.6: + resolution: {integrity: sha512-U2SN0w3OpjFRVlrc17E6TMDmH58Xl9rai1MblNjAdwWp07Kk+llmzX0hjDpQdrDGzwmvOtgM5yI+meYX6iZ2xA==} + engines: {node: '>=10.2.0'} + enhanced-resolve@5.20.1: resolution: {integrity: sha512-Qohcme7V1inbAfvjItgw0EaxVX5q2rdVEZHRBrEQdRZTssLDGsL8Lwrznl8oQ/6kuTJONLaDcGjkNP247XEhcA==} engines: {node: '>=10.13.0'} @@ -3127,6 +3197,10 @@ packages: natural-compare@1.4.0: resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + negotiator@0.6.3: + resolution: {integrity: sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==} + engines: {node: '>= 0.6'} + negotiator@1.0.0: resolution: {integrity: sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==} engines: {node: '>= 0.6'} @@ -3162,6 +3236,10 @@ packages: resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} engines: {node: '>=0.10.0'} + object-hash@3.0.0: + resolution: {integrity: sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==} + engines: {node: '>= 6'} + object-inspect@1.13.4: resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==} engines: {node: '>= 0.4'} @@ -3472,6 +3550,21 @@ packages: resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==} engines: {node: '>=8'} + socket.io-adapter@2.5.6: + resolution: {integrity: sha512-DkkO/dz7MGln0dHn5bmN3pPy+JmywNICWrJqVWiVOyvXjWQFIv9c2h24JrQLLFJ2aQVQf/Cvl1vblnd4r2apLQ==} + + socket.io-client@4.8.3: + resolution: {integrity: sha512-uP0bpjWrjQmUt5DTHq9RuoCBdFJF10cdX9X+a368j/Ft0wmaVgxlrjvK3kjvgCODOMMOz9lcaRzxmso0bTWZ/g==} + engines: {node: '>=10.0.0'} + + socket.io-parser@4.2.6: + resolution: {integrity: sha512-asJqbVBDsBCJx0pTqw3WfesSY0iRX+2xzWEWzrpcH7L6fLzrhyF8WPI8UaeM4YCuDfpwA/cgsdugMsmtz8EJeg==} + engines: {node: '>=10.0.0'} + + socket.io@4.8.3: + resolution: {integrity: sha512-2Dd78bqzzjE6KPkD5fHZmDAKRNe3J15q+YHDrIsy9WEkqttc7GY+kT9OBLSMaPbQaEd0x1BjcmtMtXkfpc+T5A==} + engines: {node: '>=10.2.0'} + source-map-js@1.2.1: resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} engines: {node: '>=0.10.0'} @@ -3922,6 +4015,22 @@ packages: resolution: {integrity: sha512-+QU2zd6OTD8XWIJCbffaiQeH9U73qIqafo1x6V1snCWYGJf6cVE0cDR4D8xRzcEnfI21IFrUPzPGtcPf8AC+Rw==} engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} + ws@8.18.3: + resolution: {integrity: sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + + xmlhttprequest-ssl@2.1.2: + resolution: {integrity: sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==} + engines: {node: '>=0.4.0'} + y18n@5.0.8: resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} engines: {node: '>=10'} @@ -5149,7 +5258,7 @@ snapshots: lodash: 4.18.1 rxjs: 7.8.2 - '@nestjs/core@11.1.18(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@11.1.18)(reflect-metadata@0.2.2)(rxjs@7.8.2)': + '@nestjs/core@11.1.18(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@11.1.18)(@nestjs/websockets@11.1.19)(reflect-metadata@0.2.2)(rxjs@7.8.2)': dependencies: '@nestjs/common': 11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2) '@nuxt/opencollective': 0.4.1 @@ -5162,6 +5271,7 @@ snapshots: uid: 2.0.2 optionalDependencies: '@nestjs/platform-express': 11.1.18(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.18) + '@nestjs/websockets': 11.1.19(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.18)(@nestjs/platform-socket.io@11.1.19)(reflect-metadata@0.2.2)(rxjs@7.8.2) '@nestjs/mapped-types@2.1.1(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)': dependencies: @@ -5174,7 +5284,7 @@ snapshots: '@nestjs/platform-express@11.1.18(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.18)': dependencies: '@nestjs/common': 11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2) - '@nestjs/core': 11.1.18(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@11.1.18)(reflect-metadata@0.2.2)(rxjs@7.8.2) + '@nestjs/core': 11.1.18(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@11.1.18)(@nestjs/websockets@11.1.19)(reflect-metadata@0.2.2)(rxjs@7.8.2) cors: 2.8.6 express: 5.2.1 multer: 2.1.1 @@ -5183,6 +5293,18 @@ snapshots: transitivePeerDependencies: - supports-color + '@nestjs/platform-socket.io@11.1.19(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/websockets@11.1.19)(rxjs@7.8.2)': + dependencies: + '@nestjs/common': 11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2) + '@nestjs/websockets': 11.1.19(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.18)(@nestjs/platform-socket.io@11.1.19)(reflect-metadata@0.2.2)(rxjs@7.8.2) + rxjs: 7.8.2 + socket.io: 4.8.3 + tslib: 2.8.1 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + '@nestjs/schematics@11.0.10(chokidar@4.0.3)(typescript@5.9.3)': dependencies: '@angular-devkit/core': 19.2.23(chokidar@4.0.3) @@ -5198,7 +5320,7 @@ snapshots: dependencies: '@microsoft/tsdoc': 0.16.0 '@nestjs/common': 11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2) - '@nestjs/core': 11.1.18(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@11.1.18)(reflect-metadata@0.2.2)(rxjs@7.8.2) + '@nestjs/core': 11.1.18(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@11.1.18)(@nestjs/websockets@11.1.19)(reflect-metadata@0.2.2)(rxjs@7.8.2) '@nestjs/mapped-types': 2.1.1(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2) js-yaml: 4.1.1 lodash: 4.18.1 @@ -5212,11 +5334,23 @@ snapshots: '@nestjs/testing@11.1.18(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.18)(@nestjs/platform-express@11.1.18)': dependencies: '@nestjs/common': 11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2) - '@nestjs/core': 11.1.18(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@11.1.18)(reflect-metadata@0.2.2)(rxjs@7.8.2) + '@nestjs/core': 11.1.18(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@11.1.18)(@nestjs/websockets@11.1.19)(reflect-metadata@0.2.2)(rxjs@7.8.2) tslib: 2.8.1 optionalDependencies: '@nestjs/platform-express': 11.1.18(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.18) + '@nestjs/websockets@11.1.19(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.18)(@nestjs/platform-socket.io@11.1.19)(reflect-metadata@0.2.2)(rxjs@7.8.2)': + dependencies: + '@nestjs/common': 11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2) + '@nestjs/core': 11.1.18(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@11.1.18)(@nestjs/websockets@11.1.19)(reflect-metadata@0.2.2)(rxjs@7.8.2) + iterare: 1.2.1 + object-hash: 3.0.0 + reflect-metadata: 0.2.2 + rxjs: 7.8.2 + tslib: 2.8.1 + optionalDependencies: + '@nestjs/platform-socket.io': 11.1.19(@nestjs/common@11.1.18(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/websockets@11.1.19)(rxjs@7.8.2) + '@noble/hashes@1.8.0': {} '@nuxt/opencollective@0.4.1': @@ -5569,6 +5703,8 @@ snapshots: dependencies: tslib: 2.8.1 + '@socket.io/component-emitter@3.1.2': {} + '@tailwindcss/node@4.2.2': dependencies: '@jridgewell/remapping': 2.3.5 @@ -5637,6 +5773,13 @@ snapshots: tailwindcss: 4.2.2 vite: 8.0.8(@types/node@24.12.2)(jiti@2.6.1)(terser@5.46.1) + '@tanstack/query-core@5.100.1': {} + + '@tanstack/react-query@5.100.1(react@19.2.5)': + dependencies: + '@tanstack/query-core': 5.100.1 + react: 19.2.5 + '@tokenizer/inflate@0.4.1': dependencies: debug: 4.4.3 @@ -5691,6 +5834,10 @@ snapshots: '@types/cookiejar@2.1.5': {} + '@types/cors@2.8.19': + dependencies: + '@types/node': 24.12.2 + '@types/eslint-scope@3.7.7': dependencies: '@types/eslint': 9.6.1 @@ -5784,6 +5931,10 @@ snapshots: dependencies: '@types/webidl-conversions': 7.0.3 + '@types/ws@8.18.1': + dependencies: + '@types/node': 24.12.2 + '@types/yargs-parser@21.0.3': {} '@types/yargs@17.0.35': @@ -6106,6 +6257,11 @@ snapshots: '@xtuc/long@4.2.2': {} + accepts@1.3.8: + dependencies: + mime-types: 2.1.35 + negotiator: 0.6.3 + accepts@2.0.0: dependencies: mime-types: 3.0.2 @@ -6263,6 +6419,8 @@ snapshots: base64-js@1.5.1: {} + base64id@2.0.0: {} + baseline-browser-mapping@2.10.17: {} bl@4.1.0: @@ -6535,6 +6693,37 @@ snapshots: encodeurl@2.0.0: {} + engine.io-client@6.6.4: + dependencies: + '@socket.io/component-emitter': 3.1.2 + debug: 4.4.3 + engine.io-parser: 5.2.3 + ws: 8.18.3 + xmlhttprequest-ssl: 2.1.2 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + + engine.io-parser@5.2.3: {} + + engine.io@6.6.6: + dependencies: + '@types/cors': 2.8.19 + '@types/node': 24.12.2 + '@types/ws': 8.18.1 + accepts: 1.3.8 + base64id: 2.0.0 + cookie: 0.7.2 + cors: 2.8.6 + debug: 4.4.3 + engine.io-parser: 5.2.3 + ws: 8.18.3 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + enhanced-resolve@5.20.1: dependencies: graceful-fs: 4.2.11 @@ -7643,6 +7832,8 @@ snapshots: natural-compare@1.4.0: {} + negotiator@0.6.3: {} + negotiator@1.0.0: {} neo-async@2.6.2: {} @@ -7669,6 +7860,8 @@ snapshots: object-assign@4.1.1: {} + object-hash@3.0.0: {} + object-inspect@1.13.4: {} on-finished@2.4.1: @@ -7994,6 +8187,47 @@ snapshots: slash@3.0.0: {} + socket.io-adapter@2.5.6: + dependencies: + debug: 4.4.3 + ws: 8.18.3 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + + socket.io-client@4.8.3: + dependencies: + '@socket.io/component-emitter': 3.1.2 + debug: 4.4.3 + engine.io-client: 6.6.4 + socket.io-parser: 4.2.6 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + + socket.io-parser@4.2.6: + dependencies: + '@socket.io/component-emitter': 3.1.2 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + socket.io@4.8.3: + dependencies: + accepts: 1.3.8 + base64id: 2.0.0 + cors: 2.8.6 + debug: 4.4.3 + engine.io: 6.6.6 + socket.io-adapter: 2.5.6 + socket.io-parser: 4.2.6 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + source-map-js@1.2.1: {} source-map-support@0.5.13: @@ -8450,6 +8684,10 @@ snapshots: imurmurhash: 0.1.4 signal-exit: 4.1.0 + ws@8.18.3: {} + + xmlhttprequest-ssl@2.1.2: {} + y18n@5.0.8: {} yallist@3.1.1: {}