From b999310eb9846aff2c5601d51b86804ee0dd643f Mon Sep 17 00:00:00 2001 From: EJClaw Date: Thu, 22 Oct 2026 13:07:41 +0900 Subject: [PATCH] =?UTF-8?q?=EC=A0=9C=EC=9E=91=EB=90=9C=20=ED=80=B4?= =?UTF-8?q?=EC=A6=88=205=EB=8B=A8=EA=B3=84:=20=EA=B2=80=ED=86=A0=20?= =?UTF-8?q?=EB=8C=80=EA=B8=B0(=EC=A0=84=EC=B2=B4=EA=B3=B5=EA=B0=9C=20?= =?UTF-8?q?=ED=80=B4=EC=A6=88=20=E2=86=92=20=EC=84=9C=EB=B2=84=20=EB=85=B8?= =?UTF-8?q?=EB=9E=98=20DB).=20=EC=A0=80=EC=9E=A5=ED=95=A0=20=EB=95=8C=20DB?= =?UTF-8?q?=EC=97=90=20=EC=97=86=EB=8A=94=20=EA=B3=A1=EA=B3=BC=20=EC=98=81?= =?UTF-8?q?=EC=83=81=C2=B7=EC=A0=9C=EB=AA=A9=C2=B7=EA=B0=80=EC=88=98=C2=B7?= =?UTF-8?q?=EC=A7=81=EC=A0=91=20=EC=A0=95=ED=95=9C=20=ED=95=98=EC=9D=B4?= =?UTF-8?q?=EB=9D=BC=EC=9D=B4=ED=8A=B8=EA=B0=80=20DB=EC=99=80=20=EB=8B=A4?= =?UTF-8?q?=EB=A5=B8=20=EA=B3=A1=EC=9D=84=20=EB=AA=A8=EC=95=84=20=EA=B4=80?= =?UTF-8?q?=EB=A6=AC=EC=9E=90=EA=B0=80=20=ED=95=AD=EB=AA=A9=EB=A7=88?= =?UTF-8?q?=EB=8B=A4=20DB=20=EC=9C=A0=EC=A7=80/=ED=80=B4=EC=A6=88=20?= =?UTF-8?q?=EA=B0=92=EC=9D=84=20=EA=B3=A0=EB=A5=B4=EA=B1=B0=EB=82=98=20?= =?UTF-8?q?=EC=83=88=20=EA=B3=A1=EC=9D=84=20=EC=97=B0=EB=8F=84=C2=B7?= =?UTF-8?q?=EC=9E=A5=EB=A5=B4=C2=B7=EB=82=9C=EC=9D=B4=EB=8F=84=EC=99=80=20?= =?UTF-8?q?=ED=95=A8=EA=BB=98=20=EC=B6=94=EA=B0=80(=ED=80=B4=EC=A6=88=20?= =?UTF-8?q?=EA=B3=A1=EC=9D=B4=20=EA=B7=B8=20DB=20=EA=B3=A1=EC=97=90=20?= =?UTF-8?q?=EC=97=B0=EA=B2=B0).=20=EB=B3=B5=EC=88=98=EC=A0=95=EB=8B=B5?= =?UTF-8?q?=EC=9D=80=20DB=20=EB=B3=84=EC=B9=AD=EC=97=90,=20=ED=95=9C=20?= =?UTF-8?q?=EB=B2=88=20=EC=A0=95=ED=95=9C=20=EA=B0=92=EC=9D=80=20=EB=8B=A4?= =?UTF-8?q?=EC=8B=9C=20=EB=AC=BB=EC=A7=80=20=EC=95=8A=EC=9D=8C.=20?= =?UTF-8?q?=EA=B4=80=EB=A6=AC=EC=9E=90=20=EB=A9=94=EB=89=B4=20'=EA=B2=80?= =?UTF-8?q?=ED=86=A0=20=EB=8C=80=EA=B8=B0'(=EA=B0=9C=EC=88=98=20=ED=91=9C?= =?UTF-8?q?=EC=8B=9C),=20=EC=B2=98=EB=A6=AC=ED=95=9C=20=EA=B2=83=20?= =?UTF-8?q?=EA=B8=B0=EB=A1=9D=C2=B7=EA=B0=90=EC=82=AC=20=EB=A1=9C=EA=B7=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/server/src/custom-quiz.test.ts | 31 ++ .../src/db/migrations/010_quiz_reviews.sql | 18 ++ apps/server/src/http/admin-quizzes.ts | 48 ++- apps/server/src/http/admin.ts | 1 + apps/server/src/quizzes/review.ts | 205 ++++++++++++ apps/web/src/pages/admin/AdminApp.tsx | 17 + apps/web/src/pages/admin/QuizzesPage.tsx | 6 +- apps/web/src/pages/admin/ReviewsPage.tsx | 295 ++++++++++++++++++ apps/web/src/pages/admin/reviewCount.ts | 12 + docs/12-decisions.md | 3 +- 10 files changed, 632 insertions(+), 4 deletions(-) create mode 100644 apps/server/src/db/migrations/010_quiz_reviews.sql create mode 100644 apps/server/src/quizzes/review.ts create mode 100644 apps/web/src/pages/admin/ReviewsPage.tsx create mode 100644 apps/web/src/pages/admin/reviewCount.ts diff --git a/apps/server/src/custom-quiz.test.ts b/apps/server/src/custom-quiz.test.ts index 239485a..94082f0 100644 --- a/apps/server/src/custom-quiz.test.ts +++ b/apps/server/src/custom-quiz.test.ts @@ -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) => 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); +}); diff --git a/apps/server/src/db/migrations/010_quiz_reviews.sql b/apps/server/src/db/migrations/010_quiz_reviews.sql new file mode 100644 index 0000000..dcec0bd --- /dev/null +++ b/apps/server/src/db/migrations/010_quiz_reviews.sql @@ -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); diff --git a/apps/server/src/http/admin-quizzes.ts b/apps/server/src/http/admin-quizzes.ts index eddab05..ec35668 100644 --- a/apps/server/src/http/admin-quizzes.ts +++ b/apps/server/src/http/admin-quizzes.ts @@ -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, 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, 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 }); diff --git a/apps/server/src/http/admin.ts b/apps/server/src/http/admin.ts index 98f42ba..d3e14f5 100644 --- a/apps/server/src/http/admin.ts +++ b/apps/server/src/http/admin.ts @@ -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, diff --git a/apps/server/src/quizzes/review.ts b/apps/server/src/quizzes/review.ts new file mode 100644 index 0000000..390f284 --- /dev/null +++ b/apps/server/src/quizzes/review.ts @@ -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('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 = { 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; +} diff --git a/apps/web/src/pages/admin/AdminApp.tsx b/apps/web/src/pages/admin/AdminApp.tsx index 83bc39e..84d6ebc 100644 --- a/apps/web/src/pages/admin/AdminApp.tsx +++ b/apps/web/src/pages/admin/AdminApp.tsx @@ -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 ; +} + +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 (