From 1e304f48e50aff48b58b5dd971c366af32ad7cf5 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: Sun, 26 Apr 2026 23:44:00 +0900 Subject: [PATCH] feat(web): add legacy import admin --- apps/web/src/pages/admin/LegacyImportPage.tsx | 407 ++++++++++++++++++ .../web/src/pages/admin/LegacyMatchesPage.tsx | 259 +++++++++++ 2 files changed, 666 insertions(+) create mode 100644 apps/web/src/pages/admin/LegacyImportPage.tsx create mode 100644 apps/web/src/pages/admin/LegacyMatchesPage.tsx 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..bf85177d --- /dev/null +++ b/apps/web/src/pages/admin/LegacyMatchesPage.tsx @@ -0,0 +1,259 @@ +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'; +import { teamIndexLabel } from '../../lib/league'; + +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.winnerTeamIndex) return '-'; + const winnerScore = + match.winnerTeamIndex === match.teamAIndex + ? match.teamAWins + : match.teamBWins; + const loserScore = + match.winnerTeamIndex === match.teamAIndex + ? match.teamBWins + : match.teamAWins; + return `${teamIndexLabel(match.winnerTeamIndex)} ${winnerScore}:${loserScore}`; +} + +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 && ( + + )} +
+ ); +}