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

591 lines
22 KiB
TypeScript

import { useMemo, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import type {
MatchDetailResponse,
MatchGameMode,
MatchScheduleItemView,
} from '@lolympus/contracts';
import { Link, useParams } from 'react-router';
import {
useCreateMatch,
useDeleteMatch,
useMatches,
useMe,
useUpdateMatch,
} from '../../api/hooks';
import type { MatchMutationRequest } from '../../api/types';
import { DEFAULT_COMMUNITY_ID } from '../../config';
const DEFAULT_FORM: MatchMutationRequest = {
title: '',
description: '',
mapId: 11,
scheduledAt: toInputValue(new Date(Date.now() + 24 * 60 * 60 * 1000)),
maxParticipants: 10,
gameCount: 3,
gameMode: 'pair',
doubleEliminationResetFinalEnabled: true,
prizes: [],
notices: [],
schedule: [],
};
const GAME_MODE_LABEL: Record<MatchGameMode, string> = {
pair: '페어',
'round-robin': '라운드 로빈',
'double-elimination': '더블 엘리미네이션',
};
function resolveRoundRobinFullRoundCount(maxParticipants?: number) {
const teamCount = Math.floor(Number(maxParticipants ?? 10) / 5);
if (teamCount < 2) return 0;
return teamCount % 2 === 0 ? teamCount - 1 : teamCount;
}
function normalizeRoundRobinMaxRounds(
value: number | undefined,
maxParticipants?: number,
) {
if (!value || !Number.isFinite(value)) return undefined;
const fullRoundCount = resolveRoundRobinFullRoundCount(maxParticipants);
return Math.max(1, Math.min(fullRoundCount, Math.floor(value)));
}
function normalizeSeriesGameCount(value: number | undefined) {
if (!value || !Number.isFinite(value) || value < 1) return 3;
const integer = Math.floor(value);
return integer % 2 === 0 ? integer + 1 : integer;
}
function RequiredBadge() {
return (
<span className="ml-1 inline-flex items-center border border-primary/20 bg-primary/5 px-1.5 py-0.5 text-xs font-bold text-primary">
필수
</span>
);
}
function toInputValue(value: string | Date) {
const date = value instanceof Date ? value : new Date(value);
const offset = date.getTimezoneOffset();
return new Date(date.getTime() - offset * 60_000).toISOString().slice(0, 16);
}
function toIsoFromInput(value: string) {
return new Date(value).toISOString();
}
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 parseLines(value: string) {
return value
.split(/\r?\n/u)
.map((line) => line.trim())
.filter(Boolean);
}
function parseSchedule(value: string): MatchScheduleItemView[] {
return parseLines(value).map((line) => {
const [time, ...labelParts] = line.split('|').map((part) => part.trim());
return {
time: time || '00:00',
label: labelParts.join('|') || '일정',
};
});
}
function scheduleToText(schedule: MatchScheduleItemView[] = []) {
return schedule.map((item) => `${item.time}|${item.label}`).join('\n');
}
function makeForm(match?: MatchDetailResponse): MatchMutationRequest & {
prizesText: string;
noticesText: string;
scheduleText: string;
} {
if (!match) {
return {
...DEFAULT_FORM,
prizesText: '',
noticesText: '',
scheduleText: '',
};
}
return {
title: match.title,
description: match.description,
mapId: match.mapId,
scheduledAt: toInputValue(match.scheduledAt),
maxParticipants: match.maxParticipants,
gameCount: match.gameCount,
gameMode: match.gameMode ?? 'pair',
roundRobinMaxRounds: match.roundRobinMaxRounds,
doubleEliminationResetFinalEnabled:
match.doubleEliminationResetFinalEnabled ?? true,
prizes: match.prizes,
notices: match.notices,
schedule: match.schedule,
prizesText: match.prizes.join('\n'),
noticesText: match.notices.join('\n'),
scheduleText: scheduleToText(match.schedule),
};
}
export default function MatchAdminPage() {
const { cid } = useParams();
const communityId = cid ?? DEFAULT_COMMUNITY_ID;
const queryClient = useQueryClient();
const meQuery = useMe();
const matchesQuery = useMatches({ limit: 200 }, communityId);
const createMutation = useCreateMatch(communityId);
const updateMutation = useUpdateMatch(communityId);
const deleteMutation = useDeleteMatch(communityId);
const [editing, setEditing] = useState<MatchDetailResponse | null>(null);
const [showForm, setShowForm] = useState(false);
const [form, setForm] = useState(makeForm());
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 matches = useMemo(
() => [...(matchesQuery.data ?? [])].sort((a, b) => new Date(b.scheduledAt).getTime() - new Date(a.scheduledAt).getTime()),
[matchesQuery.data],
);
const roundRobinFullRoundCount = resolveRoundRobinFullRoundCount(
form.maxParticipants,
);
async function invalidate() {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['matches', communityId] }),
queryClient.invalidateQueries({ queryKey: ['match', communityId] }),
]);
}
function openCreate() {
setEditing(null);
setForm(makeForm());
setShowForm(true);
setMessage(null);
}
function openEdit(match: MatchDetailResponse) {
setEditing(match);
setForm(makeForm(match));
setShowForm(true);
setMessage(null);
}
function buildPayload(): MatchMutationRequest {
return {
title: form.title.trim(),
description: form.description?.trim() ?? '',
mapId: Number(form.mapId ?? 11),
scheduledAt: toIsoFromInput(form.scheduledAt),
maxParticipants: Number(form.maxParticipants ?? 10),
gameCount: Number(form.gameCount ?? 3),
gameMode: form.gameMode,
doubleEliminationResetFinalEnabled:
form.gameMode === 'double-elimination'
? Boolean(form.doubleEliminationResetFinalEnabled)
: undefined,
roundRobinMaxRounds:
form.gameMode === 'round-robin'
? normalizeRoundRobinMaxRounds(
form.roundRobinMaxRounds,
form.maxParticipants,
)
: undefined,
prizes: parseLines(form.prizesText),
notices: parseLines(form.noticesText),
schedule: parseSchedule(form.scheduleText),
};
}
function submit() {
setMessage(null);
if (!form.title.trim()) {
setMessage('제목을 입력해주세요.');
return;
}
if (!form.scheduledAt) {
setMessage('시작 시간을 입력해주세요.');
return;
}
const payload = buildPayload();
const callbacks = {
onSuccess: async () => {
await invalidate();
setShowForm(false);
setEditing(null);
setMessage(editing ? '내전을 수정했습니다.' : '내전을 만들었습니다.');
},
onError: (error: Error) => setMessage(error.message),
};
if (editing) {
updateMutation.mutate({ matchId: editing._id, body: payload }, callbacks);
return;
}
createMutation.mutate(payload, callbacks);
}
if (!canManage && !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">
내전 관리는 owner/admin만 사용할 수 있습니다.
</p>
</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">내전 관리</h1>
<p className="mt-1 text-sm text-base-content/45">
내전 생성, 모집 정원, 게임 모드와 공지 내용을 관리합니다.
</p>
</div>
<button type="button" className="btn btn-primary btn-sm px-5 text-xs" onClick={openCreate}>
새 내전 만들기
</button>
</div>
{message && (
<div className="mb-4 border border-primary/20 bg-primary/5 px-3 py-2 text-xs text-base-content/60">
{message}
</div>
)}
{showForm && (
<section className="mb-6 border border-base-content/10 bg-base-100 p-4">
<div className="mb-4 flex items-center justify-between gap-3">
<h2 className="text-sm font-bold">
{editing ? '내전 수정' : '새 내전'}
</h2>
<button
type="button"
className="text-xs text-base-content/35 hover:text-base-content"
onClick={() => setShowForm(false)}
>
닫기
</button>
</div>
<div className="grid md:grid-cols-2 gap-3">
<label className="text-xs text-base-content/45 md:col-span-2">
제목
<RequiredBadge />
<input
required
value={form.title}
onChange={(event) => setForm((current) => ({ ...current, title: event.target.value }))}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
/>
</label>
<label className="text-xs text-base-content/45 md:col-span-2">
설명
<span className="ml-1 text-xs text-base-content/25">선택</span>
<textarea
value={form.description}
onChange={(event) => setForm((current) => ({ ...current, description: event.target.value }))}
rows={3}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
/>
</label>
<label className="text-xs text-base-content/45">
시작 시간
<RequiredBadge />
<input
required
type="datetime-local"
value={form.scheduledAt}
onChange={(event) => setForm((current) => ({ ...current, scheduledAt: event.target.value }))}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
/>
</label>
<label className="text-xs text-base-content/45">
정원
<select
value={form.maxParticipants}
onChange={(event) => {
const maxParticipants = Number(event.target.value);
setForm((current) => ({
...current,
maxParticipants,
roundRobinMaxRounds: normalizeRoundRobinMaxRounds(
current.roundRobinMaxRounds,
maxParticipants,
),
}));
}}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
>
{(form.gameMode === 'double-elimination'
? [20, 40]
: [10, 20, 30, 40, 50, 60]
).map((value) => (
<option key={value} value={value}>{value}명</option>
))}
</select>
</label>
<label className="text-xs text-base-content/45">
게임 수
<input
type="number"
min={1}
step={form.gameMode === 'double-elimination' ? 2 : 1}
value={form.gameCount}
onChange={(event) => setForm((current) => ({ ...current, gameCount: Number(event.target.value) }))}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
/>
{form.gameMode === 'double-elimination' && (
<span className="mt-1 block text-xs text-base-content/30">
승자조는 현재 3판 2선승으로 진행됩니다. 추후 5판 3선승도 같은
구조로 지원합니다.
</span>
)}
</label>
<label className="text-xs text-base-content/45">
게임 모드
<select
value={form.gameMode}
onChange={(event) => {
const gameMode = event.target.value as MatchGameMode;
setForm((current) => ({
...current,
gameMode,
maxParticipants:
gameMode === 'double-elimination' &&
current.maxParticipants !== 20 &&
current.maxParticipants !== 40
? 20
: current.maxParticipants,
gameCount:
gameMode === 'double-elimination'
? normalizeSeriesGameCount(current.gameCount)
: current.gameCount,
}));
}}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
>
{Object.entries(GAME_MODE_LABEL).map(([value, label]) => (
<option key={value} value={value}>{label}</option>
))}
</select>
<span className="mt-1 block text-xs text-amber-500/80">
현재 경매/코드 연결은 페어 방식 기준으로 동작합니다.
</span>
</label>
{form.gameMode === 'round-robin' && (
<label className="text-xs text-base-content/45">
최대 라운드 수
<span className="ml-1 text-xs text-base-content/25">선택</span>
<input
type="number"
min={1}
max={roundRobinFullRoundCount || undefined}
placeholder="예: 3"
value={form.roundRobinMaxRounds ?? ''}
onChange={(event) =>
setForm((current) => ({
...current,
roundRobinMaxRounds:
event.target.value === ''
? undefined
: Number(event.target.value),
}))
}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
/>
<span className="mt-1 block text-xs text-base-content/30">
비워두면 전체 {roundRobinFullRoundCount}라운드로 생성됩니다.
</span>
</label>
)}
{form.gameMode === 'double-elimination' && (
<label className="flex items-center gap-2 border border-base-content/10 px-3 py-2 text-xs text-base-content/55">
<input
type="checkbox"
checked={Boolean(form.doubleEliminationResetFinalEnabled)}
onChange={(event) =>
setForm((current) => ({
...current,
doubleEliminationResetFinalEnabled:
event.target.checked,
}))
}
/>
그랜드 파이널 리셋 허용
</label>
)}
<label className="text-xs text-base-content/45">
상품 (줄바꿈 구분)
<textarea
value={form.prizesText}
onChange={(event) => setForm((current) => ({ ...current, prizesText: event.target.value }))}
rows={4}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
/>
</label>
<label className="text-xs text-base-content/45">
공지 (줄바꿈 구분)
<textarea
value={form.noticesText}
onChange={(event) => setForm((current) => ({ ...current, noticesText: event.target.value }))}
rows={4}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
/>
</label>
<label className="text-xs text-base-content/45 md:col-span-2">
일정 (`시간|라벨`, 줄바꿈 구분)
<textarea
value={form.scheduleText}
onChange={(event) => setForm((current) => ({ ...current, scheduleText: event.target.value }))}
rows={3}
placeholder="20:50|로비 오픈"
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm font-mono"
/>
</label>
</div>
<div className="mt-4 flex gap-2">
<button
type="button"
className="btn btn-primary btn-sm px-5 text-xs"
disabled={createMutation.isPending || updateMutation.isPending}
onClick={submit}
>
{editing ? '수정 저장' : '생성'}
</button>
<button
type="button"
className="btn btn-ghost btn-sm px-5 text-xs"
onClick={() => setShowForm(false)}
>
취소
</button>
</div>
</section>
)}
<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-xs 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>
{matches.map((match) => (
<tr key={match._id} className="border-b border-base-content/5">
<td className="px-3 py-2 text-xs text-base-content/45">
{formatDate(match.scheduledAt)}
</td>
<td className="px-3 py-2">
<Link to={`/match/${match._id}`} className="text-sm font-bold hover:text-primary">
{match.title}
</Link>
<div className="mt-0.5 text-xs text-base-content/30">
{match.description || '-'}
</div>
</td>
<td className="px-3 py-2 text-xs">{match.status}</td>
<td className="px-3 py-2 text-xs tabular-nums">
{match.participants.length}/{match.maxParticipants}
</td>
<td className="px-3 py-2 text-xs">
{GAME_MODE_LABEL[match.gameMode ?? 'pair']}
{match.gameMode === 'round-robin' &&
match.roundRobinMaxRounds && (
<span className="block text-xs text-base-content/30">
최대 {match.roundRobinMaxRounds}R
</span>
)}
{match.gameMode === 'double-elimination' && (
<span className="block text-xs text-base-content/30">
GF 리셋{' '}
{match.doubleEliminationResetFinalEnabled
? '허용'
: '없음'}
</span>
)}
</td>
<td className="px-3 py-2 text-right">
<div className="inline-flex gap-2">
<button
type="button"
className="text-xs px-2 py-1 border border-base-content/10 text-base-content/50 hover:text-primary"
onClick={() => openEdit(match)}
>
수정
</button>
<button
type="button"
className="text-xs px-2 py-1 border border-red-500/20 text-red-400 hover:bg-red-500/10"
disabled={
deleteMutation.isPending ||
match.status !== 'recruiting'
}
title={
match.status === 'recruiting'
? '내전 삭제'
: '팀 구성이 확정된 내전 기록은 삭제할 수 없습니다.'
}
onClick={() => {
if (!window.confirm('이 내전을 삭제할까요?')) return;
deleteMutation.mutate(match._id, {
onSuccess: invalidate,
onError: (error) =>
setMessage(error instanceof Error ? error.message : '삭제 실패'),
});
}}
>
삭제
</button>
</div>
</td>
</tr>
))}
{matches.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>
);
}