From e4726a7da8da3b80b36d5240a9f36cc73b23c69a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=EB=8B=A4=ED=98=84=20=28Dahyeon=20Park=29?= Date: Fri, 1 May 2026 17:45:21 +0900 Subject: [PATCH] feat(web): implement tournament support client --- apps/web/.env.development | 7 + apps/web/.env.example | 7 + apps/web/.env.production | 8 + apps/web/.env.test | 6 + apps/web/.gitignore | 24 + apps/web/eslint.config.js | 23 + apps/web/index.html | 13 + apps/web/package.json | 45 + apps/web/public/_headers | 9 + apps/web/public/_redirects | 1 + apps/web/public/auth/silent-callback.html | 8 + apps/web/public/favicon.svg | 1 + apps/web/public/icons.svg | 24 + apps/web/public/riot.txt | 1 + apps/web/src/App.css | 1 + apps/web/src/App.tsx | 106 ++ apps/web/src/api/hooks.ts | 664 +++++++++++ apps/web/src/api/mappers.ts | 522 +++++++++ apps/web/src/api/types.ts | 737 ++++++++++++ apps/web/src/api/useAuctionSocket.ts | 121 ++ apps/web/src/api/useRiotRefreshSocket.ts | 73 ++ apps/web/src/assets/hero.png | Bin 0 -> 44919 bytes apps/web/src/assets/position/Bottom_icon.png | Bin 0 -> 665 bytes apps/web/src/assets/position/Jungle_icon.png | Bin 0 -> 2322 bytes apps/web/src/assets/position/Middle_icon.png | Bin 0 -> 574 bytes .../src/assets/position/Specialist_icon.png | Bin 0 -> 713 bytes apps/web/src/assets/position/Support_icon.png | Bin 0 -> 1335 bytes apps/web/src/assets/position/Top_icon.png | Bin 0 -> 582 bytes apps/web/src/assets/react.svg | 1 + apps/web/src/assets/vite.svg | 1 + apps/web/src/components/DevAuthSwitcher.tsx | 58 + apps/web/src/config.ts | 92 ++ apps/web/src/index.css | 46 + apps/web/src/main.tsx | 26 + apps/web/src/pages/AuctionPage.tsx | 802 +++++++++++++ apps/web/src/pages/AuthCallback.tsx | 17 + .../src/pages/CommunityInternalStatsPage.tsx | 388 +++++++ apps/web/src/pages/HomePage.tsx | 239 ++++ .../web/src/pages/InternalMatchDetailPage.tsx | 262 +++++ apps/web/src/pages/Login.tsx | 47 + apps/web/src/pages/MatchDetailPage.tsx | 885 ++++++++++++++ apps/web/src/pages/UserHistoryPage.tsx | 1019 +++++++++++++++++ apps/web/src/pages/admin/LegacyImportPage.tsx | 407 +++++++ .../web/src/pages/admin/LegacyMatchesPage.tsx | 252 ++++ .../src/pages/admin/TournamentCodesPage.tsx | 355 ++++++ apps/web/tsconfig.app.json | 25 + apps/web/tsconfig.json | 7 + apps/web/tsconfig.node.json | 24 + apps/web/vite.config.ts | 12 + 49 files changed, 7366 insertions(+) create mode 100644 apps/web/.env.development create mode 100644 apps/web/.env.example create mode 100644 apps/web/.env.production create mode 100644 apps/web/.env.test create mode 100644 apps/web/.gitignore create mode 100644 apps/web/eslint.config.js create mode 100644 apps/web/index.html create mode 100644 apps/web/package.json create mode 100644 apps/web/public/_headers create mode 100644 apps/web/public/_redirects create mode 100644 apps/web/public/auth/silent-callback.html create mode 100644 apps/web/public/favicon.svg create mode 100644 apps/web/public/icons.svg create mode 100644 apps/web/public/riot.txt create mode 100644 apps/web/src/App.css create mode 100644 apps/web/src/App.tsx create mode 100644 apps/web/src/api/hooks.ts create mode 100644 apps/web/src/api/mappers.ts create mode 100644 apps/web/src/api/types.ts create mode 100644 apps/web/src/api/useAuctionSocket.ts create mode 100644 apps/web/src/api/useRiotRefreshSocket.ts create mode 100644 apps/web/src/assets/hero.png create mode 100644 apps/web/src/assets/position/Bottom_icon.png create mode 100644 apps/web/src/assets/position/Jungle_icon.png create mode 100644 apps/web/src/assets/position/Middle_icon.png create mode 100644 apps/web/src/assets/position/Specialist_icon.png create mode 100644 apps/web/src/assets/position/Support_icon.png create mode 100644 apps/web/src/assets/position/Top_icon.png create mode 100644 apps/web/src/assets/react.svg create mode 100644 apps/web/src/assets/vite.svg create mode 100644 apps/web/src/components/DevAuthSwitcher.tsx create mode 100644 apps/web/src/config.ts create mode 100644 apps/web/src/index.css create mode 100644 apps/web/src/main.tsx create mode 100644 apps/web/src/pages/AuctionPage.tsx create mode 100644 apps/web/src/pages/AuthCallback.tsx create mode 100644 apps/web/src/pages/CommunityInternalStatsPage.tsx create mode 100644 apps/web/src/pages/HomePage.tsx create mode 100644 apps/web/src/pages/InternalMatchDetailPage.tsx create mode 100644 apps/web/src/pages/Login.tsx create mode 100644 apps/web/src/pages/MatchDetailPage.tsx create mode 100644 apps/web/src/pages/UserHistoryPage.tsx create mode 100644 apps/web/src/pages/admin/LegacyImportPage.tsx create mode 100644 apps/web/src/pages/admin/LegacyMatchesPage.tsx create mode 100644 apps/web/src/pages/admin/TournamentCodesPage.tsx create mode 100644 apps/web/tsconfig.app.json create mode 100644 apps/web/tsconfig.json create mode 100644 apps/web/tsconfig.node.json create mode 100644 apps/web/vite.config.ts diff --git a/apps/web/.env.development b/apps/web/.env.development new file mode 100644 index 00000000..cd55dbf3 --- /dev/null +++ b/apps/web/.env.development @@ -0,0 +1,7 @@ +VITE_API_BASE_URL=http://localhost:3000 +VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1 +VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3 +VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863 +VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev +VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback +VITE_MSAL_SILENT_REDIRECT_URI=http://localhost:5173/auth/silent-callback.html diff --git a/apps/web/.env.example b/apps/web/.env.example new file mode 100644 index 00000000..969d2d5c --- /dev/null +++ b/apps/web/.env.example @@ -0,0 +1,7 @@ +VITE_API_BASE_URL=http://localhost:3000 +VITE_DEFAULT_COMMUNITY_ID= +VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3 +VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/ +VITE_MSAL_API_SCOPE=api://lolympus-api/access_as_user +VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback +VITE_MSAL_SILENT_REDIRECT_URI=http://localhost:5173/auth/silent-callback.html diff --git a/apps/web/.env.production b/apps/web/.env.production new file mode 100644 index 00000000..64d88a8a --- /dev/null +++ b/apps/web/.env.production @@ -0,0 +1,8 @@ +VITE_API_BASE_URL=https://lolympus-api.dahyeon.us +VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1 +VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3 +VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863 +VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev +VITE_MSAL_REDIRECT_URI=https://lolympus.dahyeon.us/auth/callback +VITE_MSAL_SILENT_REDIRECT_URI=https://lolympus.dahyeon.us/auth/silent-callback.html + diff --git a/apps/web/.env.test b/apps/web/.env.test new file mode 100644 index 00000000..be6c0bbe --- /dev/null +++ b/apps/web/.env.test @@ -0,0 +1,6 @@ +VITE_API_BASE_URL=https://lolympus-test-api.dahyeon.us +VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1 +VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3 +VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863 +VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev +VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback diff --git a/apps/web/.gitignore b/apps/web/.gitignore new file mode 100644 index 00000000..a547bf36 --- /dev/null +++ b/apps/web/.gitignore @@ -0,0 +1,24 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/apps/web/eslint.config.js b/apps/web/eslint.config.js new file mode 100644 index 00000000..5e6b472f --- /dev/null +++ b/apps/web/eslint.config.js @@ -0,0 +1,23 @@ +import js from '@eslint/js' +import globals from 'globals' +import reactHooks from 'eslint-plugin-react-hooks' +import reactRefresh from 'eslint-plugin-react-refresh' +import tseslint from 'typescript-eslint' +import { defineConfig, globalIgnores } from 'eslint/config' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + js.configs.recommended, + tseslint.configs.recommended, + reactHooks.configs.flat.recommended, + reactRefresh.configs.vite, + ], + languageOptions: { + ecmaVersion: 2020, + globals: globals.browser, + }, + }, +]) diff --git a/apps/web/index.html b/apps/web/index.html new file mode 100644 index 00000000..ae9502bc --- /dev/null +++ b/apps/web/index.html @@ -0,0 +1,13 @@ + + + + + + + 롤림푸스 - 내전 관리 + + +
+ + + diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100644 index 00000000..03e56ae4 --- /dev/null +++ b/apps/web/package.json @@ -0,0 +1,45 @@ +{ + "name": "web", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "build:test": "tsc -b && vite build --mode test", + "build:prod": "tsc -b && vite build --mode production", + "deploy:test": "node ../../scripts/deploy-cloudflare-pages.mjs test", + "deploy:prod": "node ../../scripts/deploy-cloudflare-pages.mjs prod", + "pages:login": "wrangler login", + "pages:whoami": "wrangler whoami", + "lint": "eslint .", + "preview": "vite preview" + }, + "dependencies": { + "@azure/msal-browser": "^5.8.0", + "@azure/msal-react": "^5.3.1", + "@tanstack/react-query": "^5.100.1", + "react": "^19.2.4", + "react-dom": "^19.2.4", + "react-router": "^7.14.0", + "socket.io-client": "^4.8.3" + }, + "devDependencies": { + "@eslint/js": "^9.39.4", + "@tailwindcss/vite": "^4.2.2", + "@types/node": "^24.12.2", + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^6.0.1", + "daisyui": "^5.5.19", + "eslint": "^9.39.4", + "eslint-plugin-react-hooks": "^7.0.1", + "eslint-plugin-react-refresh": "^0.5.2", + "globals": "^17.4.0", + "tailwindcss": "^4.2.2", + "typescript": "~6.0.2", + "typescript-eslint": "^8.58.0", + "vite": "^8.0.4", + "wrangler": "^4.85.0" + } +} diff --git a/apps/web/public/_headers b/apps/web/public/_headers new file mode 100644 index 00000000..05a20c9e --- /dev/null +++ b/apps/web/public/_headers @@ -0,0 +1,9 @@ +/* + X-Content-Type-Options: nosniff + Referrer-Policy: strict-origin-when-cross-origin + +/assets/* + Cache-Control: public, max-age=31536000, immutable + +/index.html + Cache-Control: no-cache diff --git a/apps/web/public/_redirects b/apps/web/public/_redirects new file mode 100644 index 00000000..7797f7c6 --- /dev/null +++ b/apps/web/public/_redirects @@ -0,0 +1 @@ +/* /index.html 200 diff --git a/apps/web/public/auth/silent-callback.html b/apps/web/public/auth/silent-callback.html new file mode 100644 index 00000000..5db0a78d --- /dev/null +++ b/apps/web/public/auth/silent-callback.html @@ -0,0 +1,8 @@ + + + + + Silent Auth + + + diff --git a/apps/web/public/favicon.svg b/apps/web/public/favicon.svg new file mode 100644 index 00000000..6893eb13 --- /dev/null +++ b/apps/web/public/favicon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/public/icons.svg b/apps/web/public/icons.svg new file mode 100644 index 00000000..e9522193 --- /dev/null +++ b/apps/web/public/icons.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/web/public/riot.txt b/apps/web/public/riot.txt new file mode 100644 index 00000000..3028f46b --- /dev/null +++ b/apps/web/public/riot.txt @@ -0,0 +1 @@ +c47e5251-44c8-4569-a3f6-3cab42fdec98 \ No newline at end of file diff --git a/apps/web/src/App.css b/apps/web/src/App.css new file mode 100644 index 00000000..e00a71c3 --- /dev/null +++ b/apps/web/src/App.css @@ -0,0 +1 @@ +/* App-specific styles — currently using Tailwind + daisyUI */ diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx new file mode 100644 index 00000000..2cfd3c0e --- /dev/null +++ b/apps/web/src/App.tsx @@ -0,0 +1,106 @@ +import { BrowserRouter, Link, Route, Routes } from 'react-router'; +import { useMsal } from '@azure/msal-react'; +import DevAuthSwitcher from './components/DevAuthSwitcher'; +import { DEFAULT_COMMUNITY_ID } from './config'; +import { useCommunity } from './api/hooks'; +import { isMsalConfigured } from './lib/auth/msal.config'; +import AuthCallbackPage from './pages/AuthCallback'; +import HomePage from './pages/HomePage'; +import LoginPage from './pages/Login'; +import MatchDetailPage from './pages/MatchDetailPage'; +import AuctionPage from './pages/AuctionPage'; +import UserHistoryPage from './pages/UserHistoryPage'; +import CommunityInternalStatsPage from './pages/CommunityInternalStatsPage'; +import InternalMatchDetailPage from './pages/InternalMatchDetailPage'; +import LegacyImportPage from './pages/admin/LegacyImportPage'; +import LegacyMatchesPage from './pages/admin/LegacyMatchesPage'; +import TournamentCodesPage from './pages/admin/TournamentCodesPage'; + +function MsalHeaderActions() { + const { accounts, instance } = useMsal(); + const account = instance.getActiveAccount() ?? accounts[0]; + + if (!account) { + return ( + + 로그인 + + ); + } + + return ( + + ); +} + +function App() { + const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID); + const communityLabel = communityQuery.data?.name ?? 'LOLYMPUS'; + + return ( + +
+ + + + } /> + } /> + } /> + } /> + } /> + } /> + } + /> + } + /> + } + /> + } + /> + } + /> + + +
+
+ ); +} + +export default App; diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts new file mode 100644 index 00000000..5853d8e6 --- /dev/null +++ b/apps/web/src/api/hooks.ts @@ -0,0 +1,664 @@ +import { InteractionStatus } from '@azure/msal-browser'; +import { useMsal } from '@azure/msal-react'; +import { useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query'; +import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config'; +import { apiFetch } from '../lib/api'; +import { + isMsalConfigured, + MSAL_API_SCOPE, + MSAL_SILENT_REDIRECT_URI, +} from '../lib/auth/msal.config'; +import type { + ApiAuction, + ApiChampionStatsResponse, + ApiCommunity, + ApiEnqueueRefreshResult, + ApiInternalMatchDetailResponse, + ApiInternalMatchListResponse, + ApiLeaderboardResponse, + LegacyImportJobsResponse, + LegacyImportMembersResponse, + LegacyMatchListResponse, + ApiMatch, + ApiRecentMatchesResponse, + ApiRecentSummaryResponse, + ApiTeamInsightsResponse, + ApiTournamentCode, + ApiUserInternalHistoryResponse, + ApiUserHistoryProfile, + DdragonManifest, + StartLegacyImportRequest, + StartLegacyImportResponse, + MatchStatus, + MatchesResponse, + MeResponse, + RiotQueueGroup, + RiotRankFilter, + RebuildLegacyMatchesResponse, + TournamentCodeBulkUploadResponse, + TournamentCodeListResponse, + TournamentCodeState, + TournamentCodeStatsResponse, + TournamentCodeUploadItem, +} from './types'; + +const DDRAGON_MANIFEST_STALE_MS = 24 * 60 * 60 * 1000; + +interface MatchesQueryOptions { + status?: MatchStatus; + limit?: number; +} + +export interface UserHistoryFilters { + queueGroup?: RiotQueueGroup; + rank?: RiotRankFilter; + seasonId?: string; + championId?: number; +} + +export interface CommunityInternalStatsFilters { + seasonId?: string; + from?: string; + to?: string; + championId?: number; + 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}`, { auth: 'none' }), + 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), + { auth: 'none' }, + ); + 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}`, { + auth: 'none', + }), + 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`, + { auth: 'none' }, + ), + enabled: Boolean(communityId && matchId), + retry: false, + }); +} + +function createUserHistoryPath( + communityId: string, + userId: string, + resource: string, + filters: UserHistoryFilters = {}, + extra: Record = {}, +) { + const searchParams = new URLSearchParams(); + if (filters.queueGroup) searchParams.set('queueGroup', filters.queueGroup); + if (filters.rank) searchParams.set('rank', filters.rank); + if (filters.seasonId) searchParams.set('seasonId', filters.seasonId); + if (filters.championId) searchParams.set('championId', String(filters.championId)); + for (const [key, value] of Object.entries(extra)) { + if (value !== null && value !== undefined && value !== '') { + searchParams.set(key, String(value)); + } + } + + const queryString = searchParams.toString(); + return `/communities/${communityId}/users/${userId}/${resource}${queryString ? `?${queryString}` : ''}`; +} + +export function useUserHistoryProfile( + userId: string | undefined, + communityId = DEFAULT_COMMUNITY_ID, +) { + return useQuery({ + queryKey: ['user-history-profile', communityId, userId ?? null], + queryFn: () => + apiFetch( + `/communities/${communityId}/users/${userId}/history-profile`, + { auth: 'none' }, + ), + enabled: Boolean(communityId && userId), + retry: false, + }); +} + +export function useChampionStats( + userId: string | undefined, + filters: UserHistoryFilters, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: [ + 'user-champion-stats', + communityId, + userId ?? null, + filters.queueGroup ?? null, + filters.rank ?? null, + filters.seasonId ?? null, + ], + queryFn: () => + apiFetch( + createUserHistoryPath(communityId, userId ?? '', 'champion-stats', filters), + { auth: 'none' }, + ), + enabled: Boolean(communityId && userId && enabled), + }); +} + +export function useRecentSummary( + userId: string | undefined, + filters: UserHistoryFilters, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: [ + 'user-recent-summary', + communityId, + userId ?? null, + filters.queueGroup ?? null, + filters.rank ?? null, + filters.seasonId ?? null, + filters.championId ?? null, + ], + queryFn: () => + apiFetch( + createUserHistoryPath(communityId, userId ?? '', 'recent-summary', filters), + { auth: 'none' }, + ), + enabled: Boolean(communityId && userId && enabled), + }); +} + +export function useRecentMatches( + userId: string | undefined, + filters: UserHistoryFilters, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useInfiniteQuery({ + queryKey: [ + 'user-recent-matches', + communityId, + userId ?? null, + filters.queueGroup ?? null, + filters.rank ?? null, + filters.seasonId ?? null, + filters.championId ?? null, + ], + queryFn: ({ pageParam }) => + apiFetch( + createUserHistoryPath(communityId, userId ?? '', 'recent-matches', filters, { + cursor: pageParam, + limit: 10, + }), + { auth: 'none' }, + ), + initialPageParam: null as number | null, + getNextPageParam: (lastPage) => lastPage.nextCursor, + enabled: Boolean(communityId && userId && enabled), + }); +} + +function createCommunityInternalStatsPath( + communityId: string, + resource: string, + filters: CommunityInternalStatsFilters = {}, + extra: Record = {}, +) { + const searchParams = new URLSearchParams(); + if (filters.seasonId) searchParams.set('seasonId', filters.seasonId); + if (filters.from) searchParams.set('from', filters.from); + if (filters.to) searchParams.set('to', filters.to); + if (filters.championId) searchParams.set('championId', String(filters.championId)); + if (filters.limit) searchParams.set('limit', String(filters.limit)); + for (const [key, value] of Object.entries(extra)) { + if (value !== null && value !== undefined && value !== '') { + searchParams.set(key, String(value)); + } + } + + const queryString = searchParams.toString(); + return `/communities/${communityId}/internal-stats/${resource}${queryString ? `?${queryString}` : ''}`; +} + +export function useCommunityInternalStatsMatches( + filters: CommunityInternalStatsFilters, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useInfiniteQuery({ + queryKey: [ + 'community-internal-stats-matches', + communityId, + filters.seasonId ?? null, + filters.from ?? null, + filters.to ?? null, + filters.championId ?? null, + filters.limit ?? null, + ], + queryFn: ({ pageParam }) => + apiFetch( + createCommunityInternalStatsPath(communityId, 'matches', filters, { + cursor: pageParam, + }), + { auth: 'none' }, + ), + initialPageParam: null as number | null, + getNextPageParam: (lastPage) => lastPage.nextCursor, + enabled: Boolean(communityId && enabled), + }); +} + +export function useCommunityLeaderboard( + filters: CommunityInternalStatsFilters, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: [ + 'community-internal-stats-leaderboard', + communityId, + filters.seasonId ?? null, + filters.from ?? null, + filters.to ?? null, + filters.championId ?? null, + ], + queryFn: () => + apiFetch( + createCommunityInternalStatsPath(communityId, 'leaderboard', filters), + { auth: 'none' }, + ), + enabled: Boolean(communityId && enabled), + }); +} + +export function useTeamInsights( + filters: CommunityInternalStatsFilters, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: [ + 'community-internal-stats-team-insights', + communityId, + filters.seasonId ?? null, + filters.from ?? null, + filters.to ?? null, + filters.championId ?? null, + ], + queryFn: () => + apiFetch( + createCommunityInternalStatsPath(communityId, 'team-insights', filters), + { auth: 'none' }, + ), + enabled: Boolean(communityId && enabled), + }); +} + +export function useInternalMatchDetail( + matchId: string | undefined, + communityId = DEFAULT_COMMUNITY_ID, +) { + return useQuery({ + queryKey: ['community-internal-stats-match', communityId, matchId ?? null], + queryFn: () => + apiFetch( + `/communities/${communityId}/internal-stats/match/${matchId}`, + { auth: 'none' }, + ), + enabled: Boolean(communityId && matchId), + retry: false, + }); +} + +export function useUserInternalHistory( + userId: string | undefined, + filters: UserHistoryFilters, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useInfiniteQuery({ + queryKey: [ + 'user-internal-history', + communityId, + userId ?? null, + filters.seasonId ?? null, + filters.championId ?? null, + ], + queryFn: ({ pageParam }) => + apiFetch( + createUserHistoryPath(communityId, userId ?? '', 'internal-history', filters, { + cursor: pageParam, + limit: 10, + }), + { auth: 'none' }, + ), + initialPageParam: null as number | null, + getNextPageParam: (lastPage) => lastPage.nextCursor, + enabled: Boolean(communityId && userId && enabled), + }); +} + +export function useRefreshUserHistory( + userId: string | undefined, + communityId = DEFAULT_COMMUNITY_ID, +) { + return useMutation({ + mutationFn: (body: { + queueGroups: RiotQueueGroup[]; + priority: 'high' | 'low'; + }) => + apiFetch( + `/communities/${communityId}/users/${userId}/refresh`, + { + method: 'POST', + body: JSON.stringify(body), + }, + ), + }); +} + +export function useDdragonManifest(locale = 'ko_KR') { + return useQuery({ + queryKey: ['ddragon-manifest', locale], + queryFn: () => + apiFetch( + `/riot/ddragon/manifest?locale=${encodeURIComponent(locale)}`, + { auth: 'none' }, + ), + staleTime: DDRAGON_MANIFEST_STALE_MS, + gcTime: DDRAGON_MANIFEST_STALE_MS, + refetchOnMount: false, + refetchOnReconnect: false, + }); +} + +export function useTournamentCodeStats( + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: ['tournament-code-stats', communityId], + queryFn: () => + apiFetch( + `/communities/${communityId}/tournament-codes/stats`, + ), + enabled: Boolean(communityId && enabled), + refetchInterval: enabled ? 30_000 : false, + retry: false, + }); +} + +export function useTournamentCodes( + options: { state?: TournamentCodeState; limit?: number }, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: [ + 'tournament-codes', + communityId, + options.state ?? null, + options.limit ?? null, + ], + queryFn: () => { + const searchParams = new URLSearchParams(); + if (options.state) searchParams.set('state', options.state); + if (options.limit) searchParams.set('limit', String(options.limit)); + const queryString = searchParams.toString(); + return apiFetch( + `/communities/${communityId}/tournament-codes${queryString ? `?${queryString}` : ''}`, + ); + }, + enabled: Boolean(communityId && enabled), + refetchInterval: enabled ? 30_000 : false, + retry: false, + }); +} + +export function useBulkUploadTournamentCodes(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (codes: TournamentCodeUploadItem[]) => + apiFetch( + `/communities/${communityId}/tournament-codes`, + { + method: 'POST', + body: JSON.stringify({ codes }), + }, + ), + }); +} + +export function useRestoreTournamentCode(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (codeId: string) => + apiFetch( + `/communities/${communityId}/tournament-codes/${codeId}/release`, + { method: 'POST' }, + ), + }); +} + +export function useDeleteTournamentCode(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (codeId: string) => + apiFetch(`/communities/${communityId}/tournament-codes/${codeId}`, { + method: 'DELETE', + }), + }); +} + +export function usePollTournamentResult(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (matchId: string) => + apiFetch<{ + jobId: string; + matchId: string; + priority: 'high' | 'low'; + attempt: number; + expandedToAllPuuids: boolean; + }>(`/communities/${communityId}/matches/${matchId}/poll-tournament-result`, { + method: 'POST', + }), + }); +} + +export function useLegacyImportMembers( + options: { windowStart?: string; windowEnd?: string }, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: [ + 'legacy-import-members', + communityId, + options.windowStart ?? null, + options.windowEnd ?? null, + ], + queryFn: () => { + const searchParams = new URLSearchParams(); + if (options.windowStart) searchParams.set('windowStart', options.windowStart); + if (options.windowEnd) searchParams.set('windowEnd', options.windowEnd); + const queryString = searchParams.toString(); + return apiFetch( + `/communities/${communityId}/legacy-import/members${queryString ? `?${queryString}` : ''}`, + ); + }, + enabled: Boolean(communityId && enabled), + }); +} + +export function useLegacyImportJobs( + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: ['legacy-import-jobs', communityId], + queryFn: () => + apiFetch( + `/communities/${communityId}/legacy-import-jobs?limit=10`, + ), + enabled: Boolean(communityId && enabled), + refetchInterval: (query) => + query.state.data?.jobs.some( + (job) => job.state === 'pending' || job.state === 'running', + ) + ? 5_000 + : false, + }); +} + +export function useStartLegacyImport(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (body: StartLegacyImportRequest) => + apiFetch( + `/communities/${communityId}/legacy-import`, + { + method: 'POST', + body: JSON.stringify(body), + }, + ), + }); +} + +export function useCancelLegacyImport(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (jobId: string) => + apiFetch( + `/communities/${communityId}/legacy-import-jobs/${jobId}/cancel`, + { method: 'POST' }, + ), + }); +} + +export function useLegacyMatches( + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useInfiniteQuery({ + queryKey: ['legacy-matches', communityId], + queryFn: ({ pageParam }) => { + const searchParams = new URLSearchParams({ limit: '50' }); + if (pageParam) searchParams.set('cursor', String(pageParam)); + return apiFetch( + `/communities/${communityId}/legacy-matches?${searchParams.toString()}`, + ); + }, + initialPageParam: null as number | null, + getNextPageParam: (lastPage) => lastPage.nextCursor, + enabled: Boolean(communityId && enabled), + }); +} + +export function useDeleteMatch(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (matchId: string) => + apiFetch(`/communities/${communityId}/matches/${matchId}`, { + method: 'DELETE', + }), + }); +} + +export function useBulkDeleteLegacyMatches(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (matchIds: string[]) => + apiFetch<{ deleted: number }>( + `/communities/${communityId}/legacy-matches/bulk-delete`, + { + method: 'POST', + body: JSON.stringify({ matchIds }), + }, + ), + }); +} + +export function useRebuildLegacyMatches(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: () => + apiFetch( + `/communities/${communityId}/legacy-matches/rebuild`, + { method: 'POST' }, + ), + }); +} + +export function useMe() { + const authUserId = useAuthUserId(); + const { accounts, inProgress, instance } = useMsal(); + const account = isMsalConfigured + ? (instance.getActiveAccount() ?? accounts[0] ?? null) + : null; + const accountKey = account?.homeAccountId ?? null; + const isMsalReady = + !isMsalConfigured || inProgress === InteractionStatus.None; + + return useQuery({ + queryKey: ['me', authUserId, accountKey], + queryFn: async () => { + if (!account) { + return apiFetch('/me'); + } + + const response = await instance.acquireTokenSilent({ + account, + scopes: [MSAL_API_SCOPE], + redirectUri: MSAL_SILENT_REDIRECT_URI, + }); + return apiFetch('/me', { + headers: { + Authorization: `Bearer ${response.accessToken}`, + }, + }); + }, + enabled: Boolean(authUserId || isMsalReady), + retry: false, + }); +} diff --git a/apps/web/src/api/mappers.ts b/apps/web/src/api/mappers.ts new file mode 100644 index 00000000..9ea5036b --- /dev/null +++ b/apps/web/src/api/mappers.ts @@ -0,0 +1,522 @@ +import type { + ApiAuction, + ApiAuctionPlayerSnapshot, + ApiAuctionTeam, + ApiMatch, + ApiMatchParticipant, + ApiPositionPreference, + ApiRiotLaneStats, + ApiRiotRecentStatsSummary, + ApiTierInfo, + MatchStatus, + Position, + RiotLane, + TeamSide, + TournamentCodeSlotView, +} 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; + gameCount: number; + tournamentCodes: TournamentCodeSlotView[]; + joined: boolean; + participants: ParticipantView[]; + teams: TeamView[]; + result?: { + winner?: string; + winnerSide?: TeamSide; + blueScore: number; + redScore: number; + riotMatchIds: string[]; + games: Array<{ + gameNumber: number; + riotMatchId: string; + winnerSide: TeamSide; + gameCreation: number; + gameDuration: number; + participants: Array<{ + userId: string; + side: TeamSide; + championId: number; + kills: number; + deaths: number; + assists: number; + win: boolean; + }>; + }>; + }; + prizes: string[]; + notices: string[]; + schedule: { time: string; label: string }[]; +} + +export interface AuctionPlayerView extends ParticipantView { + masteries: { + championId: number; + level: number; + points: number; + }[]; + recentStats: { + overall: ApiRiotLaneStats; + byLane: Partial>; + primary: ApiRiotLaneStats | null; + primarySource: "lane" | "overall" | "none"; + }; +} + +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: "챌린저", +}; + +const POSITION_TO_RIOT_LANE: Record = { + TOP: "TOP", + JGL: "JUNGLE", + MID: "MIDDLE", + ADC: "BOTTOM", + SUP: "UTILITY", +}; + +function createEmptyLaneStats(): ApiRiotLaneStats { + return { + games: 0, + wins: 0, + losses: 0, + avgKills: 0, + avgDeaths: 0, + avgAssists: 0, + avgCs: 0, + avgCsPerMin: 0, + mostPlayedChampionIds: [], + }; +} + +function createEmptyRecentStatsView(): AuctionPlayerView["recentStats"] { + return { + overall: createEmptyLaneStats(), + byLane: {}, + primary: null, + primarySource: "none", + }; +} + +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, + ); + const summary = player.recentStatsSummary; + const primary = pickPrimary(summary, mainPosition); + + 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, 5).map((mastery) => ({ + championId: mastery.championId, + level: mastery.championLevel, + points: mastery.championPoints, + })), + recentStats: { + overall: summary?.overall ?? createEmptyLaneStats(), + byLane: summary?.byLane ?? {}, + primary: primary.stats, + primarySource: primary.source, + }, + }; +} + +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: createEmptyRecentStatsView(), + } + : { + ...createFallbackParticipant(member.userId), + masteries: [], + recentStats: createEmptyRecentStatsView(), + }); + + 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), + }; +} + +function pickPrimary( + summary: ApiRiotRecentStatsSummary | undefined, + mainPosition: Position, +): { + stats: ApiRiotLaneStats | null; + source: "lane" | "overall" | "none"; +} { + if (!summary) { + return { stats: null, source: "none" }; + } + + const laneStats = summary.byLane[POSITION_TO_RIOT_LANE[mainPosition]]; + if (laneStats && laneStats.games > 0) { + return { stats: laneStats, source: "lane" }; + } + + if (summary.overall.games > 0) { + return { stats: summary.overall, source: "overall" }; + } + + return { stats: null, source: "none" }; +} + +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?.winnerSide + ? 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, + gameCount: match.gameCount ?? 3, + tournamentCodes: match.tournamentCodes ?? [], + joined: Boolean(match.joined), + participants, + teams, + result: match.result + ? { + winner: match.result.winnerSide + ? winnerTeam?.name ?? sideLabel(match.result.winnerSide) + : undefined, + winnerSide: match.result.winnerSide, + blueScore: match.result.blueScore, + redScore: match.result.redScore, + riotMatchIds: match.result.riotMatchIds, + games: [...(match.result.games ?? [])].sort( + (left, right) => left.gameNumber - right.gameNumber, + ), + } + : 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..0a431f5b --- /dev/null +++ b/apps/web/src/api/types.ts @@ -0,0 +1,737 @@ +export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP'; +export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY'; +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 { + puuid?: string; + championId: number; + championLevel: number; + championPoints: number; + lastPlayTime?: number; + championPointsSinceLastLevel?: number; + championPointsUntilNextLevel?: number; + markRequiredForNextLevel?: number; + tokensEarned?: number; + championSeasonMilestone?: number; + milestoneGrades?: string[]; + nextSeasonMilestone?: Record; +} + +export interface ApiRiotLaneStats { + games: number; + wins: number; + losses: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + avgCs: number; + avgCsPerMin: number; + mostPlayedChampionIds: number[]; +} + +export interface ApiRiotRecentStatsSummary { + overall: ApiRiotLaneStats; + byLane: Partial>; +} + +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; + identityId?: 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; + matchGameCount?: number; + createdAt: string; + updatedAt: string; +} + +export type TournamentCodeState = + | 'available' + | 'reserved' + | 'used' + | 'expired' + | 'released'; + +export type TournamentCodeSlotState = TournamentCodeState | 'pending'; + +export interface TournamentCodeSlotView { + gameNumber: number; + code: string | null; + expiresAt: string | null; + state: TournamentCodeSlotState; + riotMatchId: string | null; +} + +export interface ApiMatchParticipant { + userId: string; + puuid?: string; + 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 ApiMatchGameResultParticipant { + userId: string; + side: TeamSide; + championId: number; + kills: number; + deaths: number; + assists: number; + win: boolean; +} + +export interface ApiMatchGameResult { + gameNumber: number; + riotMatchId: string; + winnerSide: TeamSide; + gameCreation: number; + gameDuration: number; + participants: ApiMatchGameResultParticipant[]; +} + +export interface ApiMatchResult { + winnerSide?: TeamSide; + blueScore: number; + redScore: number; + mvpUserId?: string; + riotMatchIds: string[]; + games: ApiMatchGameResult[]; +} + +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; + gameCount: number; + tournamentCodes?: TournamentCodeSlotView[]; + 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 ApiIdentity { + id: string; + entraOid: string; + tenantId?: string; + email?: string; + displayName?: string; +} + +export interface ApiMembership { + user: ApiUser; + community: ApiCommunity | null; +} + +export interface MeResponse { + identity: ApiIdentity | null; + memberships: ApiMembership[]; +} + +export interface MatchesResponse { + matches: ApiMatch[]; +} + +export interface DdragonChampionEntry { + key: string; + name: string; +} + +export interface DdragonManifest { + version: string; + cdn: string; + locale: string; + champions: Record; + fetchedAt: string; +} + +export type TournamentSpectatorType = 'NONE' | 'LOBBYONLY' | 'ALL'; + +export interface ApiTournamentCode { + _id: string; + code: string; + region: string; + mapType: 'SUMMONERS_RIFT'; + teamSize: number; + spectatorType: TournamentSpectatorType; + metadata?: Record; + expiresAt: string; + state: TournamentCodeState; + matchId?: string; + gameNumber?: number; + reservedAt?: string; + usedAt?: string; + releasedAt?: string; + riotMatchId?: string; + uploadedBy: string; + uploadedAt: string; + source?: string; + notes?: string; + createdAt: string; + updatedAt: string; +} + +export interface TournamentCodeStatsResponse { + byState: Record; + expiringSoon: number; + available: number; +} + +export interface TournamentCodeListResponse { + codes: ApiTournamentCode[]; +} + +export interface TournamentCodeUploadItem { + code: string; + expiresAt: string; + spectatorType?: TournamentSpectatorType; + metadata?: Record; + source?: string; + notes?: string; +} + +export interface TournamentCodeBulkUploadResponse { + inserted: number; + duplicates: string[]; + invalid: Array<{ code: string; reason: string }>; +} + +export type RiotQueueGroup = + | 'all' + | 'summoners-rift' + | 'aram' + | 'urf' + | 'arena' + | 'internal'; +export type RiotRankFilter = 'all' | 'solo' | 'flex' | 'normal'; + +export interface ApiHistorySeason { + id: string; + label: string; + startedAt: string | null; + endedAt: string | null; +} + +export interface ApiUserHistoryProfile { + userId: string; + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + summonerLevel: number; + tiers: ApiTierInfo[]; + season: ApiHistorySeason; + seasons: ApiHistorySeason[]; + lastFetchedAt: string | null; +} + +export interface ApiChampionStatsRow { + championId: number; + games: number; + wins: number; + losses: number; + winRate: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + kda: number; + totalKills: number; + totalDeaths: number; + totalAssists: number; + doubleKills: number; + tripleKills: number; + quadraKills: number; + pentaKills: number; + avgCs: number; + avgCsPerMin: number; +} + +export interface ApiChampionStatsResponse { + queueGroup: RiotQueueGroup; + rank: RiotRankFilter; + queueIds: number[]; + season: ApiHistorySeason; + lastFetchedAt: string | null; + champions: ApiChampionStatsRow[]; + totals: ApiChampionStatsRow; +} + +export interface ApiRecentSummaryResponse { + windowSize: number; + winRate: number; + wins: number; + losses: number; + streak: { type: 'win' | 'loss'; count: number } | null; + kda: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + bestRating: { + rating: number | 'Perfect'; + kills: number; + deaths: number; + assists: number; + matchId: string; + } | null; + positionRates: Partial>; + topChampions: Array<{ + championId: number; + games: number; + winRate: number; + pickRate: number; + avgRating: number; + }>; + lastFetchedAt: string | null; +} + +export interface ApiRecentMatchTeam { + side: 100 | 200; + win: boolean; + objectives?: { baron?: number; dragon?: number; tower?: number }; + participants: Array<{ + puuid: string; + gameName: string; + tagLine: string; + championId: number; + teamPosition: string; + kills: number; + deaths: number; + assists: number; + }>; +} + +export interface ApiRecentMatchView { + matchId: string; + queueId: number; + queueLabel: string; + gameCreation: number; + gameDuration: number; + win: boolean; + remake: boolean; + championId: number; + championLevel: number; + teamPosition: string; + kills: number; + deaths: number; + assists: number; + kda: number; + rating: number; + totalCs: number; + csPerMin: number; + killParticipation: number; + visionScore: number; + controlWardsBought: number; + wardsPlaced: number; + wardsKilled: number; + damageDealtToChampions: number; + damageTaken: number; + goldEarned: number; + items: number[]; + trinket: number; + summonerSpells: [number, number]; + perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + teams: ApiRecentMatchTeam[]; +} + +export interface ApiRecentMatchesResponse { + matches: ApiRecentMatchView[]; + nextCursor: number | null; + lastFetchedAt: string | null; + season: ApiHistorySeason; +} + +export interface ApiInternalMatchCard { + matchId: string; + title: string; + scheduledAt: string; + status: 'finished' | 'in-progress'; + gameCount: number; + blueScore: number; + redScore: number; + winnerSide?: TeamSide; + games: Array<{ + gameNumber: number; + riotMatchId: string | null; + winnerSide: TeamSide | null; + gameDuration: number; + }>; + teams: Array<{ + side: TeamSide; + name: string; + members: Array<{ + userId: string; + summonerName: string; + profileIconId: number; + }>; + }>; +} + +export interface ApiInternalMatchListResponse { + matches: ApiInternalMatchCard[]; + nextCursor: number | null; + season: ApiHistorySeason; +} + +export interface ApiLeaderboardRow { + userId: string; + summonerName: string; + profileIconId: number; + games: number; + wins: number; + losses: number; + winRate: number; + totalKills: number; + totalDeaths: number; + totalAssists: number; + kda: number; + avgGoldPerMin: number; + avgKillParticipation: number; + avgCsPerMin: number; + avgDamageShare: number; + avgVisionScore: number; + byLane: Partial>; + topChampions: Array<{ championId: number; games: number; winRate: number }>; +} + +export interface ApiLeaderboardResponse { + rows: ApiLeaderboardRow[]; + season: ApiHistorySeason; +} + +export interface ApiLeaderHighlight { + metric: number; + userId: string; + summonerName: string; + championId?: number; + matchId?: string; + isSingleGame: boolean; +} + +export interface ApiTeamInsightsResponse { + season: ApiHistorySeason; + sideWinRate: { + blue: number; + red: number; + bluePicks: number; + redPicks: number; + }; + topKda: ApiLeaderHighlight | null; + mostKills: ApiLeaderHighlight | null; + topTeamGpm: ApiLeaderHighlight | null; + topKillParticipation: ApiLeaderHighlight | null; + bestFarm: ApiLeaderHighlight | null; + minGamesThreshold: number; +} + +export interface ApiInternalMatchDetailResponse { + match: ApiInternalMatchCard; + games: Array<{ + gameNumber: number; + riotMatchId: string; + gameCreation: number; + gameDuration: number; + teams: Array<{ + side: TeamSide; + win: boolean; + objectives: { baron: number; dragon: number; tower: number }; + participants: Array<{ + userId: string | null; + summonerName: string; + side: TeamSide; + teamPosition: string; + championId: number; + kills: number; + deaths: number; + assists: number; + cs: number; + csPerMin: number; + gold: number; + gpm: number; + damageDealtToChampions: number; + damageShare: number; + killParticipation: number; + visionScore: number; + items: number[]; + trinket: number; + summonerSpells: [number, number]; + perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + win: boolean; + }>; + }>; + }>; +} + +export interface ApiUserInternalHistoryResponse { + season: ApiHistorySeason; + championStats: ApiChampionStatsResponse; + summary: ApiRecentSummaryResponse; + matches: ApiRecentMatchView[]; + nextCursor: number | null; + lastFetchedAt: string | null; +} + +export type LegacyImportJobState = + | 'pending' + | 'running' + | 'completed' + | 'failed' + | 'cancelled'; + +export interface LegacyImportMemberWindow { + userId: string; + puuid: string; + displayName: string; + gameName: string; + tagLine: string; + profileIconId: number; + isActivated: boolean; + startTime: string; + endTime: string; +} + +export interface LegacyImportMembersResponse { + members: LegacyImportMemberWindow[]; +} + +export interface StartLegacyImportRequest { + windowStart?: string; + windowEnd?: string; + memberOverrides?: Array<{ + userId: string; + startTime?: string; + endTime?: string; + }>; +} + +export interface StartLegacyImportResponse { + jobId: string; + totalMembers: number; + etaSeconds: number; +} + +export interface LegacyImportJob { + _id: string; + jobId: string; + communityId: string; + triggeredBy: string; + startedAt: string; + completedAt?: string; + state: LegacyImportJobState; + windowStart: string; + windowEnd: string; + memberOverrides: Array<{ + userId: string; + puuid: string; + startTime: string; + endTime: string; + }>; + totalMembers: number; + processedMembers: number; + totalDiscoveredMatchIds: number; + totalImportedMatches: number; + totalSkippedDuplicate: number; + totalErrors: number; + averageMemberSeconds?: number; + errors?: Array<{ + puuid?: string; + matchId?: string; + reason: string; + at: string; + }>; +} + +export interface LegacyImportJobsResponse { + jobs: LegacyImportJob[]; +} + +export interface LegacyMatchListItem { + matchId: string; + title: string; + scheduledAt: string; + riotMatchId: string | null; + memberCount: number; + externalCount: number; + blueScore: number; + redScore: number; + winnerSide?: TeamSide; +} + +export interface LegacyMatchListResponse { + matches: LegacyMatchListItem[]; + nextCursor: number | null; +} + +export interface RebuildLegacyMatchesResponse { + scanned: number; + rebuilt: number; + normalizedTitles: number; + skippedMissingRaw: number; + skippedNoKnownParticipants: number; +} + +export type ApiRiotJobPriority = 'high' | 'low'; +export type ApiRiotJobState = 'queued' | 'processing' | 'completed' | 'failed'; + +export interface ApiEnqueueRefreshResult { + parentJobId: string; + subJobs: Array<{ + jobId: string; + queueGroup: RiotQueueGroup; + alreadyQueued: boolean; + etaSeconds: number; + queuePosition: number; + }>; + totalEtaSeconds: number; +} + +export interface ApiRiotRefreshEvent { + parentJobId: string; + jobId: string; + queueGroup: RiotQueueGroup; + puuid: string; + state: ApiRiotJobState; + error?: string; +} diff --git a/apps/web/src/api/useAuctionSocket.ts b/apps/web/src/api/useAuctionSocket.ts new file mode 100644 index 00000000..a9e16146 --- /dev/null +++ b/apps/web/src/api/useAuctionSocket.ts @@ -0,0 +1,121 @@ +import { useEffect, useRef, useState } from 'react'; +import { io, type Socket } from 'socket.io-client'; +import { API_BASE_URL, useAuthUserId } from '../config'; +import { acquireAccessToken } from '../lib/auth/token-provider'; +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; + } + + let disposed = false; + setConnectionStatus('connecting'); + setError(null); + + void (async () => { + const accessToken = await acquireAccessToken().catch((error) => { + console.warn('Failed to acquire socket access token:', error); + return null; + }); + if (disposed) return; + + const socket = io(`${API_BASE_URL}/auction`, { + transports: ['websocket'], + auth: accessToken + ? { token: accessToken } + : authUserId + ? { 'x-auth-user-id': authUserId } + : {}, + }); + + socketRef.current = socket; + + 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 () => { + disposed = true; + const socket = socketRef.current; + 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/api/useRiotRefreshSocket.ts b/apps/web/src/api/useRiotRefreshSocket.ts new file mode 100644 index 00000000..c53aa443 --- /dev/null +++ b/apps/web/src/api/useRiotRefreshSocket.ts @@ -0,0 +1,73 @@ +import { useEffect, useRef, useState } from 'react'; +import { io, type Socket } from 'socket.io-client'; +import { API_BASE_URL } from '../config'; +import type { ApiRiotRefreshEvent } from './types'; + +type ConnectionStatus = + | 'idle' + | 'connecting' + | 'connected' + | 'disconnected' + | 'error'; + +export function useRiotRefreshSocket({ + puuid, + parentJobId, + onEvent, +}: { + puuid?: string; + parentJobId?: string; + onEvent: (event: ApiRiotRefreshEvent) => void; +}) { + const socketRef = useRef(null); + const onEventRef = useRef(onEvent); + const [connectionStatus, setConnectionStatus] = + useState('idle'); + const [error, setError] = useState(null); + + useEffect(() => { + onEventRef.current = onEvent; + }, [onEvent]); + + useEffect(() => { + if (!puuid && !parentJobId) { + setConnectionStatus('idle'); + return; + } + + setConnectionStatus('connecting'); + setError(null); + + const socket = io(`${API_BASE_URL}/riot-refresh`, { + transports: ['websocket'], + }); + socketRef.current = socket; + + socket.on('connect', () => { + setConnectionStatus('connected'); + socket.emit('subscribe', { puuid, parentJobId }); + }); + + socket.on('disconnect', () => { + setConnectionStatus('disconnected'); + }); + + socket.on('riot-refresh', (event: ApiRiotRefreshEvent) => { + onEventRef.current(event); + }); + + socket.on('error', (payload: { message?: string }) => { + setConnectionStatus('error'); + setError(payload.message ?? '전적 갱신 소켓 연결 중 오류가 발생했습니다.'); + }); + + return () => { + socket.removeAllListeners(); + socket.disconnect(); + socketRef.current = null; + setConnectionStatus('idle'); + }; + }, [parentJobId, puuid]); + + return { connectionStatus, error }; +} diff --git a/apps/web/src/assets/hero.png b/apps/web/src/assets/hero.png new file mode 100644 index 0000000000000000000000000000000000000000..cc51a3d20ad4bc961b596a6adfd686685cd84bb0 GIT binary patch literal 44919 zcma%i^5TDbT`tlgo2c`(n!ND-Q6MGAYIbZ-QCh5-QC^YozK_ne*b_MKK#O- zIWy zd$aJVZ?rl%;eiC7d#Sl-cWLv9rA0(UOX(@I3k&yyL+3GaQ4xpb1EGC|i|{byaTI># zBO=0pyZu5XO!hzGNPch4cx%6XJAJpDa<+98BOcYNo1=XER1sv!UW z^>ZDMp%FSmVnt)n^EIR+Nth`vRO^_=UF3EWv75ym{S;#2F8MPot@-y$>ioj!)a1bE zijXPQY;U`qNwl9|wl{W>{FhMSb<>m4{;8Udp4psl)NwFRo(W-T)Y6-qDf=L#U?g<@ zV+T|3+RuE~!E&nodKrkfPcOpJ)&1|p`Tbtd12@MSE8DjWkD|9M>GZsHLf>TTbLx)B z#5K5l%gS7s(yWk?Lj{Nvm`Z-s8xb-Xr`5-xRr%w8v>!oSz{dN*MmxbscQl#Z40qSd z!PQXs-utLEF&$@S#__Lo*pOhG{l(%jyCh-0ME8owiT>U~r&q@MaDRePL(aZAAff9= zBd@*7RZxmiqK^nZH7`bTjIEQw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@SRvGEI2C*&Fp6)||`+^J{q}V(k&UH6x`v6HY%ga|Zzzs+eRs|9MaKTx`lZlikqEY5R%}gn7?6;ktN*;b3zPA!(+?J|S$5`SJ5H+=g{nY-g5Mn~Jhr|m z@tjwcc&%s>tRLj%yUz`$+6@igv3<0Y=`dxEx44hEZ(GE$MQh!MT<2L_`nJ)W?rhje zw0^vkV*ji=%WbqST{WU*)0rz4?cZoE<`ptkpg@5F1qyzP_zyN4`RKUL%sc=9002ov JPDHLkV1myZcL)Fg literal 0 HcmV?d00001 diff --git a/apps/web/src/assets/position/Bottom_icon.png b/apps/web/src/assets/position/Bottom_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..c49002d3e6d7cb5c6dd6a69e64705502d7ca7216 GIT binary patch literal 665 zcmeAS@N?(olHy`uVBq!ia0vp^9U#oX1|)5EEd~lOC3w0xhEy=Vz2!Ph#6YC&VoB-s zxEoCG-syEGoZ%@iFQ2X`yd?3|x-ORKHe2?*D?hitagVjnFEh_cDsYr}e4A$eZnN7Q z9wxU97-Se4nFTEVDLXu1VBrH1edYe!%o#h`j=S6ocF1Z@wt4Rv$35ZJgNl#>h9GH~ z@7z2<(Z_j?j2^iKcm4>nE2I{fe9F60z`%4o;@(%L#EeFjzx;ix1$i7E>=0Q9G>==5 z!{LF2bRv)$EXd-(U@55xWIh&T0E!C9$_rTVxwf;j^!X4y zwDjm#1?gKokG}}Wa!fFL zZ1H+UgNwyEYYhd#zV1FwkCw-)oSA|SUp%q?V zsPO(phRy<;A_Ipk3$;)4EW{K{WzOzd&d1t;NEn`zel7lPa$9Zb*}tySfk}?R)78&q Iol`;+06Q<~HUIzs literal 0 HcmV?d00001 diff --git a/apps/web/src/assets/position/Jungle_icon.png b/apps/web/src/assets/position/Jungle_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..88daaf694d6f7580060ad073166d0f66f20b107f GIT binary patch literal 2322 zcmV+t3GMcYP)YE^6|1R-H&!=Gkj~ehm6bc*yk`6qXn`a4b0%UN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H z81^7|aGDWE|BG}G5@Kn~{@=*IgkpnIImeb-$Mv-hxxdi?P`9q5%SuZR4Cn02e*gwcuiz6vTG8g?w2+^kY zyW+Gsl2jza=zT&+Rz79j-lS@fe>izB&3(x1K{1gxh;AKJAzl3gTY zXhK}KK4@`N&mY&Iu5R8osf}I&=LkOCU^J|^i(cdBn!Gs$xqOq7mZ^|zWmjTM)$Yo3DimBj7H-!C4axsXv(~EcR3S5G#ZUY sqtR$I8jVJy(P%UpjYgx%HZt#}e4c)$Pf0pWo^X7K8d;BJ;c*2p@of-Qo=e_0K|KeNL z|3`)2>vzg1Y!hx!7U{@kf54zp63uAAz2T^n#T`Y3&;l9L_uN3i zD+d`*upcapxhpPU;dkphE6^l6j=szCcYu5b%_g7$=T=oSF&+QO{|=;Fn;@A-QU2Hr0#0$P8*;^4#goCPM#Pd1z1d%%z)#^K>ZGRX5l&I+;DOKt(ttK%oRPj)eyiCWj$`<9Up+11Sn8 bePIawpI6JOmHr2qE*Lyr{an^LB{Ts5p()At literal 0 HcmV?d00001 diff --git a/apps/web/src/assets/position/Specialist_icon.png b/apps/web/src/assets/position/Specialist_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..0ed35aee857e7d3d1075a8d985c6b6661941ed63 GIT binary patch literal 713 zcmeAS@N?(olHy`uVBq!ia0vp^9U#oX3?#Wzf)jw0Q-Dv1E08|1DvuJxw!9Z)jc7@b zUob;`!*`B*idVh0wruvfqOEkdag%S|gm=$@b~7n@x;TbZ#J#$&qG{Zy^(#Bbi0tx~_tP!o0)(?q)ns+_|-5$41sL7njX<&Ix`j z=U)F~ZFH7$S~2(f8NFXlpLvvUBk}8#Y4tO2=4D^_R%^QCd3@S2rv1rxPwYRFvw8dM zx8@tq>8_Ux*Dc$8e#a{H__Vu?OAh4*=^O9ebYwy3+IPV z+#a!8D>rYkVcN6kN(cYx?A_cSxPsJQukmAy3(Tsy>GOE%Qm(z5Lgt1~)B18Ms5CBe z)j4f%(W=yyR_k>_Urb&4Y7bm;YMke)E83n@t5{b?tyc(rCA!3GZ&S$H@CmCvLv$Vk z>U^rSQdcfU_}zn91?<;btaqs0IcWNjZ{0_}MBZ|n<3jwIdFMAC;VpW~cc#_aLj2u> znElPuUzER?zT*Y6_vZAUD|VRsdKYY*vBde#+Z6qutldkC)=fDTR~oc)afnv+RqwlR z53CM)^-|@_sr`TSv(|gx` zWvExGi_=P*FwLoZwU%xQUl{Uj)s$0HRDzbqS$pn%zco6HkL6&t-6Y4L_tkqNqUJ6& zT9H@zbMv2#Wg9}iRc$GOf9iNVv=&t;ucLK6Vk7-dQT literal 0 HcmV?d00001 diff --git a/apps/web/src/assets/position/Support_icon.png b/apps/web/src/assets/position/Support_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..724f6c8c3d3443b6dc25cb342b5037275d2bcbd4 GIT binary patch literal 1335 zcmeAS@N?(olHy`uVBq!ia0vp^9U#oX1|)5EEd~m({PT2i45?szbFdL8#?Y|f?@IBN zOduvh!%fTV7b}_!xE>e2-Jqr?d+%83@8-)7HoV+8ovXZj#bmDUT;4 zPq~UTM~iu$mRrqLo<5j-u%L!Xbdzvdd&;td4QD3F3Tzfk?rd)O^7TZ{k%%Km*k&Js zSAmeaqaPuB_0!qM5(d(`$C?c1NJKsNU$F9b+w}(ZeVm;6W}9oo`j#(vcAZnC;kF(3 z$+T+`H3EIN7d*%p_GGJmWUJD0QzQAKuf?~96!XcmnBsn`sGQ2FNbX!*u!k-9#>uHo z(srDkM$-2p9x2F}J7)T;&t#Z(yyK~b)fu0@x3{oxMw zV=wCVs5tum%iYsU`&zj`Pg&Z)X3z#ymsi_!X)2cJk9BxhZQrwwycqgSqkZd?u?4M=jcwcg&q!warSX?-9p*1D;(!?4@?+ zK9?^ODlqgjIHZ2cE9Lmf-738O8=p+C-h0>x6fNB)vHG<0-MKoP7w%hE>&;@LwIgdz-IEhX!~uwavSGS9`Cs{MTRHTCpLo7a6QSdCB_AYu)&OpNmetUiZ&V z38Zr00wdR{*JJ-etk7Fw!yI{cs@);>6qXx&aanPDY<4a9#IomF>{0KnY07`DIA1zo zQsBD&o)GKQOUxu+)b9{GX$_+(SVo=Q^W>Sv`RYVl)P!t z=ZUhxwXS)Sj#?Bgd3sB3{^osp&mW%UH9uZcvu@H!Lrt~gOJ>MS7CP}{hREd2W}1yY weV&$SMLwrwXU^&Mw44r9F-gS}g0eFCYcAb)Y@g0104nf2UHx3vIVCg!05NxB4FCWD literal 0 HcmV?d00001 diff --git a/apps/web/src/assets/position/Top_icon.png b/apps/web/src/assets/position/Top_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..fa923fcedec2a86c90e6611f849a55ae0779c798 GIT binary patch literal 582 zcmeAS@N?(olHy`uVBq!ia0vp^9U#oX1|)5EEd~lO@p`&AhEy=Vy>xVHn4^U2#jMk< zH3htlhR%2H-d+0tolHgWrl$P1z1?DAZ#G|>JN?Zv{>dtylVIr5?B3@5|2J|rZ(}=g zCui}tTWL&3u4QZIsyVz#J;c~y>uZ&xmLh_rKbQ$X`VIac?$jAmU zLegb+gGGM4Kfrim|4!w(g>U>U+E^}qv9a*ZMi;Lu%PFhla+)Mkzr{>F3fa!z5)78&qol`;+ E02gV)g#Z8m literal 0 HcmV?d00001 diff --git a/apps/web/src/assets/react.svg b/apps/web/src/assets/react.svg new file mode 100644 index 00000000..6c87de9b --- /dev/null +++ b/apps/web/src/assets/react.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/src/assets/vite.svg b/apps/web/src/assets/vite.svg new file mode 100644 index 00000000..5101b674 --- /dev/null +++ b/apps/web/src/assets/vite.svg @@ -0,0 +1 @@ +Vite 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..978b884b --- /dev/null +++ b/apps/web/src/config.ts @@ -0,0 +1,92 @@ +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 (!import.meta.env.DEV) return 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 (!import.meta.env.DEV) return; + 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/index.css b/apps/web/src/index.css new file mode 100644 index 00000000..45ade146 --- /dev/null +++ b/apps/web/src/index.css @@ -0,0 +1,46 @@ +@import url("https://fonts.googleapis.com/css2?family=Asta+Sans:wght@300..800&family=Gamja+Flower&display=swap"); + +@import "tailwindcss"; +@plugin "daisyui" { + themes: + light --default, + dark --prefersdark; +} + +body { + margin: 0; + font-family: + "Asta Sans", + -apple-system, + BlinkMacSystemFont, + system-ui, + Roboto, + "Helvetica Neue", + "Segoe UI", + "Apple SD Gothic Neo", + "Noto Sans KR", + "Malgun Gothic", + "Apple Color Emoji", + "Segoe UI Emoji", + "Segoe UI Symbol", + sans-serif; + font-size: 14px; + line-height: 1.5; +} + +/* poro.gg style: 모든 모서리 각지게 */ +*, +*::before, +*::after { + border-radius: 0 !important; +} + +/* daisyUI badge만 살짝 둥글게 (pill 형태) */ +.badge { + border-radius: 2px !important; +} + +/* 버튼도 각지게 */ +.btn { + border-radius: 0 !important; +} diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx new file mode 100644 index 00000000..5487c4df --- /dev/null +++ b/apps/web/src/main.tsx @@ -0,0 +1,26 @@ +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'; +import { MsalAppProvider } from './lib/auth/MsalAppProvider.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/pages/AuctionPage.tsx b/apps/web/src/pages/AuctionPage.tsx new file mode 100644 index 00000000..e4317e7a --- /dev/null +++ b/apps/web/src/pages/AuctionPage.tsx @@ -0,0 +1,802 @@ +import { useEffect, useRef, useState } from 'react'; +import { Link, useParams } from 'react-router'; +import { useAuction, useDdragonManifest, 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 { + championDisplayName, + championIconUrl, + profileIconUrl, +} from '../lib/ddragon'; +import { positionIcon, positionLabel } from '../lib/league'; +import type { ApiRiotLaneStats, Position } from '../api/types'; + +function formatPoints(value: number) { + return value.toLocaleString(); +} + +const AUCTION_MAX_TEAM_SIZE = 5; +const LANE_ROWS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP']; +const POSITION_TO_RIOT_LANE = { + TOP: 'TOP', + JGL: 'JUNGLE', + MID: 'MIDDLE', + ADC: 'BOTTOM', + SUP: 'UTILITY', +} as const; + +function PosBadge({ pos }: { pos: Position }) { + return ( + + + {positionLabel[pos]} + + ); +} + +function TimerBar({ timer, maxTimer }: { timer: number; maxTimer: number }) { + const pct = maxTimer > 0 ? (timer / maxTimer) * 100 : 0; + const urgent = timer <= 5; + + return ( +
+
+
+ ); +} + +function getWinRate(stats: ApiRiotLaneStats) { + return stats.games > 0 ? Math.round((stats.wins / stats.games) * 100) : 0; +} + +function getWinRateClass(winRate: number) { + if (winRate >= 55) return 'text-blue-400'; + if (winRate >= 50) return 'text-base-content'; + return 'text-red-400'; +} + +function formatKdaRatio(stats: ApiRiotLaneStats) { + if (stats.avgDeaths === 0) return 'Perfect'; + return ((stats.avgKills + stats.avgAssists) / stats.avgDeaths).toFixed(2); +} + +function RecentSoloStats({ + player, +}: { + player: NonNullable; +}) { + const primaryStats = player.recentStats.primary; + + if (!primaryStats) { + return ( +
+

+ 최근 솔로랭크 +

+
+ 최근 솔로랭크 기록이 없습니다 +
+
+ ); + } + + const primaryWinRate = getWinRate(primaryStats); + const primaryKdaRatio = formatKdaRatio(primaryStats); + + return ( +
+
+
+

+ 최근 솔로랭크 +

+
+ + {positionLabel[player.mainPosition]} + + {player.recentStats.primarySource === 'overall' ? ( + + 전체 기준 + + ) : null} +
+
+
+ {primaryWinRate}% +
+
+ +
+
+ 전적 + + {primaryStats.wins}W{' '} + {primaryStats.losses}L + +
+
+ KDA + + {primaryStats.avgKills}/{primaryStats.avgDeaths}/{primaryStats.avgAssists} + = 3 ? 'text-emerald-400' : 'text-base-content/50'}`} + > + ({primaryKdaRatio}) + + +
+
+ 분당 CS + + {primaryStats.avgCsPerMin} + +
+
+ +
+ {LANE_ROWS.map((position) => { + const laneStats = + player.recentStats.byLane[POSITION_TO_RIOT_LANE[position]]; + const isMainLane = position === player.mainPosition; + + return ( +
+ + {positionLabel[position]} + + {laneStats && laneStats.games > 0 ? ( + + {laneStats.wins}W {laneStats.losses}L · {laneStats.avgKills}/ + {laneStats.avgDeaths}/{laneStats.avgAssists} ·{' '} + {laneStats.avgCsPerMin} CS/min + + ) : ( + — + )} +
+ ); + })} +
+
+ ); +} + +function TeamPanel({ + team, + isActive, + isLeft, +}: { + team: AuctionStateView['teams'][number]; + isActive: boolean; + isLeft: boolean; +}) { + const { data: ddragon } = useDdragonManifest(); + 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'; + const teamSize = team.members.length + 1; + const isFull = teamSize >= AUCTION_MAX_TEAM_SIZE; + + return ( +
+
+
+
+
+ + {team.side === 'blue' ? '블루팀' : '레드팀'} + + + 팀장: {team.captainName} + +
+ + {formatPoints(team.points)}P + +
+
+ + 팀장 포함 {teamSize}/{AUCTION_MAX_TEAM_SIZE} + + {isFull && 정원 완료} +
+
+ +
+ {team.members.length === 0 ? ( +
+ 아직 멤버가 없습니다 +
+ ) : ( + team.members.map((member) => ( +
+ +
+ +
+
+ + {member.summonerName} + +
+ + + + {member.cost} + +
+ )) + )} + + {Array.from({ + length: Math.max(0, AUCTION_MAX_TEAM_SIZE - 1 - team.members.length), + }).map((_, index) => ( +
+
+ — +
+ ))} +
+
+ ); +} + +function PlayerSpotlight({ + state, +}: { + state: AuctionStateView; +}) { + const { data: ddragon } = useDdragonManifest(); + const player = state.currentPlayer; + if (!player) return null; + + return ( +
+
+
+ + + +
+
+ + {player.summonerName} + + + #{player.tag} + +
+
+ {formatTierLabel(player.tier)} +
+
+ + + {' '} + {positionLabel[player.subPosition]} + +
+
+
+
+ +
+
+

+ 숙련도 높은 챔피언 +

+
+ {player.masteries.length > 0 ? ( + player.masteries.map((mastery) => { + const iconUrl = championIconUrl(ddragon, mastery.championId); + const displayName = + championDisplayName(ddragon, mastery.championId) ?? + String(mastery.championId); + return ( +
+
+ {iconUrl ? ( + {displayName} + ) : null} +
+
+
+ {displayName} +
+
+ Lv.{mastery.level} · {(mastery.points / 1000).toFixed(0)}K +
+
+
+ ); + }) + ) : ( +
+ 숙련도 데이터가 없습니다. +
+ )} +
+
+ + +
+ + {(state.phase === 'bidding' || state.phase === 'sold') && ( +
+
+ + {state.phase === 'sold' ? '낙찰가' : '현재 입찰가'} + +
+ {state.currentBidder && ( + + {state.currentBidder === 'blue' ? '블루' : '레드'} + + )} + + {state.currentBid > 0 ? formatPoints(state.currentBid) : '—'} + +
+
+
+ )} +
+ ); +} + +function BidControls({ + state, + captainSide, + onBid, +}: { + 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; + const activeTeamSize = activeTeam ? activeTeam.members.length + 1 : 0; + const isActiveTeamFull = activeTeamSize >= AUCTION_MAX_TEAM_SIZE; + + useEffect(() => { + setBidAmount(Math.max(minBid, Math.ceil(minBid / 10) * 10)); + }, [state.currentBid, minBid]); + + if (state.phase !== 'bidding') return null; + + if (!activeTeam) { + return ( +
+ 관전자 모드입니다. 우측 상단에서 조작자 역할을 선택하면 입찰할 수 있습니다. +
+ ); + } + + const presets = [50, 100, 150, 200, 300, 500]; + + return ( +
+
+ {presets.map((preset) => ( + + ))} + + setBidAmount(Math.max(minBid, Number(event.target.value))) + } + min={minBid} + disabled={isActiveTeamFull} + 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: AuctionStateView['bids'] }) { + const endRef = useRef(null); + + useEffect(() => { + endRef.current?.scrollIntoView({ behavior: 'smooth' }); + }, [bids.length]); + + if (bids.length === 0) return null; + + return ( +
+
+ + 입찰 기록 + +
+
+ {bids.map((bid, index) => ( +
+ + {bid.side === 'blue' ? '블루' : '레드'} + + → + + {formatPoints(bid.amount)}P + +
+ ))} +
+
+
+ ); +} + +export default function AuctionPage() { + const { id } = useParams(); + const meQuery = useMe(); + const currentUser = + meQuery.data?.memberships.find( + (membership) => membership.community?._id === DEFAULT_COMMUNITY_ID, + )?.user ?? null; + 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 timer = window.setInterval(() => setNow(Date.now()), 1000); + return () => window.clearInterval(timer); + }, []); + + const liveAuction = socket.auction ?? auctionQuery.data ?? null; + const auctionState = + liveAuction && matchQuery.data + ? mapApiAuctionToAuctionState(liveAuction, matchQuery.data, new Date(now)) + : null; + + useEffect(() => { + if (auctionState?.currentPlayer) { + setAssignedPosition(auctionState.currentPlayer.mainPosition); + } + }, [auctionState?.currentPlayer?.id]); + + if (!DEFAULT_COMMUNITY_ID) { + return ( +
+ + `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. + +
+ ); + } + + if (matchQuery.isLoading || (auctionQuery.isLoading && !socket.auction)) { + return ( +
+ 경매를 연결하는 중... +
+ ); + } + + if (auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404 && !socket.auction) { + return ( +
+

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

+ + 내전 상세로 돌아가기 + +
+ ); + } + + if (!auctionState || !matchQuery.data) { + return ( +
+ + 경매 상태를 불러오지 못했습니다. + +
+ ); + } + + const canManageAuction = + import.meta.env.DEV || + currentUser?.role === 'owner' || + currentUser?.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} +
+ )} + +
+
+

