제작된 퀴즈 5단계: 검토 대기(전체공개 퀴즈 → 서버 노래 DB). 저장할 때 DB에 없는 곡과 영상·제목·가수·직접 정한 하이라이트가 DB와 다른 곡을 모아 관리자가 항목마다 DB 유지/퀴즈 값을 고르거나 새 곡을 연도·장르·난이도와 함께 추가(퀴즈 곡이 그 DB 곡에 연결). 복수정답은 DB 별칭에, 한 번 정한 값은 다시 묻지 않음. 관리자 메뉴 '검토 대기'(개수 표시), 처리한 것 기록·감사 로그

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-22 13:07:41 +09:00
parent 4a40be696b
commit b999310eb9
10 changed files with 632 additions and 4 deletions

View File

@@ -11,6 +11,8 @@ import { ConfirmSheet } from '../../components/ui';
import { SongsPage } from './SongsPage';
import { YoutubePage } from './YoutubePage';
import { QuizEditor, QuizzesPage } from './QuizzesPage';
import { ReviewsPage } from './ReviewsPage';
import { useReviewCount } from './reviewCount';
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';
@@ -57,6 +59,17 @@ export default function AdminApp() {
);
}
const isSuper = role === 'superadmin';
return <AdminShell role={role} isSuper={isSuper} />;
}
function AdminShell({ role, isSuper }: { role: Role; isSuper: boolean }) {
const reviews = useReviewCount((s) => s.n);
const refreshReviews = useReviewCount((s) => s.refresh);
useEffect(() => {
refreshReviews();
const t = setInterval(refreshReviews, 60_000);
return () => clearInterval(t);
}, [refreshReviews]);
return (
<div className="admin-layout">
<nav className="admin-side" aria-label="관리자 메뉴">
@@ -72,6 +85,9 @@ export default function AdminApp() {
<NavLink to="/admin/stats">📈 통계</NavLink>
<div className="sep">퀴즈</div>
<NavLink to="/admin/quizzes">📋 퀴즈</NavLink>
<NavLink to="/admin/reviews">
✅ 검토 대기{reviews > 0 && <span className="badge warn" style={{ marginLeft: 'auto' }}>{reviews}</span>}
</NavLink>
<div className="sep">운영</div>
<NavLink to="/admin/rooms">🚪 방</NavLink>
<NavLink to="/admin/site">⚙️ 사이트</NavLink>
@@ -90,6 +106,7 @@ export default function AdminApp() {
<Route path="stats" element={<StatsPage />} />
<Route path="quizzes" element={<QuizzesPage />} />
<Route path="quizzes/:id" element={<QuizEditor />} />
<Route path="reviews" element={<ReviewsPage />} />
<Route path="rooms" element={<RoomsPage />} />
<Route path="site" element={<SiteSettings />} />
{isSuper && <Route path="users" element={<UsersPage />} />}

View File

@@ -23,6 +23,7 @@ import { ConfirmSheet, Sheet } from '../../components/ui';
import { PlayRules, Section, Seg } from '../../components/RoomSettings';
import { YtPreview } from './SongsPage';
import { PositionEditor } from './PositionEditor';
import { useReviewCount } from './reviewCount';
const mmss = (s: number | null | undefined) => (s == null ? '-' : `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, '0')}`);
const VIS_LABEL: Record<QuizVisibility, string> = { private: '비공개', partial: '일부공개', public: '전체공개' };
@@ -172,13 +173,14 @@ export function QuizEditor() {
if (!draft) return false;
setBusy(true);
try {
const r = await apiCall<{ quiz: QuizDetail }>('PUT', `/api/admin/quizzes/${id}`, payload(draft));
const r = await apiCall<{ quiz: QuizDetail; reviews: { pending: number } }>('PUT', `/api/admin/quizzes/${id}`, payload(draft));
// keep the client keys (selection) of items that were already there, in order
const d = toDraft(r.quiz);
d.items = d.items.map((it, i) => ({ ...it, key: draft.items[i]?.key ?? it.key }));
setDraft(d);
setSaved(JSON.stringify(payload(d)));
toast('저장했어요.');
toast(r.reviews.pending ? `저장했어요. 서버 DB에 없거나 다른 곡 ${r.reviews.pending}곡이 관리자 검토 대기에 있어요.` : '저장했어요.');
useReviewCount.getState().refresh();
// DB facts of newly linked songs
const fresh = await apiCall<{ db: Record<number, DbInfo> }>('GET', `/api/admin/quizzes/${id}`);
setDb(fresh.db);

View File

@@ -0,0 +1,295 @@
/**
* 관리자 → 검토 대기: songs of 전체공개 quizzes that are missing in the server DB or differ from it.
* Differences are chosen field by field (서버 DB 값 유지 / 퀴즈 값으로); new songs get year·genres·level and are added.
*/
import { useCallback, useEffect, useState } from 'react';
import { Link } from 'react-router';
import { LEVELS } from '@mq/shared/lite';
import { apiCall } from '../../net/api';
import { toast } from '../../store/toast';
import { YtPreview, type Genre } from './SongsPage';
import { useReviewCount } from './reviewCount';
type Field = 'title' | 'artist' | 'video' | 'highlight';
interface Proposal {
title: string;
artist: string;
videoId: string;
highlightSec: number | null;
durationSec: number | null;
titleAnswers: string[];
artistAnswers: string[];
}
interface Review {
id: number;
quiz: { id: number; name: string; owner: string };
n: number | null;
kind: 'new' | 'diff';
fields: Field[];
proposal: Proposal;
db: { id: number; title: string; artist: string; year: number | null; youtube_id: string | null; youtube_status: string; highlight_sec: number | null; duration_sec: number | null } | null;
status: string;
result: string | null;
createdAt: number;
decidedAt: number | null;
decidedBy: string | null;
}
const mmss = (s: number | null | undefined) => (s == null ? '-' : `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, '0')}`);
const FIELD: Record<Field, string> = { title: '제목', artist: '가수', video: '영상', highlight: '하이라이트' };
const when = (ms: number | null) => (ms ? new Date(ms).toLocaleString('ko-KR', { dateStyle: 'short', timeStyle: 'short' }) : '-');
export function ReviewsPage() {
const [tab, setTab] = useState<'pending' | 'done'>('pending');
const [list, setList] = useState<Review[] | null>(null);
const [genres, setGenres] = useState<Genre[]>([]);
const refreshCount = useReviewCount((s) => s.refresh);
const load = useCallback(() => {
apiCall<{ reviews: Review[] }>('GET', `/api/admin/reviews${tab === 'done' ? '?status=done' : ''}`)
.then((r) => setList(r.reviews))
.catch((e: Error) => toast(e.message, 'error'));
refreshCount();
}, [tab, refreshCount]);
useEffect(load, [load]);
useEffect(() => {
void apiCall<{ genres: Genre[] }>('GET', '/api/admin/genres').then((r) => setGenres(r.genres));
}, []);
return (
<>
<h1>검토 대기</h1>
<p className="muted">전체공개 퀴즈의 곡 중 서버 노래 DB에 없거나 DB와 다른 곡이에요. 고른 값이 서버 DB에 들어가고, 이 퀴즈의 복수정답도 DB 별칭에 들어가요. 한 번 정한 값은 다시 묻지 않아요.</p>
<div className="seg" role="tablist" style={{ maxWidth: 360 }}>
<button type="button" role="tab" aria-selected={tab === 'pending'} className={tab === 'pending' ? 'on' : ''} onClick={() => setTab('pending')}>
퀴즈 곡 검토
</button>
<button type="button" role="tab" aria-selected={tab === 'done'} className={tab === 'done' ? 'on' : ''} onClick={() => setTab('done')}>
처리한 것
</button>
</div>
{list?.length === 0 && <p className="muted">{tab === 'pending' ? '검토할 곡이 없어요.' : '아직 처리한 것이 없어요.'}</p>}
<div className="stack" style={{ gap: 12 }}>
{list?.map((r) =>
tab === 'done' ? (
<div key={r.id} className="card row small">
<span className={`badge ${r.status === 'applied' ? 'ok' : ''}`}>{r.status === 'applied' ? '반영' : '안 함'}</span>
<b>{r.proposal.title}</b> <span className="muted">· {r.proposal.artist}</span>
<span className="grow muted">
{r.result} · {r.quiz.name} · {r.decidedBy ?? '?'} · {when(r.decidedAt)}
</span>
</div>
) : r.kind === 'diff' ? (
<DiffCard key={r.id} r={r} onDone={load} />
) : (
<NewCard key={r.id} r={r} genres={genres} onDone={load} />
),
)}
</div>
</>
);
}
function Head({ r }: { r: Review }) {
return (
<div className="row small" style={{ gap: 6 }}>
<span className={`badge ${r.kind === 'new' ? 'warn' : 'teal'}`}>{r.kind === 'new' ? 'DB에 없는 곡' : 'DB와 다름'}</span>
<span className="muted">
<Link to={`/admin/quizzes/${r.quiz.id}`}>{r.quiz.name}</Link> {r.n ? `${r.n}번` : ''} · 만든 사람 {r.quiz.owner} · {when(r.createdAt)}
</span>
</div>
);
}
function DiffCard({ r, onDone }: { r: Review; onDone: () => void }) {
const [take, setTake] = useState<Set<Field>>(new Set(r.fields));
const [listen, setListen] = useState<{ id: string; start: number } | null>(null);
const [busy, setBusy] = useState(false);
const api = { current: null } as { current: { time(): number | undefined } | null };
const d = r.db!;
const dbVal = (f: Field) => (f === 'title' ? d.title : f === 'artist' ? d.artist : f === 'video' ? (d.youtube_status === 'matched' ? d.youtube_id : null) : d.highlight_sec);
const qVal = (f: Field) => (f === 'title' ? r.proposal.title : f === 'artist' ? r.proposal.artist : f === 'video' ? r.proposal.videoId : r.proposal.highlightSec);
const show = (f: Field, v: string | number | null) => (v == null ? <span className="muted">없음</span> : f === 'highlight' ? mmss(v as number) : String(v));
const act = async (path: string, body?: unknown) => {
setBusy(true);
try {
const res = await apiCall<{ result?: string }>('POST', `/api/admin/reviews/${r.id}/${path}`, body ?? {});
toast(res.result ?? '반영하지 않았어요.');
onDone();
} catch (e) {
toast((e as Error).message, 'error');
} finally {
setBusy(false);
}
};
const quizVideo = r.proposal.videoId;
const dbVideo = d.youtube_status === 'matched' ? d.youtube_id : null;
return (
<div className="card stack" style={{ gap: 10 }}>
<Head r={r} />
<b>
서버 곡 #{d.id} · {d.title} - {d.artist}
</b>
<div className="table-wrap">
<table className="data-table">
<thead>
<tr>
<th>항목</th>
<th>서버 DB 값</th>
<th>퀴즈 값</th>
<th>쓸 값</th>
</tr>
</thead>
<tbody>
{r.fields.map((f) => (
<tr key={f}>
<td>{FIELD[f]}</td>
<td>
{show(f, dbVal(f))}
{f === 'video' && dbVideo && (
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setListen({ id: dbVideo, start: 0 })} aria-label="서버 DB 영상 듣기">
▶
</button>
)}
{f === 'highlight' && dbVideo && d.highlight_sec != null && (
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setListen({ id: dbVideo, start: d.highlight_sec! })} aria-label="서버 DB 하이라이트 듣기">
▶
</button>
)}
</td>
<td>
{show(f, qVal(f))}
{(f === 'video' || f === 'highlight') && (
<button
type="button"
className="btn btn-sm btn-ghost"
onClick={() => setListen({ id: quizVideo, start: f === 'highlight' ? (r.proposal.highlightSec ?? 0) : 0 })}
aria-label={`퀴즈 ${FIELD[f]} 듣기`}
>
▶
</button>
)}
</td>
<td>
<div className="seg" role="radiogroup" aria-label={`${FIELD[f]} 쓸 값`} style={{ minWidth: 200 }}>
<button type="button" role="radio" aria-checked={!take.has(f)} className={!take.has(f) ? 'on' : ''} onClick={() => setTake(new Set([...take].filter((x) => x !== f)))}>
DB 유지
</button>
<button type="button" role="radio" aria-checked={take.has(f)} className={take.has(f) ? 'on' : ''} onClick={() => setTake(new Set([...take, f]))}>
퀴즈 값
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
{listen && (
<div style={{ maxWidth: 420 }}>
<YtPreview key={`${listen.id}@${listen.start}`} videoId={listen.id} start={listen.start} apiRef={api} />
</div>
)}
{(r.proposal.titleAnswers.length > 0 || r.proposal.artistAnswers.length > 0) && (
<p className="muted small" style={{ margin: 0 }}>
복수정답(DB 별칭에 추가): {[...r.proposal.titleAnswers, ...r.proposal.artistAnswers].join(', ')}
</p>
)}
<div className="row">
<button type="button" className="btn btn-primary" disabled={busy} onClick={() => void act('apply', { take: [...take] })}>
적용
</button>
<button type="button" className="btn" disabled={busy} onClick={() => void act('reject')}>
반영 안 함
</button>
</div>
</div>
);
}
function NewCard({ r, genres, onDone }: { r: Review; genres: Genre[]; onDone: () => void }) {
const p = r.proposal;
const [title, setTitle] = useState(p.title);
const [artist, setArtist] = useState(p.artist);
const [year, setYear] = useState('');
const [level, setLevel] = useState(5);
const [picked, setPicked] = useState<string[]>([]);
const [busy, setBusy] = useState(false);
const [listen, setListen] = useState(false);
const api = { current: null } as { current: { time(): number | undefined } | null };
const act = async (path: string, body?: unknown) => {
setBusy(true);
try {
const res = await apiCall<{ result?: string }>('POST', `/api/admin/reviews/${r.id}/${path}`, body ?? {});
toast(res.result ?? '반영하지 않았어요.');
onDone();
} catch (e) {
toast((e as Error).message, 'error');
} finally {
setBusy(false);
}
};
const y = Number(year);
return (
<div className="card stack" style={{ gap: 10 }}>
<Head r={r} />
<div className="form-grid">
<label className="field">
제목
<input className="input" value={title} maxLength={200} onChange={(e) => setTitle(e.target.value)} />
</label>
<label className="field">
가수 (여러 명은 쉼표로)
<input className="input" value={artist} maxLength={200} onChange={(e) => setArtist(e.target.value)} />
</label>
<label className="field">
발매 연도
<input className="input" inputMode="numeric" value={year} placeholder="예: 2024" onChange={(e) => setYear(e.target.value.replace(/\D/g, '').slice(0, 4))} />
</label>
<label className="field">
난이도 (게임에 나오려면 필요)
<select className="input" value={level} onChange={(e) => setLevel(Number(e.target.value))}>
{LEVELS.map(([name], i) => (
<option key={i} value={i + 1}>
★{i + 1} {name}
</option>
))}
</select>
</label>
</div>
<div className="field">
장르
<div className="row" style={{ gap: 6 }}>
{genres.map((g) => (
<button key={g.id} type="button" className="chip" aria-pressed={picked.includes(g.id)} onClick={() => setPicked(picked.includes(g.id) ? picked.filter((x) => x !== g.id) : [...picked, g.id])}>
{g.name}
</button>
))}
</div>
</div>
<p className="small muted" style={{ margin: 0 }}>
영상 {p.videoId} · 길이 {mmss(p.durationSec)} · 하이라이트 {p.highlightSec != null ? mmss(p.highlightSec) : '자동'}
{(p.titleAnswers.length > 0 || p.artistAnswers.length > 0) && ` · 복수정답 ${[...p.titleAnswers, ...p.artistAnswers].join(', ')}`}{' '}
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setListen(!listen)}>
{listen ? '닫기' : '▶ 듣기'}
</button>
</p>
{listen && (
<div style={{ maxWidth: 420 }}>
<YtPreview videoId={p.videoId} start={p.highlightSec ?? 0} apiRef={api} />
</div>
)}
<div className="row">
<button
type="button"
className="btn btn-primary"
disabled={busy || !title.trim() || !artist.trim() || (year !== '' && (y < 1900 || y > 2100))}
onClick={() => void act('apply', { song: { title: title.trim(), artist: artist.trim(), year: year ? y : null, genres: picked, level } })}
>
서버 DB에 추가
</button>
<button type="button" className="btn" disabled={busy} onClick={() => void act('reject')}>
반영 안 함
</button>
</div>
</div>
);
}

View File

@@ -0,0 +1,12 @@
/** 검토 대기 count for the admin side menu badge. */
import { create } from 'zustand';
import { apiCall } from '../../net/api';
export const useReviewCount = create<{ n: number; refresh: () => void }>((set) => ({
n: 0,
refresh: () => {
apiCall<{ pending: number }>('GET', '/api/admin/reviews/count')
.then((r) => set({ n: r.pending }))
.catch(() => {});
},
}));