356 lines
13 KiB
TypeScript
356 lines
13 KiB
TypeScript
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<TournamentCodeState | ''>('');
|
|
const [mode, setMode] = useState<'csv' | 'json'>('csv');
|
|
const [text, setText] = useState('');
|
|
const [message, setMessage] = useState<string | null>(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 (
|
|
<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">
|
|
`VITE_DEFAULT_COMMUNITY_ID`를 설정하거나 올바른 커뮤니티 경로로
|
|
접속해주세요.
|
|
</p>
|
|
</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>
|
|
<p className="mt-2 text-sm text-base-content/40">
|
|
로그인한 계정의 커뮤니티 권한을 확인하고 있습니다.
|
|
</p>
|
|
</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">
|
|
토너먼트 코드 풀은 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}/tournament-codes`}
|
|
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">
|
|
<h1 className="text-2xl font-black text-base-content">
|
|
토너먼트 코드 풀
|
|
</h1>
|
|
<p className="mt-1 text-sm text-base-content/45">
|
|
외부에서 생성한 코드를 업로드하고, 매치에 자동 할당되는 풀을 관리합니다.
|
|
</p>
|
|
</div>
|
|
|
|
<section className="grid sm:grid-cols-5 gap-3 mb-6">
|
|
{STATES.map((state) => (
|
|
<div key={state} className="border border-base-content/10 bg-base-100 p-4">
|
|
<div className="text-[10px] uppercase tracking-wider text-base-content/30">
|
|
{state}
|
|
</div>
|
|
<div className="mt-2 text-2xl font-black tabular-nums">
|
|
{counts?.[state] ?? 0}
|
|
</div>
|
|
</div>
|
|
))}
|
|
</section>
|
|
|
|
<section className="border border-base-content/10 bg-base-100 p-4 mb-6">
|
|
<div className="flex items-center justify-between gap-3 mb-3">
|
|
<h2 className="text-sm font-bold">Bulk 업로드</h2>
|
|
<div className="flex gap-1">
|
|
<button
|
|
type="button"
|
|
className={`px-3 py-1 text-xs border ${mode === 'csv' ? 'border-primary/40 text-primary bg-primary/5' : 'border-base-content/10 text-base-content/40'}`}
|
|
onClick={() => setMode('csv')}
|
|
>
|
|
간단 CSV
|
|
</button>
|
|
<button
|
|
type="button"
|
|
className={`px-3 py-1 text-xs border ${mode === 'json' ? 'border-primary/40 text-primary bg-primary/5' : 'border-base-content/10 text-base-content/40'}`}
|
|
onClick={() => setMode('json')}
|
|
>
|
|
확장 JSON
|
|
</button>
|
|
</div>
|
|
</div>
|
|
<textarea
|
|
value={text}
|
|
onChange={(event) => setText(event.target.value)}
|
|
rows={7}
|
|
placeholder={
|
|
mode === 'csv'
|
|
? 'KR-ABCD-1234,2026-05-30T18:00:00Z,메모'
|
|
: '[{"code":"KR-ABCD-1234","expiresAt":"2026-05-30T18:00:00Z","source":"external"}]'
|
|
}
|
|
className="w-full border border-base-content/10 bg-transparent p-3 text-xs font-mono focus:outline-none focus:border-primary/30"
|
|
/>
|
|
<div className="mt-3 flex items-center gap-3">
|
|
<button
|
|
type="button"
|
|
className="btn btn-primary btn-sm px-5 text-xs"
|
|
disabled={uploadMutation.isPending || !text.trim()}
|
|
onClick={handleUpload}
|
|
>
|
|
{uploadMutation.isPending ? '업로드 중...' : '업로드'}
|
|
</button>
|
|
{message && <span className="text-xs text-base-content/45">{message}</span>}
|
|
</div>
|
|
</section>
|
|
|
|
<section className="border border-base-content/10 bg-base-100 overflow-hidden">
|
|
<div className="px-4 py-3 border-b border-base-content/10 flex items-center justify-between gap-3">
|
|
<h2 className="text-sm font-bold">코드 목록</h2>
|
|
<select
|
|
value={stateFilter}
|
|
onChange={(event) => setStateFilter(event.target.value as TournamentCodeState | '')}
|
|
className="border border-base-content/10 bg-transparent px-2 py-1 text-xs"
|
|
>
|
|
<option value="">전체</option>
|
|
{STATES.map((state) => (
|
|
<option key={state} value={state}>
|
|
{state}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</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">상태</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>
|
|
{codes.map((code) => (
|
|
<tr key={code._id} className="border-b border-base-content/5">
|
|
<td className="px-3 py-2 font-mono text-xs font-bold">
|
|
{code.code}
|
|
</td>
|
|
<td className="px-3 py-2 text-xs">{code.state}</td>
|
|
<td className="px-3 py-2 text-xs text-base-content/50">
|
|
{formatDate(code.expiresAt)}
|
|
</td>
|
|
<td className="px-3 py-2 text-xs text-base-content/50">
|
|
{code.matchId ? (
|
|
<Link to={`/match/${code.matchId}`} className="text-primary">
|
|
{code.matchId.slice(-6)} · {code.gameNumber}경기
|
|
</Link>
|
|
) : (
|
|
'-'
|
|
)}
|
|
</td>
|
|
<td className="px-3 py-2 text-xs text-base-content/50">
|
|
{code.source ?? '-'}
|
|
</td>
|
|
<td className="px-3 py-2">
|
|
<div className="flex justify-end gap-2">
|
|
{(code.state === 'released' || code.state === 'reserved') && (
|
|
<button
|
|
type="button"
|
|
className="text-[11px] px-2 py-1 border border-base-content/10 text-base-content/50 hover:text-primary"
|
|
onClick={() =>
|
|
restoreMutation.mutate(code._id, {
|
|
onSuccess: invalidate,
|
|
})
|
|
}
|
|
>
|
|
available 환원
|
|
</button>
|
|
)}
|
|
{code.state === 'available' && (
|
|
<button
|
|
type="button"
|
|
className="text-[11px] px-2 py-1 border border-red-500/20 text-red-400"
|
|
onClick={() =>
|
|
deleteMutation.mutate(code._id, {
|
|
onSuccess: invalidate,
|
|
})
|
|
}
|
|
>
|
|
폐기
|
|
</button>
|
|
)}
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
))}
|
|
{codes.length === 0 && (
|
|
<tr>
|
|
<td
|
|
colSpan={6}
|
|
className="px-4 py-10 text-center text-sm text-base-content/35"
|
|
>
|
|
코드가 없습니다.
|
|
</td>
|
|
</tr>
|
|
)}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</section>
|
|
</main>
|
|
);
|
|
}
|