Files
lolympus-tournament-support/apps/web/src/pages/admin/MatchAdminPage.tsx
T
dahyeon 7e0cd7cb19 fix: keep best-of-three grand finals open for results
Allow a separate grand final format and repair prematurely completed finals without dropping accepted games. Replay the correction record alongside subsequent results.
2026-11-10 18:49:26 +09:00

668 lines
25 KiB
TypeScript

import { useEffect, useMemo, useRef, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import type {
GrandFinalGameCount,
MatchDetailResponse,
MatchGameMode,
MatchLifecycleStatus,
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';
import { Btn, Chip, ErrorNote, LoadingNote, Pill, type PillTone } from '../../ui';
import { AdminNotice, AdminPage } from '../../components/AdminPage';
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,
doubleEliminationGrandFinalGameCount: 3,
prizes: [],
notices: [],
schedule: [],
};
const GAME_MODE_LABEL: Record<MatchGameMode, string> = {
pair: '페어',
'round-robin': '라운드 로빈',
'double-elimination': '더블 엘리미네이션',
};
const MATCH_STATES = {
recruiting: { label: '모집 중', tone: 'live' },
'team-built': { label: '팀빌딩 완료', tone: 'gold' },
'in-progress': { label: '진행 중', tone: 'accent' },
finished: { label: '종료', tone: 'neutral' },
} satisfies Record<MatchLifecycleStatus, { label: string; tone: PillTone }>;
const matchStatusFilters = Object.keys(MATCH_STATES) as MatchLifecycleStatus[];
function matchModeDetail(match: MatchDetailResponse) {
if (match.gameMode === 'round-robin' && match.roundRobinMaxRounds) {
return `최대 ${match.roundRobinMaxRounds}라운드`;
}
if (match.gameMode === 'double-elimination') {
const finalGames = match.doubleEliminationGrandFinalGameCount ?? 1;
const finalFormat = finalGames === 1 ? '단판' : `${finalGames}전 ${Math.ceil(finalGames / 2)}선승`;
return `결승 ${finalFormat} · 리셋 ${match.doubleEliminationResetFinalEnabled ? '허용' : '없음'}`;
}
}
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,
doubleEliminationGrandFinalGameCount:
match.doubleEliminationGrandFinalGameCount ?? 1,
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 [statusFilter, setStatusFilter] = useState<MatchLifecycleStatus>();
const matchesQuery = useMatches({ limit: 200, status: statusFilter }, 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 isConfigLocked = editing !== null && editing.status !== 'recruiting';
const [message, setMessage] = useState<string | null>(null);
const formHeading = useRef<HTMLHeadingElement>(null);
useEffect(() => {
if (showForm) formHeading.current?.focus();
}, [showForm, editing]);
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 {
const details: MatchMutationRequest = {
title: form.title.trim(),
description: form.description?.trim() ?? '',
mapId: Number(form.mapId ?? 11),
scheduledAt: toIsoFromInput(form.scheduledAt),
prizes: parseLines(form.prizesText),
notices: parseLines(form.noticesText),
schedule: parseSchedule(form.scheduleText),
};
if (isConfigLocked) return details;
return {
...details,
maxParticipants: Number(form.maxParticipants ?? 10),
gameCount: Number(form.gameCount ?? 3),
gameMode: form.gameMode,
doubleEliminationResetFinalEnabled:
form.gameMode === 'double-elimination'
? Boolean(form.doubleEliminationResetFinalEnabled)
: undefined,
doubleEliminationGrandFinalGameCount:
form.gameMode === 'double-elimination'
? form.doubleEliminationGrandFinalGameCount
: undefined,
roundRobinMaxRounds:
form.gameMode === 'round-robin'
? normalizeRoundRobinMaxRounds(
form.roundRobinMaxRounds,
form.maxParticipants,
)
: undefined,
};
}
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);
}
function matchActions(match: MatchDetailResponse) {
return (
<div className="flex flex-wrap gap-2">
<Btn onClick={() => openEdit(match)} variant="secondary">수정</Btn>
{match.status === 'recruiting' && (
<Btn
variant="destructive"
disabled={deleteMutation.isPending}
onClick={() => {
if (!window.confirm('이 내전을 삭제할까요?')) return;
deleteMutation.mutate(match._id, {
onSuccess: invalidate,
onError: (error) => setMessage(error instanceof Error ? error.message : '삭제 실패'),
});
}}
>
삭제
</Btn>
)}
</div>
);
}
if (meQuery.isLoading) {
return <AdminNotice title="권한 확인 중" />;
}
if (!canManage) {
return (
<AdminNotice title="권한이 필요합니다">
<p className="mt-2 text-sm text-base-content/40">
내전 관리는 owner/admin만 사용할 수 있습니다.
</p>
</AdminNotice>
);
}
return (
<AdminPage
communityId={communityId}
title="내전 관리"
description="내전 생성, 모집 정원, 게임 모드와 공지 내용을 관리합니다."
>
<div className="mb-4 flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-wrap gap-2" role="group" aria-label="내전 상태 필터">
<Chip selected={!statusFilter} onClick={() => setStatusFilter(undefined)}>전체</Chip>
{matchStatusFilters.map((status) => (
<Chip key={status} selected={statusFilter === status} onClick={() => setStatusFilter(status)}>
{MATCH_STATES[status].label}
</Chip>
))}
</div>
<Btn variant="primary" onClick={openCreate}>
새 내전 만들기
</Btn>
</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 ref={formHeading} tabIndex={-1} className="scroll-mt-28 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="lts-input mt-1 w-full"
/>
</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="lts-textarea mt-1 w-full"
/>
</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="lts-input mt-1 w-full"
/>
</label>
<label className="text-xs text-base-content/45">
정원
<select
disabled={isConfigLocked}
value={form.maxParticipants}
onChange={(event) => {
const maxParticipants = Number(event.target.value);
setForm((current) => ({
...current,
maxParticipants,
roundRobinMaxRounds: normalizeRoundRobinMaxRounds(
current.roundRobinMaxRounds,
maxParticipants,
),
}));
}}
className="lts-select mt-1 w-full"
>
{(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">
{form.gameMode === 'double-elimination' ? '승자조 게임 수' : '게임 수'}
<input
type="number"
disabled={isConfigLocked}
min={1}
step={form.gameMode === 'double-elimination' ? 2 : 1}
value={form.gameCount}
onChange={(event) => setForm((current) => ({ ...current, gameCount: Number(event.target.value) }))}
className="lts-input mt-1 w-full"
/>
{form.gameMode === 'double-elimination' && (
<span className="mt-1 block text-xs text-base-content/30">
승자조 시리즈에 적용됩니다. 패자조는 단판입니다.
</span>
)}
</label>
<label className="text-xs text-base-content/45">
게임 모드
<select
disabled={isConfigLocked}
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="lts-select mt-1 w-full"
>
{Object.entries(GAME_MODE_LABEL).map(([value, label]) => (
<option key={value} value={value}>{label}</option>
))}
</select>
<span className="mt-1 block text-xs text-gold">
현재 경매/코드 연결은 페어 방식 기준으로 동작합니다.
</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"
disabled={isConfigLocked}
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="lts-input mt-1 w-full"
/>
<span className="mt-1 block text-xs text-base-content/30">
비워두면 전체 {roundRobinFullRoundCount}라운드로 생성됩니다.
</span>
</label>
)}
{form.gameMode === 'double-elimination' && (
<label className="text-xs text-base-content/45">
그랜드 파이널 형식
<select
className="lts-select mt-1 w-full"
disabled={isConfigLocked}
value={form.doubleEliminationGrandFinalGameCount ?? 1}
onChange={(event) =>
setForm((current) => ({
...current,
doubleEliminationGrandFinalGameCount: Number(event.target.value) as GrandFinalGameCount,
}))
}
>
<option value={1}>단판</option>
<option value={3}>3전 2선승</option>
<option value={5}>5전 3선승</option>
</select>
</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"
disabled={isConfigLocked}
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="lts-textarea mt-1 w-full"
/>
</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="lts-textarea mt-1 w-full"
/>
</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="lts-textarea mt-1 w-full font-mono"
/>
</label>
</div>
<div className="mt-4 flex gap-2">
<Btn
variant="primary"
disabled={createMutation.isPending || updateMutation.isPending}
onClick={submit}
>
{editing ? '수정 저장' : '생성'}
</Btn>
<Btn
variant="ghost"
onClick={() => setShowForm(false)}
>
취소
</Btn>
</div>
</section>
)}
{matchesQuery.isLoading ? (
<LoadingNote label="내전 목록을 불러오는 중" />
) : matchesQuery.isError ? (
<ErrorNote title="내전 목록을 불러오지 못했습니다" action={<Btn onClick={() => void matchesQuery.refetch()}>다시 시도</Btn>} />
) : matches.length === 0 ? (
<p role="status" className="lts-panel p-6 text-center text-sm text-content-muted">
{statusFilter ? '이 상태의 내전이 없습니다.' : '등록된 내전이 없습니다.'}
</p>
) : (
<section className="lts-panel overflow-hidden" aria-label="내전 목록">
<ul className="divide-y divide-line lg:hidden">
{matches.map((match) => (
<li key={match._id} className="space-y-2 px-4 py-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<Link to={`/match/${match._id}`} className="min-w-0 break-words text-sm font-bold hover:text-primary">
{match.title}
</Link>
<Pill tone={MATCH_STATES[match.status].tone}>{MATCH_STATES[match.status].label}</Pill>
</div>
<p className="text-xs text-content-muted">
{formatDate(match.scheduledAt)} · {match.participants.length}/{match.maxParticipants}명
</p>
<details className="text-sm">
<summary className="cursor-pointer py-2 font-semibold">상세·관리</summary>
<p className="mb-2 text-xs text-content-muted">
{GAME_MODE_LABEL[match.gameMode ?? 'pair']}
{matchModeDetail(match) && ` · ${matchModeDetail(match)}`}
</p>
{match.description && <p className="mb-3 break-words text-sm text-content-muted">{match.description}</p>}
{matchActions(match)}
</details>
</li>
))}
</ul>
<div className="hidden overflow-x-auto lg:block">
<table className="lts-table">
<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"><Pill tone={MATCH_STATES[match.status].tone}>{MATCH_STATES[match.status].label}</Pill></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']}
<span className="block text-xs text-content-muted">{matchModeDetail(match)}</span>
</td>
<td className="px-3 py-2 text-right">
<div className="inline-block">{matchActions(match)}</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
)}
</AdminPage>
);
}