8단계 관리자: 노래 추가·초성 검색·일괄 작업·휴지통·가져오기/내보내기·중복 병합·하이라이트 지정, 가수 별칭, 장르, 통계와 난이도 제안, 방 강제 종료, 수집 실행/멈추기, 새 방 기본 설정·잠금 + 출제 기록(song_plays)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -17,7 +17,7 @@ interface RoomState {
|
||||
rtt: number | null;
|
||||
/** Join failed with this message (wrong password, unknown room…). */
|
||||
joinError: string | null;
|
||||
left: null | 'leave' | 'kicked' | 'closed' | 'elsewhere';
|
||||
left: null | 'leave' | 'kicked' | 'closed' | 'elsewhere' | 'admin';
|
||||
/** Room chat in seq order (docs/06), last CHAT_KEEP lines. */
|
||||
chat: ChatLine[];
|
||||
/** My lines not confirmed by the server yet: always drawn at the bottom (docs/06 지연 없는 전송). */
|
||||
|
||||
@@ -21,6 +21,7 @@ const LEFT_TEXT: Record<string, string> = {
|
||||
closed: '오래 접속하지 않아 방에서 나갔어요.',
|
||||
elsewhere: '다른 방에 들어가서 이 방에서는 나갔어요.',
|
||||
leave: '방에서 나왔어요.',
|
||||
admin: '관리자가 방을 닫았어요.',
|
||||
};
|
||||
|
||||
export default function RoomPage() {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
/**
|
||||
* 관리자 페이지 (docs/02): side menu + content. Stage 1 has 대시보드 · 사이트 · 사용자 · 관리자 · 기록;
|
||||
* 노래 · 가수 · 장르 · 수집 · 통계 · 방 are listed and open in later stages.
|
||||
* 관리자 페이지 (docs/02): side menu + content — 대시보드 · 노래 · 가수 · 장르 · 수집 · 통계 · 방 · 사이트 · 사용자 · 관리자 · 기록.
|
||||
*/
|
||||
import { useCallback, useEffect, useState, type FormEvent } from 'react';
|
||||
import { Link, NavLink, Navigate, Route, Routes } from 'react-router';
|
||||
@@ -9,7 +8,10 @@ import { ApiError, apiCall, discordLoginUrl } from '../../net/api';
|
||||
import { useSession } from '../../store/session';
|
||||
import { toast } from '../../store/toast';
|
||||
import { ConfirmSheet } from '../../components/ui';
|
||||
import { CollectPage, SongsPage } from './SongsPage';
|
||||
import { SongsPage } from './SongsPage';
|
||||
import { ArtistsPage, CollectPage, GenresPage, RoomsPage, StatsPage } from './AdminMore';
|
||||
import { RoomSettings, type CatalogMeta } from '../../components/RoomSettings';
|
||||
import { DEFAULT_ROOM_CONFIG, type RoomConfig } from '@mq/shared/lite';
|
||||
|
||||
const fmt = (ms: number | null | undefined) => (ms ? new Date(ms).toLocaleString('ko-KR', { dateStyle: 'short', timeStyle: 'short' }) : '-');
|
||||
|
||||
@@ -26,7 +28,6 @@ function useLoad<T>(path: string | null) {
|
||||
return { data, error, reload, setData };
|
||||
}
|
||||
|
||||
const SOON = ['가수', '장르', '통계', '방'];
|
||||
|
||||
export default function AdminApp() {
|
||||
const me = useSession((s) => s.me);
|
||||
@@ -62,13 +63,12 @@ export default function AdminApp() {
|
||||
</NavLink>
|
||||
<div className="sep">노래 DB</div>
|
||||
<NavLink to="/admin/songs">🎵 노래</NavLink>
|
||||
<NavLink to="/admin/artists">🎤 가수</NavLink>
|
||||
<NavLink to="/admin/genres">🏷 장르</NavLink>
|
||||
<NavLink to="/admin/collect">📥 수집</NavLink>
|
||||
{SOON.map((s) => (
|
||||
<a key={s} className="soon" aria-disabled="true" title="다음 단계에서 열려요">
|
||||
{s} <span className="badge">준비 중</span>
|
||||
</a>
|
||||
))}
|
||||
<NavLink to="/admin/stats">📈 통계</NavLink>
|
||||
<div className="sep">운영</div>
|
||||
<NavLink to="/admin/rooms">🚪 방</NavLink>
|
||||
<NavLink to="/admin/site">⚙️ 사이트</NavLink>
|
||||
{isSuper && <NavLink to="/admin/users">👤 사용자</NavLink>}
|
||||
{isSuper && <NavLink to="/admin/admins">🛡 관리자</NavLink>}
|
||||
@@ -79,6 +79,10 @@ export default function AdminApp() {
|
||||
<Route index element={<Dashboard role={role} />} />
|
||||
<Route path="songs" element={<SongsPage />} />
|
||||
<Route path="collect" element={<CollectPage />} />
|
||||
<Route path="artists" element={<ArtistsPage />} />
|
||||
<Route path="genres" element={<GenresPage />} />
|
||||
<Route path="stats" element={<StatsPage />} />
|
||||
<Route path="rooms" element={<RoomsPage />} />
|
||||
<Route path="site" element={<SiteSettings />} />
|
||||
{isSuper && <Route path="users" element={<UsersPage />} />}
|
||||
{isSuper && <Route path="admins" element={<AdminsPage />} />}
|
||||
@@ -91,9 +95,14 @@ export default function AdminApp() {
|
||||
}
|
||||
|
||||
function Dashboard({ role }: { role: Role }) {
|
||||
const { data, error } = useLoad<{ users: { total: number; guests: number; members: number; banned: number }; connections: number; uptimeSec: number; memoryMb: number }>(
|
||||
'/api/admin/overview',
|
||||
);
|
||||
const { data, error } = useLoad<{
|
||||
users: { total: number; guests: number; members: number; banned: number };
|
||||
connections: number;
|
||||
uptimeSec: number;
|
||||
memoryMb: number;
|
||||
rooms: { total: number; playing: number };
|
||||
}>('/api/admin/overview');
|
||||
const { data: plays } = useLoad<{ today: { plays: number; games: number } }>('/api/admin/stats?sort=suggest');
|
||||
const { data: cat } = useLoad<{ total: number; youtube: { matched: number }; lyrics: number }>('/api/admin/catalog');
|
||||
return (
|
||||
<>
|
||||
@@ -128,6 +137,18 @@ function Dashboard({ role }: { role: Role }) {
|
||||
<b>{data.memoryMb}MB</b>
|
||||
<span>서버 메모리</span>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<b>
|
||||
{data.rooms.playing} / {data.rooms.total}
|
||||
</b>
|
||||
<span>게임 중 / 열린 방</span>
|
||||
</div>
|
||||
{plays && (
|
||||
<div className="stat">
|
||||
<b>{plays.today.games}</b>
|
||||
<span>최근 24시간 게임 ({plays.today.plays}문제)</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{cat && (
|
||||
@@ -146,7 +167,6 @@ function Dashboard({ role }: { role: Role }) {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<p className="muted small">진행 중인 방과 오늘 플레이 수는 방 기능이 들어오면 여기에 보여요.</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -160,8 +180,25 @@ interface Site {
|
||||
chatRatePerSec: number;
|
||||
chatBurst: number;
|
||||
questionLimitSec: number;
|
||||
roomDefaults: Partial<RoomConfig>;
|
||||
roomLocks: string[];
|
||||
}
|
||||
|
||||
/** Settings an admin can pin for every room (사이트 → 잠금). */
|
||||
const LOCKABLE: [keyof RoomConfig, string][] = [
|
||||
['mode', '모드'],
|
||||
['listenSec', '듣고맞출시간'],
|
||||
['startAt', '재생위치'],
|
||||
['level', '난이도'],
|
||||
['answer', '정답방식'],
|
||||
['strict', '정답인식'],
|
||||
['hint', '힌트공개'],
|
||||
['skipVotes', '스킵인원'],
|
||||
['replayVotes', '다시듣기인원'],
|
||||
['count', '문제 수'],
|
||||
['visibility', '방 공개'],
|
||||
];
|
||||
|
||||
function SiteSettings() {
|
||||
const { data, error } = useLoad<{ site: Site }>('/api/admin/site');
|
||||
const [s, setS] = useState<Site | null>(null);
|
||||
@@ -230,6 +267,7 @@ function SiteSettings() {
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<RoomDefaults site={s} onChange={(p) => setS({ ...s, ...p })} />
|
||||
<div>
|
||||
<button className="btn btn-primary">저장</button>
|
||||
</div>
|
||||
@@ -237,6 +275,60 @@ function SiteSettings() {
|
||||
);
|
||||
}
|
||||
|
||||
/** 새 방의 기본 설정 + 잠금 (docs/04 설정 저장): the same settings form hosts use. */
|
||||
function RoomDefaults({ site, onChange }: { site: Site; onChange: (p: Partial<Site>) => void }) {
|
||||
const [meta, setMeta] = useState<CatalogMeta | null>(null);
|
||||
const [pool, setPool] = useState({ playable: 0, total: 0 });
|
||||
const config: RoomConfig = { ...DEFAULT_ROOM_CONFIG, ...site.roomDefaults, title: '새 방 기본값' } as RoomConfig;
|
||||
useEffect(() => {
|
||||
void apiCall<CatalogMeta>('GET', '/api/catalog/meta').then(setMeta, () => {});
|
||||
}, []);
|
||||
const key = JSON.stringify(site.roomDefaults);
|
||||
useEffect(() => {
|
||||
void apiCall<{ playable: number; total: number }>('POST', '/api/pool/count', site.roomDefaults).then(setPool, () => {});
|
||||
}, [key]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
return (
|
||||
<fieldset className="card stack" style={{ margin: 0 }}>
|
||||
<legend style={{ fontWeight: 800, padding: '0 6px' }}>새 방 기본 설정 · 잠금</legend>
|
||||
<p className="muted small">새로 만드는 방은 이 설정으로 시작해요. 잠근 항목은 방장이 바꿀 수 없어요(방 이름·비밀번호는 제외).</p>
|
||||
<div className="row" role="group" aria-label="잠금">
|
||||
{LOCKABLE.map(([k, label]) => (
|
||||
<label key={k} className="check small">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={site.roomLocks.includes(k)}
|
||||
onChange={(e) => onChange({ roomLocks: e.target.checked ? [...site.roomLocks, k] : site.roomLocks.filter((x) => x !== k) })}
|
||||
/>
|
||||
🔒 {label}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<div className="row">
|
||||
<button type="button" className="btn btn-sm" onClick={() => onChange({ roomDefaults: {}, roomLocks: [] })}>
|
||||
처음 기본값으로
|
||||
</button>
|
||||
</div>
|
||||
<div style={{ maxWidth: 560 }}>
|
||||
<RoomSettings
|
||||
config={config}
|
||||
editable
|
||||
meta={meta}
|
||||
artists={[]}
|
||||
pool={pool}
|
||||
hasPassword={false}
|
||||
onPatch={(p) => {
|
||||
const { title: _t, ...rest } = p as Partial<RoomConfig>;
|
||||
const merged: Record<string, unknown> = { ...site.roomDefaults, ...rest };
|
||||
if (rest.strict) merged.strict = { ...config.strict, ...rest.strict };
|
||||
onChange({ roomDefaults: merged as Partial<RoomConfig> });
|
||||
}}
|
||||
onPassword={() => {}}
|
||||
/>
|
||||
</div>
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
|
||||
interface AdminUser {
|
||||
id: string;
|
||||
nickname: string;
|
||||
|
||||
537
apps/web/src/pages/admin/AdminMore.tsx
Normal file
537
apps/web/src/pages/admin/AdminMore.tsx
Normal file
@@ -0,0 +1,537 @@
|
||||
/**
|
||||
* 관리자 → 가수 · 장르 · 통계 · 방 · 수집 (docs/02 관리자 페이지).
|
||||
*/
|
||||
import { useCallback, useEffect, useState, type FormEvent } from 'react';
|
||||
import { apiCall } from '../../net/api';
|
||||
import { toast } from '../../store/toast';
|
||||
import { ConfirmSheet } from '../../components/ui';
|
||||
|
||||
const fmt = (ms: number | null | undefined) => (ms ? new Date(ms).toLocaleString('ko-KR', { dateStyle: 'short', timeStyle: 'short' }) : '-');
|
||||
const pct = (n: number, d: number) => (d ? `${Math.round((n / d) * 100)}%` : '-');
|
||||
|
||||
function useLoad<T>(path: string) {
|
||||
const [data, setData] = useState<T | null>(null);
|
||||
const reload = useCallback(() => void apiCall<T>('GET', path).then(setData, (e: Error) => toast(e.message, 'error')), [path]);
|
||||
useEffect(reload, [reload]);
|
||||
return { data, reload };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 가수
|
||||
interface ArtistRow {
|
||||
id: number;
|
||||
name: string;
|
||||
kind: 'solo' | 'group' | 'unit' | null;
|
||||
songs: number;
|
||||
aliases: string[];
|
||||
}
|
||||
|
||||
export function ArtistsPage() {
|
||||
const [q, setQ] = useState('');
|
||||
const [query, setQuery] = useState('');
|
||||
const [page, setPage] = useState(0);
|
||||
const { data, reload } = useLoad<{ total: number; rows: ArtistRow[]; pageSize: number }>(`/api/admin/artists?q=${encodeURIComponent(query)}&page=${page}`);
|
||||
const [edit, setEdit] = useState<{ id: number; name: string; kind: string; aliases: string } | null>(null);
|
||||
const pages = data ? Math.max(1, Math.ceil(data.total / data.pageSize)) : 1;
|
||||
const save = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!edit) return;
|
||||
try {
|
||||
await apiCall('PATCH', `/api/admin/artists/${edit.id}`, {
|
||||
name: edit.name.trim(),
|
||||
kind: edit.kind || null,
|
||||
aliases: edit.aliases.split(',').map((x) => x.trim()).filter(Boolean),
|
||||
});
|
||||
toast('저장했어요.');
|
||||
setEdit(null);
|
||||
reload();
|
||||
} catch (ex) {
|
||||
toast((ex as Error).message, 'error');
|
||||
}
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<h1>가수</h1>
|
||||
<p className="muted small">별칭을 넣으면 그 가수의 모든 노래에서 정답으로 인정돼요. 예) 아이유 = IU = 이지은</p>
|
||||
<form
|
||||
className="row"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
setPage(0);
|
||||
setQuery(q.trim());
|
||||
}}
|
||||
>
|
||||
<input className="input grow" style={{ maxWidth: 360 }} placeholder="가수 이름·별칭" value={q} onChange={(e) => setQ(e.target.value)} aria-label="가수 검색" />
|
||||
<button className="btn">검색</button>
|
||||
{data && <span className="muted small">{data.total.toLocaleString()}명</span>}
|
||||
</form>
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>이름</th>
|
||||
<th>구분</th>
|
||||
<th>곡 수</th>
|
||||
<th>별칭</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data?.rows.map((a) =>
|
||||
edit?.id === a.id ? (
|
||||
<tr key={a.id} className="sel">
|
||||
<td colSpan={5}>
|
||||
<form className="row" onSubmit={save}>
|
||||
<input className="input sm" style={{ width: 160 }} value={edit.name} onChange={(e) => setEdit({ ...edit, name: e.target.value })} aria-label="이름" />
|
||||
<select className="input sm" style={{ width: 'auto' }} value={edit.kind} onChange={(e) => setEdit({ ...edit, kind: e.target.value })} aria-label="구분">
|
||||
<option value="">-</option>
|
||||
<option value="solo">솔로</option>
|
||||
<option value="group">그룹</option>
|
||||
<option value="unit">유닛</option>
|
||||
</select>
|
||||
<input className="input sm grow" style={{ width: 'auto', minWidth: 220 }} placeholder="별칭 (쉼표로 구분)" value={edit.aliases} onChange={(e) => setEdit({ ...edit, aliases: e.target.value })} aria-label="별칭" />
|
||||
<button className="btn btn-sm btn-primary">저장</button>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setEdit(null)}>
|
||||
취소
|
||||
</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
<tr key={a.id}>
|
||||
<td>{a.name}</td>
|
||||
<td className="small">{a.kind ? { solo: '솔로', group: '그룹', unit: '유닛' }[a.kind] : '-'}</td>
|
||||
<td className="mono">{a.songs}</td>
|
||||
<td className="small">{a.aliases.join(', ') || '-'}</td>
|
||||
<td>
|
||||
<button type="button" className="btn btn-sm" onClick={() => setEdit({ id: a.id, name: a.name, kind: a.kind ?? '', aliases: a.aliases.join(', ') })} aria-label={`${a.name} 고치기`}>
|
||||
고치기
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
),
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="row">
|
||||
<button className="btn btn-sm" disabled={page === 0} onClick={() => setPage(page - 1)}>
|
||||
이전
|
||||
</button>
|
||||
<span className="muted small mono">
|
||||
{page + 1} / {pages}
|
||||
</span>
|
||||
<button className="btn btn-sm" disabled={page + 1 >= pages} onClick={() => setPage(page + 1)}>
|
||||
다음
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 장르
|
||||
interface GenreRow {
|
||||
id: string;
|
||||
name: string;
|
||||
grp: 'region' | 'style' | 'theme';
|
||||
sort: number;
|
||||
hidden: boolean;
|
||||
songs: number;
|
||||
}
|
||||
const GRP: Record<GenreRow['grp'], string> = { region: '지역', style: '스타일', theme: '테마' };
|
||||
|
||||
export function GenresPage() {
|
||||
const { data, reload } = useLoad<{ genres: GenreRow[] }>('/api/admin/genres');
|
||||
const [add, setAdd] = useState({ id: '', name: '', grp: 'style' as GenreRow['grp'] });
|
||||
const patch = async (id: string, p: Partial<GenreRow>) => {
|
||||
try {
|
||||
await apiCall('PATCH', `/api/admin/genres/${id}`, p);
|
||||
reload();
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error');
|
||||
}
|
||||
};
|
||||
const list = data?.genres ?? [];
|
||||
const move = (g: GenreRow, dir: -1 | 1) => {
|
||||
const same = list.filter((x) => x.grp === g.grp);
|
||||
const i = same.findIndex((x) => x.id === g.id);
|
||||
const other = same[i + dir];
|
||||
if (!other) return;
|
||||
void Promise.all([apiCall('PATCH', `/api/admin/genres/${g.id}`, { sort: other.sort }), apiCall('PATCH', `/api/admin/genres/${other.id}`, { sort: g.sort })]).then(reload, (e: Error) => toast(e.message, 'error'));
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<h1>장르</h1>
|
||||
<p className="muted small">같은 묶음끼리는 "또는", 다른 묶음끼리는 "그리고"로 골라요(예: K-POP 그리고 발라드). 숨긴 장르는 방 설정에 안 보여요.</p>
|
||||
<form
|
||||
className="row"
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await apiCall('POST', '/api/admin/genres', add);
|
||||
toast('추가했어요.');
|
||||
setAdd({ id: '', name: '', grp: add.grp });
|
||||
reload();
|
||||
} catch (ex) {
|
||||
toast((ex as Error).message, 'error');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<input className="input sm" style={{ width: 140 }} placeholder="ID (영문, 예: citypop)" value={add.id} onChange={(e) => setAdd({ ...add, id: e.target.value.toLowerCase() })} aria-label="새 장르 ID" />
|
||||
<input className="input sm" style={{ width: 160 }} placeholder="이름" value={add.name} onChange={(e) => setAdd({ ...add, name: e.target.value })} aria-label="새 장르 이름" />
|
||||
<select className="input sm" style={{ width: 'auto' }} value={add.grp} onChange={(e) => setAdd({ ...add, grp: e.target.value as GenreRow['grp'] })} aria-label="묶음">
|
||||
{Object.entries(GRP).map(([k, v]) => (
|
||||
<option key={k} value={k}>
|
||||
{v}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button className="btn btn-sm btn-primary" disabled={!add.id || !add.name.trim()}>
|
||||
장르 추가
|
||||
</button>
|
||||
</form>
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>묶음</th>
|
||||
<th>이름</th>
|
||||
<th>ID</th>
|
||||
<th>곡 수</th>
|
||||
<th>순서</th>
|
||||
<th>숨김</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{list.map((g) => (
|
||||
<tr key={g.id}>
|
||||
<td className="small">{GRP[g.grp]}</td>
|
||||
<td>
|
||||
<input
|
||||
className="input sm"
|
||||
style={{ width: 150 }}
|
||||
defaultValue={g.name}
|
||||
aria-label={`${g.name} 이름`}
|
||||
onBlur={(e) => e.target.value.trim() && e.target.value.trim() !== g.name && void patch(g.id, { name: e.target.value.trim() })}
|
||||
/>
|
||||
</td>
|
||||
<td className="mono small">{g.id}</td>
|
||||
<td className="mono">{g.songs.toLocaleString()}</td>
|
||||
<td>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => move(g, -1)} aria-label={`${g.name} 위로`}>
|
||||
▲
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => move(g, 1)} aria-label={`${g.name} 아래로`}>
|
||||
▼
|
||||
</button>
|
||||
</td>
|
||||
<td>
|
||||
<input type="checkbox" checked={g.hidden} onChange={(e) => void patch(g.id, { hidden: e.target.checked })} aria-label={`${g.name} 숨김`} />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 통계
|
||||
interface StatRow {
|
||||
id: number;
|
||||
title: string;
|
||||
artist: string;
|
||||
level: number | null;
|
||||
plays: number;
|
||||
correct: number;
|
||||
avg_ms: number | null;
|
||||
last_at: number;
|
||||
suggest: number | null;
|
||||
}
|
||||
|
||||
export function StatsPage() {
|
||||
const [sort, setSort] = useState('plays');
|
||||
const [page, setPage] = useState(0);
|
||||
const { data, reload } = useLoad<{ total: number; rows: StatRow[]; pageSize: number; today: { plays: number; games: number }; suggestions: number }>(`/api/admin/stats?sort=${sort}&page=${page}`);
|
||||
const pages = data ? Math.max(1, Math.ceil(data.total / data.pageSize)) : 1;
|
||||
return (
|
||||
<>
|
||||
<h1>통계</h1>
|
||||
{data && (
|
||||
<div className="stat-row">
|
||||
<div className="stat">
|
||||
<b>{data.today.games}</b>
|
||||
<span>최근 24시간 게임</span>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<b>{data.today.plays}</b>
|
||||
<span>최근 24시간 문제</span>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<b>{data.suggestions}</b>
|
||||
<span>난이도 조정 제안</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<p className="muted small">5번 이상 나온 곡만 제안해요. 80% 넘게 8초 안에 맞히면 한 단계 쉽게, 30% 아래로 맞히면 한 단계 어렵게.</p>
|
||||
<div className="row">
|
||||
<label className="field-inline">
|
||||
정렬
|
||||
<select className="input sm" value={sort} onChange={(e) => (setSort(e.target.value), setPage(0))}>
|
||||
<option value="plays">출제 수</option>
|
||||
<option value="correct">정답률</option>
|
||||
<option value="fast">빨리 맞힌 순</option>
|
||||
<option value="suggest">조정 제안만</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>노래</th>
|
||||
<th>난이도</th>
|
||||
<th>출제</th>
|
||||
<th>정답률</th>
|
||||
<th>평균 정답 시간</th>
|
||||
<th>마지막</th>
|
||||
<th>제안</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data?.rows.map((r) => (
|
||||
<tr key={r.id}>
|
||||
<td>
|
||||
<b>{r.title}</b> - {r.artist}
|
||||
</td>
|
||||
<td className="mono">{r.level ? `★${r.level}` : '-'}</td>
|
||||
<td className="mono">{r.plays}</td>
|
||||
<td className="mono">{pct(r.correct, r.plays)}</td>
|
||||
<td className="mono">{r.avg_ms !== null ? `${(r.avg_ms / 1000).toFixed(1)}초` : '-'}</td>
|
||||
<td className="small">{fmt(r.last_at)}</td>
|
||||
<td>
|
||||
{r.suggest !== null && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
onClick={() => void apiCall('POST', '/api/admin/stats/apply', { songId: r.id, level: r.suggest }).then(() => (toast(`★${r.suggest}로 바꿨어요.`), reload()), (e: Error) => toast(e.message, 'error'))}
|
||||
>
|
||||
★{r.level} → ★{r.suggest} 승인
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{data?.rows.length === 0 && <p className="muted">아직 게임 기록이 없어요.</p>}
|
||||
<div className="row">
|
||||
<button className="btn btn-sm" disabled={page === 0} onClick={() => setPage(page - 1)}>
|
||||
이전
|
||||
</button>
|
||||
<span className="muted small mono">
|
||||
{page + 1} / {pages}
|
||||
</span>
|
||||
<button className="btn btn-sm" disabled={page + 1 >= pages} onClick={() => setPage(page + 1)}>
|
||||
다음
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 방
|
||||
interface AdminRoom {
|
||||
code: string;
|
||||
title: string;
|
||||
visibility: string;
|
||||
status: 'lobby' | 'playing';
|
||||
host: string;
|
||||
createdAt: number;
|
||||
game: { phase: string; n: number; total: number } | null;
|
||||
players: { id: string; nickname: string; online: boolean }[];
|
||||
}
|
||||
|
||||
export function RoomsPage() {
|
||||
const { data, reload } = useLoad<{ rooms: AdminRoom[] }>('/api/admin/rooms');
|
||||
const [closing, setClosing] = useState<AdminRoom | null>(null);
|
||||
useEffect(() => {
|
||||
const t = setInterval(reload, 5000);
|
||||
return () => clearInterval(t);
|
||||
}, [reload]);
|
||||
return (
|
||||
<>
|
||||
<h1>방</h1>
|
||||
<p className="muted small">비공개 방까지 모두 보여요. 5초마다 새로 고쳐요.</p>
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>코드</th>
|
||||
<th>이름</th>
|
||||
<th>공개</th>
|
||||
<th>상태</th>
|
||||
<th>방장</th>
|
||||
<th>참가자</th>
|
||||
<th>만든 시각</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data?.rooms.map((r) => (
|
||||
<tr key={r.code}>
|
||||
<td className="mono">{r.code}</td>
|
||||
<td>{r.title}</td>
|
||||
<td className="small">{{ public: '공개', private: '비공개', password: '비밀번호' }[r.visibility] ?? r.visibility}</td>
|
||||
<td>
|
||||
<span className={`badge ${r.status === 'playing' ? 'live' : 'teal'}`}>{r.status === 'playing' ? (r.game ? `게임 ${r.game.n}/${r.game.total}` : '게임 중') : '대기'}</span>
|
||||
</td>
|
||||
<td>{r.host}</td>
|
||||
<td className="small">
|
||||
{r.players.length}명 · {r.players.map((p) => `${p.nickname}${p.online ? '' : '(끊김)'}`).join(', ')}
|
||||
</td>
|
||||
<td className="small">{fmt(r.createdAt)}</td>
|
||||
<td>
|
||||
<button type="button" className="btn btn-sm btn-danger" onClick={() => setClosing(r)}>
|
||||
강제 종료
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{data?.rooms.length === 0 && <p className="muted">열린 방이 없어요.</p>}
|
||||
{closing && (
|
||||
<ConfirmSheet
|
||||
title={`"${closing.title}" 방을 닫을까요?`}
|
||||
body={`${closing.players.length}명이 첫 화면으로 돌아가고 "관리자가 방을 닫았어요" 안내를 봐요.`}
|
||||
confirm="강제 종료"
|
||||
danger
|
||||
onConfirm={() => void apiCall('POST', `/api/admin/rooms/${closing.code}/close`).then(() => (toast('방을 닫았어요.'), reload()), (e: Error) => toast(e.message, 'error'))}
|
||||
onClose={() => setClosing(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 수집
|
||||
interface Job {
|
||||
id: number;
|
||||
kind: string;
|
||||
status: string;
|
||||
done: number;
|
||||
total: number;
|
||||
started_at: number;
|
||||
finished_at: number | null;
|
||||
}
|
||||
const STATUS: Record<string, string> = { running: '진행 중', done: '완료', failed: '실패', stopped: '멈춤' };
|
||||
|
||||
export function CollectPage() {
|
||||
const { data, reload } = useLoad<{ kinds: { id: string; label: string; limit?: boolean }[]; jobs: Job[]; cookieProblem: boolean }>('/api/admin/collect');
|
||||
const [limit, setLimit] = useState<Record<string, string>>({});
|
||||
const [log, setLog] = useState<{ id: number; text: string } | null>(null);
|
||||
useEffect(() => {
|
||||
const t = setInterval(reload, 5000);
|
||||
return () => clearInterval(t);
|
||||
}, [reload]);
|
||||
const label = (kind: string) => data?.kinds.find((k) => k.id === kind)?.label ?? { 'import-norabose': '노라보세 가져오기', 'import-sta': '스타맵 가져오기' }[kind] ?? kind;
|
||||
return (
|
||||
<>
|
||||
<h1>수집</h1>
|
||||
{data?.cookieProblem && <p className="guest-warning">⚠ 유튜브 뮤직 쿠키가 로그아웃된 것 같아요. 새 쿠키를 서버에 넣어야 원곡 찾기가 다시 돌아요.</p>}
|
||||
<p className="muted small">작업은 서버에서 따로 돌아가요(게임에는 영향 없음). 유튜브 원곡 찾기는 매일 새벽 4시 10분에 3,000곡씩 자동으로도 돌아요.</p>
|
||||
<div className="stack">
|
||||
{data?.kinds.map((k) => {
|
||||
const running = data.jobs.find((j) => j.kind === k.id && j.status === 'running');
|
||||
return (
|
||||
<div key={k.id} className="card row">
|
||||
<b className="grow">{k.label}</b>
|
||||
{k.limit && (
|
||||
<label className="field-inline">
|
||||
곡 수
|
||||
<input className="input sm" inputMode="numeric" placeholder="300" value={limit[k.id] ?? ''} onChange={(e) => setLimit({ ...limit, [k.id]: e.target.value.replace(/\D/g, '') })} aria-label={`${k.label} 곡 수`} />
|
||||
</label>
|
||||
)}
|
||||
{running ? (
|
||||
<>
|
||||
<span className="mono small">
|
||||
{running.done.toLocaleString()} / {running.total.toLocaleString()}
|
||||
</span>
|
||||
<button type="button" className="btn btn-sm btn-danger" onClick={() => void apiCall('POST', `/api/admin/collect/${running.id}/stop`).then(() => (toast('멈추라고 했어요.'), reload()), (e: Error) => toast(e.message, 'error'))}>
|
||||
멈추기
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-primary"
|
||||
onClick={() =>
|
||||
void apiCall('POST', '/api/admin/collect/run', { kind: k.id, ...(k.limit ? { limit: Number(limit[k.id] || 300) } : {}) }).then(
|
||||
() => (toast('시작했어요.'), setTimeout(reload, 1500)),
|
||||
(e: Error) => toast(e.message, 'error'),
|
||||
)
|
||||
}
|
||||
>
|
||||
실행
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<h2>기록</h2>
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>작업</th>
|
||||
<th>상태</th>
|
||||
<th>진행</th>
|
||||
<th>시작</th>
|
||||
<th>끝</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data?.jobs.map((j) => (
|
||||
<tr key={j.id}>
|
||||
<td>{label(j.kind)}</td>
|
||||
<td>{STATUS[j.status] ?? j.status}</td>
|
||||
<td className="mono">
|
||||
{j.done.toLocaleString()} / {j.total.toLocaleString()}
|
||||
</td>
|
||||
<td className="small">{fmt(j.started_at)}</td>
|
||||
<td className="small">{fmt(j.finished_at)}</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
onClick={() => void apiCall<{ job: { log: string } }>('GET', `/api/admin/collect/${j.id}`).then((r) => setLog({ id: j.id, text: r.job.log || '(기록 없음)' }), (e: Error) => toast(e.message, 'error'))}
|
||||
>
|
||||
로그
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{log && (
|
||||
<div className="card">
|
||||
<div className="row">
|
||||
<b className="grow">작업 #{log.id} 로그</b>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setLog(null)}>
|
||||
닫기
|
||||
</button>
|
||||
</div>
|
||||
<pre className="lyrics" style={{ maxHeight: 360, overflow: 'auto' }}>
|
||||
{log.text}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
/**
|
||||
* 관리자 → 노래 (docs/02 노래 관리 화면): 검색·필터·정렬 표 + 오른쪽 편집 패널(유튜브 미리듣기·후보 고르기·하이라이트·별칭).
|
||||
* 관리자 → 노래 (docs/02 노래 관리 화면): 검색(초성 포함)·필터·정렬 표 + 오른쪽 편집 패널(유튜브 미리듣기·후보 고르기·
|
||||
* 하이라이트 "지금 위치로"·별칭), 노래 추가, 선택한 곡 일괄 작업, 휴지통, 가져오기/내보내기, 중복 정리.
|
||||
*/
|
||||
import { useCallback, useEffect, useMemo, useState, type FormEvent } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type FormEvent } from 'react';
|
||||
import { apiCall } from '../../net/api';
|
||||
import { toast } from '../../store/toast';
|
||||
import { ConfirmSheet, Sheet } from '../../components/ui';
|
||||
|
||||
interface Genre {
|
||||
id: string;
|
||||
@@ -28,6 +30,9 @@ interface Row {
|
||||
sources: string[];
|
||||
has_lyrics: boolean;
|
||||
hidden: boolean;
|
||||
plays: number;
|
||||
correct: number;
|
||||
deleted_at: number | null;
|
||||
}
|
||||
interface Detail {
|
||||
song: Row & { youtube_title: string | null; highlight_sec: number | null; highlight_source: string | null; note: string | null; mv_youtube_id: string | null };
|
||||
@@ -52,7 +57,7 @@ const YT_LABEL: Record<Row['youtube_status'], [string, string]> = {
|
||||
none: ['없음', ''],
|
||||
dead: ['재생 불가', 'warn'],
|
||||
};
|
||||
const SOURCE_LABEL: Record<string, string> = { norabose: '노라보세', sta: '스타맵' };
|
||||
const SOURCE_LABEL: Record<string, string> = { norabose: '노라보세', sta: '스타맵', admin: '관리자' };
|
||||
const mmss = (s: number | null) => (s == null ? '-' : `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, '0')}`);
|
||||
const pct = (n: number, d: number) => (d ? `${Math.round((n / d) * 100)}%` : '-');
|
||||
|
||||
@@ -60,9 +65,16 @@ export function SongsPage() {
|
||||
const [genres, setGenres] = useState<Genre[]>([]);
|
||||
const [stats, setStats] = useState<Stats | null>(null);
|
||||
const [q, setQ] = useState('');
|
||||
const [f, setF] = useState({ q: '', genres: [] as string[], yearFrom: '', yearTo: '', level: '', youtube: '', source: '', sort: 'recent', page: 0 });
|
||||
const [f, setF] = useState({ q: '', genres: [] as string[], yearFrom: '', yearTo: '', level: '', youtube: '', source: '', sort: 'recent', lyrics: '', highlight: '', hidden: '', trash: '', page: 0 });
|
||||
const [data, setData] = useState<{ total: number; rows: Row[]; pageSize: number } | null>(null);
|
||||
const [selected, setSelected] = useState<number | null>(null);
|
||||
const [checked, setChecked] = useState<Set<number>>(new Set());
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [dupes, setDupes] = useState(false);
|
||||
const [bulkAct, setBulkAct] = useState('hide');
|
||||
const [bulkVal, setBulkVal] = useState('');
|
||||
const [confirmBulk, setConfirmBulk] = useState(false);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const loadStats = useCallback(() => void apiCall<Stats>('GET', '/api/admin/catalog').then(setStats).catch(() => {}), []);
|
||||
useEffect(() => {
|
||||
@@ -74,7 +86,7 @@ export function SongsPage() {
|
||||
const p = new URLSearchParams();
|
||||
if (f.q) p.set('q', f.q);
|
||||
if (f.genres.length) p.set('genres', f.genres.join(','));
|
||||
for (const k of ['yearFrom', 'yearTo', 'level', 'youtube', 'source', 'sort'] as const) if (f[k]) p.set(k, f[k]);
|
||||
for (const k of ['yearFrom', 'yearTo', 'level', 'youtube', 'source', 'sort', 'lyrics', 'highlight', 'hidden', 'trash'] as const) if (f[k]) p.set(k, f[k]);
|
||||
p.set('page', String(f.page));
|
||||
return p.toString();
|
||||
}, [f]);
|
||||
@@ -85,14 +97,81 @@ export function SongsPage() {
|
||||
}, [query]);
|
||||
useEffect(reload, [reload]);
|
||||
|
||||
const set = (patch: Partial<typeof f>) => setF((x) => ({ ...x, page: 0, ...patch }));
|
||||
const set = (patch: Partial<typeof f>) => {
|
||||
setChecked(new Set());
|
||||
setF((x) => ({ ...x, page: 0, ...patch }));
|
||||
};
|
||||
const trash = f.trash === '1';
|
||||
const exportQuery = query.replace(/(^|&)page=\d+/, '');
|
||||
const runBulk = async () => {
|
||||
const ids = [...checked];
|
||||
const body: Record<string, unknown> = { ids, action: bulkAct };
|
||||
if (bulkAct === 'level') body.level = bulkVal ? Number(bulkVal) : null;
|
||||
if (bulkAct === 'addGenre' || bulkAct === 'removeGenre') body.genre = bulkVal;
|
||||
try {
|
||||
const r = await apiCall<{ changed: number }>('POST', '/api/admin/songs/bulk', body);
|
||||
toast(`${r.changed}곡에 적용했어요.`);
|
||||
setChecked(new Set());
|
||||
reload();
|
||||
loadStats();
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error');
|
||||
}
|
||||
};
|
||||
const importFile = async (file: File) => {
|
||||
const text = await file.text();
|
||||
const format = /\.csv$/i.test(file.name) ? 'csv' : 'json';
|
||||
try {
|
||||
const r = await apiCall<{ added: number; existing: number; skipped: number[]; badVideo: number }>('POST', '/api/admin/songs/import', { format, text });
|
||||
toast(`새 곡 ${r.added}곡, 이미 있던 곡 ${r.existing}곡${r.skipped.length ? `, 건너뛴 줄 ${r.skipped.length}개` : ''}${r.badVideo ? `, 쓸 수 없는 영상 ${r.badVideo}개` : ''}`, 'info', 6000);
|
||||
reload();
|
||||
loadStats();
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error');
|
||||
}
|
||||
};
|
||||
const toggleGenre = (id: string) => set({ genres: f.genres.includes(id) ? f.genres.filter((g) => g !== id) : [...f.genres, id] });
|
||||
const pages = data ? Math.max(1, Math.ceil(data.total / data.pageSize)) : 1;
|
||||
|
||||
return (
|
||||
<div className={`songs-layout ${selected ? 'with-panel' : ''}`}>
|
||||
<div className="stack" style={{ minWidth: 0 }}>
|
||||
<h1>노래</h1>
|
||||
<div className="row">
|
||||
<h1 className="grow">{trash ? '휴지통' : '노래'}</h1>
|
||||
{!trash && (
|
||||
<button type="button" className="btn btn-primary btn-sm" onClick={() => setAdding(true)}>
|
||||
+ 노래 추가
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="btn btn-sm" onClick={() => setDupes(true)}>
|
||||
중복 정리
|
||||
</button>
|
||||
<a className="btn btn-sm" href={`/api/admin/songs/export?${exportQuery}&format=csv`} download>
|
||||
CSV 내보내기
|
||||
</a>
|
||||
<a className="btn btn-sm" href={`/api/admin/songs/export?${exportQuery}`} download>
|
||||
JSON 내보내기
|
||||
</a>
|
||||
<button type="button" className="btn btn-sm" onClick={() => fileRef.current?.click()}>
|
||||
가져오기
|
||||
</button>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept=".csv,.json,application/json,text/csv"
|
||||
hidden
|
||||
aria-label="가져올 파일"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) void importFile(file);
|
||||
e.target.value = '';
|
||||
}}
|
||||
/>
|
||||
<button type="button" className={`btn btn-sm ${trash ? 'btn-mustard' : ''}`} aria-pressed={trash} onClick={() => set({ trash: trash ? '' : '1' })}>
|
||||
🗑 휴지통
|
||||
</button>
|
||||
</div>
|
||||
{trash && <p className="muted small">지운 곡은 30일 동안 여기에 있다가 완전히 지워져요. 복원하면 다시 출제돼요.</p>}
|
||||
{stats && (
|
||||
<div className="stat-row">
|
||||
<div className="stat">
|
||||
@@ -179,13 +258,98 @@ export function SongsPage() {
|
||||
<option value="level">난이도</option>
|
||||
<option value="peak">차트 최고 순위</option>
|
||||
<option value="title">제목</option>
|
||||
<option value="plays">출제 수</option>
|
||||
<option value="correct">정답률</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="field-inline">
|
||||
가사
|
||||
<select className="input sm" value={f.lyrics} onChange={(e) => set({ lyrics: e.target.value })}>
|
||||
<option value="">전체</option>
|
||||
<option value="1">있음</option>
|
||||
<option value="0">없음</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="field-inline">
|
||||
하이라이트
|
||||
<select className="input sm" value={f.highlight} onChange={(e) => set({ highlight: e.target.value })}>
|
||||
<option value="">전체</option>
|
||||
<option value="1">있음</option>
|
||||
<option value="0">없음</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="field-inline">
|
||||
숨김
|
||||
<select className="input sm" value={f.hidden} onChange={(e) => set({ hidden: e.target.value })}>
|
||||
<option value="">전체</option>
|
||||
<option value="0">출제</option>
|
||||
<option value="1">숨김</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
{checked.size > 0 && (
|
||||
<div className="row bulk-bar" role="region" aria-label="선택한 곡 일괄 작업">
|
||||
<b>{checked.size}곡 선택</b>
|
||||
<select className="input sm" style={{ width: 'auto' }} value={bulkAct} onChange={(e) => (setBulkAct(e.target.value), setBulkVal(''))} aria-label="일괄 작업">
|
||||
{trash ? (
|
||||
<option value="restore">복원</option>
|
||||
) : (
|
||||
<>
|
||||
<option value="hide">숨기기</option>
|
||||
<option value="show">출제하기(숨김 해제)</option>
|
||||
<option value="level">난이도 바꾸기</option>
|
||||
<option value="addGenre">장르 넣기</option>
|
||||
<option value="removeGenre">장르 빼기</option>
|
||||
<option value="rematch">유튜브 다시 찾기</option>
|
||||
<option value="trash">휴지통으로</option>
|
||||
</>
|
||||
)}
|
||||
</select>
|
||||
{bulkAct === 'level' && (
|
||||
<select className="input sm" style={{ width: 'auto' }} value={bulkVal} onChange={(e) => setBulkVal(e.target.value)} aria-label="바꿀 난이도">
|
||||
<option value="">없음</option>
|
||||
{Array.from({ length: 10 }, (_, i) => (
|
||||
<option key={i + 1} value={i + 1}>
|
||||
{i + 1}단계
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{(bulkAct === 'addGenre' || bulkAct === 'removeGenre') && (
|
||||
<select className="input sm" style={{ width: 'auto' }} value={bulkVal} onChange={(e) => setBulkVal(e.target.value)} aria-label="장르">
|
||||
<option value="">장르 고르기</option>
|
||||
{genres.map((g) => (
|
||||
<option key={g.id} value={g.id}>
|
||||
{g.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-primary"
|
||||
disabled={(bulkAct === 'addGenre' || bulkAct === 'removeGenre') && !bulkVal}
|
||||
onClick={() => (bulkAct === 'trash' || bulkAct === 'rematch' ? setConfirmBulk(true) : void runBulk())}
|
||||
>
|
||||
적용
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setChecked(new Set())}>
|
||||
선택 해제
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label="이 쪽 전체 선택"
|
||||
checked={!!data?.rows.length && data.rows.every((r) => checked.has(r.id))}
|
||||
onChange={(e) => setChecked(e.target.checked ? new Set([...checked, ...(data?.rows.map((r) => r.id) ?? [])]) : new Set([...checked].filter((id) => !data?.rows.some((r) => r.id === id))))}
|
||||
/>
|
||||
</th>
|
||||
<th>제목</th>
|
||||
<th>가수</th>
|
||||
<th>연도</th>
|
||||
@@ -193,14 +357,29 @@ export function SongsPage() {
|
||||
<th>난이도</th>
|
||||
<th>유튜브</th>
|
||||
<th>가사</th>
|
||||
<th>출제·정답률</th>
|
||||
<th>출처</th>
|
||||
{trash && <th />}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data?.rows.map((r) => (
|
||||
<tr key={r.id} className={selected === r.id ? 'sel' : ''} onClick={() => setSelected(r.id)} style={{ cursor: 'pointer' }}>
|
||||
<tr key={r.id} className={selected === r.id ? 'sel' : ''} onClick={() => !trash && setSelected(r.id)} style={{ cursor: trash ? 'default' : 'pointer' }}>
|
||||
<td onClick={(e) => e.stopPropagation()}>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={`${r.title} 선택`}
|
||||
checked={checked.has(r.id)}
|
||||
onChange={(e) => {
|
||||
const next = new Set(checked);
|
||||
if (e.target.checked) next.add(r.id);
|
||||
else next.delete(r.id);
|
||||
setChecked(next);
|
||||
}}
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<button type="button" className="linklike" onClick={() => setSelected(r.id)}>
|
||||
<button type="button" className="linklike" disabled={trash} onClick={() => setSelected(r.id)}>
|
||||
{r.title}
|
||||
</button>
|
||||
{r.hidden && <span className="badge">숨김</span>}
|
||||
@@ -213,7 +392,25 @@ export function SongsPage() {
|
||||
<span className={`badge ${YT_LABEL[r.youtube_status][1]}`}>{YT_LABEL[r.youtube_status][0]}</span>
|
||||
</td>
|
||||
<td>{r.has_lyrics ? '있음' : '-'}</td>
|
||||
<td className="mono small">{r.plays ? `${r.plays}회 · ${pct(r.correct, r.plays)}` : '-'}</td>
|
||||
<td className="small">{r.sources.map((s) => SOURCE_LABEL[s] ?? s).join(', ')}</td>
|
||||
{trash && (
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
void apiCall('POST', `/api/admin/songs/${r.id}/restore`).then(
|
||||
() => (toast('복원했어요.'), reload(), loadStats()),
|
||||
(ex: Error) => toast(ex.message, 'error'),
|
||||
);
|
||||
}}
|
||||
>
|
||||
복원
|
||||
</button>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
@@ -243,14 +440,171 @@ export function SongsPage() {
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{adding && (
|
||||
<AddSongSheet
|
||||
genres={genres}
|
||||
onClose={() => setAdding(false)}
|
||||
onAdded={(id) => {
|
||||
setAdding(false);
|
||||
reload();
|
||||
loadStats();
|
||||
setSelected(id);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{dupes && <DuplicatesSheet onClose={() => setDupes(false)} onMerged={() => (reload(), loadStats())} />}
|
||||
{confirmBulk && (
|
||||
<ConfirmSheet
|
||||
title={bulkAct === 'trash' ? `${checked.size}곡을 휴지통으로 옮길까요?` : `${checked.size}곡의 유튜브를 다시 찾을까요?`}
|
||||
body={bulkAct === 'trash' ? '30일 안에는 휴지통에서 복원할 수 있어요.' : '지금 영상(관리자가 정한 영상 포함)을 지우고, 다음 원곡 찾기 때 다시 찾아요.'}
|
||||
confirm="적용"
|
||||
danger={bulkAct === 'trash'}
|
||||
onConfirm={() => void runBulk()}
|
||||
onClose={() => setConfirmBulk(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 노래 추가: 제목 + 가수만 넣어도 돼요. 유튜브 주소를 넣으면 퍼가기 가능 여부를 확인해요. */
|
||||
function AddSongSheet({ genres, onClose, onAdded }: { genres: Genre[]; onClose: () => void; onAdded: (id: number) => void }) {
|
||||
const [form, setForm] = useState({ title: '', artist: '', year: '', level: '', youtube: '', genres: [] as string[] });
|
||||
const [busy, setBusy] = useState(false);
|
||||
return (
|
||||
<Sheet label="노래 추가" onClose={onClose}>
|
||||
<h2>노래 추가</h2>
|
||||
<form
|
||||
className="stack"
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await apiCall<{ id: number }>('POST', '/api/admin/songs', {
|
||||
title: form.title.trim(),
|
||||
artist: form.artist.trim(),
|
||||
year: form.year ? Number(form.year) : null,
|
||||
level: form.level ? Number(form.level) : null,
|
||||
genres: form.genres,
|
||||
youtube: form.youtube.trim() || null,
|
||||
});
|
||||
toast('추가했어요.');
|
||||
onAdded(r.id);
|
||||
} catch (ex) {
|
||||
toast((ex as Error).message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<label className="field">
|
||||
제목
|
||||
<input className="input" autoFocus value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} />
|
||||
</label>
|
||||
<label className="field">
|
||||
가수 (여러 명이면 쉼표로)
|
||||
<input className="input" value={form.artist} onChange={(e) => setForm({ ...form, artist: e.target.value })} />
|
||||
</label>
|
||||
<div className="two">
|
||||
<label className="field">
|
||||
연도
|
||||
<input className="input" inputMode="numeric" value={form.year} onChange={(e) => setForm({ ...form, year: e.target.value.replace(/\D/g, '') })} />
|
||||
</label>
|
||||
<label className="field">
|
||||
난이도
|
||||
<select className="input" value={form.level} onChange={(e) => setForm({ ...form, level: e.target.value })}>
|
||||
<option value="">없음</option>
|
||||
{Array.from({ length: 10 }, (_, i) => (
|
||||
<option key={i + 1} value={i + 1}>
|
||||
{i + 1}단계
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div className="row">
|
||||
{genres.map((g) => (
|
||||
<button
|
||||
key={g.id}
|
||||
type="button"
|
||||
className="chip"
|
||||
aria-pressed={form.genres.includes(g.id)}
|
||||
onClick={() => setForm({ ...form, genres: form.genres.includes(g.id) ? form.genres.filter((x) => x !== g.id) : [...form.genres, g.id] })}
|
||||
>
|
||||
{g.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<label className="field">
|
||||
유튜브 주소 (없으면 비워 두세요. 원곡 찾기가 찾아요)
|
||||
<input className="input" placeholder="https://youtu.be/…" value={form.youtube} onChange={(e) => setForm({ ...form, youtube: e.target.value })} />
|
||||
</label>
|
||||
<button className="btn btn-primary btn-block" disabled={busy || !form.title.trim() || !form.artist.trim()}>
|
||||
{busy ? '추가하는 중…' : '추가'}
|
||||
</button>
|
||||
</form>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
interface DupGroup {
|
||||
key: string;
|
||||
songs: { id: number; title: string; artist: string; year: number | null; youtube_status: string; plays: number }[];
|
||||
}
|
||||
|
||||
/** 중복 정리: same normalized title+artist. Pick the one to keep; the others merge into it. */
|
||||
function DuplicatesSheet({ onClose, onMerged }: { onClose: () => void; onMerged: () => void }) {
|
||||
const [groups, setGroups] = useState<DupGroup[] | null>(null);
|
||||
const [keep, setKeep] = useState<Record<string, number>>({});
|
||||
const load = useCallback(() => void apiCall<{ groups: DupGroup[] }>('GET', '/api/admin/songs/duplicates').then((r) => setGroups(r.groups), (e: Error) => toast(e.message, 'error')), []);
|
||||
useEffect(load, [load]);
|
||||
return (
|
||||
<Sheet label="중복 정리" onClose={onClose}>
|
||||
<h2>중복 정리</h2>
|
||||
<p className="muted small">제목·가수를 정리했을 때 같은 곡이에요. 남길 곡을 고르면 나머지의 별칭·장르·출처·영상·통계를 옮기고 휴지통으로 보내요.</p>
|
||||
{!groups ? (
|
||||
<p className="muted">불러오는 중…</p>
|
||||
) : groups.length === 0 ? (
|
||||
<p className="muted">중복된 곡이 없어요.</p>
|
||||
) : (
|
||||
<div className="stack" style={{ maxHeight: '60vh', overflowY: 'auto' }}>
|
||||
{groups.map((g) => {
|
||||
const target = keep[g.key] ?? g.songs.find((x) => x.youtube_status === 'matched')?.id ?? g.songs[0]!.id;
|
||||
return (
|
||||
<div key={g.key} className="card">
|
||||
{g.songs.map((x) => (
|
||||
<label key={x.id} className="check">
|
||||
<input type="radio" name={g.key} checked={target === x.id} onChange={() => setKeep({ ...keep, [g.key]: x.id })} />
|
||||
#{x.id} {x.title} - {x.artist} {x.year ?? ''} <span className="badge">{x.youtube_status}</span> {x.plays ? <span className="small muted">출제 {x.plays}</span> : null}
|
||||
</label>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-primary"
|
||||
onClick={() =>
|
||||
void apiCall('POST', '/api/admin/songs/merge', { target, others: g.songs.map((x) => x.id).filter((id) => id !== target) }).then(
|
||||
() => (toast('합쳤어요.'), load(), onMerged()),
|
||||
(e: Error) => toast(e.message, 'error'),
|
||||
)
|
||||
}
|
||||
>
|
||||
#{target}로 합치기
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
function SongEditor({ id, genres, onClose, onSaved }: { id: number; genres: Genre[]; onClose: () => void; onSaved: () => void }) {
|
||||
const [d, setD] = useState<Detail | null>(null);
|
||||
const [form, setForm] = useState({ title: '', artist: '', year: '', level: '', youtube: '', highlight: '', titleAliases: '', artistAliases: '', note: '', hidden: false, genres: [] as string[] });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [confirmTrash, setConfirmTrash] = useState(false);
|
||||
const previewRef = useRef<{ time(): number | undefined } | null>(null);
|
||||
/** The address as loaded: `youtube` is only sent when the admin changed it (review 2026-10-18). */
|
||||
const [loadedYoutube, setLoadedYoutube] = useState('');
|
||||
const load = useCallback(() => {
|
||||
@@ -406,14 +760,21 @@ function SongEditor({ id, genres, onClose, onSaved }: { id: number; genres: Genr
|
||||
</button>
|
||||
)}
|
||||
{videoId && (
|
||||
<div className="yt-preview">
|
||||
<iframe
|
||||
src={`https://www.youtube-nocookie.com/embed/${videoId}${form.highlight ? `?start=${Math.floor(Number(form.highlight))}` : ''}`}
|
||||
title="유튜브 미리듣기"
|
||||
allow="autoplay; encrypted-media"
|
||||
loading="lazy"
|
||||
/>
|
||||
</div>
|
||||
<>
|
||||
<YtPreview videoId={videoId} start={form.highlight ? Number(form.highlight) : 0} apiRef={previewRef} />
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
onClick={() => {
|
||||
const t = previewRef.current?.time();
|
||||
if (t === undefined) return toast('미리듣기를 먼저 재생해 주세요.', 'error');
|
||||
setForm({ ...form, highlight: t.toFixed(1) });
|
||||
toast(`하이라이트를 ${t.toFixed(1)}초로 정했어요. 저장을 눌러 주세요.`);
|
||||
}}
|
||||
>
|
||||
⏱ 지금 위치를 하이라이트로
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{d.candidates.length > 0 && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
@@ -466,51 +827,71 @@ function SongEditor({ id, genres, onClose, onSaved }: { id: number; genres: Genr
|
||||
<button className="btn btn-primary" disabled={busy}>
|
||||
{busy ? '저장 중…' : '저장'}
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setConfirmTrash(true)}>
|
||||
🗑 휴지통으로
|
||||
</button>
|
||||
</form>
|
||||
{confirmTrash && (
|
||||
<ConfirmSheet
|
||||
title="이 노래를 휴지통으로 옮길까요?"
|
||||
body="30일 안에는 휴지통에서 복원할 수 있어요."
|
||||
confirm="휴지통으로"
|
||||
danger
|
||||
onConfirm={() =>
|
||||
void apiCall('DELETE', `/api/admin/songs/${id}`).then(
|
||||
() => (toast('휴지통으로 옮겼어요.'), onSaved(), onClose()),
|
||||
(e: Error) => toast(e.message, 'error'),
|
||||
)
|
||||
}
|
||||
onClose={() => setConfirmTrash(false)}
|
||||
/>
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
export function CollectPage() {
|
||||
const [stats, setStats] = useState<Stats | null>(null);
|
||||
useEffect(() => {
|
||||
const load = () => void apiCall<Stats>('GET', '/api/admin/catalog').then(setStats).catch(() => {});
|
||||
load();
|
||||
const t = setInterval(load, 10_000);
|
||||
return () => clearInterval(t);
|
||||
}, []);
|
||||
const KIND: Record<string, string> = { 'import-norabose': '노라보세 가져오기', 'import-sta': '스타맵 가져오기', 'match-youtube': '유튜브 원곡 찾기' };
|
||||
const STATUS: Record<string, string> = { running: '진행 중', done: '완료', failed: '실패', stopped: '멈춤' };
|
||||
return (
|
||||
<>
|
||||
<h1>수집</h1>
|
||||
<p className="muted small">수집 작업은 서버에서 따로 돌아가요. 지금은 실행 기록만 보여요(관리자 화면에서 실행하는 기능은 다음 단계).</p>
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>작업</th>
|
||||
<th>상태</th>
|
||||
<th>진행</th>
|
||||
<th>시작</th>
|
||||
<th>끝</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{stats?.jobs.map((j) => (
|
||||
<tr key={j.id}>
|
||||
<td>{KIND[j.kind] ?? j.kind}</td>
|
||||
<td>{STATUS[j.status] ?? j.status}</td>
|
||||
<td className="mono">
|
||||
{j.done.toLocaleString()} / {j.total.toLocaleString()}
|
||||
</td>
|
||||
<td className="small">{new Date(j.started_at).toLocaleString('ko-KR')}</td>
|
||||
<td className="small">{j.finished_at ? new Date(j.finished_at).toLocaleString('ko-KR') : '-'}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
declare global {
|
||||
interface Window {
|
||||
YT?: any;
|
||||
onYouTubeIframeAPIReady?: () => void;
|
||||
}
|
||||
}
|
||||
|
||||
let ytApi: Promise<void> | null = null;
|
||||
function loadYt(): Promise<void> {
|
||||
ytApi ??= new Promise<void>((resolve) => {
|
||||
if (window.YT?.Player) return resolve();
|
||||
const prev = window.onYouTubeIframeAPIReady;
|
||||
window.onYouTubeIframeAPIReady = () => {
|
||||
prev?.();
|
||||
resolve();
|
||||
};
|
||||
const sc = document.createElement('script');
|
||||
sc.src = 'https://www.youtube.com/iframe_api';
|
||||
document.head.appendChild(sc);
|
||||
});
|
||||
return ytApi;
|
||||
}
|
||||
|
||||
/** 미리듣기 with the IFrame API, so "지금 위치를 하이라이트로" can read the position. */
|
||||
function YtPreview({ videoId, start, apiRef }: { videoId: string; start: number; apiRef: { current: { time(): number | undefined } | null } }) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
let player: any = null;
|
||||
let dead = false;
|
||||
void loadYt().then(() => {
|
||||
if (dead || !host.current) return;
|
||||
const el = document.createElement('div');
|
||||
host.current.replaceChildren(el);
|
||||
player = new window.YT.Player(el, { videoId, width: '100%', height: '100%', playerVars: { start: Math.floor(start), rel: 0, playsinline: 1 } });
|
||||
apiRef.current = { time: () => (typeof player?.getCurrentTime === 'function' ? player.getCurrentTime() : undefined) };
|
||||
});
|
||||
return () => {
|
||||
dead = true;
|
||||
apiRef.current = null;
|
||||
if (typeof player?.destroy === 'function') player.destroy();
|
||||
};
|
||||
// start only matters when the video changes
|
||||
}, [videoId]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
return <div className="yt-preview" ref={host} aria-label="유튜브 미리듣기" />;
|
||||
}
|
||||
|
||||
@@ -444,3 +444,4 @@ input.input.sm { width: 76px; }
|
||||
.welcome h1 { font-size: 1.75rem; }
|
||||
.header-user-name { display: none; }
|
||||
}
|
||||
.bulk-bar { background: var(--primary-soft); border: 2px solid var(--ink); border-radius: 12px; padding: 8px 12px; position: sticky; top: 72px; z-index: 5; }
|
||||
|
||||
Reference in New Issue
Block a user