퀴즈 파일 A단계: 관리자 → 퀴즈 '파일로 만들기'(.xlsx·.csv를 브라우저가 라이브러리 없이 읽음, 열 이름으로 링크·정답·설명·힌트·순번 인식, 시트 선택, 잘못된 링크·중복 영상 표시), 편집 화면 '파일에서 가져오기'(뒤에 추가·목록 바꾸기)·'엑셀로 내보내기'·빈 양식. 파일 곡은 적힌 값 그대로(DB 연결·검토 대기 없음). 곡별 힌트를 하나씩 보여 준 뒤 초성 힌트(자동은 N초마다, 투표는 한 번에 하나)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-23 18:06:28 +09:00
parent e44df482a6
commit 3c5e26f9b7
23 changed files with 1285 additions and 55 deletions

View File

@@ -246,3 +246,73 @@ test('검토 대기: a 전체공개 quiz sends new songs and differences to admi
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);
});
test('파일로 만들기: values as written, hints by vote, never sent to 검토 대기; a game shows the own hint, then the 초성', async () => {
start();
const sa = await adminCookie(TEST_SUPERADMINS[0]);
const fileItem = (p: Record<string, unknown>) => item({ fromFile: true, hints: [], ...p });
const bad = await api(s.base, '/api/admin/quizzes/file', { method: 'POST', cookie: sa, body: JSON.stringify({ name: '빈 파일', items: [] }) });
expect(bad.res.status).toBe(400);
const r = await api(s.base, '/api/admin/quizzes/file', {
method: 'POST',
cookie: sa,
body: JSON.stringify({
name: '게임 BGM',
items: [
// the video is the DB song's, but a file song is not linked to it (no DB comparison)
fileItem({ videoId: 'goodday0001', title: '리그 오브 레전드', artist: 'Still Here', hints: ['AOS(MOBA)'], songId: 5 }),
fileItem({ videoId: 'nodesc00001', title: '원신', artist: '', hints: ['확인필요'] }),
],
}),
});
expect(r.res.status).toBe(200);
const q = (await api(s.base, `/api/admin/quizzes/${r.body.id}`, { cookie: sa })).body.quiz;
expect(q.settings.hint).toBe('manual');
expect(q.items).toMatchObject([
{ songId: null, title: '리그 오브 레전드', artist: 'Still Here', hints: ['AOS(MOBA)'], fromFile: true },
{ songId: null, title: '원신', artist: '', hints: ['확인필요'], fromFile: true },
]);
// 전체공개 save: file songs stay out of 검토 대기, an editor song next to them does not
const saved = await api(s.base, `/api/admin/quizzes/${q.id}`, {
method: 'PUT',
cookie: sa,
body: JSON.stringify({ ...q, visibility: 'public', items: [...q.items, item({ videoId: 'editor00001', title: '직접 넣은 곡', artist: '가수' })] }),
});
expect(saved.res.status).toBe(200);
expect(saved.body.reviews.pending).toBe(1);
// an editor song still needs a singer
const noArtist = await api(s.base, `/api/admin/quizzes/${q.id}`, { method: 'PUT', cookie: sa, body: JSON.stringify({ ...q, items: [item({ videoId: 'editor00002', title: '곡', artist: '' })] }) });
expect(noArtist.res.status).toBe(400);
const code: string = (await api(s.base, '/api/rooms', { method: 'POST', cookie: sa, body: '{}' })).body.code;
const cl = await new Client(s.base, sa).connect();
cl.send({ t: 'join', code });
await cl.waitFor((m) => m.t === 'room');
cl.send({ t: 'config', patch: { quizId: q.id, hint: 'manual', hintVotes: '1' } });
await cl.waitFor((m) => m.t === 'room' && m.room.config.quizId === q.id && m.room.config.hint === 'manual');
let seen = 0;
const iv = setInterval(() => {
for (const m of cl.messages.slice(seen)) if (m.t === 'prepare') cl.send({ t: 'audio', n: m.n, ev: 'ready' });
seen = cl.messages.length;
}, 5);
try {
cl.send({ t: 'start' });
const play = (await cl.waitFor((m) => m.t === 'play' && m.n === 1)) as Msg<'play'>;
await sleep(Math.max(0, play.startAt - Date.now()) + 15);
cl.send({ t: 'vote', kind: 'hint' });
const g1 = (await cl.waitFor((m) => m.t === 'game' && !!m.game?.hints.length)) as Msg<'game'>;
expect(g1.game!.hints).toEqual([{ text: 'AOS(MOBA)', chosung: false }]);
expect(g1.game!.hintMore).toBe(true);
cl.send({ t: 'vote', kind: 'hint' });
const g2 = (await cl.waitFor((m) => m.t === 'game' && m.game?.hints.length === 2)) as Msg<'game'>;
expect(g2.game!.hints[1]).toEqual({ text: 'ㄹㄱ ㅇㅂ ㄹㅈㄷ', chosung: true });
expect(g2.game!.hint).toBe('AOS(MOBA) · ㄹㄱ ㅇㅂ ㄹㅈㄷ');
expect(g2.game!.hintMore).toBe(false);
cl.send({ t: 'chat', text: '리그 오브 레전드' });
const ans = (await cl.waitFor((m) => m.t === 'answer')) as Msg<'answer'>;
expect(ans.line.answer?.text).toBe('리그 오브 레전드 - Still Here');
} finally {
clearInterval(iv);
cl.close();
}
});

View File

@@ -0,0 +1,4 @@
-- 퀴즈 파일로 만들기: hints per song (shown one by one before the 초성 hint) and songs that came from a file
-- (used as written, never sent to 검토 대기).
ALTER TABLE custom_quiz_items ADD COLUMN hints TEXT NOT NULL DEFAULT '[]';
ALTER TABLE custom_quiz_items ADD COLUMN from_file INTEGER NOT NULL DEFAULT 0;

