제작된 퀴즈 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

@@ -204,3 +204,34 @@ test('플레이리스트 가져오기: DB songs by video, cleaned YouTube titles
const g = await guest(s.base, '손님');
expect((await api(s.base, `/api/admin/quizzes/pick/playlist/${job.id}`, { cookie: g.cookie })).res.status).toBe(403);
});
test('검토 대기: a 전체공개 quiz sends new songs and differences to admins; applied or rejected ones are not asked again', async () => {
const song = start();
const sa = await adminCookie(TEST_SUPERADMINS[0]);
const items = [
item({ songId: song, videoId: 'goodday0002', title: '좋은 날 (Good Day)', artist: '아이유', auto: false, startSec: 0, highlightSec: 75, titleAnswers: ['굿데이'] }),
item({ videoId: 'newsong0001', title: '새 노래', artist: '새 가수', durationSec: 201 }),
];
const q = await makeQuiz(sa, { visibility: 'private', items });
expect(q.r.body.reviews.pending).toBe(0); // 비공개: nothing to review
const save = (body: Record<string, unknown>) => api(s.base, `/api/admin/quizzes/${q.id}`, { method: 'PUT', cookie: sa, body: JSON.stringify({ name: '퀴즈', description: '', visibility: 'public', settings: settings(), ...body }) });
const r1 = await save({ items: q.r.body.quiz.items });
expect(r1.body.reviews.pending).toBe(2);
const list = (await api(s.base, '/api/admin/reviews', { cookie: sa })).body.reviews as { id: number; kind: string; fields: string[] }[];
const diff = list.find((x) => x.kind === 'diff')!;
const fresh = list.find((x) => x.kind === 'new')!;
expect(diff.fields.sort()).toEqual(['highlight', 'title', 'video']);
// take the video and highlight, keep the DB title
const a = await api(s.base, `/api/admin/reviews/${diff.id}/apply`, { method: 'POST', cookie: sa, body: JSON.stringify({ take: ['video', 'highlight'] }) });
expect(a.body.result).toContain('영상·하이라이트');
expect(s.db.query<{ title: string; youtube_id: string; highlight_sec: number }, [number]>('SELECT title, youtube_id, highlight_sec FROM songs WHERE id = ?').get(song)).toEqual({ title: '좋은 날', youtube_id: 'goodday0002', highlight_sec: 75 });
// new song: registered with a level so it can come up in games
const b = await api(s.base, `/api/admin/reviews/${fresh.id}/apply`, { method: 'POST', cookie: sa, body: JSON.stringify({ song: { year: 2024, level: 5 } }) });
expect(b.body.result).toContain('새 곡');
const added = s.db.query<{ id: number; youtube_id: string; youtube_status: string; duration_sec: number }, []>("SELECT id, youtube_id, youtube_status, duration_sec FROM songs WHERE title = '새 노래'").get()!;
expect(added).toMatchObject({ youtube_id: 'newsong0001', youtube_status: 'matched', duration_sec: 201 });
expect(s.db.query<{ song_id: number }, []>("SELECT song_id FROM custom_quiz_items WHERE video_id = 'newsong0001'").get()!.song_id).toBe(added.id);
// saving again: the title difference was decided (DB kept) → not asked again; the new song is now the same
const again = await save({ items: (await api(s.base, `/api/admin/quizzes/${q.id}`, { cookie: sa })).body.quiz.items });
expect(again.body.reviews.pending).toBe(0);
});

View File