+ 경매 팀빌딩 +

+

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

+
+
+
+ + {phaseLabel[auctionState.phase]} + + {auctionState.phase === 'bidding' && ( + + {auctionState.timer}s + + )} +
+
+ 소켓: {socket.connectionStatus} + {/* 임시 운영용: 로그인/권한 확인 없이 조작자 역할을 선택할 수 있게 열어둔다. */} + +
+
+
+ + {auctionState.phase === 'bidding' && ( + + )} + +
+
+ +
+ +
+ {auctionState.phase === 'complete' ? ( +
+
+ 경매 완료 +
+
+ 모든 선수가 팀에 배정되었습니다. +
+ + 결과 확인 + +
+ ) : ( + <> + + + {auctionState.phase === 'sold' && auctionState.currentBidder && ( +
+ {auctionState.currentBidder === 'blue' ? '블루팀' : '레드팀'} 낙찰 + {' '}— {formatPoints(auctionState.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/AuthCallback.tsx b/apps/web/src/pages/AuthCallback.tsx new file mode 100644 index 00000000..1476342f --- /dev/null +++ b/apps/web/src/pages/AuthCallback.tsx @@ -0,0 +1,17 @@ +import { useEffect } from 'react'; +import { useNavigate } from 'react-router'; + +export default function AuthCallbackPage() { + const navigate = useNavigate(); + + useEffect(() => { + const timer = window.setTimeout(() => navigate('/', { replace: true }), 300); + return () => window.clearTimeout(timer); + }, [navigate]); + + return ( +
+ 로그인 처리 중... +
+ ); +} diff --git a/apps/web/src/pages/CommunityInternalStatsPage.tsx b/apps/web/src/pages/CommunityInternalStatsPage.tsx new file mode 100644 index 00000000..65a84da6 --- /dev/null +++ b/apps/web/src/pages/CommunityInternalStatsPage.tsx @@ -0,0 +1,388 @@ +import { Link, useSearchParams } from 'react-router'; +import { + useCommunity, + useCommunityInternalStatsMatches, + useCommunityLeaderboard, + useDdragonManifest, + useTeamInsights, +} from '../api/hooks'; +import type { + ApiInternalMatchCard, + ApiLeaderHighlight, + ApiLeaderboardRow, + TeamSide, +} from '../api/types'; +import { DEFAULT_COMMUNITY_ID } from '../config'; +import { championDisplayName, championIconUrl, profileIconUrl } from '../lib/ddragon'; + +function formatDateTime(value: string) { + return new Intl.DateTimeFormat('ko-KR', { + month: 'long', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + }).format(new Date(value)); +} + +function formatDuration(seconds: number) { + const minutes = Math.floor(seconds / 60); + const rest = seconds % 60; + return `${minutes}:${String(rest).padStart(2, '0')}`; +} + +function sideLabel(side: TeamSide) { + return side === 'blue' ? '블루팀' : '레드팀'; +} + +function sideText(side: TeamSide) { + return side === 'blue' ? 'text-blue-400' : 'text-red-400'; +} + +function ratioClass(value: number) { + if (value >= 55) return 'text-blue-400'; + if (value >= 50) return 'text-amber-400'; + return 'text-base-content/45'; +} + +function ChampionChip({ + championId, + manifest, +}: { + championId: number; + manifest: ReturnType['data']; +}) { + const icon = championIconUrl(manifest, championId); + const name = championDisplayName(manifest, championId) ?? String(championId); + return ( + + + {icon ? : null} + + {name} + + ); +} + +function MatchCard({ + match, + manifest, +}: { + match: ApiInternalMatchCard; + manifest: ReturnType['data']; +}) { + return ( + +
+
+
+
+ {formatDateTime(match.scheduledAt)} +
+

+ {match.title} +

+
+ {match.games.map((game) => ( + + {game.gameNumber}경기 + {game.winnerSide ? ( + + {sideLabel(game.winnerSide)} 승 + + ) : ( + '대기' + )} + {formatDuration(game.gameDuration)} + + ))} +
+
+ +
+
+
+
{match.blueScore}
+
BLUE
+
+
VS
+
+
{match.redScore}
+
RED
+
+
+
+ +
+ {match.teams.map((team) => ( +
+
+ {team.name} +
+
+ {team.members.slice(0, 5).map((member) => ( +
+ + + + + {member.summonerName} + +
+ ))} +
+
+ ))} +
+
+
+ + ); +} + +function HighlightCard({ + title, + highlight, + suffix = '', +}: { + title: string; + highlight: ApiLeaderHighlight | null | undefined; + suffix?: string; +}) { + return ( +
+
+ {title} +
+
+ {highlight ? `${highlight.metric}${suffix}` : '-'} +
+
+ {highlight?.summonerName ?? '기록 없음'} +
+
+ ); +} + +function LeaderboardTable({ + rows, + manifest, +}: { + rows: ApiLeaderboardRow[]; + manifest: ReturnType['data']; +}) { + return ( +
+
+ + + + + + + + + + + + + + + + {rows.map((row, index) => ( + + + + + + + + + + + + ))} + {rows.length === 0 && ( + + + + )} + +
#소환사승률게임KDAGPM킬관여분당 CS주 챔피언
+ {index + 1} + + + + + + + {row.summonerName} + + + + {row.winRate}% + + {row.games} + + {row.kda} + + {row.avgGoldPerMin} + + {row.avgKillParticipation}% + + {row.avgCsPerMin} + +
+ {row.topChampions.map((champion) => ( + + ))} +
+
+ 아직 집계할 내전 기록이 없습니다. +
+
+
+ ); +} + +export default function CommunityInternalStatsPage() { + const [searchParams] = useSearchParams(); + const championIdParam = Number(searchParams.get('championId')); + const championId = + Number.isFinite(championIdParam) && championIdParam > 0 + ? championIdParam + : undefined; + const filters = { + seasonId: searchParams.get('seasonId') ?? undefined, + championId, + limit: 12, + }; + const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID); + const matchesQuery = useCommunityInternalStatsMatches(filters); + const leaderboardQuery = useCommunityLeaderboard(filters); + const insightsQuery = useTeamInsights(filters); + const { data: ddragon } = useDdragonManifest(); + const matches = matchesQuery.data?.pages.flatMap((page) => page.matches) ?? []; + const season = + leaderboardQuery.data?.season ?? matchesQuery.data?.pages[0]?.season ?? null; + + if (!DEFAULT_COMMUNITY_ID) { + return ( +
+ `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. +
+ ); + } + + return ( +
+ + ← 홈으로 + + +
+
+
+

+ Community Records +

+

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

+

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

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

최근 내전

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

선수 순위

+
+ 포지션은 Riot Match의 라인 정보를 기준으로 합니다. +
+
+ +
+
+ ); +} diff --git a/apps/web/src/pages/HomePage.tsx b/apps/web/src/pages/HomePage.tsx new file mode 100644 index 00000000..5b2737b5 --- /dev/null +++ b/apps/web/src/pages/HomePage.tsx @@ -0,0 +1,239 @@ +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-base-content/8 text-base-content/40 border-base-content/10', + }; + + return ( + + {status} + + ); +} + +function MapBadge({ map }: { map: string }) { + return ( + + {map} + + ); +} + +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 ( +
+
+
+

+ 다음 내전 +

+ + 내전 전적 보기 + +
+ + {nextMatch ? ( + +
+
+
+
+
+

+ {nextMatch.title} +

+ +
+

+ {nextMatch.description} +

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

+ 예정된 내전 +

+
+ {upcomingCards.length > 0 ? ( + upcomingCards.map((match) => ( + +
+
+

+ {match.title} +

+ +
+
+
{match.date} {match.time}
+
+ {match.participants.length}/{match.maxParticipants}명 +
+
+
+ +
+
+ + )) + ) : ( +
+ 예정된 추가 매치가 없습니다. +
+ )} +
+
+ +
+

+ 지난 내전 기록 +

+
+ + + + + + + + + + + + {finishedMatches.length > 0 ? ( + finishedMatches.map((match) => ( + + + + + + + + )) + ) : ( + + + + )} + +
날짜내전맵참가결과
+ {match.date} + + + {match.title} + + + + + {match.participants.length}명 + + {match.result?.winner ? `${match.result.winner} 승리` : '-'} +
+ 아직 종료된 내전 기록이 없습니다. +
+
+
+
+ ); +} diff --git a/apps/web/src/pages/InternalMatchDetailPage.tsx b/apps/web/src/pages/InternalMatchDetailPage.tsx new file mode 100644 index 00000000..86197eac --- /dev/null +++ b/apps/web/src/pages/InternalMatchDetailPage.tsx @@ -0,0 +1,262 @@ +import { Link, useParams } from 'react-router'; +import { useDdragonManifest, useInternalMatchDetail } from '../api/hooks'; +import type { ApiInternalMatchDetailResponse, TeamSide } from '../api/types'; +import { DEFAULT_COMMUNITY_ID } from '../config'; +import { championDisplayName, championIconUrl, itemIconUrl } from '../lib/ddragon'; +import { LANE_LABELS } from '../lib/riot-history'; + +function formatDateTime(value: string | number) { + return new Intl.DateTimeFormat('ko-KR', { + month: 'long', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + }).format(new Date(value)); +} + +function formatDuration(seconds: number) { + const minutes = Math.floor(seconds / 60); + const rest = seconds % 60; + return `${minutes}:${String(rest).padStart(2, '0')}`; +} + +function sideLabel(side: TeamSide) { + return side === 'blue' ? '블루팀' : '레드팀'; +} + +function sideClass(side: TeamSide) { + return side === 'blue' ? 'text-blue-400 border-blue-500/20' : 'text-red-400 border-red-500/20'; +} + +function ChampionCell({ + championId, + manifest, +}: { + championId: number; + manifest: ReturnType['data']; +}) { + const icon = championIconUrl(manifest, championId); + const name = championDisplayName(manifest, championId) ?? String(championId); + return ( +
+ + {icon ? : null} + + {name} +
+ ); +} + +function ItemStrip({ + items, + trinket, + manifest, +}: { + items: number[]; + trinket: number; + manifest: ReturnType['data']; +}) { + return ( +
+ {[...items, trinket].map((itemId, index) => { + const icon = itemIconUrl(manifest, itemId); + return ( + + {icon ? : null} + + ); + })} +
+ ); +} + +function GamePanel({ + game, + manifest, +}: { + game: ApiInternalMatchDetailResponse['games'][number]; + manifest: ReturnType['data']; +}) { + return ( +
+
+
+

+ {game.gameNumber}경기 +

+

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

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

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

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

+ {detail.match.title} +

+

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

+
+
+
+
{detail.match.blueScore}
+
BLUE
+
+
VS
+
+
{detail.match.redScore}
+
RED
+
+
+
+
+ +
+ {detail.games.map((game) => ( + + ))} +
+
+ ); +} diff --git a/apps/web/src/pages/Login.tsx b/apps/web/src/pages/Login.tsx new file mode 100644 index 00000000..7bbca0e1 --- /dev/null +++ b/apps/web/src/pages/Login.tsx @@ -0,0 +1,47 @@ +import { useMsal } from "@azure/msal-react"; +import { + isMsalConfigured, + MSAL_API_SCOPE, + msalInstance, +} from "../lib/auth/msal.config"; + +function LoginButton() { + const { instance } = useMsal(); + + return ( + + ); +} + +export default function LoginPage() { + return ( +
+
+

로그인

+

+ Entra ID 계정으로 LOLYMPUS 정보를 불러옵니다. +

+
+ {isMsalConfigured && msalInstance ? ( + + ) : ( +
+ MSAL 환경변수 설정이 필요합니다. +
+ )} +
+
+
+ ); +} diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx new file mode 100644 index 00000000..4cb92c48 --- /dev/null +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -0,0 +1,885 @@ +import { useEffect, useState } from 'react'; +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { Link, useNavigate, useParams } from 'react-router'; +import { + useAuction, + useDdragonManifest, + useMatch, + useMe, + usePollTournamentResult, + useTournamentCodeStats, +} from '../api/hooks'; +import { + 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 { profileIconUrl } from '../lib/ddragon'; +import { positionIcon, positionLabel } from '../lib/league'; +import type { Position, TournamentCodeSlotView } from '../api/types'; + +function PosBadge({ pos, sub }: { pos: Position; sub?: boolean }) { + return ( + + + {positionLabel[pos]} + + ); +} + +function TierCell({ participant }: { participant: ParticipantView }) { + if (!participant.tier) { + return ( +
+ 티어 정보 없음 +
+ ); + } + + return ( +
+ + {formatTierLabel(participant.tier)} + + {participant.tier.leaguePoints > 0 && ( + + {participant.tier.leaguePoints}LP + + )} +
+ ); +} + +function statusBadge(status: MatchDetailView['status']) { + switch (status) { + case 'recruiting': + return { + label: '모집 중', + cls: 'bg-green-500/15 text-green-500 border-green-500/20', + }; + case 'team-built': + return { + label: '팀빌딩 완료', + cls: 'bg-amber-500/15 text-amber-500 border-amber-500/20', + }; + case 'in-progress': + return { + 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({ + participant, + index, + assignedPos, +}: { + participant: ParticipantView; + index: number; + assignedPos?: Position; +}) { + const { data: ddragon } = useDdragonManifest(); + return ( + + + {index + 1} + + + +
+ +
+
+ + {participant.summonerName} + + + #{participant.tag} + +
+ + + + + + {assignedPos ? ( + + + + ) : ( + <> + + + + + + + + )} + + ); +} + +function ParticipantTable({ + participants, + maxParticipants, + joined, + canJoin, + onJoin, + isJoining, +}: { + participants: ParticipantView[]; + maxParticipants: number; + joined: boolean; + canJoin: boolean; + onJoin: () => void; + isJoining: boolean; +}) { + return ( +
+
+

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

+ +
+
+ + + + + + + + + + + + {participants.map((participant, index) => ( + + ))} + +
#소환사현재 티어주 포지션부 포지션
+
+ {participants.length < maxParticipants && ( +
+ + {maxParticipants - participants.length}자리 남음 + +
+ )} +
+ ); +} + +function TeamCard({ + team, + isWinner, +}: { + team: TeamView; + isWinner?: boolean; +}) { + const borderColor = + 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 && ( + + WIN + + )} +
+
+ + + + + + + + + + + {team.participants.map((participant, index) => ( + + ))} + +
#소환사현재 티어포지션
+
+ ); +} + +function SideCard({ + title, + children, +}: { + title: string; + children: React.ReactNode; +}) { + return ( +
+
+

+ {title} +

+
+
{children}
+
+ ); +} + +function formatTournamentCodeExpiry(value: string | null) { + if (!value) return null; + return new Intl.DateTimeFormat('ko-KR', { + month: 'long', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + }).format(new Date(value)); +} + +function isExpiringSoon(value: string | null) { + if (!value) return false; + const expiresAt = new Date(value).getTime(); + return expiresAt - Date.now() <= 24 * 60 * 60 * 1000; +} + +function TournamentCodeDisplay({ slot }: { slot: TournamentCodeSlotView }) { + const [copied, setCopied] = useState(false); + const expired = slot.state === 'expired'; + const used = slot.state === 'used'; + const expiringSoon = isExpiringSoon(slot.expiresAt); + + async function copyCode() { + if (!slot.code) return; + await navigator.clipboard.writeText(slot.code); + setCopied(true); + window.setTimeout(() => setCopied(false), 1600); + } + + return ( +
+
+ + {expired ? '코드 만료' : slot.code} + + {slot.code && !expired && ( + + )} +
+
+ {used + ? '사용됨' + : expired + ? '운영자에게 새 코드를 요청해주세요.' + : `만료: ${formatTournamentCodeExpiry(slot.expiresAt)}`} +
+
+ ); +} + +function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) { + return ( +
+ {slots.map((slot) => ( +
+ + {slot.gameNumber}경기 + + {slot.code ? ( + + ) : ( + + 발급 대기 중... 운영자가 코드를 채우면 자동으로 붙습니다. + + )} +
+ ))} +
+ ); +} + +function PoolStatsHint({ enabled }: { enabled: boolean }) { + const statsQuery = useTournamentCodeStats(DEFAULT_COMMUNITY_ID, enabled); + if (!enabled) return null; + const available = statsQuery.data?.available ?? 0; + const expiringSoon = statsQuery.data?.expiringSoon ?? 0; + + return ( +
+
+ 풀 잔여 {available}개 + {expiringSoon > 0 ? ` · 만료 임박 ${expiringSoon}개` : ''} +
+ + 코드 풀 관리 + +
+ ); +} + +function formatGameDuration(seconds: number) { + const minutes = Math.floor(seconds / 60); + const rest = seconds % 60; + return `${minutes}:${String(rest).padStart(2, '0')}`; +} + +function resultSideLabel(side: 'blue' | 'red') { + return side === 'blue' ? '블루팀' : '레드팀'; +} + +function resultSideClass(side: 'blue' | 'red') { + return side === 'blue' ? 'text-blue-400' : 'text-red-400'; +} + +function MatchResultPanel({ match }: { match: MatchDetailView }) { + if (!match.result) return null; + + const gamesByNumber = new Map( + match.result.games.map((game) => [game.gameNumber, game]), + ); + const gameNumbers = Array.from( + { length: match.gameCount }, + (_, index) => index + 1, + ); + + return ( +
+
+
+
+ {match.result.blueScore} +
+
+ 블루팀 +
+
+
+ VS +
+
+
+ {match.result.redScore} +
+
+ 레드팀 +
+
+
+
+ {match.result.winner + ? `${match.result.winner} 승리` + : `결과 수집 중 · ${match.result.games.length}/${match.gameCount}경기`} +
+
+ {gameNumbers.map((gameNumber) => { + const game = gamesByNumber.get(gameNumber); + return ( +
+ + {gameNumber}경기 + + {game ? ( +
+ + {resultSideLabel(game.winnerSide)} 승 + + + {game.riotMatchId} + +
+ ) : ( + 대기 중 + )} + + {game ? formatGameDuration(game.gameDuration) : '-'} + +
+ ); + })} +
+
+ ); +} + +export default function MatchDetailPage() { + const { id } = useParams(); + const navigate = useNavigate(); + const queryClient = useQueryClient(); + const authUserId = useAuthUserId(); + const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); + const meQuery = useMe(); + const currentUser = + meQuery.data?.memberships.find( + (membership) => membership.community?._id === DEFAULT_COMMUNITY_ID, + )?.user ?? null; + const canUseMemberActions = Boolean(currentUser || authUserId); + const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID); + const [blueCaptainUserId, setBlueCaptainUserId] = useState(''); + const [redCaptainUserId, setRedCaptainUserId] = useState(''); + const pollTournamentResultMutation = usePollTournamentResult( + DEFAULT_COMMUNITY_ID, + ); + + const joinMatchMutation = useMutation({ + mutationFn: () => + apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants`, { + method: 'POST', + body: JSON.stringify({ + preferredPositions: + currentUser?.preferredPositions.length + ? currentUser.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`); + }, + }); + + function handlePollTournamentResult() { + if (!id) return; + pollTournamentResultMutation.mutate(id, { + onSuccess: async () => { + await queryClient.invalidateQueries({ + queryKey: ['match', DEFAULT_COMMUNITY_ID, id ?? null], + }); + }, + }); + } + + 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 ( +
+

내전을 찾을 수 없습니다

+ + 홈으로 돌아가기 + +
+ ); + } + + const match = mapApiMatchToMatchDetail(matchQuery.data); + const si = statusBadge(match.status); + const canManageAuction = + currentUser?.role === 'owner' || currentUser?.role === 'admin'; + const isCheckingPermissions = + meQuery.isLoading || (meQuery.isFetching && !meQuery.data); + 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 ( +
+ + + + + 목록으로 + + +
+
+

+ {match.title} +

+ + {si.label} + +
+

{match.description}

+
+ {match.date} {match.time} + | + + {match.participants.length}/{match.maxParticipants}명 + + | + + {match.map} + +
+
+ + {joinMatchMutation.error instanceof Error && ( +
+ {joinMatchMutation.error.message} +
+ )} + + {startAuctionMutation.error instanceof Error && ( +
+ {startAuctionMutation.error.message} +
+ )} + + {pollTournamentResultMutation.error instanceof Error && ( +
+ {pollTournamentResultMutation.error.message} +
+ )} + + + +
+
+ {match.status === 'recruiting' ? ( + <> + joinMatchMutation.mutate()} + isJoining={joinMatchMutation.isPending} + /> + + {isCheckingPermissions ? ( +
+

+ 권한 확인 중 +

+

+ 관리자 권한을 확인한 뒤 경매 시작 버튼을 표시합니다. +

+
+ ) : canManageAuction ? ( +
+
+

+ 경매 시작 +

+

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

+
+ + {showAuctionLink ? ( + + 경매 페이지 열기 + + ) : ( +
+ + +
+ + {!canUseMemberActions && ( + + 로그인 또는 Dev Auth에 owner/admin User ID를 먼저 입력해주세요. + + )} +
+
+ )} +
+ ) : null} + + ) : ( +
+ {match.teams.map((team) => ( + + ))} + {showAuctionLink && ( +
+ + 경매 페이지 열기 + +
+ )} +
+ )} +
+ +
+ {match.schedule.length > 0 && ( + +
    + {match.schedule.map((item, index) => ( +
  • + + {item.time} + + {item.label} +
  • + ))} +
+
+ )} + + {(match.status === 'team-built' || match.status === 'in-progress') && ( + + + + + )} + + {canManageAuction && + (match.status === 'team-built' || match.status === 'in-progress') && ( + +

+ Riot match-v5에서 토너먼트 코드가 붙은 경기를 다시 찾습니다. +

+ +
+ )} + + {match.prizes.length > 0 && ( + +
    + {match.prizes.map((prize, index) => ( +
  • + ▸ + {prize} +
  • + ))} +
+
+ )} + + {match.notices.length > 0 && ( + +
    + {match.notices.map((notice, index) => ( +
  • + • + {notice} +
  • + ))} +
+
+ )} +
+
+
+ ); +} diff --git a/apps/web/src/pages/UserHistoryPage.tsx b/apps/web/src/pages/UserHistoryPage.tsx new file mode 100644 index 00000000..28dcf98a --- /dev/null +++ b/apps/web/src/pages/UserHistoryPage.tsx @@ -0,0 +1,1019 @@ +import { useMemo, useState } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { Link, useParams, useSearchParams } from "react-router"; +import { + useChampionStats, + useDdragonManifest, + useRecentMatches, + useRecentSummary, + useRefreshUserHistory, + useUserInternalHistory, + useUserHistoryProfile, + type UserHistoryFilters, +} from "../api/hooks"; +import { useRiotRefreshSocket } from "../api/useRiotRefreshSocket"; +import { formatTierLabel, getTierColorToken } from "../api/mappers"; +import type { + ApiChampionStatsRow, + ApiEnqueueRefreshResult, + ApiRiotRefreshEvent, + ApiRecentMatchView, + DdragonManifest, + RiotQueueGroup, + RiotRankFilter, +} from "../api/types"; +import { DEFAULT_COMMUNITY_ID } from "../config"; +import { ApiError } from "../lib/api"; +import { + championDisplayName, + championIconUrl, + itemIconUrl, + profileIconUrl, +} from "../lib/ddragon"; +import { + isRiotQueueGroup, + isRiotRankFilter, + LANE_LABELS, + QUEUE_GROUP_TABS, + RANK_FILTER_TABS, +} from "../lib/riot-history"; + +type ChampionSortKey = "games" | "winRate" | "kda" | "avgCsPerMin"; + +const SORT_LABELS: Record = { + games: "게임 수", + winRate: "승률", + kda: "KDA", + avgCsPerMin: "분당 CS", +}; + +function formatDuration(seconds: number) { + const minutes = Math.floor(seconds / 60); + const rest = seconds % 60; + return `${minutes}:${String(rest).padStart(2, "0")}`; +} + +function formatDate(ms: number) { + return new Intl.DateTimeFormat("ko-KR", { + month: "long", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + }).format(new Date(ms)); +} + +function formatLastFetched(value: string | null | undefined) { + if (!value) return "저장된 갱신 시각 없음"; + return new Intl.DateTimeFormat("ko-KR", { + month: "long", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + }).format(new Date(value)); +} + +function formatEta(seconds: number) { + if (seconds < 60) return `${Math.max(1, Math.ceil(seconds))}초`; + return `${Math.ceil(seconds / 60)}분`; +} + +function formatRefreshError(error: unknown) { + if (error instanceof ApiError) { + const data = error.data; + if ( + typeof data === "object" && + data !== null && + "retryAfterSeconds" in data && + typeof data.retryAfterSeconds === "number" + ) { + return `잠시 후 다시 시도해 주세요. 약 ${formatEta(data.retryAfterSeconds)} 뒤에 요청할 수 있습니다.`; + } + return error.message; + } + return error instanceof Error ? error.message : "갱신 요청에 실패했습니다."; +} + +function ratioClass(value: number) { + if (value >= 55) return "text-blue-400"; + if (value >= 50) return "text-amber-400"; + return "text-base-content/50"; +} + +function kdaClass(value: number) { + if (value >= 4) return "text-amber-400"; + if (value >= 3) return "text-emerald-400"; + return "text-base-content/60"; +} + +function FilterButton({ + active, + children, + onClick, +}: { + active: boolean; + children: React.ReactNode; + onClick: () => void; +}) { + return ( + + ); +} + +function ChampionIcon({ + championId, + manifest, + size = "md", +}: { + championId: number; + manifest: DdragonManifest | null | undefined; + size?: "sm" | "md" | "lg"; +}) { + const iconUrl = championIconUrl(manifest, championId); + const displayName = + championDisplayName(manifest, championId) ?? String(championId); + const sizeClass = + size === "lg" ? "w-12 h-12" : size === "sm" ? "w-5 h-5" : "w-8 h-8"; + + return ( +
+ {iconUrl ? ( + {displayName} + ) : null} +
+ ); +} + +function SummaryCard({ + label, + value, + sub, +}: { + label: string; + value: React.ReactNode; + sub?: React.ReactNode; +}) { + return ( +
+
+ {label} +
+
+ {value} +
+ {sub && ( +
{sub}
+ )} +
+ ); +} + +function ChampionStatsTable({ + rows, + manifest, + selectedChampionId, + onChampionSelect, +}: { + rows: ApiChampionStatsRow[]; + manifest: DdragonManifest | null | undefined; + selectedChampionId?: number; + onChampionSelect: (championId: number | null) => void; +}) { + if (rows.length === 0) { + return ( +
+ 조건에 맞는 챔피언 통계가 아직 없습니다. +
+ ); + } + + return ( +
+
+ + + + + + + + + + + + + + + + + + {rows.map((row) => { + const displayName = + championDisplayName(manifest, row.championId) ?? + String(row.championId); + const selected = selectedChampionId === row.championId; + return ( + + + + + + + + + + + + + + ); + })} + +
챔피언승률게임승/패KDA킬데스어시스트멀티킬CS필터
+
+ + + {displayName} + +
+
+ {row.winRate}% + + {row.games} + + {row.wins} /{" "} + {row.losses} + + {row.kda} + + {row.totalKills} + + {row.totalDeaths} + + {row.totalAssists} + + {row.doubleKills}/{row.tripleKills}/{row.quadraKills}/ + {row.pentaKills} + + {row.avgCs} · {row.avgCsPerMin}/m + + +
+
+
+ ); +} + +function ItemGrid({ + match, + manifest, +}: { + match: ApiRecentMatchView; + manifest: DdragonManifest | null | undefined; +}) { + const slots = [...match.items, match.trinket]; + return ( +
+ {slots.map((itemId, index) => { + const url = itemIconUrl(manifest, itemId); + return ( +
+ {url ? ( + + ) : null} +
+ ); + })} +
+ ); +} + +function TeamMini({ + match, + manifest, +}: { + match: ApiRecentMatchView; + manifest: DdragonManifest | null | undefined; +}) { + return ( +
+ {match.teams.map((team) => ( +
+ {team.participants.map((participant) => { + const championName = + championDisplayName(manifest, participant.championId) ?? + String(participant.championId); + return ( +
+ + + {participant.gameName || championName} + +
+ ); + })} +
+ ))} +
+ ); +} + +function RecentMatchCard({ + match, + manifest, +}: { + match: ApiRecentMatchView; + manifest: DdragonManifest | null | undefined; +}) { + const championName = + championDisplayName(manifest, match.championId) ?? String(match.championId); + const accent = match.win ? "border-l-blue-500" : "border-l-red-500"; + const resultClass = match.win ? "text-blue-400" : "text-red-400"; + + return ( +
+
+
+
+ {match.remake ? "다시하기" : match.win ? "승리" : "패배"} +
+
+ {match.queueLabel} +
+
+ {formatDate(match.gameCreation)} +
+
+ {formatDuration(match.gameDuration)} +
+
+ +
+ +
+
+ {championName} +
+
+ Lv.{match.championLevel} ·{" "} + {(LANE_LABELS[match.teamPosition] ?? match.teamPosition) || + "포지션 없음"} +
+
+ 스펠 {match.summonerSpells.join(" / ")} +
+
+
+ +
+
+ {match.kills} + / + {match.deaths} + / + {match.assists} +
+
+ {match.deaths === 0 ? "Perfect" : `${match.kda} 평점`} +
+
+ 킬 관여 {match.killParticipation}% +
+
+ +
+
+
+ CS{" "} + + {match.totalCs} + {" "} + ({match.csPerMin}/m) +
+
+ 시야{" "} + + {match.visionScore} + {" "} + 제어와드 {match.controlWardsBought} +
+
+ 피해량{" "} + + {match.damageDealtToChampions.toLocaleString()} + +
+
+
+ + +
+
+ +
+
+
+
+
+ ); +} + +export default function UserHistoryPage() { + const { userId } = useParams(); + const queryClient = useQueryClient(); + const [searchParams, setSearchParams] = useSearchParams(); + const [championSearch, setChampionSearch] = useState(""); + const [sortKey, setSortKey] = useState("games"); + const [refreshResult, setRefreshResult] = + useState(null); + const [refreshNotice, setRefreshNotice] = useState(null); + const queueGroupParam = searchParams.get("queueGroup"); + const rankParam = searchParams.get("rank"); + const queueGroup: RiotQueueGroup = isRiotQueueGroup(queueGroupParam) + ? queueGroupParam + : "summoners-rift"; + const isInternalQueue = queueGroup === "internal"; + const rank: RiotRankFilter = + !isInternalQueue && isRiotRankFilter(rankParam) ? rankParam : "all"; + const championIdParam = Number(searchParams.get("championId")); + const championId = + Number.isFinite(championIdParam) && championIdParam > 0 + ? championIdParam + : undefined; + const filters: UserHistoryFilters = { + queueGroup, + rank, + championId, + seasonId: searchParams.get("seasonId") ?? undefined, + }; + const aggregateFilters: UserHistoryFilters = { + queueGroup, + rank, + seasonId: filters.seasonId, + }; + const { data: ddragon } = useDdragonManifest(); + const profileQuery = useUserHistoryProfile(userId, DEFAULT_COMMUNITY_ID); + const standardHistoryEnabled = !isInternalQueue; + const championStatsQuery = useChampionStats( + userId, + aggregateFilters, + DEFAULT_COMMUNITY_ID, + standardHistoryEnabled, + ); + const summaryQuery = useRecentSummary( + userId, + filters, + DEFAULT_COMMUNITY_ID, + standardHistoryEnabled, + ); + const recentMatchesQuery = useRecentMatches( + userId, + filters, + DEFAULT_COMMUNITY_ID, + standardHistoryEnabled, + ); + const internalHistoryQuery = useUserInternalHistory( + userId, + filters, + DEFAULT_COMMUNITY_ID, + isInternalQueue, + ); + const refreshMutation = useRefreshUserHistory(userId, DEFAULT_COMMUNITY_ID); + + const profile = profileQuery.data; + const primaryTier = + profile?.tiers.find((tier) => tier.queueType === "RANKED_SOLO_5x5") ?? + profile?.tiers[0]; + const internalPages = internalHistoryQuery.data?.pages ?? []; + const internalFirstPage = internalPages[0]; + const summary = isInternalQueue + ? internalFirstPage?.summary + : summaryQuery.data; + const matches = isInternalQueue + ? internalPages.flatMap((page) => page.matches) + : (recentMatchesQuery.data?.pages.flatMap((page) => page.matches) ?? []); + const historyLastFetchedAt = isInternalQueue + ? internalFirstPage?.lastFetchedAt + : recentMatchesQuery.data?.pages[0]?.lastFetchedAt; + const matchesLoading = isInternalQueue + ? internalHistoryQuery.isLoading + : recentMatchesQuery.isLoading; + const hasNextPage = isInternalQueue + ? internalHistoryQuery.hasNextPage + : recentMatchesQuery.hasNextPage; + const isFetchingNextPage = isInternalQueue + ? internalHistoryQuery.isFetchingNextPage + : recentMatchesQuery.isFetchingNextPage; + const selectedChampionName = championId + ? (championDisplayName(ddragon, championId) ?? String(championId)) + : null; + + const visibleChampionRows = useMemo(() => { + const rows = isInternalQueue + ? (internalFirstPage?.championStats.champions ?? []) + : (championStatsQuery.data?.champions ?? []); + const keyword = championSearch.trim().toLowerCase(); + return rows + .filter((row) => { + if (!keyword) return true; + const displayName = + championDisplayName(ddragon, row.championId) ?? + String(row.championId); + return displayName.toLowerCase().includes(keyword); + }) + .sort((left, right) => right[sortKey] - left[sortKey]); + }, [ + championSearch, + championStatsQuery.data?.champions, + ddragon, + internalFirstPage?.championStats.champions, + isInternalQueue, + sortKey, + ]); + + const refreshSocket = useRiotRefreshSocket({ + puuid: isInternalQueue ? undefined : profile?.puuid, + parentJobId: refreshResult?.parentJobId, + onEvent: (event: ApiRiotRefreshEvent) => { + if (!profile || event.puuid !== profile.puuid) return; + void invalidateHistoryQueries(); + if (event.state === "completed") { + setRefreshNotice("갱신이 완료되어 전적을 다시 불러왔습니다."); + } + if (event.state === "failed") { + setRefreshNotice( + event.error + ? `갱신 실패: ${event.error}` + : "갱신에 실패했습니다. 잠시 후 다시 시도해 주세요.", + ); + } + }, + }); + + function updateSearch(next: Partial>) { + const params = new URLSearchParams(searchParams); + for (const [key, value] of Object.entries(next)) { + if (value === null || value === undefined || value === "") { + params.delete(key); + } else { + params.set(key, String(value)); + } + } + setSearchParams(params); + } + + async function invalidateHistoryQueries() { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: [ + "user-history-profile", + DEFAULT_COMMUNITY_ID, + userId ?? null, + ], + }), + queryClient.invalidateQueries({ + queryKey: ["user-champion-stats", DEFAULT_COMMUNITY_ID, userId ?? null], + }), + queryClient.invalidateQueries({ + queryKey: ["user-recent-summary", DEFAULT_COMMUNITY_ID, userId ?? null], + }), + queryClient.invalidateQueries({ + queryKey: ["user-recent-matches", DEFAULT_COMMUNITY_ID, userId ?? null], + }), + queryClient.invalidateQueries({ + queryKey: [ + "user-internal-history", + DEFAULT_COMMUNITY_ID, + userId ?? null, + ], + }), + ]); + } + + function handleRefresh() { + if (!userId) return; + if (isInternalQueue) { + setRefreshResult(null); + setRefreshNotice("과거의 토너먼트 결과 수집 데이터를 다시 조회합니다."); + void queryClient.invalidateQueries({ + queryKey: [ + "user-internal-history", + DEFAULT_COMMUNITY_ID, + userId ?? null, + ], + }); + return; + } + refreshMutation.mutate( + { queueGroups: [queueGroup], priority: "high" }, + { + onSuccess: (result) => { + setRefreshResult(result); + const alreadyQueued = result.subJobs.every( + (job) => job.alreadyQueued, + ); + setRefreshNotice( + alreadyQueued + ? `이미 갱신 작업이 대기 중입니다. 예상 ${formatEta(result.totalEtaSeconds)} 후 반영됩니다.` + : `갱신을 요청했습니다. 예상 ${formatEta(result.totalEtaSeconds)} 후 반영됩니다.`, + ); + }, + onError: (error) => { + setRefreshNotice(formatRefreshError(error)); + }, + }, + ); + } + + if (!DEFAULT_COMMUNITY_ID) { + return ( +
+ + `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. + +
+ ); + } + + if (profileQuery.isLoading) { + return ( +
+ + 소환사 전적을 불러오는 중... + +
+ ); + } + + if (profileQuery.error || !profile) { + return ( +
+

소환사를 찾을 수 없습니다

+ + 홈으로 돌아가기 + +
+ ); + } + + return ( +
+ + ← 목록으로 + + +
+
+
+ +
+
+
+

+ {profile.gameName} +

+ + #{profile.tagLine} + +
+
+ Lv.{profile.summonerLevel} + {primaryTier ? ( + + {formatTierLabel(primaryTier)} {primaryTier.leaguePoints}LP + + ) : ( + 랭크 정보 없음 + )} + 시즌: {profile.season.label} + 최근 저장: {formatLastFetched(profile.lastFetchedAt)} +
+
+
+
+ {isInternalQueue ? ( + <> + {/* 내전 탭은 토너먼트 결과 DB를 조회합니다. */} + {/* Riot API 갱신 없이 수집된 내전 결과를 다시 불러옵니다. */} + 내전 기록이 확인되지 않을 경우 버튼을 눌러 갱신 (테스트) + + ) : ( + <> + {/* 이 페이지는 저장된 경기 DB만 조회합니다. */} +
+ {/* Riot API 갱신은 버튼 클릭 시 큐에서 처리합니다. */} + 아래 버튼을 누르면 기록이 갱신됩니다. + + )} +
+ + {!isInternalQueue && ( +
+ 갱신 소켓: {refreshSocket.connectionStatus} +
+ )} +
+
+ {(refreshNotice || refreshSocket.error) && ( +
+ {refreshNotice ?? refreshSocket.error} +
+ )} +
+ +
+
+ {QUEUE_GROUP_TABS.map((tab) => ( + + updateSearch({ queueGroup: tab.value, championId: null }) + } + > + {tab.label} + + ))} +
+
+ {!isInternalQueue ? ( +
+ {RANK_FILTER_TABS.map((tab) => ( + + updateSearch({ rank: tab.value, championId: null }) + } + > + {tab.label} + + ))} +
+ ) : ( +
+ 내전 탭은 토너먼트 코드 결과 수집 데이터를 기준으로 집계합니다. +
+ )} + {selectedChampionName && ( + + )} + {profile.seasons.length > 0 && ( + + )} +
+
+ +
+

+ 최근 {summary?.windowSize ?? 20}게임 전적 요약 +

+
+ + + + +
+
+ 자주 플레이한 챔피언 +
+
+ {(summary?.topChampions ?? []).map((champion) => ( + + ))} + {(summary?.topChampions ?? []).length === 0 && ( + + 기록 없음 + + )} +
+
+
+
+ +
+
+
+

챔피언 통계

+

+ 저장된 데이터를 기준으로 집계합니다. 최신 데이터가 반영되지 않을 + 수 있습니다. +

+
+
+ setChampionSearch(event.target.value)} + placeholder="챔피언 검색" + className="border border-base-content/10 bg-transparent px-3 py-2 text-xs focus:outline-none focus:border-primary/30" + /> + +
+
+ + updateSearch({ championId: nextChampionId }) + } + /> +
+ +
+
+

매치 히스토리

+ + 최근 저장: {formatLastFetched(historyLastFetchedAt)} + +
+ + {matchesLoading ? ( +
+ 최근 경기를 불러오는 중... +
+ ) : matches.length === 0 ? ( +
+ 조건에 맞는 최근 경기 기록이 없습니다. +
+ ) : ( +
+ {matches.map((match) => ( + + ))} +
+ )} + + {hasNextPage && ( + + )} +
+
+ ); +} diff --git a/apps/web/src/pages/admin/LegacyImportPage.tsx b/apps/web/src/pages/admin/LegacyImportPage.tsx new file mode 100644 index 00000000..3479e51d --- /dev/null +++ b/apps/web/src/pages/admin/LegacyImportPage.tsx @@ -0,0 +1,407 @@ +import { useEffect, useMemo, useState } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { Link, useParams } from 'react-router'; +import { + useCancelLegacyImport, + useLegacyImportJobs, + useLegacyImportMembers, + useMe, + useStartLegacyImport, +} from '../../api/hooks'; +import type { LegacyImportJob, StartLegacyImportRequest } from '../../api/types'; +import { DEFAULT_COMMUNITY_ID } from '../../config'; + +const DEFAULT_START = '2024-05-01T00:00:00.000Z'; + +function toInputValue(value: string) { + const date = new Date(value); + const local = new Date(date.getTime() - date.getTimezoneOffset() * 60_000); + return local.toISOString().slice(0, 16); +} + +function fromInputValue(value: string) { + return value ? new Date(value).toISOString() : undefined; +} + +function formatDate(value: string | undefined) { + if (!value) return '-'; + return new Intl.DateTimeFormat('ko-KR', { + month: 'long', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + }).format(new Date(value)); +} + +function formatEta(seconds: number) { + if (seconds < 60) return `${Math.max(1, Math.ceil(seconds))}초`; + if (seconds < 3600) return `${Math.ceil(seconds / 60)}분`; + return `${Math.ceil(seconds / 3600)}시간`; +} + +function progress(job: LegacyImportJob) { + if (job.totalMembers === 0) return 100; + return Math.round((job.processedMembers / job.totalMembers) * 100); +} + +function JobCard({ + job, + onCancel, + cancelling, +}: { + job: LegacyImportJob; + onCancel: (jobId: string) => void; + cancelling: boolean; +}) { + const running = job.state === 'pending' || job.state === 'running'; + const remaining = Math.max(0, job.totalMembers - job.processedMembers); + const eta = remaining * (job.averageMemberSeconds ?? 60); + + return ( +
+
+
+
+ {job.jobId} +
+
+ + {job.state} + + + {job.processedMembers}/{job.totalMembers}명 · 발견{' '} + {job.totalDiscoveredMatchIds} · import {job.totalImportedMatches} · + 중복 {job.totalSkippedDuplicate} · 에러 {job.totalErrors} + +
+
+ {running && ( + + )} +
+
+
+
+
+ + {formatDate(job.windowStart)} ~ {formatDate(job.windowEnd)} + + {running ? `예상 남은 시간 ${formatEta(eta)}` : formatDate(job.completedAt)} +
+
+ ); +} + +export default function LegacyImportPage() { + const { cid } = useParams(); + const communityId = cid ?? DEFAULT_COMMUNITY_ID; + const queryClient = useQueryClient(); + const meQuery = useMe(); + const [windowStart, setWindowStart] = useState(toInputValue(DEFAULT_START)); + const [windowEnd, setWindowEnd] = useState(''); + const [message, setMessage] = useState(null); + const [overrides, setOverrides] = useState< + Record + >({}); + const currentUser = + meQuery.data?.memberships.find( + (membership) => membership.community?._id === communityId, + )?.user ?? null; + const canManage = currentUser?.role === 'owner' || currentUser?.role === 'admin'; + const membersQuery = useLegacyImportMembers( + { + windowStart: fromInputValue(windowStart), + windowEnd: fromInputValue(windowEnd), + }, + communityId, + canManage, + ); + const jobsQuery = useLegacyImportJobs(communityId, canManage); + const startMutation = useStartLegacyImport(communityId); + const cancelMutation = useCancelLegacyImport(communityId); + const members = membersQuery.data?.members ?? []; + + useEffect(() => { + setOverrides( + Object.fromEntries( + members.map((member) => [ + member.userId, + { + startTime: toInputValue(member.startTime), + endTime: toInputValue(member.endTime), + }, + ]), + ), + ); + }, [members]); + + const manageableMemberships = + meQuery.data?.memberships.filter((membership) => { + const role = membership.user.role; + return Boolean( + membership.community && (role === 'owner' || role === 'admin'), + ); + }) ?? []; + const runningJob = useMemo( + () => + jobsQuery.data?.jobs.find( + (job) => job.state === 'pending' || job.state === 'running', + ), + [jobsQuery.data?.jobs], + ); + + async function invalidate() { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: ['legacy-import-jobs', communityId] }), + queryClient.invalidateQueries({ queryKey: ['legacy-matches', communityId] }), + queryClient.invalidateQueries({ + queryKey: ['community-internal-stats-matches', communityId], + }), + queryClient.invalidateQueries({ + queryKey: ['community-internal-stats-leaderboard', communityId], + }), + ]); + } + + function handleStart() { + if (!window.confirm('과거 type=tourney 매치 백필을 시작할까요? 야간/유휴 시간대 실행을 권장합니다.')) { + return; + } + const payload: StartLegacyImportRequest = { + windowStart: fromInputValue(windowStart), + windowEnd: fromInputValue(windowEnd), + memberOverrides: members.map((member) => ({ + userId: member.userId, + startTime: fromInputValue(overrides[member.userId]?.startTime ?? ''), + endTime: fromInputValue(overrides[member.userId]?.endTime ?? ''), + })), + }; + startMutation.mutate(payload, { + onSuccess: async (result) => { + await invalidate(); + setMessage( + `백필 작업을 시작했습니다. ${result.totalMembers}명, 예상 ${formatEta(result.etaSeconds)}.`, + ); + }, + onError: (error) => { + setMessage(error instanceof Error ? error.message : '백필 시작 실패'); + }, + }); + } + + if (!communityId) { + return ( +
+

커뮤니티 설정이 필요합니다

+
+ ); + } + + if (meQuery.isPending) { + return ( +
+

권한 확인 중...

+
+ ); + } + + if (!canManage) { + return ( +
+

권한이 필요합니다

+

+ Legacy 백필은 owner/admin만 실행할 수 있습니다. +

+ {manageableMemberships.length > 0 && ( +
+ {manageableMemberships.map((membership) => ( + + {membership.community?.name ?? '관리 가능한 커뮤니티'}로 이동 + + ))} +
+ )} +
+ ); + } + + return ( +
+ + ← 목록으로 + +
+
+

+ Legacy 내전 백필 +

+

+ 커뮤니티 멤버 PUUID로 과거 `type=tourney` 매치를 찾아 내전 기록으로 import합니다. +

+
+ + Legacy 매치 정리 + +
+ +
+

검색 윈도우

+
+ + + +
+ {message && ( +
+ {message} +
+ )} +
+ +
+
+

멤버별 윈도우

+

+ 기본 시작일은 2024-05-01이며, 필요하면 멤버별 시작/종료 시간을 조정할 수 있습니다. + 비활성 멤버는 종료일이 마지막 업데이트 시각으로 잡힙니다. +

+
+
+ + + + + + + + + + + + {members.map((member) => ( + + + + + + + + ))} + {members.length === 0 && ( + + + + )} + +
멤버Riot ID상태시작종료
+ {member.displayName} + + {member.gameName}#{member.tagLine} + + {member.isActivated ? '활성' : '비활성'} + + + setOverrides((current) => ({ + ...current, + [member.userId]: { + ...current[member.userId], + startTime: event.target.value, + endTime: current[member.userId]?.endTime ?? '', + }, + })) + } + className="border border-base-content/10 bg-transparent px-2 py-1 text-xs" + /> + + + setOverrides((current) => ({ + ...current, + [member.userId]: { + ...current[member.userId], + startTime: current[member.userId]?.startTime ?? '', + endTime: event.target.value, + }, + })) + } + className="border border-base-content/10 bg-transparent px-2 py-1 text-xs" + /> +
+ Riot 계정이 있는 멤버가 없습니다. +
+
+
+ +
+

작업 이력

+ {(jobsQuery.data?.jobs ?? []).map((job) => ( + + cancelMutation.mutate(jobId, { + onSuccess: invalidate, + }) + } + /> + ))} + {(jobsQuery.data?.jobs ?? []).length === 0 && ( +
+ 아직 실행한 백필 작업이 없습니다. +
+ )} +
+
+ ); +} diff --git a/apps/web/src/pages/admin/LegacyMatchesPage.tsx b/apps/web/src/pages/admin/LegacyMatchesPage.tsx new file mode 100644 index 00000000..adabd578 --- /dev/null +++ b/apps/web/src/pages/admin/LegacyMatchesPage.tsx @@ -0,0 +1,252 @@ +import { useMemo, useState } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { Link, useParams } from 'react-router'; +import { + useBulkDeleteLegacyMatches, + useDeleteMatch, + useLegacyMatches, + useMe, + useRebuildLegacyMatches, +} from '../../api/hooks'; +import type { LegacyMatchListItem } from '../../api/types'; +import { DEFAULT_COMMUNITY_ID } from '../../config'; + +function formatDate(value: string) { + return new Intl.DateTimeFormat('ko-KR', { + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + }).format(new Date(value)); +} + +function resultLabel(match: LegacyMatchListItem) { + if (!match.winnerSide) return '-'; + return match.winnerSide === 'blue' + ? `블루 ${match.blueScore}:${match.redScore}` + : `레드 ${match.redScore}:${match.blueScore}`; +} + +export default function LegacyMatchesPage() { + const { cid } = useParams(); + const communityId = cid ?? DEFAULT_COMMUNITY_ID; + const queryClient = useQueryClient(); + const meQuery = useMe(); + const [selected, setSelected] = useState>({}); + const currentUser = + meQuery.data?.memberships.find( + (membership) => membership.community?._id === communityId, + )?.user ?? null; + const canManage = currentUser?.role === 'owner' || currentUser?.role === 'admin'; + const matchesQuery = useLegacyMatches(communityId, canManage); + const deleteMutation = useDeleteMatch(communityId); + const bulkDeleteMutation = useBulkDeleteLegacyMatches(communityId); + const rebuildMutation = useRebuildLegacyMatches(communityId); + const matches = matchesQuery.data?.pages.flatMap((page) => page.matches) ?? []; + const selectedIds = useMemo( + () => Object.entries(selected).filter(([, value]) => value).map(([id]) => id), + [selected], + ); + + async function invalidate() { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: ['legacy-matches', communityId] }), + queryClient.invalidateQueries({ queryKey: ['matches', communityId] }), + queryClient.invalidateQueries({ + queryKey: ['community-internal-stats-matches', communityId], + }), + queryClient.invalidateQueries({ + queryKey: ['community-internal-stats-leaderboard', communityId], + }), + queryClient.invalidateQueries({ + queryKey: ['community-internal-stats-team-insights', communityId], + }), + ]); + } + + if (!communityId) { + return ( +
+

커뮤니티 설정이 필요합니다

+
+ ); + } + + if (meQuery.isPending) { + return ( +
+

권한 확인 중...

+
+ ); + } + + if (!canManage) { + return ( +
+

권한이 필요합니다

+

+ Legacy 매치 정리는 owner/admin만 사용할 수 있습니다. +

+
+ ); + } + + return ( +
+ + ← Legacy 백필 + +
+
+

+ Legacy 매치 정리 +

+

+ 백필로 들어온 매치를 확인하고 외부 토너먼트 기록을 삭제할 수 있습니다. +

+
+
+ + +
+
+ + {rebuildMutation.data && ( +
+ 재구성 완료: {rebuildMutation.data.scanned}개 확인 ·{' '} + {rebuildMutation.data.rebuilt}개 갱신 · 제목 정리{' '} + {rebuildMutation.data.normalizedTitles}개 +
+ )} + +
+
+ + + + + + + + + + + + + + + {matches.map((match) => ( + + + + + + + + + + + ))} + {matches.length === 0 && ( + + + + )} + +
+ 0 && selectedIds.length === matches.length} + onChange={(event) => { + const checked = event.target.checked; + setSelected( + Object.fromEntries(matches.map((match) => [match.matchId, checked])), + ); + }} + /> + 시간매치Riot matchId우리 멤버외부결과작업
+ + setSelected((current) => ({ + ...current, + [match.matchId]: event.target.checked, + })) + } + /> + + {formatDate(match.scheduledAt)} + + + {match.title} + + + {match.riotMatchId ?? '-'} + {match.memberCount}명{match.externalCount}명{resultLabel(match)} + +
+ Legacy import 매치가 없습니다. +
+
+
+ + {matchesQuery.hasNextPage && ( + + )} +
+ ); +} diff --git a/apps/web/src/pages/admin/TournamentCodesPage.tsx b/apps/web/src/pages/admin/TournamentCodesPage.tsx new file mode 100644 index 00000000..77b3647f --- /dev/null +++ b/apps/web/src/pages/admin/TournamentCodesPage.tsx @@ -0,0 +1,355 @@ +import { useMemo, useState } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { Link, useParams } from 'react-router'; +import { + useBulkUploadTournamentCodes, + useDeleteTournamentCode, + useMe, + useRestoreTournamentCode, + useTournamentCodes, + useTournamentCodeStats, +} from '../../api/hooks'; +import type { + TournamentCodeState, + TournamentCodeUploadItem, +} from '../../api/types'; +import { DEFAULT_COMMUNITY_ID } from '../../config'; + +const STATES: TournamentCodeState[] = [ + 'available', + 'reserved', + 'released', + 'used', + 'expired', +]; + +function formatDate(value: string | undefined) { + if (!value) return '-'; + return new Intl.DateTimeFormat('ko-KR', { + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + }).format(new Date(value)); +} + +function parseCsv(text: string): TournamentCodeUploadItem[] { + return text + .split(/\r?\n/u) + .map((line) => line.trim()) + .filter(Boolean) + .map((line) => { + const [code, expiresAt, notes] = line.split(',').map((part) => part.trim()); + return { code, expiresAt, notes }; + }); +} + +function parseJson(text: string): TournamentCodeUploadItem[] { + const parsed = JSON.parse(text) as unknown; + if (Array.isArray(parsed)) return parsed as TournamentCodeUploadItem[]; + if ( + typeof parsed === 'object' && + parsed !== null && + 'codes' in parsed && + Array.isArray((parsed as { codes: unknown }).codes) + ) { + return (parsed as { codes: TournamentCodeUploadItem[] }).codes; + } + throw new Error('JSON은 배열 또는 { codes: [...] } 형태여야 합니다.'); +} + +export default function TournamentCodesPage() { + const { cid } = useParams(); + const communityId = cid ?? DEFAULT_COMMUNITY_ID; + const queryClient = useQueryClient(); + const meQuery = useMe(); + const [stateFilter, setStateFilter] = useState(''); + const [mode, setMode] = useState<'csv' | 'json'>('csv'); + const [text, setText] = useState(''); + const [message, setMessage] = useState(null); + const currentUser = + meQuery.data?.memberships.find( + (membership) => membership.community?._id === communityId, + )?.user ?? null; + const canManage = currentUser?.role === 'owner' || currentUser?.role === 'admin'; + const manageableMemberships = + meQuery.data?.memberships.filter((membership) => { + const role = membership.user.role; + return Boolean( + membership.community && (role === 'owner' || role === 'admin'), + ); + }) ?? []; + const statsQuery = useTournamentCodeStats(communityId, canManage); + const listQuery = useTournamentCodes( + { state: stateFilter || undefined, limit: 200 }, + communityId, + canManage, + ); + const uploadMutation = useBulkUploadTournamentCodes(communityId); + const restoreMutation = useRestoreTournamentCode(communityId); + const deleteMutation = useDeleteTournamentCode(communityId); + + const counts = statsQuery.data?.byState; + const codes = useMemo( + () => listQuery.data?.codes ?? [], + [listQuery.data?.codes], + ); + + async function invalidate() { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: ['tournament-code-stats', communityId], + }), + queryClient.invalidateQueries({ + queryKey: ['tournament-codes', communityId], + }), + queryClient.invalidateQueries({ + queryKey: ['matches', communityId], + }), + ]); + } + + function handleUpload() { + setMessage(null); + let payload: TournamentCodeUploadItem[]; + try { + payload = mode === 'csv' ? parseCsv(text) : parseJson(text); + } catch (error) { + setMessage(error instanceof Error ? error.message : '입력 파싱 실패'); + return; + } + + uploadMutation.mutate(payload, { + onSuccess: async (result) => { + await invalidate(); + setMessage( + `업로드 완료: ${result.inserted}개 추가, 중복 ${result.duplicates.length}개, invalid ${result.invalid.length}개`, + ); + }, + onError: (error) => { + setMessage(error instanceof Error ? error.message : '업로드 실패'); + }, + }); + } + + if (!communityId) { + return ( +
+

커뮤니티 설정이 필요합니다

+

+ `VITE_DEFAULT_COMMUNITY_ID`를 설정하거나 올바른 커뮤니티 경로로 + 접속해주세요. +

+
+ ); + } + + if (meQuery.isPending) { + return ( +
+

권한 확인 중...

+

+ 로그인한 계정의 커뮤니티 권한을 확인하고 있습니다. +

+
+ ); + } + + if (!canManage) { + return ( +
+

권한이 필요합니다

+

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

+ {manageableMemberships.length > 0 && ( +
+ {manageableMemberships.map((membership) => ( + + {membership.community?.name ?? '관리 가능한 커뮤니티'}로 이동 + + ))} +
+ )} +
+ ); + } + + return ( +
+ + ← 목록으로 + +
+

+ 토너먼트 코드 풀 +

+

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

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

Bulk 업로드

+
+ + +
+
+