View File

@@ -90,6 +90,8 @@ export class Game {
private runningSince: number | null = null;
private limitMs: number | null = null;
hint: string | null = null;
/** Hints shown in this question: the song's own (제작된 퀴즈) one by one, then the 초성 hint. */
private shownHints: { text: string; chosung: boolean }[] = [];
/** 통계: how the hint came (null = none), chat lines that were not the answer and who sent them, replays. */
private stat = { hint: null as 'auto' | 'vote' | null, wrong: 0, wrongBy: new Set<string>(), replays: 0 };
private lyrics: string[] | null = null;
@@ -196,6 +198,7 @@ export class Game {
this.elapsedMs = 0;
this.runningSince = null;
this.hint = null;
this.shownHints = [];
this.stat = { hint: null, wrong: 0, wrongBy: new Set(), replays: 0 };
this.revealUntil = null;
for (const v of Object.values(this.votes)) v.clear();
@@ -288,13 +291,26 @@ export class Game {
this.broadcast();
}
/** Hints this song has: its own ones, then the 초성 hint. */
private hintCount(): number {
return (this.song?.hints?.length ?? 0) + 1;
}
private hintMore(): boolean {
return !!this.song && this.shownHints.length < this.hintCount();
}
/** The next hint: the song's own hints one by one, the 초성 hint last. */
private showHint(how: 'auto' | 'vote' = 'auto'): void {
if (this.hint || !this.song) return;
this.stat.hint = how;
this.hint = hintText(this.song, this.room.config.answer);
if (this.lyrics && this.song.lyrics) this.lyrics = lyricsCard(this.song.lyrics, this.song.title, 1);
if (!this.song || !this.hintMore()) return;
this.stat.hint ??= how;
const own = this.song.hints ?? [];
const i = this.shownHints.length;
const next = i < own.length ? { text: own[i]!, chosung: false } : { text: hintText(this.song, this.room.config.answer), chosung: true };
this.shownHints.push(next);
this.hint = this.shownHints.map((h) => h.text).join(' · ');
if (next.chosung && this.lyrics && this.song.lyrics) this.lyrics = lyricsCard(this.song.lyrics, this.song.title, 1);
this.votes.hint.clear();
this.room.say(null, `힌트가 공개됐어요: ${this.hint}`);
this.room.say(null, `${this.hintCount() > 1 ? `힌트 ${i + 1}` : '힌트'}가 공개됐어요: ${next.text}`);
this.broadcast();
}
@@ -417,7 +433,7 @@ export class Game {
if (this.phase !== 'play') return;
const el = this.elapsed(now);
const c = this.room.config;
if (typeof c.hint === 'number' && !this.hint && this.runningSince !== null && el >= c.hint * 1000) this.showHint();
if (typeof c.hint === 'number' && this.hintMore() && this.runningSince !== null && el >= c.hint * 1000 * (this.shownHints.length + 1)) this.showHint();
if (this.limitMs !== null && el >= this.limitMs) return this.endQuestion(null, 'timeout');
if (this.playing && !this.clipOver && this.clip.endSec !== null) {
const expectedEnd = this.audioStartAt + (this.clip.endSec - this.audioAtSec) * 1000;
@@ -503,9 +519,9 @@ export class Game {
const c = this.room.config;
if (kind === 'hint') {
if (c.hint === 'none') return '이 방은 힌트가 꺼져 있어요.';
if (this.hint) return '이미 공개된 힌트예요.';
if (!this.hintMore()) return this.hintCount() > 1 ? '힌트를 모두 공개했어요.' : '이미 공개된 힌트예요.';
if (c.hint !== 'manual') {
const left = Math.max(1, Math.ceil(c.hint - (this.elapsed() / 1000)));
const left = Math.max(1, Math.ceil(c.hint * (this.shownHints.length + 1) - this.elapsed() / 1000));
return `힌트는 ${left}초 뒤에 공개돼요.`;
}
}
@@ -636,7 +652,9 @@ export class Game {
clipSec: this.clip.endSec !== null ? this.clip.endSec - this.clip.startSec : null,
clipOver: this.clipOver,
hint: this.hint,
hintAtSec: typeof c.hint === 'number' ? c.hint : null,
hints: this.shownHints,
hintMore: this.hintMore(),
hintAtSec: typeof c.hint === 'number' && this.hintMore() ? c.hint * (this.shownHints.length + 1) : null,
lyrics: this.lyrics,
votes: { skip: [...this.votes.skip], hint: [...this.votes.hint], replay: [...this.votes.replay], next: [...this.votes.next] },
need: { skip: this.need('skip'), hint: this.need('hint'), replay: this.need('replay'), next: this.need('next') },

View File

@@ -4,7 +4,7 @@
*/
import type { Context, Hono } from 'hono';
import { z } from 'zod';
import { QuizSaveSchema, songMatchKey, type Role } from '@mq/shared';
import { DEFAULT_QUIZ_SETTINGS, QuizSaveSchema, songMatchKey, type Role } from '@mq/shared';
import type { Database } from 'bun:sqlite';
import { CustomQuizzes, type QuizLimits } from '../quizzes/store';
import type { YtmSong } from '../collector/ytmusic';
@@ -63,6 +63,24 @@ export function mountQuizAdmin(app: Hono<Env>, d: QuizAdminDeps, h: { actor: (c:
return c.json({ id });
});
/** 파일로 만들기: a new quiz with the songs read from a file (the browser reads the file; values used as written). */
app.post('/quizzes/file', async (c) => {
const p = z.object({ name: z.string().trim().min(1).max(60), items: QuizSaveSchema.shape.items.min(1) }).safeParse(await h.body(c));
if (!p.success) return c.json({ error: `만들 내용이 올바르지 않아요: ${p.error.issues.slice(0, 3).map((i) => i.path.join('.') || i.message).join(', ')}` }, 400);
const limits = d.limits();
if (limits.maxSongs && p.data.items.length > limits.maxSongs) return c.json({ error: `퀴즈 하나에는 곡을 ${limits.maxSongs}곡까지 넣을 수 있어요.` }, 400);
const id = d.quizzes.create(h.actor(c), p.data.name, limits);
if (typeof id === 'string') return c.json({ error: id }, 400);
const items = p.data.items.map((it) => ({ ...it, id: undefined, songId: null, fromFile: true }));
// songs with their own hints: hints come by vote unless the maker changes it in 설정
const settings = { ...DEFAULT_QUIZ_SETTINGS, ...(items.some((it) => it.hints.length) ? { hint: 'manual' as const } : {}) };
const saved = d.quizzes.save(id, { name: p.data.name, description: '', visibility: 'private', settings, items }, limits);
if (typeof saved === 'string') return c.json({ error: saved }, 400);
d.audit.log(h.actor(c), 'quiz.create', String(id), null, { name: p.data.name, songs: items.length, from: 'file' });
d.onChange?.();
return c.json({ id });
});
// ---------------------------------------------------------------- 검토 대기 (전체공개 퀴즈 → 서버 노래 DB)
app.get('/reviews/count', (c) => {
const levels = playStats(d.db, { sort: 'suggest', size: 1 }).suggestions;

View File

@@ -1,7 +1,7 @@
/** Admin API (docs/02 관리자 페이지). Mounted under /api/admin. Ported from joke-app (rooms/games parts come later). */
import { Hono, type Context } from 'hono';
import { z } from 'zod';
import { nicknameError, normalizeNickname, type Role } from '@mq/shared';
import { nicknameError, normalizeNickname, parseVideoId, type Role } from '@mq/shared';
import type { Audit, Roles } from '../admin/roles';
import { SiteSettingsSchema, type SettingsStore } from '../admin/settings';
import type { Sessions } from '../auth/sessions';
@@ -48,20 +48,8 @@ export interface AdminDeps {
type Env = { Variables: { userId: string | null; role: Role } };
const DISCORD_ID = /^\d{17,20}$/;
const VIDEO_ID = /^[\w-]{11}$/;
/** Accepts https://youtu.be/ID, youtube.com/watch?v=ID, music.youtube.com/watch?v=ID or the bare ID. */
export function parseVideoId(s: string): string | null {
const t = s.trim();
if (VIDEO_ID.test(t)) return t;
try {
const u = new URL(t);
const id = u.hostname === 'youtu.be' ? u.pathname.slice(1) : u.searchParams.get('v');
return id && VIDEO_ID.test(id) ? id : null;
} catch {
return null;
}
}
/** Accepts the usual YouTube URL shapes or the bare ID (shared with the quiz file reader). */
export { parseVideoId };
const SongPatchSchema = z.object({
title: z.string().trim().min(1).max(200).optional(),

View File

@@ -2,6 +2,7 @@
* 검토 대기 (전체공개 퀴즈 → 서버 노래 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.
* Songs that came from a quiz file (파일로 만들기) are used as written and never wait here.
*/
import type { Database } from 'bun:sqlite';
import { createSong } from '../songs/admin-ops';
@@ -42,7 +43,7 @@ export function syncReviews(db: Database, quizId: number, now = Date.now()): { p
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 = ?')
.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 = ? AND from_file = 0')
.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',

View File

@@ -26,6 +26,8 @@ interface ItemRow {
artist: string;
title_answers: string;
artist_answers: string;
hints: string;
from_file: number;
duration_sec: number | null;
auto: number;
start_sec: number | null;
@@ -62,6 +64,8 @@ const item = (r: ItemRow): QuizItem => ({
artist: r.artist,
titleAnswers: JSON.parse(r.title_answers) as string[],
artistAnswers: JSON.parse(r.artist_answers) as string[],
hints: JSON.parse(r.hints) as string[],
fromFile: !!r.from_file,
durationSec: r.duration_sec,
auto: !!r.auto,
startSec: r.start_sec,
@@ -112,7 +116,7 @@ export class CustomQuizzes {
items(id: number): QuizItem[] {
return this.db
.query<ItemRow, [number]>(
'SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? ORDER BY pos, id',
'SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? ORDER BY pos, id',
)
.all(id)
.map(item);
@@ -121,7 +125,7 @@ export class CustomQuizzes {
item(quizId: number, itemId: number): QuizItem | null {
const r = this.db
.query<ItemRow, [number, number]>(
'SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? AND id = ?',
'SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? AND id = ?',
)
.get(quizId, itemId);
return r ? item(r) : null;
@@ -142,11 +146,11 @@ export class CustomQuizzes {
.run(data.name, data.description, data.visibility, JSON.stringify(data.settings), now, id);
const keep = new Set<number>();
const ins = this.db.query(
`INSERT INTO custom_quiz_items (quiz_id, pos, song_id, video_id, title, artist, title_answers, artist_answers, duration_sec, auto, start_sec, highlight_sec)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
`INSERT INTO custom_quiz_items (quiz_id, pos, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, duration_sec, auto, start_sec, highlight_sec)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
);
const upd = this.db.query(
`UPDATE custom_quiz_items SET pos = ?, song_id = ?, video_id = ?, title = ?, artist = ?, title_answers = ?, artist_answers = ?, duration_sec = ?, auto = ?,
`UPDATE custom_quiz_items SET pos = ?, song_id = ?, video_id = ?, title = ?, artist = ?, title_answers = ?, artist_answers = ?, hints = ?, from_file = ?, duration_sec = ?, auto = ?,
start_sec = ?, highlight_sec = ? WHERE id = ? AND quiz_id = ?`,
);
const alias = this.db.query("INSERT OR IGNORE INTO song_aliases (song_id, part, alias, source) VALUES (?, ?, ?, 'quiz')");
@@ -161,6 +165,8 @@ export class CustomQuizzes {
it.artist,
JSON.stringify(titleAnswers),
JSON.stringify(artistAnswers),
JSON.stringify(it.hints ?? []),
it.fromFile ? 1 : 0,
it.durationSec,
it.auto ? 1 : 0,
it.auto ? null : it.startSec,

View File

@@ -30,6 +30,8 @@ export interface QuizSong {
/** Main artist ids (same singer not twice in a row, docs/05 출제 목록). */
artistIds: number[];
lyrics: string | null;
/** 제작된 퀴즈: the song's own hints, shown one by one before the 초성 hint. */
hints?: string[];
}
export function quizSong(db: Database, id: number): QuizSong | null {
@@ -73,9 +75,9 @@ export function quizSong(db: Database, id: number): QuizSong | null {
export function quizItemSong(db: Database, quizId: number, itemId: number): QuizSong | null {
const it = db
.query<
{ 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; start_sec: number | null; highlight_sec: number | null },
{ id: number; song_id: number | null; video_id: string; title: string; artist: string; title_answers: string; artist_answers: string; hints: string; duration_sec: number | null; auto: number; start_sec: number | null; highlight_sec: number | null },
[number, number]
>('SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? AND id = ?')
>('SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, hints, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? AND id = ?')
.get(quizId, itemId);
if (!it) return null;
const base = it.song_id ? quizSong(db, it.song_id) : null;
@@ -103,6 +105,7 @@ export function quizItemSong(db: Database, quizId: number, itemId: number): Quiz
artistAliases: uniq([...(JSON.parse(it.artist_answers) as string[]), ...(base ? [base.artist, ...base.artistAliases] : [])]),
artistIds: base?.artistIds ?? [],
lyrics: base?.lyrics ?? null,
hints: JSON.parse(it.hints) as string[],
};
}

View File

@@ -217,12 +217,15 @@ export function GameScreen({ room, game }: { room: RoomView; game: GameView }) {
</div>
)}
<div className="row" style={{ marginTop: 8 }}>
{game.hint ? (
<span className="hint">
{game.hint} <small>초성 힌트</small>
{(game.hints ?? []).map((h, i) => (
<span key={i} className="hint">
{h.text} <small>{h.chosung ? '초성 힌트' : `힌트 ${i + 1}`}</small>
</span>
))}
{game.hintAtSec !== null && game.phase === 'play' ? (
<span className="small muted">
{game.hints?.length ? '다음 힌트' : '힌트'}는 {Math.max(0, Math.ceil(game.hintAtSec - elapsed / 1000))}초 뒤에 공개돼요
</span>
) : game.hintAtSec !== null && game.phase === 'play' ? (
<span className="small muted">힌트는 {Math.max(0, Math.ceil(game.hintAtSec - elapsed / 1000))}초 뒤에 공개돼요</span>
) : null}
</div>
</div>

View File

@@ -0,0 +1,299 @@
/**
* 퀴즈 파일 (관리자 → 퀴즈): 파일로 만들기 (a new quiz from .xlsx / .csv), 파일에서 가져오기 (into the open quiz),
* 엑셀로 내보내기 and 빈 양식. The browser reads the file; columns are recognised by their headers and can be changed.
* Values are used as written — bad links and repeated videos are listed and left out.
*/
import { useMemo, useState } from 'react';
import {
QUIZ_COLUMN_LABEL,
guessColumns,
headerRow,
parseQuizRows,
quizTemplateRows,
quizToRows,
readSheetFile,
writeXlsx,
type QuizColumn,
type QuizItem,
type Sheet,
} from '@mq/shared/lite';
import { toast } from '../../store/toast';
import { ConfirmSheet } from '../../components/ui';
const MAX_BYTES = 20 * 1024 * 1024;
const COLUMN_ORDER: QuizColumn[] = ['link', 'answer', 'desc', 'hint', 'answers', 'descAnswers', 'order', 'start', 'highlight'];
function download(name: string, bytes: Uint8Array) {
const url = URL.createObjectURL(new Blob([bytes as Uint8Array<ArrayBuffer>], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }));
const a = document.createElement('a');
a.href = url;
a.download = `${name.replace(/[\\/:*?"<>|]/g, ' ').trim() || '퀴즈'}.xlsx`;
document.body.append(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
/** 엑셀로 내보내기: the songs as a file this screen reads back. */
export function exportQuiz(name: string, items: QuizItem[]) {
const { rows, widths } = quizToRows(items);
download(name, writeXlsx(name, rows, widths));
}
export function downloadTemplate() {
const { rows, widths } = quizTemplateRows();
download('퀴즈 양식', writeXlsx('퀴즈', rows, widths));
}
export function QuizFileImport({
mode,
existing = [],
onCreate,
onApply,
onClose,
}: {
/** create: 파일로 만들기 (new quiz) · into: 파일에서 가져오기 (the open quiz). */
mode: 'create' | 'into';
existing?: QuizItem[];
onCreate?: (name: string, items: QuizItem[]) => Promise<void>;
onApply?: (items: QuizItem[], replace: boolean) => void;
onClose: () => void;
}) {
const [file, setFile] = useState<{ name: string; sheets: Sheet[] } | null>(null);
const [sheetIdx, setSheetIdx] = useState(0);
const [columns, setColumns] = useState<(QuizColumn | null)[]>([]);
const [headerAt, setHeaderAt] = useState(0);
const [name, setName] = useState('');
const [busy, setBusy] = useState(false);
const [confirmReplace, setConfirmReplace] = useState(false);
const pickSheet = (sheets: Sheet[], i: number) => {
const rows = sheets[i]?.rows ?? [];
const h = headerRow(rows);
setSheetIdx(i);
setHeaderAt(h);
setColumns(guessColumns(rows[h] ?? []));
};
const open = async (f: File) => {
if (f.size > MAX_BYTES) return toast('파일이 너무 커요(20MB까지).', 'error');
try {
const sheets = (await readSheetFile(f.name, new Uint8Array(await f.arrayBuffer()))).filter((s) => s.rows.length > 0);
if (!sheets.length) return toast('파일에 내용이 없어요.', 'error');
setFile({ name: f.name, sheets });
setName(f.name.replace(/\.[^.]+$/, '').slice(0, 60));
// the sheet that has the most usable rows
const best = sheets.map((s, i) => [i, parseQuizRows(s.rows, guessColumns(s.rows[headerRow(s.rows)] ?? []), headerRow(s.rows)).items.length] as const).sort((a, b) => b[1] - a[1])[0]![0];
pickSheet(sheets, best);
} catch (e) {
toast((e as Error).message || '파일을 읽지 못했어요.', 'error');
}
};
const sheet = file?.sheets[sheetIdx];
const header = sheet?.rows[headerAt] ?? [];
const parsed = useMemo(() => (sheet ? parseQuizRows(sheet.rows, columns, headerAt) : null), [sheet, columns, headerAt]);
const missing = (['link', 'answer'] as const).filter((c) => !columns.includes(c));
const bad = parsed?.rows.filter((r) => r.problem) ?? [];
const items = parsed?.items ?? [];
const inList = new Set(existing.map((x) => x.videoId));
const appendable = items.filter((x) => !inList.has(x.videoId));
const width = Math.max(header.length, ...(sheet?.rows.slice(headerAt, headerAt + 20).map((r) => r.length) ?? [0]));
const setColumn = (i: number, v: QuizColumn | null) =>
setColumns((cur) => {
const next = [...cur];
while (next.length < width) next.push(null);
// one column per use (힌트 may be several)
if (v && v !== 'hint') for (let k = 0; k < next.length; k++) if (next[k] === v) next[k] = null;
next[i] = v;
return next;
});
const create = async () => {
if (!onCreate || !name.trim() || !items.length) return;
setBusy(true);
try {
await onCreate(name.trim(), items);
} finally {
setBusy(false);
}
};
return (
<div className="card stack" style={{ gap: 12 }}>
<div className="row" style={{ justifyContent: 'space-between' }}>
<b>📄 {mode === 'create' ? '파일로 만들기' : '파일에서 가져오기'}</b>
<button type="button" className="btn btn-sm btn-ghost" onClick={onClose} aria-label="닫기">
✕
</button>
</div>
<div className="row">
<label className="btn btn-primary">
{file ? '다른 파일 고르기' : '파일 고르기 (.xlsx, .csv)'}
<input
type="file"
accept=".xlsx,.csv,.tsv,.txt,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/csv"
hidden
aria-label="퀴즈 파일"
onChange={(e) => {
const f = e.target.files?.[0];
e.target.value = '';
if (f) void open(f);
}}
/>
</label>
<button type="button" className="btn" onClick={downloadTemplate}>
📥 빈 양식 받기
</button>
{file && <span className="muted small">{file.name}</span>}
</div>
{!file && (
<p className="muted small" style={{ margin: 0 }}>
한 줄에 한 곡씩, 첫 줄은 열 이름이에요. <b>유튜브 영상 링크</b>와 <b>정답</b>(예: 게임 제목)은 꼭 있어야 하고, <b>설명</b>(예: 노래 제목)은 정답을 공개할 때 같이
보여요. <b>힌트</b> 열은 문제마다 먼저 나오고, 그다음 힌트로 초성이 나와요. <b>순번</b> 열이 있으면 그 순서대로 넣어요. 적힌 값은 고치지 않고 그대로 써요.
</p>
)}
{file && sheet && (
<>
{file.sheets.length > 1 && (
<label className="field-inline">
시트
<select className="input sm" style={{ width: 'auto' }} value={sheetIdx} onChange={(e) => pickSheet(file.sheets, Number(e.target.value))} aria-label="시트">
{file.sheets.map((s, i) => (
<option key={i} value={i}>
{s.name} ({Math.max(0, s.rows.length - 1)}줄)
</option>
))}
</select>
</label>
)}
<div className="stack" style={{ gap: 6 }}>
<span className="field">열 {missing.length ? '— 아래에서 골라 주세요' : '(열 이름으로 찾았어요. 다르면 바꿔 주세요)'}</span>
<div className="file-cols">
{Array.from({ length: width }, (_, i) => (
<label key={i} className="file-col">
<span className="small clamp1" title={header[i] ?? ''}>
{header[i]?.trim() || `${i + 1}번째 열`}
</span>
<select className="input sm" value={columns[i] ?? ''} onChange={(e) => setColumn(i, (e.target.value || null) as QuizColumn | null)} aria-label={`${header[i] || `${i + 1}번째 열`} 쓰임`}>
<option value="">안 씀</option>
{COLUMN_ORDER.map((c) => (
<option key={c} value={c}>
{QUIZ_COLUMN_LABEL[c]}
</option>
))}
</select>
</label>
))}
</div>
{missing.length > 0 && <span className="warn-text small">{missing.map((c) => QUIZ_COLUMN_LABEL[c]).join(', ')} 열을 골라 주세요.</span>}
</div>
{!missing.length && parsed && (
<>
<div className="small">
<b>{items.length}곡</b>
{bad.length > 0 && <span className="warn-text"> · 빠지는 줄 {bad.length}개</span>}
{mode === 'into' && items.length > appendable.length && <span className="muted"> · 이미 목록에 있는 영상 {items.length - appendable.length}곡</span>}
</div>
{bad.length > 0 && (
<div className="table-wrap" style={{ maxHeight: 200, overflowY: 'auto' }}>
<table className="data-table">
<thead>
<tr>
<th style={{ width: 60 }}>줄</th>
<th>빠지는 이유</th>
<th>링크</th>
</tr>
</thead>
<tbody>
{bad.map((r) => (
<tr key={r.line}>
<td className="mono">{r.line}</td>
<td className="warn-text small">{r.problem}</td>
<td className="small">
<span className="clamp1" style={{ maxWidth: 360 }}>
{r.link || '-'}
</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{items.length > 0 && (
<div className="table-wrap" style={{ maxHeight: 420, overflowY: 'auto' }}>
<table className="data-table">
<thead>
<tr>
<th style={{ width: 44 }}>#</th>
<th>정답</th>
<th>설명</th>
<th>힌트</th>
<th>영상</th>
</tr>
</thead>
<tbody>
{items.map((it, i) => (
<tr key={it.videoId}>
<td className="mono">{i + 1}</td>
<td>
<b>{it.title}</b>
{it.titleAnswers.length > 0 && <div className="muted small">또는 {it.titleAnswers.join(', ')}</div>}
</td>
<td className="small">{it.artist || <span className="muted">-</span>}</td>
<td className="small">{[...it.hints, '초성'].join(' → ')}</td>
<td className="small">
<a href={`https://youtu.be/${it.videoId}`} target="_blank" rel="noreferrer">
{it.videoId} ↗
</a>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{mode === 'create' ? (
<form
className="row"
onSubmit={(e) => {
e.preventDefault();
void create();
}}
>
<label className="field-inline grow">
퀴즈 이름
<input className="input grow" value={name} maxLength={60} onChange={(e) => setName(e.target.value)} aria-label="퀴즈 이름" />
</label>
<button className="btn btn-primary" disabled={busy || !name.trim() || !items.length}>
{busy ? '만드는 중…' : `${items.length}곡으로 만들기`}
</button>
</form>
) : (
<div className="row">
<button type="button" className="btn btn-primary" disabled={!appendable.length} onClick={() => onApply?.(appendable, false)}>
{appendable.length}곡 목록 뒤에 추가
</button>
<button type="button" className="btn btn-danger" disabled={!items.length} onClick={() => setConfirmReplace(true)}>
지금 목록을 지우고 바꾸기
</button>
</div>
)}
</>
)}
</>
)}
{confirmReplace && (
<ConfirmSheet
title="지금 목록을 바꿀까요?"
body={`지금 곡 목록 ${existing.length}곡과 그 곡들의 정답·위치 설정이 사라지고 파일의 ${items.length}곡으로 바뀌어요. 저장하기 전에는 되돌릴 수 있어요(저장하지 않고 나가기).`}
confirm="목록 바꾸기"
danger
onClose={() => setConfirmReplace(false)}
onConfirm={() => onApply?.(items, true)}
/>
)}
</div>
);
}

View File

@@ -24,6 +24,7 @@ import { PlayRules, Section, Seg } from '../../components/RoomSettings';
import { YtPreview } from './SongsPage';
import { PositionEditor } from './PositionEditor';
import { useReviewCount } from './reviewCount';
import { QuizFileImport, exportQuiz } from './QuizFile';
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: '전체공개' };
@@ -36,6 +37,7 @@ export function QuizzesPage() {
const [list, setList] = useState<QuizSummary[] | null>(null);
const [name, setName] = useState('');
const [adding, setAdding] = useState(false);
const [fromFile, setFromFile] = useState(false);
const nav = useNavigate();
const load = useCallback(() => {
apiCall<{ quizzes: QuizSummary[] }>('GET', `/api/admin/quizzes${all ? '?all=1' : ''}`)
@@ -63,6 +65,21 @@ export function QuizzesPage() {
)}
</div>
<p className="muted">직접 만든 퀴즈예요. 방 설정에서 "제작된 퀴즈"를 고르면 이 퀴즈의 곡이 순서대로(또는 섞어서) 전부 나와요. 듣고맞추기에서만 쓸 수 있어요.</p>
{fromFile && (
<QuizFileImport
mode="create"
onClose={() => setFromFile(false)}
onCreate={async (quizName, items) => {
try {
const r = await apiCall<{ id: number }>('POST', '/api/admin/quizzes/file', { name: quizName, items });
toast(`"${quizName}" 퀴즈를 ${items.length}곡으로 만들었어요.`);
nav(`/admin/quizzes/${r.id}`);
} catch (e) {
toast((e as Error).message, 'error');
}
}}
/>
)}
<div className="quiz-grid">
{list?.map((q) => (
<Link key={q.id} to={`/admin/quizzes/${q.id}`} className="quiz-card">
@@ -103,6 +120,12 @@ export function QuizzesPage() {
<span aria-hidden>+</span> 퀴즈 추가
</button>
)}
{!fromFile && (
<button type="button" className="quiz-card add plus" onClick={() => setFromFile(true)}>
<span aria-hidden>📄</span> 파일로 만들기
<small className="muted">엑셀(.xlsx)·CSV</small>
</button>
)}
</div>
{list && list.length === 0 && !adding && <p className="muted">아직 만든 퀴즈가 없어요. "퀴즈 추가"를 눌러 시작해 보세요.</p>}
</>
@@ -126,6 +149,10 @@ export interface DbInfo {
videoId: string | null;
}
/** A song picked in the editor (search, address, playlist): answers, hints and positions start empty. */
type NewSong = Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'hints' | 'fromFile' | 'auto' | 'startSec' | 'highlightSec'>;
const fresh = (it: NewSong): QuizItem => ({ ...it, titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, auto: true, startSec: null, highlightSec: null });
let keySeq = 0;
const newKey = () => `k${++keySeq}`;
const toDraft = (q: QuizDetail): Draft => ({
@@ -151,6 +178,7 @@ export function QuizEditor() {
const [confirmDelete, setConfirmDelete] = useState(false);
const [owner, setOwner] = useState<{ ownerName: string; plays: number } | null>(null);
const [importOpen, setImportOpen] = useState(false);
const [fileOpen, setFileOpen] = useState(false);
const load = useCallback(() => {
apiCall<{ quiz: QuizDetail; db: Record<number, DbInfo> }>('GET', `/api/admin/quizzes/${id}`)
@@ -274,6 +302,9 @@ export function QuizEditor() {
</Link>
<h1 className="grow">{draft.name || '이름 없는 퀴즈'}</h1>
{dirty ? <span className="badge warn" role="status">● 저장하지 않은 변경이 있어요</span> : <span className="muted small">저장됨</span>}
<button type="button" className="btn" disabled={!draft.items.length} onClick={() => exportQuiz(draft.name, draft.items)} title="곡 목록을 다시 올릴 수 있는 엑셀 파일로 받아요">
📥 엑셀로 내보내기
</button>
<button type="button" className="btn btn-primary" disabled={busy || !dirty} onClick={() => void save()} title="Ctrl+S">
{busy ? '저장 중…' : '저장'} <span className="kbd">Ctrl+S</span>
</button>
@@ -298,6 +329,9 @@ export function QuizEditor() {
<button type="button" className="btn" onClick={() => (setParams({}), setTab('songs'), setImportOpen(true))}>
🔗 플레이리스트 가져오기
</button>
<button type="button" className="btn" onClick={() => (setParams({}), setTab('songs'), setFileOpen(true))}>
📄 파일에서 가져오기
</button>
<button type="button" className="btn btn-primary" onClick={() => setParams({})}>
✋ 직접 하나씩 추가
</button>
@@ -305,7 +339,17 @@ export function QuizEditor() {
</div>
)}
{tab === 'songs' ? (
<SongsTab items={draft.items} db={db} settings={draft.settings} onItems={(items) => set({ items })} importOpen={importOpen} setImportOpen={setImportOpen} />
<SongsTab
items={draft.items}
db={db}
settings={draft.settings}
onItems={(items) => set({ items })}
importOpen={importOpen}
setImportOpen={setImportOpen}
fileOpen={fileOpen}
setFileOpen={setFileOpen}
onHints={() => draft.settings.hint === 'none' && set({ settings: { ...draft.settings, hint: 'manual' } })}
/>
) : (
<SettingsTab draft={draft} onChange={set} onDelete={() => setConfirmDelete(true)} />
)}
@@ -406,6 +450,9 @@ function SongsTab({
onItems,
importOpen,
setImportOpen,
fileOpen,
setFileOpen,
onHints,
}: {
items: DraftItem[];
db: Record<number, DbInfo | null>;
@@ -413,17 +460,21 @@ function SongsTab({
onItems: (items: DraftItem[]) => void;
importOpen: boolean;
setImportOpen: (on: boolean) => void;
fileOpen: boolean;
setFileOpen: (on: boolean) => void;
/** Songs with their own hints came in: hints should not stay off. */
onHints: () => void;
}) {
const [sel, setSel] = useState<string | null>(null);
const [dragKey, setDragKey] = useState<string | null>(null);
const [overKey, setOverKey] = useState<string | null>(null);
const selected = items.find((i) => i.key === sel) ?? null;
const add = (it: Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'auto' | 'startSec' | 'highlightSec'>) => {
const add = (it: NewSong) => {
if (items.some((x) => x.videoId === it.videoId || (it.songId && x.songId === it.songId))) {
toast('이미 목록에 있는 곡이에요.', 'error');
return false;
}
const n: DraftItem = { ...it, titleAnswers: [], artistAnswers: [], auto: true, startSec: null, highlightSec: null, key: newKey() };
const n: DraftItem = { ...fresh(it), key: newKey() };
onItems([...items, n]);
toast(`${items.length + 1}번에 추가했어요: ${it.title}`);
return true;
@@ -443,28 +494,42 @@ function SongsTab({
return (
<div className={`songs-layout quiz ${selected ? 'with-panel' : ''}`}>
<div className="stack" style={{ gap: 12, minWidth: 0 }}>
{importOpen ? (
{fileOpen ? (
<QuizFileImport
mode="into"
existing={items}
onClose={() => setFileOpen(false)}
onApply={(rows, replace) => {
const added = rows.map((r) => ({ ...r, key: newKey() }));
onItems(replace ? added : [...items, ...added]);
setSel(null);
setFileOpen(false);
if (rows.some((r) => r.hints.length)) onHints();
toast(`${added.length}곡을 ${replace ? '새 목록으로 넣었어요' : '목록 뒤에 추가했어요'}. 저장해야 반영돼요.`);
}}
/>
) : importOpen ? (
<PlaylistImport
existing={items}
onClose={() => setImportOpen(false)}
onApply={(rows, replace) => {
const base = replace ? [] : items;
const seen = new Set(base.flatMap((x) => [x.videoId, x.songId ? `s${x.songId}` : '']));
const fresh: DraftItem[] = [];
const added: DraftItem[] = [];
for (const r of rows) {
if (seen.has(r.videoId!) || (r.songId && seen.has(`s${r.songId}`))) continue;
seen.add(r.videoId!);
if (r.songId) seen.add(`s${r.songId}`);
fresh.push({ songId: r.songId, videoId: r.videoId!, title: r.title, artist: r.artist, durationSec: r.durationSec, titleAnswers: [], artistAnswers: [], auto: true, startSec: null, highlightSec: null, key: newKey() });
added.push({ ...fresh({ songId: r.songId, videoId: r.videoId!, title: r.title, artist: r.artist, durationSec: r.durationSec }), key: newKey() });
}
onItems([...base, ...fresh]);
onItems([...base, ...added]);
setSel(null);
setImportOpen(false);
toast(`${fresh.length}곡을 ${replace ? '새 목록으로 넣었어요' : '목록 뒤에 추가했어요'}${rows.length > fresh.length ? ` (이미 있는 ${rows.length - fresh.length}곡 제외)` : ''}. 저장해야 반영돼요.`);
toast(`${added.length}곡을 ${replace ? '새 목록으로 넣었어요' : '목록 뒤에 추가했어요'}${rows.length > added.length ? ` (이미 있는 ${rows.length - added.length}곡 제외)` : ''}. 저장해야 반영돼요.`);
}}
/>
) : (
<AddSong onAdd={add} onImport={() => setImportOpen(true)} />
<AddSong onAdd={add} onImport={() => setImportOpen(true)} onFile={() => setFileOpen(true)} />
)}
{items.length === 0 ? (
<p className="muted">아직 곡이 없어요. 위에서 제목·가수로 찾거나 유튜브 주소를 붙여 넣어 추가해 주세요.</p>
@@ -516,8 +581,9 @@ function SongsTab({
<b>{it.title}</b>
<div className="muted small">
{it.artist}
{!it.songId && <span className="badge" style={{ marginLeft: 6 }}>DB에 없음</span>}
{it.fromFile ? <span className="badge" style={{ marginLeft: 6 }}>파일</span> : !it.songId && <span className="badge" style={{ marginLeft: 6 }}>DB에 없음</span>}
</div>
{it.hints.length > 0 && <div className="muted small">힌트: {it.hints.join(' → ')}</div>}
</td>
<td className="small">{[...it.titleAnswers, ...it.artistAnswers].join(', ') || <span className="muted">-</span>}</td>
<td className="mono small">{mmss(it.durationSec ?? (it.songId ? db[it.songId]?.durationSec : null))}</td>
@@ -561,7 +627,7 @@ function SongsTab({
);
}
function AddSong({ onAdd, onImport }: { onAdd: (it: Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'auto' | 'startSec' | 'highlightSec'>) => boolean; onImport: () => void }) {
function AddSong({ onAdd, onImport, onFile }: { onAdd: (it: NewSong) => boolean; onImport: () => void; onFile: () => void }) {
const [q, setQ] = useState('');
const [dbHits, setDbHits] = useState<DbHit[] | null>(null);
const [ytHits, setYtHits] = useState<YtHit[] | null>(null);
@@ -618,6 +684,9 @@ function AddSong({ onAdd, onImport }: { onAdd: (it: Omit<QuizItem, 'titleAnswers
<button type="button" className="btn" onClick={onImport}>
🔗 플레이리스트 가져오기
</button>
<button type="button" className="btn" onClick={onFile}>
📄 파일
</button>
</form>
{video && <VideoAdd v={video} onAdd={(it) => done(onAdd(it))} />}
{dbHits && (
@@ -672,7 +741,7 @@ function AddSong({ onAdd, onImport }: { onAdd: (it: Omit<QuizItem, 'titleAnswers
);
}
function VideoAdd({ v, onAdd }: { v: VideoInfo; onAdd: (it: Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'auto' | 'startSec' | 'highlightSec'>) => void }) {
function VideoAdd({ v, onAdd }: { v: VideoInfo; onAdd: (it: NewSong) => void }) {
const [title, setTitle] = useState(v.title);
const [artist, setArtist] = useState(v.artist);
const api = useRef<{ time(): number | undefined } | null>(null);
@@ -1003,9 +1072,13 @@ function ItemPanel({
<input className="input" value={item.title} maxLength={200} onChange={(e) => onPatch({ title: e.target.value })} />
</label>
<label className="field">
가수
{item.fromFile ? '설명 (정답과 같이 공개돼요)' : '가수'}
<input className="input" value={item.artist} maxLength={200} onChange={(e) => onPatch({ artist: e.target.value })} />
</label>
<div className="field">
힌트 (적은 순서대로 하나씩 나오고, 마지막에 초성 힌트가 나와요)
<ChipsInput values={item.hints} onChange={(hints) => onPatch({ hints: hints.slice(0, 5) })} label="힌트" placeholder="힌트 입력 후 Enter (예: 액션 RPG)" />
</div>
<div className="field">
제목 추가 정답 (복수정답)
<ChipsInput values={item.titleAnswers} onChange={(titleAnswers) => onPatch({ titleAnswers })} label="제목 추가 정답" placeholder="다른 표기 입력 후 Enter (예: 좋은날, Good Day)" />
@@ -1014,7 +1087,9 @@ function ItemPanel({
가수 추가 정답
<ChipsInput values={item.artistAnswers} onChange={(artistAnswers) => onPatch({ artistAnswers })} label="가수 추가 정답" placeholder="다른 표기 입력 후 Enter (예: IU)" />
</div>
{item.songId ? (
{item.fromFile ? (
<p className="muted small">파일에서 넣은 곡이에요. 적힌 값 그대로 쓰고, 서버 노래 DB 검토에는 올라가지 않아요.</p>
) : item.songId ? (
<p className="muted small">
서버 노래 #{item.songId}와 연결된 곡이에요. 추가 정답은 저장할 때 서버 DB 별칭에도 들어가요.
{db && (db.titleAliases.length > 0 || db.artistAliases.length > 0) && (

View File

@@ -360,6 +360,9 @@ input.input.sm { width: 76px; }
.quiz-card.plus { align-items: center; justify-content: center; font-weight: 800; cursor: pointer; gap: 4px; }
.quiz-card.plus span { font-size: 1.6rem; }
.clamp2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.clamp1 { display: block; max-width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
.file-cols { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 8px; }
.file-col { display: flex; flex-direction: column; gap: 4px; min-width: 0; font-weight: 700; }
.quiz-head { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.quiz-head h1 { margin: 0; }
.songs-layout.with-panel.quiz { grid-template-columns: minmax(0, 1fr) 520px; }