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