Files
lolympus-tournament-support/apps/web/src/pages/admin/LegacyMatchesPage.tsx
T

260 lines
9.9 KiB
TypeScript

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>
);
}