@@ -0,0 +1,18 @@
-- 검토 대기: songs of 전체공개 quizzes that differ from (or are missing in) the server DB, decided by an admin.
CREATE TABLE quiz_reviews (
id INTEGER PRIMARY KEY AUTOINCREMENT,
quiz_id INTEGER NOT NULL REFERENCES custom_quizzes(id) ON DELETE CASCADE,
item_id INTEGER NOT NULL, -- custom_quiz_items.id (ids are never reused)
song_id INTEGER REFERENCES songs(id) ON DELETE SET NULL,
kind TEXT NOT NULL CHECK (kind IN ('new','diff')),
fields TEXT NOT NULL DEFAULT '[]', -- diff: which of title/artist/video/highlight differ
proposal_json TEXT NOT NULL, -- the quiz's values {title, artist, videoId, highlightSec, durationSec, titleAnswers, artistAnswers}
hash TEXT NOT NULL, -- same proposal decided before → not asked again
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','applied','rejected')),
result TEXT,
created_at INTEGER NOT NULL,
decided_by TEXT,
decided_at INTEGER
);
CREATE UNIQUE INDEX quiz_reviews_pending ON quiz_reviews(item_id) WHERE status = 'pending';
CREATE INDEX quiz_reviews_status ON quiz_reviews(status, created_at);

View File

