/** * 관리자 → 노래 (docs/02 노래 관리 화면): 검색·필터·정렬 표 + 오른쪽 편집 패널(유튜브 미리듣기·후보 고르기·하이라이트·별칭). */ import { useCallback, useEffect, useMemo, useState, type FormEvent } from 'react'; import { apiCall } from '../../net/api'; import { toast } from '../../store/toast'; interface Genre { id: string; name: string; grp: 'region' | 'style' | 'theme'; songs: number; } interface Row { id: number; melon_id: number | null; title: string; artist: string; year: number | null; duration_sec: number | null; youtube_id: string | null; youtube_status: 'matched' | 'candidate' | 'none' | 'dead'; youtube_source: string | null; youtube_channel: string | null; peak_rank: number | null; level: number | null; genres: string[]; sources: string[]; has_lyrics: boolean; hidden: boolean; } interface Detail { song: Row & { youtube_title: string | null; highlight_sec: number | null; highlight_source: string | null; note: string | null; mv_youtube_id: string | null }; genres: { genre_id: string }[]; levels: { scope: string; level: number; source: string }[]; aliases: { part: 'title' | 'artist'; alias: string }[]; lyrics: { text: string } | null; sources: { source: string; ref: string }[]; candidates: { video_id: string; title: string | null; channel: string | null; duration_sec: number | null; score: number; source: string }[]; } interface Stats { total: number; youtube: { matched: number; candidate: number; none: number; dead: number; tried: number }; lyrics: number; sources: Record; jobs: { id: number; kind: string; status: string; done: number; total: number; started_at: number; finished_at: number | null }[]; } const YT_LABEL: Record = { matched: ['확정', 'ok'], candidate: ['후보', 'warn'], none: ['없음', ''], dead: ['재생 불가', 'warn'], }; const SOURCE_LABEL: Record = { norabose: '노라보세', sta: '스타맵' }; 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)}%` : '-'); export function SongsPage() { const [genres, setGenres] = useState([]); const [stats, setStats] = useState(null); const [q, setQ] = useState(''); const [f, setF] = useState({ q: '', genres: [] as string[], yearFrom: '', yearTo: '', level: '', youtube: '', source: '', sort: 'recent', page: 0 }); const [data, setData] = useState<{ total: number; rows: Row[]; pageSize: number } | null>(null); const [selected, setSelected] = useState(null); const loadStats = useCallback(() => void apiCall('GET', '/api/admin/catalog').then(setStats).catch(() => {}), []); useEffect(() => { void apiCall<{ genres: Genre[] }>('GET', '/api/admin/genres').then((r) => setGenres(r.genres)); loadStats(); }, [loadStats]); const query = useMemo(() => { 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]); p.set('page', String(f.page)); return p.toString(); }, [f]); const reload = useCallback(() => { apiCall<{ total: number; rows: Row[]; pageSize: number }>('GET', `/api/admin/songs?${query}`) .then(setData) .catch((e: Error) => toast(e.message, 'error')); }, [query]); useEffect(reload, [reload]); const set = (patch: Partial) => setF((x) => ({ ...x, page: 0, ...patch })); 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 (

노래

{stats && (
{stats.total.toLocaleString()} 전체 곡
{pct(stats.youtube.matched, stats.total)} 유튜브 확정 {stats.youtube.matched.toLocaleString()}
{stats.youtube.candidate.toLocaleString()} 후보 확인 대기
{stats.youtube.none.toLocaleString()} 유튜브 없음
{pct(stats.lyrics, stats.total)} 가사 보유 {stats.lyrics.toLocaleString()}
)}
{ e.preventDefault(); set({ q: q.trim() }); }} > setQ(e.target.value)} aria-label="노래 검색" /> {data && {data.total.toLocaleString()}곡}
{genres.map((g) => ( ))}
{data?.rows.map((r) => ( setSelected(r.id)} style={{ cursor: 'pointer' }}> ))}
제목 가수 연도 장르 난이도 유튜브 가사 출처
{r.hidden && 숨김} {r.artist} {r.year ?? '-'} {r.genres.map((g) => genres.find((x) => x.id === g)?.name ?? g).join(', ')} {r.level ? `★${r.level}` : '-'} {YT_LABEL[r.youtube_status][0]} {r.has_lyrics ? '있음' : '-'} {r.sources.map((s) => SOURCE_LABEL[s] ?? s).join(', ')}
{f.page + 1} / {pages}
{selected && ( setSelected(null)} onSaved={() => { reload(); loadStats(); }} /> )}
); } function SongEditor({ id, genres, onClose, onSaved }: { id: number; genres: Genre[]; onClose: () => void; onSaved: () => void }) { const [d, setD] = useState(null); const [form, setForm] = useState({ title: '', artist: '', year: '', level: '', youtube: '', highlight: '', titleAliases: '', artistAliases: '', note: '', hidden: false, genres: [] as string[] }); const [busy, setBusy] = useState(false); /** The address as loaded: `youtube` is only sent when the admin changed it (review 2026-10-18). */ const [loadedYoutube, setLoadedYoutube] = useState(''); const load = useCallback(() => { apiCall('GET', `/api/admin/songs/${id}`) .then((x) => { setD(x); const lv = x.levels.find((l) => l.scope === 'all'); setLoadedYoutube(x.song.youtube_id ? `https://youtu.be/${x.song.youtube_id}` : ''); setForm({ title: x.song.title, artist: x.song.artist, year: x.song.year ? String(x.song.year) : '', level: lv ? String(lv.level) : '', youtube: x.song.youtube_id ? `https://youtu.be/${x.song.youtube_id}` : '', highlight: x.song.highlight_sec != null ? String(x.song.highlight_sec) : '', titleAliases: x.aliases.filter((a) => a.part === 'title').map((a) => a.alias).join(', '), artistAliases: x.aliases.filter((a) => a.part === 'artist').map((a) => a.alias).join(', '), note: x.song.note ?? '', hidden: x.song.hidden, genres: x.genres.map((g) => g.genre_id), }); }) .catch((e: Error) => toast(e.message, 'error')); }, [id]); useEffect(load, [load]); if (!d) return ; const split = (s: string) => s.split(',').map((x) => x.trim()).filter(Boolean); const save = async (e: FormEvent) => { e.preventDefault(); setBusy(true); try { await apiCall('PATCH', `/api/admin/songs/${id}`, { title: form.title, artist: form.artist, year: form.year ? Number(form.year) : null, level: form.level ? Number(form.level) : null, genres: form.genres, ...(form.youtube.trim() !== loadedYoutube ? { youtube: form.youtube.trim() || null } : {}), highlightSec: form.highlight ? Number(form.highlight) : null, titleAliases: split(form.titleAliases), artistAliases: split(form.artistAliases), note: form.note || null, hidden: form.hidden, }); toast('저장했어요.'); load(); onSaved(); } catch (ex) { toast((ex as Error).message, 'error'); } finally { setBusy(false); } }; const videoId = /youtu\.be\/([\w-]{11})/.exec(form.youtube)?.[1] ?? d.song.youtube_id; return (