From 7989da96d016722746dc03597c2fc4b79ca6513c 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: Sat, 25 Apr 2026 04:29:00 +0900 Subject: [PATCH] feat(web): add auction and admin workflows --- apps/web/src/pages/AuctionPage.tsx | 802 ++++++++++++++++++ apps/web/src/pages/admin/LegacyImportPage.tsx | 407 +++++++++ .../web/src/pages/admin/LegacyMatchesPage.tsx | 252 ++++++ .../src/pages/admin/TournamentCodesPage.tsx | 355 ++++++++ 4 files changed, 1816 insertions(+) create mode 100644 apps/web/src/pages/AuctionPage.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 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/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 업로드

+
+ + +
+
+