@@ -12,6 +12,7 @@ import { pickSearcher } from '../collector/ytmusic';
import { listSongs } from '../songs/store';
import { audioFile, type AudioLinks } from '../songs/audio';
import { getImportJob, startImport, type Lavalink } from '../quizzes/playlist';
import { applyReview, listReviews, pendingCount, rejectReview, syncReviews } from '../quizzes/review';
import { checkEmbed, type EmbedState } from '../collector/oembed';
type Env = { Variables: { userId: string | null; role: Role } };
@@ -61,6 +62,48 @@ export function mountQuizAdmin(app: Hono<Env>, d: QuizAdminDeps, h: { actor: (c:
return c.json({ id });
});
// ---------------------------------------------------------------- 검토 대기 (전체공개 퀴즈 → 서버 노래 DB)
app.get('/reviews/count', (c) => c.json({ pending: pendingCount(d.db) }));
app.get('/reviews', (c) => c.json({ reviews: listReviews(d.db, c.req.query('status') === 'done' ? 'done' : 'pending'), pending: pendingCount(d.db) }));
app.post('/reviews/:id/apply', async (c) => {
const id = Number(c.req.param('id'));
const p = z
.object({
take: z.array(z.enum(['title', 'artist', 'video', 'highlight'])).optional(),
song: z
.object({
title: z.string().trim().max(200).optional(),
artist: z.string().trim().max(200).optional(),
year: z.number().int().min(1900).max(2100).nullable().optional(),
genres: z.array(z.string().max(30)).max(20).optional(),
level: z.number().int().min(1).max(10).nullable().optional(),
})
.optional(),
})
.safeParse(await h.body(c));
if (!p.success) return c.json({ error: '입력 값이 올바르지 않아요.' }, 400);
const r = listReviews(d.db).find((x) => x.id === id);
if (!r) return c.json({ error: '이미 처리했거나 없는 검토예요.' }, 404);
// a video that becomes the DB video is checked like any admin edit
let embed: { author: string; title: string } | undefined;
if (r.kind === 'new' || p.data.take?.includes('video')) {
const v = await d.videoOf(r.proposal.videoId);
if (typeof v === 'string') return c.json({ error: v }, 400);
embed = { author: v.author, title: v.title };
}
const result = applyReview(d.db, id, p.data, h.actor(c), embed);
if (result.startsWith('!')) return c.json({ error: result.slice(1) }, 400);
d.audit.log(h.actor(c), 'review.apply', String(id), { quiz: r.quiz.name, song: r.db?.id ?? null }, { result, take: p.data.take ?? null });
d.onChange?.();
return c.json({ ok: true, result, pending: pendingCount(d.db) });
});
app.post('/reviews/:id/reject', (c) => {
const id = Number(c.req.param('id'));
if (!rejectReview(d.db, id, h.actor(c))) return c.json({ error: '이미 처리했거나 없는 검토예요.' }, 404);
d.audit.log(h.actor(c), 'review.reject', String(id), null, null);
return c.json({ ok: true, pending: pendingCount(d.db) });
});
// ---------------------------------------------------------------- song pickers (before /quizzes/:id)
/** 서버 노래 검색: title/artist/초성, songs with a confirmed video first. */
app.get('/quizzes/pick/db', (c) => {
@@ -188,15 +231,18 @@ export function mountQuizAdmin(app: Hono<Env>, d: QuizAdminDeps, h: { actor: (c:
if (!p.success) return c.json({ error: `저장할 내용이 올바르지 않아요: ${p.error.issues.slice(0, 3).map((i) => i.path.join('.')).join(', ')}` }, 400);
const saved = d.quizzes.save(q.id, p.data, d.limits());
if (typeof saved === 'string') return c.json({ error: saved }, 400);
// 전체공개: songs that differ from the server DB wait for an admin (검토 대기)
const reviews = syncReviews(d.db, q.id);
d.audit.log(h.actor(c), 'quiz.save', String(q.id), { name: q.name, songs: q.songs, visibility: q.visibility }, { name: saved.name, songs: saved.items.length, visibility: saved.visibility });
d.onChange?.();
return c.json({ quiz: saved });
return c.json({ quiz: saved, reviews });
});
app.delete('/quizzes/:id', (c) => {
const q = mine(c);
if (!q) return c.json({ error: '퀴즈를 찾을 수 없어요.' }, 404);
d.quizzes.remove(q.id);
syncReviews(d.db, q.id);
d.audit.log(h.actor(c), 'quiz.delete', String(q.id), { name: q.name, songs: q.songs }, null);
d.onChange?.();
return c.json({ ok: true });

View File

@@ -131,6 +131,7 @@ export function createAdminApp(d: AdminDeps) {
quizzes: new CustomQuizzes(d.db),
limits: () => ({ maxSongs: d.settings.getSite().quizMaxSongs, maxPerUser: d.settings.getSite().quizMaxPerUser }),
audit: d.audit,
onChange: d.onCatalogChange,
searchYoutube: d.searchYoutube,
audio: d.audio,
checkEmbed: d.checkEmbed,

View File

@@ -0,0 +1,205 @@
/**
* 검토 대기 (전체공개 퀴즈 → 서버 노래 DB): after a 전체공개 quiz is saved, every song that is not in the DB, or whose
* video / title / artist / 직접 정한 하이라이트 differs from its DB song, waits here. An admin picks, field by field, the DB
* value or the quiz's; new songs get year/genres/level filled in and are added. Decided proposals are not asked again.
*/
import type { Database } from 'bun:sqlite';
import { createSong } from '../songs/admin-ops';
import { updateSong } from '../songs/store';
export type ReviewField = 'title' | 'artist' | 'video' | 'highlight';
export interface Proposal {
title: string;
artist: string;
videoId: string;
highlightSec: number | null;
durationSec: number | null;
titleAnswers: string[];
artistAnswers: string[];
}
interface ItemRow {
id: number;
song_id: number | null;
video_id: string;
title: string;
artist: string;
title_answers: string;
artist_answers: string;
duration_sec: number | null;
auto: number;
highlight_sec: number | null;
}
const hashOf = (kind: string, songId: number | null, fields: string[], p: Proposal) =>
new Bun.CryptoHasher('sha1').update(JSON.stringify([kind, songId, fields, p.title, p.artist, p.videoId, fields.includes('highlight') ? p.highlightSec : null])).digest('hex');
/** Brings the pending reviews of one quiz up to date with what it holds now. */
export function syncReviews(db: Database, quizId: number, now = Date.now()): { pending: number } {
const q = db.query<{ visibility: string; deleted_at: number | null }, [number]>('SELECT visibility, deleted_at FROM custom_quizzes WHERE id = ?').get(quizId);
if (!q || q.deleted_at || q.visibility !== 'public') {
db.query("DELETE FROM quiz_reviews WHERE quiz_id = ? AND status = 'pending'").run(quizId);
return { pending: 0 };
}
const items = db
.query<ItemRow, [number]>('SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, duration_sec, auto, highlight_sec FROM custom_quiz_items WHERE quiz_id = ?')
.all(quizId);
const song = db.query<{ title: string; artist: string; youtube_id: string | null; youtube_status: string; highlight_sec: number | null }, [number]>(
'SELECT title, artist, youtube_id, youtube_status, highlight_sec FROM songs WHERE id = ? AND deleted_at IS NULL',
);
const decided = db.query<{ n: number }, [number, string]>("SELECT COUNT(*) n FROM quiz_reviews WHERE item_id = ? AND hash = ? AND status <> 'pending'");
// field values an admin already answered for this song of the quiz ("title:좋은 날 (Good Day)")
const answered = db.query<{ fields: string; proposal_json: string }, [number]>("SELECT fields, proposal_json FROM quiz_reviews WHERE item_id = ? AND status <> 'pending' AND kind = 'diff'");
const valueOf = (f: ReviewField, p: Proposal) => (f === 'title' ? p.title.trim() : f === 'artist' ? p.artist.trim() : f === 'video' ? p.videoId : String(p.highlightSec));
const drop = db.query("DELETE FROM quiz_reviews WHERE item_id = ? AND status = 'pending'");
db.transaction(() => {
for (const it of items) {
const p: Proposal = {
title: it.title,
artist: it.artist,
videoId: it.video_id,
highlightSec: it.auto ? null : it.highlight_sec,
durationSec: it.duration_sec,
titleAnswers: JSON.parse(it.title_answers),
artistAnswers: JSON.parse(it.artist_answers),
};
const s = it.song_id ? song.get(it.song_id) : null;
let kind: 'new' | 'diff' = 'new';
const fields: ReviewField[] = [];
if (s) {
kind = 'diff';
if (p.videoId !== (s.youtube_status === 'matched' ? s.youtube_id : null)) fields.push('video');
if (p.title.trim() !== s.title) fields.push('title');
if (p.artist.trim() !== s.artist) fields.push('artist');
if (p.highlightSec !== null && (s.highlight_sec === null || Math.abs(p.highlightSec - s.highlight_sec) > 1)) fields.push('highlight');
const seen = new Set(
answered.all(it.id).flatMap((a) => (JSON.parse(a.fields) as ReviewField[]).map((f) => `${f}:${valueOf(f, JSON.parse(a.proposal_json) as Proposal)}`)),
);
for (let i = fields.length - 1; i >= 0; i--) if (seen.has(`${fields[i]}:${valueOf(fields[i]!, p)}`)) fields.splice(i, 1);
if (!fields.length) {
drop.run(it.id);
continue;
}
}
const songId = s ? it.song_id : null;
const hash = hashOf(kind, songId, fields, p);
if (decided.get(it.id, hash)!.n) {
drop.run(it.id);
continue;
}
db.query(
`INSERT INTO quiz_reviews (quiz_id, item_id, song_id, kind, fields, proposal_json, hash, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(item_id) WHERE status = 'pending' DO UPDATE SET song_id = excluded.song_id, kind = excluded.kind, fields = excluded.fields,
proposal_json = excluded.proposal_json, hash = excluded.hash, created_at = CASE WHEN quiz_reviews.hash = excluded.hash THEN quiz_reviews.created_at ELSE excluded.created_at END`,
).run(quizId, it.id, songId, kind, JSON.stringify(fields), JSON.stringify(p), hash, now);
}
// songs taken out of the quiz
const ids = items.map((i) => i.id);
db.query(`DELETE FROM quiz_reviews WHERE quiz_id = ? AND status = 'pending' ${ids.length ? `AND item_id NOT IN (${ids.map(() => '?').join(',')})` : ''}`).run(quizId, ...ids);
})();
return { pending: db.query<{ n: number }, [number]>("SELECT COUNT(*) n FROM quiz_reviews WHERE quiz_id = ? AND status = 'pending'").get(quizId)!.n };
}
export function pendingCount(db: Database): number {
return db.query<{ n: number }, []>("SELECT COUNT(*) n FROM quiz_reviews WHERE status = 'pending'").get()!.n;
}
export function listReviews(db: Database, status: 'pending' | 'done' = 'pending', limit = 200) {
const rows = db
.query<
{ id: number; quiz_id: number; quiz_name: string; owner_name: string | null; item_id: number; pos: number | null; song_id: number | null; kind: 'new' | 'diff'; fields: string; proposal_json: string; status: string; result: string | null; created_at: number; decided_at: number | null; decided_name: string | null },
[number]
>(
`SELECT r.id, r.quiz_id, q.name quiz_name, u.nickname owner_name, r.item_id, i.pos, r.song_id, r.kind, r.fields, r.proposal_json, r.status, r.result, r.created_at, r.decided_at,
d.nickname decided_name
FROM quiz_reviews r JOIN custom_quizzes q ON q.id = r.quiz_id LEFT JOIN users u ON u.id = q.owner_id
LEFT JOIN custom_quiz_items i ON i.id = r.item_id LEFT JOIN users d ON d.id = r.decided_by
WHERE ${status === 'pending' ? "r.status = 'pending'" : "r.status <> 'pending'"} ORDER BY ${status === 'pending' ? 'r.created_at, r.id' : 'r.decided_at DESC'} LIMIT ?`,
)
.all(limit);
const song = db.query<{ id: number; title: string; artist: string; year: number | null; youtube_id: string | null; youtube_status: string; highlight_sec: number | null; duration_sec: number | null }, [number]>(
'SELECT id, title, artist, year, youtube_id, youtube_status, highlight_sec, duration_sec FROM songs WHERE id = ?',
);
return rows.map((r) => ({
id: r.id,
quiz: { id: r.quiz_id, name: r.quiz_name, owner: r.owner_name ?? '?' },
n: r.pos !== null ? r.pos + 1 : null,
kind: r.kind,
fields: JSON.parse(r.fields) as ReviewField[],
proposal: JSON.parse(r.proposal_json) as Proposal,
db: r.song_id ? (song.get(r.song_id) ?? null) : null,
status: r.status,
result: r.result,
createdAt: r.created_at,
decidedAt: r.decided_at,
decidedBy: r.decided_name,
}));
}
export interface Decision {
/** diff: the fields to take from the quiz (others keep the DB value). */
take?: ReviewField[];
/** new: what to register (defaults to the quiz's title/artist). */
song?: { title?: string; artist?: string; year?: number | null; genres?: string[]; level?: number | null };
}
/**
* Applies a review. `embed` gives the YouTube channel/title of a video that becomes the DB video.
* Returns a short result text or an error message (prefixed by "!").
*/
export function applyReview(db: Database, id: number, d: Decision, by: string, embed: { author: string; title: string } | undefined, now = Date.now()): string {
const r = db.query<{ item_id: number; song_id: number | null; kind: string; fields: string; proposal_json: string; status: string }, [number]>(
'SELECT item_id, song_id, kind, fields, proposal_json, status FROM quiz_reviews WHERE id = ?',
).get(id);
if (!r || r.status !== 'pending') return '!이미 처리했거나 없는 검토예요.';
const p = JSON.parse(r.proposal_json) as Proposal;
const addAnswers = (songId: number) => {
const ins = db.query("INSERT OR IGNORE INTO song_aliases (song_id, part, alias, source) VALUES (?, ?, ?, 'quiz')");
for (const a of p.titleAnswers) ins.run(songId, 'title', a);
for (const a of p.artistAnswers) ins.run(songId, 'artist', a);
};
let result: string;
if (r.kind === 'new') {
const s = d.song ?? {};
const [songId, created] = createSong(
db,
{
title: s.title?.trim() || p.title,
artist: s.artist?.trim() || p.artist,
year: s.year ?? null,
genres: s.genres ?? [],
level: s.level ?? null,
youtubeId: p.videoId,
highlightSec: p.highlightSec,
},
embed,
);
if (p.durationSec) db.query('UPDATE songs SET duration_sec = COALESCE(duration_sec, ?) WHERE id = ?').run(p.durationSec, songId);
addAnswers(songId);
db.query('UPDATE custom_quiz_items SET song_id = ? WHERE id = ?').run(songId, r.item_id);
result = created ? `새 곡 #${songId}로 추가` : `이미 있던 곡 #${songId}에 연결(DB 값은 그대로)`;
} else {
if (!r.song_id) return '!연결된 서버 곡이 지워졌어요.';
const take = (d.take ?? []).filter((f) => (JSON.parse(r.fields) as string[]).includes(f));
updateSong(
db,
r.song_id,
{
...(take.includes('title') ? { title: p.title.trim() } : {}),
...(take.includes('artist') ? { artist: p.artist.trim() } : {}),
...(take.includes('video') ? { youtubeId: p.videoId } : {}),
...(take.includes('highlight') ? { highlightSec: p.highlightSec } : {}),
},
take.includes('video') ? embed : undefined,
);
addAnswers(r.song_id);
const names: Record<string, string> = { title: '제목', artist: '가수', video: '영상', highlight: '하이라이트' };
result = take.length ? `퀴즈 값으로 바꿈: ${take.map((f) => names[f]).join('·')}` : 'DB 값 유지';
}
db.query("UPDATE quiz_reviews SET status = 'applied', result = ?, decided_by = ?, decided_at = ? WHERE id = ?").run(result, by, now, id);
return result;
}
export function rejectReview(db: Database, id: number, by: string, now = Date.now()): boolean {
return db.query("UPDATE quiz_reviews SET status = 'rejected', result = '반영 안 함', decided_by = ?, decided_at = ? WHERE id = ? AND status = 'pending'").run(by, now, id).changes > 0;
}

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(() => {});
},
}));

View File

@@ -179,7 +179,8 @@
8. 퀴즈당 곡 수·계정당 퀴즈 수 제한은 관리자 → 사이트에서 정하고 기본은 무제한(0)
9. 게임 중 "퀴즈 저장·불러오기"(진행 상황 저장)는 이름이 헷갈려서 "진행 저장·불러오기"로 바꿨다
10. 플레이리스트 가져오기: 유튜브·유튜브 뮤직·스포티파이 주소를 .6 Lavalink(`LAVALINK_URL`·`LAVALINK_PW`)로 읽는다(스포티파이 키로는 플레이리스트를 못 읽음). 서버 DB에 있는 곡은 그 곡, 유튜브는 그 영상(제목의 Official MV 등 정리), 스포티파이는 유튜브 뮤직에서 원곡 찾기와 같은 기준으로 찾고 애매하면 "확인 필요". 결과에서 고른 곡만 뒤에 추가하거나 목록을 바꾼다
11. 다음 단계: 전체공개 퀴즈 곡·하이라이트 → 관리자 검토 대기 → 서버 DB, 플레이 통계(힌트·오답·다시듣기·퀴즈별) → 난이도 조정 검토 대기
11. 검토 대기(관리자 → 검토 대기): 전체공개로 저장하면 서버 DB에 없는 곡과 DB와 영상·제목·가수·직접 정한 하이라이트가 다른 곡이 올라간다. 다른 값은 항목마다 "DB 유지 / 퀴즈 값"을 고르고, 없는 곡은 연도·장르·난이도를 채워 추가한다(퀴즈 곡이 그 DB 곡과 연결됨). 복수정답은 DB 별칭에 들어가고, 한 번 정한 값(항목+값)은 다시 묻지 않는다
12. 다음 단계: 플레이 통계(힌트·오답·다시듣기·퀴즈별) → 난이도 조정 검토 대기
## 원곡 찾기 자동 확정 기준 (2026-10-22)
1. 제목 일치 + 가수 일치(라틴 악센트 무시 JAŸ-Z=JAY-Z, `및`·with·feat 구분, 앞 The 무시, 확정곡 2곡 이상에서 확인된 한글/영문 이름 짝 태연=TAEYEON) + 길이 차이 15초 이내 + 커버·노래방·라이브·다른 버전 아님. "Radio Edit/Original Version"은 같은 녹음으로 본다