feat(web): add legacy import admin

This commit is contained in:
dahyeon committed 2026-04-26 23:44:00 +09:00
1 parent ad3c37c48c
commit 1e304f48e5
2 files changed
+666

No files matched your search

@@ -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 (
<div className="border border-base-content/10 bg-base-100 p-4">
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
<div>
<div className="text-[11px] font-mono text-base-content/35">
{job.jobId}
</div>
<div className="mt-1 flex flex-wrap items-center gap-2">
<span className="text-sm font-black text-base-content">
{job.state}
</span>
<span className="text-xs text-base-content/40">
{job.processedMembers}/{job.totalMembers}명 · 발견{' '}
{job.totalDiscoveredMatchIds} · import {job.totalImportedMatches} ·
중복 {job.totalSkippedDuplicate} · 에러 {job.totalErrors}
</span>
</div>
</div>
{running && (
<button
type="button"
className="btn btn-ghost btn-xs px-3 text-red-400"
disabled={cancelling}
onClick={() => onCancel(job.jobId)}
>
취소
</button>
)}
</div>
<div className="mt-3 h-2 bg-base-content/8">
<div
className="h-full bg-primary"
style={{ width: `${progress(job)}%` }}
/>
</div>
<div className="mt-2 flex flex-wrap justify-between gap-2 text-[11px] text-base-content/35">
<span>
{formatDate(job.windowStart)} ~ {formatDate(job.windowEnd)}
</span>
<span>{running ? `예상 남은 시간 ${formatEta(eta)}` : formatDate(job.completedAt)}</span>
</div>
</div>
);
}
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<string | null>(null);
const [overrides, setOverrides] = useState<
Record<string, { startTime: string; endTime: string }>
>({});
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 (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<h1 className="text-lg font-bold">커뮤니티 설정이 필요합니다</h1>
</main>
);
}
if (meQuery.isPending) {
return (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<h1 className="text-lg font-bold">권한 확인 중...</h1>
</main>
);
}
if (!canManage) {
return (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<h1 className="text-lg font-bold">권한이 필요합니다</h1>
<p className="mt-2 text-sm text-base-content/40">
Legacy 백필은 owner/admin만 실행할 수 있습니다.
</p>
{manageableMemberships.length > 0 && (
<div className="mt-5 flex flex-wrap justify-center gap-2">
{manageableMemberships.map((membership) => (
<Link
key={membership.community?._id ?? membership.user._id}
to={`/admin/communities/${membership.community?._id}/legacy-import`}
className="btn btn-primary btn-sm px-4 text-xs"
>
{membership.community?.name ?? '관리 가능한 커뮤니티'}로 이동
</Link>
))}
</div>
)}
</main>
);
}
return (
<main className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
<Link to="/" className="inline-flex text-xs text-base-content/40 hover:text-base-content mb-5">
← 목록으로
</Link>
<div className="mb-6 flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3">
<div>
<h1 className="text-2xl font-black text-base-content">
Legacy 내전 백필
</h1>
<p className="mt-1 text-sm text-base-content/45">
커뮤니티 멤버 PUUID로 과거 `type=tourney` 매치를 찾아 내전 기록으로 import합니다.
</p>
</div>
<Link
to={`/admin/communities/${communityId}/legacy-matches`}
className="btn btn-ghost btn-sm px-4 text-xs"
>
Legacy 매치 정리
</Link>
</div>
<section className="border border-base-content/10 bg-base-100 p-4 mb-6">
<h2 className="text-sm font-bold mb-3">검색 윈도우</h2>
<div className="grid sm:grid-cols-[1fr_1fr_auto] gap-3 items-end">
<label className="text-xs text-base-content/45">
시작일
<input
type="datetime-local"
value={windowStart}
onChange={(event) => setWindowStart(event.target.value)}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-xs"
/>
</label>
<label className="text-xs text-base-content/45">
종료일
<input
type="datetime-local"
value={windowEnd}
onChange={(event) => setWindowEnd(event.target.value)}
placeholder="비우면 지금"
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-xs"
/>
</label>
<button
type="button"
className="btn btn-primary btn-sm px-5 text-xs"
disabled={startMutation.isPending || Boolean(runningJob)}
onClick={handleStart}
>
{runningJob
? '작업 진행 중'
: startMutation.isPending
? '시작 중...'
: '백필 시작'}
</button>
</div>
{message && (
<div className="mt-3 border border-primary/15 bg-primary/5 px-3 py-2 text-xs text-base-content/55">
{message}
</div>
)}
</section>
<section className="border border-base-content/10 bg-base-100 overflow-hidden mb-6">
<div className="px-4 py-3 border-b border-base-content/10">
<h2 className="text-sm font-bold">멤버별 윈도우</h2>
<p className="mt-1 text-[11px] text-base-content/35">
기본 시작일은 2024-05-01이며, 필요하면 멤버별 시작/종료 시간을 조정할 수 있습니다.
비활성 멤버는 종료일이 마지막 업데이트 시각으로 잡힙니다.
</p>
</div>
<div className="overflow-x-auto">
<table className="w-full min-w-[900px] text-left">
<thead>
<tr className="bg-base-200/40 border-b border-base-content/10 text-[11px] uppercase tracking-wider text-base-content/35">
<th className="px-3 py-2">멤버</th>
<th className="px-3 py-2">Riot ID</th>
<th className="px-3 py-2">상태</th>
<th className="px-3 py-2">시작</th>
<th className="px-3 py-2">종료</th>
</tr>
</thead>
<tbody>
{members.map((member) => (
<tr key={member.userId} className="border-b border-base-content/5">
<td className="px-3 py-2 text-sm font-bold">
{member.displayName}
</td>
<td className="px-3 py-2 text-xs text-base-content/45">
{member.gameName}#{member.tagLine}
</td>
<td className="px-3 py-2 text-xs">
{member.isActivated ? '활성' : '비활성'}
</td>
<td className="px-3 py-2">
<input
type="datetime-local"
value={overrides[member.userId]?.startTime ?? ''}
onChange={(event) =>
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"
/>
</td>
<td className="px-3 py-2">
<input
type="datetime-local"
value={overrides[member.userId]?.endTime ?? ''}
onChange={(event) =>
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"
/>
</td>
</tr>
))}
{members.length === 0 && (
<tr>
<td colSpan={5} className="px-4 py-8 text-center text-sm text-base-content/35">
Riot 계정이 있는 멤버가 없습니다.
</td>
</tr>
)}
</tbody>
</table>
</div>
</section>
<section className="space-y-3">
<h2 className="text-sm font-bold">작업 이력</h2>
{(jobsQuery.data?.jobs ?? []).map((job) => (
<JobCard
key={job.jobId}
job={job}
cancelling={cancelMutation.isPending}
onCancel={(jobId) =>
cancelMutation.mutate(jobId, {
onSuccess: invalidate,
})
}
/>
))}
{(jobsQuery.data?.jobs ?? []).length === 0 && (
<div className="border border-base-content/10 bg-base-100 px-4 py-8 text-center text-sm text-base-content/35">
아직 실행한 백필 작업이 없습니다.
</div>
)}
</section>
</main>
);
}
@@ -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<Record<string, boolean>>({});
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 (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<h1 className="text-lg font-bold">커뮤니티 설정이 필요합니다</h1>
</main>
);
}
if (meQuery.isPending) {
return (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<h1 className="text-lg font-bold">권한 확인 중...</h1>
</main>
);
}
if (!canManage) {
return (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<h1 className="text-lg font-bold">권한이 필요합니다</h1>
<p className="mt-2 text-sm text-base-content/40">
Legacy 매치 정리는 owner/admin만 사용할 수 있습니다.
</p>
</main>
);
}
return (
<main className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
<Link
to={`/admin/communities/${communityId}/legacy-import`}
className="inline-flex text-xs text-base-content/40 hover:text-base-content mb-5"
>
← Legacy 백필
</Link>
<div className="mb-6 flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3">
<div>
<h1 className="text-2xl font-black text-base-content">
Legacy 매치 정리
</h1>
<p className="mt-1 text-sm text-base-content/45">
백필로 들어온 매치를 확인하고 외부 토너먼트 기록을 삭제할 수 있습니다.
</p>
</div>
<div className="flex flex-wrap gap-2">
<button
type="button"
className="btn btn-primary btn-sm px-4 text-xs"
disabled={rebuildMutation.isPending}
onClick={() => {
if (!window.confirm('현재 가입자 기준으로 과거 매치를 재구성할까요?')) {
return;
}
rebuildMutation.mutate(undefined, { onSuccess: invalidate });
}}
>
{rebuildMutation.isPending ? '재구성 중...' : '과거 데이터 재구성'}
</button>
<button
type="button"
className="btn btn-ghost btn-sm px-4 text-xs text-red-400"
disabled={selectedIds.length === 0 || bulkDeleteMutation.isPending}
onClick={() => {
if (!window.confirm(`${selectedIds.length}개 매치를 삭제할까요?`)) return;
bulkDeleteMutation.mutate(selectedIds, {
onSuccess: async () => {
setSelected({});
await invalidate();
},
});
}}
>
선택 삭제 ({selectedIds.length})
</button>
</div>
</div>
{rebuildMutation.data && (
<div className="mb-4 border border-primary/20 bg-primary/5 px-3 py-2 text-xs text-base-content/55">
재구성 완료: {rebuildMutation.data.scanned}개 확인 ·{' '}
{rebuildMutation.data.rebuilt}개 갱신 · 제목 정리{' '}
{rebuildMutation.data.normalizedTitles}개
</div>
)}
<section className="border border-base-content/10 bg-base-100 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full min-w-[900px] text-left">
<thead>
<tr className="bg-base-200/40 border-b border-base-content/10 text-[11px] uppercase tracking-wider text-base-content/35">
<th className="px-3 py-2 w-8">
<input
type="checkbox"
checked={matches.length > 0 && selectedIds.length === matches.length}
onChange={(event) => {
const checked = event.target.checked;
setSelected(
Object.fromEntries(matches.map((match) => [match.matchId, checked])),
);
}}
/>
</th>
<th className="px-3 py-2">시간</th>
<th className="px-3 py-2">매치</th>
<th className="px-3 py-2">Riot matchId</th>
<th className="px-3 py-2">우리 멤버</th>
<th className="px-3 py-2">외부</th>
<th className="px-3 py-2">결과</th>
<th className="px-3 py-2 text-right">작업</th>
</tr>
</thead>
<tbody>
{matches.map((match) => (
<tr key={match.matchId} className="border-b border-base-content/5">
<td className="px-3 py-2">
<input
type="checkbox"
checked={Boolean(selected[match.matchId])}
onChange={(event) =>
setSelected((current) => ({
...current,
[match.matchId]: event.target.checked,
}))
}
/>
</td>
<td className="px-3 py-2 text-xs text-base-content/45">
{formatDate(match.scheduledAt)}
</td>
<td className="px-3 py-2">
<Link
to={`/communities/${communityId}/internal-stats/match/${match.matchId}`}
className="text-sm font-bold hover:text-primary"
>
{match.title}
</Link>
</td>
<td className="px-3 py-2 text-xs font-mono text-base-content/40">
{match.riotMatchId ?? '-'}
</td>
<td className="px-3 py-2 text-xs">{match.memberCount}명</td>
<td className="px-3 py-2 text-xs">{match.externalCount}명</td>
<td className="px-3 py-2 text-xs">{resultLabel(match)}</td>
<td className="px-3 py-2 text-right">
<button
type="button"
className="text-[11px] px-2 py-1 border border-red-500/20 text-red-400 hover:bg-red-500/10"
disabled={deleteMutation.isPending}
onClick={() => {
if (!window.confirm('이 매치를 삭제할까요?')) return;
deleteMutation.mutate(match.matchId, {
onSuccess: invalidate,
});
}}
>
삭제
</button>
</td>
</tr>
))}
{matches.length === 0 && (
<tr>
<td colSpan={8} className="px-4 py-10 text-center text-sm text-base-content/35">
Legacy import 매치가 없습니다.
</td>
</tr>
)}
</tbody>
</table>
</div>
</section>
{matchesQuery.hasNextPage && (
<button
type="button"
className="mt-3 w-full border border-base-content/15 bg-base-100 py-3 text-sm font-bold text-base-content/60 hover:text-primary hover:border-primary/30 disabled:opacity-40"
disabled={matchesQuery.isFetchingNextPage}
onClick={() => matchesQuery.fetchNextPage()}
>
{matchesQuery.isFetchingNextPage ? '불러오는 중...' : '+ 더 보기'}
</button>
)}
</main>
);
}