퀴즈 편집 수정: 저장 중에 바꾼 내용이 응답으로 덮여 사라지고 '저장됨'으로 보이던 것(보낸 내용과 지금 내용이 다르면 지금 내용을 두고 새 곡 id만 붙임, 저장 안 됨 유지). 새로 추가한 서버 DB 곡의 하이라이트가 DB 값 대신 곡 길이 30%로 보이고 자동을 끄면 그 값으로 굳던 것(추가 즉시 /quizzes/pick/songs로 DB 정보를 받고, 받기 전엔 자동 스위치·표시 이동 잠금). e2e/quiz.e2e.ts로 두 경로 회귀 확인

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-22 13:26:10 +09:00
parent a0907b551b
commit e44df482a6
6 changed files with 202 additions and 34 deletions

View File

@@ -85,6 +85,9 @@ test('editor API: save items with extra answers (into the DB aliases for linked
const items = r.body.quiz.items as { id: number }[];
const re = await api(s.base, `/api/admin/quizzes/${id}`, { method: 'PUT', cookie: sa, body: JSON.stringify({ name: '테스트', description: '설명', visibility: 'public', settings: settings(), items: [r.body.quiz.items[1], r.body.quiz.items[0]] }) });
expect(re.body.quiz.items.map((i: { id: number }) => i.id)).toEqual([items[1]!.id, items[0]!.id]);
// DB facts of a song added in the editor before saving (자동 uses the DB highlight)
const facts = await api(s.base, `/api/admin/quizzes/pick/songs?ids=${song},999999`, { cookie: sa });
expect(facts.body.db).toEqual({ [song]: { titleAliases: ['Good Day'], artistAliases: [], highlightSec: 61, durationSec: 230, videoId: 'goodday0001' } });
// an admin who did not make it cannot open it
s.db.query("INSERT INTO admins (discord_id, note, added_by, added_at) VALUES ('900000000000000077', null, null, 0)").run();
const other = await adminCookie('900000000000000077');

View File

@@ -206,26 +206,18 @@ export function mountQuizAdmin(app: Hono<Env>, d: QuizAdminDeps, h: { actor: (c:
return job ? c.json({ job }) : c.json({ error: '가져오기 작업을 찾을 수 없어요.' }, 404);
});
/** DB facts of songs just added in the editor (before saving): aliases and the DB highlight for 자동. */
app.get('/quizzes/pick/songs', (c) => {
const ids = (c.req.query('ids') ?? '').split(',').map(Number).filter((x) => Number.isInteger(x) && x > 0).slice(0, 500);
return c.json({ db: dbFacts(d.db, ids) });
});
// ---------------------------------------------------------------- one quiz
app.get('/quizzes/:id', (c) => {
const q = mine(c);
if (!q) return c.json({ error: '퀴즈를 찾을 수 없어요.' }, 404);
const detail = d.quizzes.get(q.id)!;
// DB facts the editor shows next to each song: aliases that already count, the DB highlight for 자동.
const ids = [...new Set(detail.items.map((i) => i.songId).filter((x): x is number => !!x))];
const db: Record<number, { titleAliases: string[]; artistAliases: string[]; highlightSec: number | null; durationSec: number | null; videoId: string | null }> = {};
for (const id of ids) {
const s = d.db.query<{ highlight_sec: number | null; duration_sec: number | null; youtube_id: string | null }, [number]>('SELECT highlight_sec, duration_sec, youtube_id FROM songs WHERE id = ?').get(id);
if (!s) continue;
const al = d.db.query<{ part: string; alias: string }, [number]>('SELECT part, alias FROM song_aliases WHERE song_id = ?').all(id);
db[id] = {
titleAliases: al.filter((a) => a.part === 'title').map((a) => a.alias),
artistAliases: al.filter((a) => a.part === 'artist').map((a) => a.alias),
highlightSec: s.highlight_sec,
durationSec: s.duration_sec,
videoId: s.youtube_id,
};
}
const db = dbFacts(d.db, detail.items.map((i) => i.songId).filter((x): x is number => !!x));
return c.json({ quiz: detail, db, limits: d.limits() });
});
@@ -253,3 +245,23 @@ export function mountQuizAdmin(app: Hono<Env>, d: QuizAdminDeps, h: { actor: (c:
return c.json({ ok: true });
});
}
/** DB facts the editor shows next to each linked song: aliases that already count, the DB highlight/length/video for 자동. */
function dbFacts(db: Database, songIds: number[]) {
const out: Record<number, { titleAliases: string[]; artistAliases: string[]; highlightSec: number | null; durationSec: number | null; videoId: string | null }> = {};
const song = db.query<{ highlight_sec: number | null; duration_sec: number | null; youtube_id: string | null }, [number]>('SELECT highlight_sec, duration_sec, youtube_id FROM songs WHERE id = ?');
const aliases = db.query<{ part: string; alias: string }, [number]>('SELECT part, alias FROM song_aliases WHERE song_id = ?');
for (const id of new Set(songIds)) {
const s = song.get(id);
if (!s) continue;
const al = aliases.all(id);
out[id] = {
titleAliases: al.filter((a) => a.part === 'title').map((a) => a.alias),
artistAliases: al.filter((a) => a.part === 'artist').map((a) => a.alias),
highlightSec: s.highlight_sec,
durationSec: s.duration_sec,
videoId: s.youtube_id,
};
}
return out;
}

View File

@@ -42,8 +42,8 @@ export function PositionEditor({
}: Positions & {
videoId: string;
durationSec: number | null;
/** The server DB highlight of this video (유튜브 "가장 많이 다시 본 구간"), used while 자동. */
dbHighlightSec: number | null;
/** The server DB highlight of this video (유튜브 "가장 많이 다시 본 구간"), used while 자동; undefined while it loads. */
dbHighlightSec: number | null | undefined;
defaultStartAt: 'start' | 'highlight';
onChange: (p: Positions) => void;
}) {
@@ -138,7 +138,8 @@ export function PositionEditor({
const length = dur || durationSec || 0;
const autoStart = 0;
const autoHighlight = dbHighlightSec ?? (length ? Math.round(length * 0.3) : null);
const dbLoading = dbHighlightSec === undefined;
const autoHighlight = dbLoading ? null : (dbHighlightSec ?? (length ? Math.round(length * 0.3) : null));
const start = auto ? autoStart : (startSec ?? 0);
const highlight = auto ? autoHighlight : highlightSec;
const pct = (s: number | null) => (s == null || !length ? 0 : Math.min(100, Math.max(0, (s / length) * 100)));
@@ -148,6 +149,8 @@ export function PositionEditor({
};
/** Manual positions from now on: both markers keep where they are, the moved one changes. */
const setMarker = (which: 'start' | 'highlight', sec: number) => {
// 자동 → 직접 needs the DB highlight first, or the other marker would be fixed at a guess
if (dbLoading && auto) return;
const s = Math.round(Math.min(Math.max(0, sec), length || sec) * 10) / 10;
onChange({
auto: false,
@@ -207,6 +210,7 @@ export function PositionEditor({
type="button"
className={`toggle ${auto ? 'on' : ''}`}
aria-pressed={auto}
disabled={dbLoading}
onClick={() =>
onChange(auto ? { auto: false, startSec: 0, highlightSec: autoHighlight } : { auto: true, startSec: null, highlightSec: null })
}
@@ -271,7 +275,9 @@ export function PositionEditor({
/>
</div>
<p className="muted small">
{auto
{dbLoading
? '서버 DB 하이라이트를 불러오는 중이에요…'
: auto
? `자동: 처음은 0초, 하이라이트는 ${dbHighlightSec != null ? '서버 DB 값' : '아직 서버 DB 값이 없어 곡 길이의 30% 지점'}이에요. 표시를 옮기면 자동이 꺼져요.`
: '표시를 끌거나 "지금 위치로"를 눌러 정해요. 재생바를 누르면 그 위치로 이동해요.'}
</p>

View File

@@ -144,7 +144,7 @@ export function QuizEditor() {
const nav = useNavigate();
const [saved, setSaved] = useState<string>('');
const [draft, setDraft] = useState<Draft | null>(null);
const [db, setDb] = useState<Record<number, DbInfo>>({});
const [db, setDb] = useState<Record<number, DbInfo | null>>({});
const [tab, setTab] = useState<'songs' | 'settings'>('songs');
const [busy, setBusy] = useState(false);
const [leaveTo, setLeaveTo] = useState<string | null>(null);
@@ -169,21 +169,28 @@ export function QuizEditor() {
const dirtyRef = useRef(dirty);
dirtyRef.current = dirty;
const draftRef = useRef(draft);
draftRef.current = draft;
const save = useCallback(async (): Promise<boolean> => {
if (!draft) return false;
const sent = draftRef.current;
if (!sent) return false;
const sentJson = JSON.stringify(payload(sent));
setBusy(true);
try {
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 r = await apiCall<{ quiz: QuizDetail; reviews: { pending: number } }>('PUT', `/api/admin/quizzes/${id}`, JSON.parse(sentJson));
// what the server keeps, with the client keys (selection) of the items as sent (same order)
const d = toDraft(r.quiz);
d.items = d.items.map((it, i) => ({ ...it, key: draft.items[i]?.key ?? it.key }));
setDraft(d);
d.items = d.items.map((it, i) => ({ ...it, key: sent.items[i]?.key ?? it.key }));
setSaved(JSON.stringify(payload(d)));
// edits made while the request was on its way stay (and stay unsaved); new items get their ids
const now = draftRef.current;
if (!now || JSON.stringify(payload(now)) === sentJson) setDraft(d);
else {
const ids = new Map(d.items.map((it) => [it.key, it.id]));
setDraft({ ...now, items: now.items.map((it) => (it.id || !ids.has(it.key) ? it : { ...it, id: ids.get(it.key) })) });
}
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);
return true;
} catch (e) {
toast((e as Error).message, 'error');
@@ -191,7 +198,20 @@ export function QuizEditor() {
} finally {
setBusy(false);
}
}, [draft, id]);
}, [id]);
// DB facts (aliases, the DB highlight for 자동) of songs added since loading: fetched as soon as they appear
const asked = useRef(new Set<number>());
useEffect(() => {
if (!draft) return;
const missing = [...new Set(draft.items.map((i) => i.songId).filter((x): x is number => !!x && !(x in db) && !asked.current.has(x)))];
if (!missing.length) return;
for (const x of missing) asked.current.add(x);
apiCall<{ db: Record<number, DbInfo> }>('GET', `/api/admin/quizzes/pick/songs?ids=${missing.join(',')}`)
.then((r) => setDb((cur) => ({ ...cur, ...Object.fromEntries(missing.map((x) => [x, r.db[x] ?? null])) })))
.catch(() => {
for (const x of missing) asked.current.delete(x);
});
}, [draft, db]);
const saveRef = useRef(save);
saveRef.current = save;
@@ -388,7 +408,7 @@ function SongsTab({
setImportOpen,
}: {
items: DraftItem[];
db: Record<number, DbInfo>;
db: Record<number, DbInfo | null>;
settings: QuizSettings;
onItems: (items: DraftItem[]) => void;
importOpen: boolean;
@@ -528,7 +548,7 @@ function SongsTab({
item={selected}
index={items.indexOf(selected)}
total={items.length}
db={selected.songId ? (db[selected.songId] ?? null) : null}
db={selected.songId ? db[selected.songId] : null}
defaultStartAt={settings.startAt}
onPatch={(p) => patch(selected.key, p)}
onMove={(to) => move(items.indexOf(selected), to)}
@@ -936,7 +956,8 @@ function ItemPanel({
item: DraftItem;
index: number;
total: number;
db: DbInfo | null;
/** undefined: still loading the DB facts of the linked song. */
db: DbInfo | null | undefined;
defaultStartAt: 'start' | 'highlight';
onPatch: (p: Partial<QuizItem>) => void;
onMove: (to: number) => void;
@@ -973,7 +994,7 @@ function ItemPanel({
auto={item.auto}
startSec={item.startSec}
highlightSec={item.highlightSec}
dbHighlightSec={db && db.videoId === item.videoId ? db.highlightSec : null}
dbHighlightSec={db === undefined ? undefined : db && db.videoId === item.videoId ? db.highlightSec : null}
defaultStartAt={defaultStartAt}
onChange={onPatch}
/>

126
e2e/quiz.e2e.ts Normal file
View File

@@ -0,0 +1,126 @@
/**
* 관리자 → 퀴즈 editor in a real browser:
* - a DB song added from the search shows (and, with 자동 off, keeps) the DB highlight, not the 30% guess
* - an edit made while 저장 is on its way stays and stays unsaved
* Run: bun run build && bun e2e/quiz.e2e.ts (needs /usr/bin/google-chrome)
*/
import { chromium, type Browser, type BrowserContext } from 'playwright-core';
import { mkdirSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { loadConfig } from '../apps/server/src/config';
import { startServer } from '../apps/server/src/server';
import { Catalog } from '../apps/server/src/collector/catalog';
const PORT = Number(process.env.E2E_PORT ?? 4627);
const ORIGIN = `http://localhost:${PORT}`;
const SHOTS = process.env.E2E_SHOTS ?? join(import.meta.dir, '../test-results');
mkdirSync(SHOTS, { recursive: true });
const TMP = mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'mq-e2e-'));
const SUPER = '900000000000000001';
const app = startServer({
config: loadConfig({ PORT: String(PORT), DB_PATH: join(TMP, 'app.db'), PUBLIC_ORIGIN: ORIGIN, SUPERADMIN_DISCORD_IDS: SUPER, DISCORD_CLIENT_ID: '1561284577564037140', DISCORD_CLIENT_SECRET: 'e2e' }),
log: () => {},
staticDir: join(import.meta.dir, '../apps/web/dist'),
stopWaitMs: 200,
discordExchange: async (code) => ({ id: code, username: 'u', global_name: '사금향', avatar: null }),
checkEmbed: async () => ({ state: 'ok', author: 'IU - Topic', title: 'Official Audio' }),
quizAdmin: { searchYoutube: async () => [], lavalink: null },
});
const db = app.db;
{
const [id] = new Catalog(db).upsert({ title: '좋은 날', artists: [{ name: '아이유' }], year: 2010, durationSec: 236, genres: ['kpop'], source: 'e2e', ref: '1' });
db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = 'jeqdYqsrsA0', highlight_sec = 95 WHERE id = ?").run(id!);
}
const browser: Browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true });
const errors: string[] = [];
const step = async (name: string, fn: () => Promise<void>) => {
const t0 = performance.now();
try {
await fn();
console.log(`✓ ${name} (${Math.round(performance.now() - t0)}ms)`);
} catch (e) {
console.log(`✗ ${name}: ${(e as Error).message.split('\n')[0]}`);
throw e;
}
};
const expect = (ok: unknown, msg: string) => {
if (!ok) throw new Error(msg);
};
async function fakeDiscord(ctx: BrowserContext, discordId: string) {
await ctx.route(`${ORIGIN}/api/auth/discord/start*`, async (route) => {
const res = await fetch(route.request().url(), { redirect: 'manual', headers: { cookie: (await route.request().headerValue('cookie')) ?? '' } });
const consent = new URL(res.headers.get('location')!);
const back = `${ORIGIN}/api/auth/discord/callback?code=${discordId}&state=${consent.searchParams.get('state')}`;
await route.fulfill({ status: 200, headers: { 'content-type': 'text/html', 'set-cookie': res.headers.get('set-cookie') ?? '' }, body: `<script>location.replace(${JSON.stringify(back)})</script>` });
});
}
let failed = false;
try {
const ctx = await browser.newContext({ viewport: { width: 1500, height: 950 }, locale: 'ko-KR' });
await fakeDiscord(ctx, SUPER);
const p = await ctx.newPage();
p.on('pageerror', (e) => errors.push(e.message));
await p.goto(`${ORIGIN}/api/auth/discord/start`);
await p.waitForURL(`${ORIGIN}/**`);
await step('퀴즈 추가 → 서버 DB 곡 추가 → 패널의 하이라이트는 DB 값(1:35), 자동 끄고 저장해도 95초', async () => {
await p.goto(`${ORIGIN}/admin/quizzes`);
await p.getByRole('button', { name: '퀴즈 추가' }).click();
await p.getByPlaceholder('예) 2000년대').fill('e2e 퀴즈');
await p.getByRole('button', { name: '확인' }).click();
await p.getByRole('button', { name: '✋ 직접 하나씩 추가' }).click();
await p.getByLabel('곡 추가 검색').fill('좋은 날');
await p.getByRole('button', { name: '찾기', exact: true }).click();
await p.locator('.cand', { hasText: '좋은 날' }).getByRole('button', { name: '추가' }).click();
await p.locator('.quiz-songs tbody tr').first().click();
const hl = p.locator('.pos-row', { hasText: '하이라이트' }).locator('.mono');
await p.waitForFunction(() => document.querySelector('.pos-editor .toggle:not([disabled])'));
expect((await hl.innerText()) === '1:35.0', `하이라이트가 DB 값이 아님: ${await hl.innerText()}`);
await p.locator('.pos-editor .toggle').click();
expect((await hl.innerText()) === '1:35.0', `자동을 끈 뒤 하이라이트: ${await hl.innerText()}`);
await p.keyboard.press('Control+s');
await p.getByText('저장됨').waitFor();
const it = db.query<{ auto: number; highlight_sec: number }, []>('SELECT auto, highlight_sec FROM custom_quiz_items').get()!;
expect(it.auto === 0 && it.highlight_sec === 95, `저장된 값: ${JSON.stringify(it)}`);
});
await step('저장 중에 바꾼 이름이 응답 뒤에도 남고 "저장 안 됨"으로 보임', async () => {
await p.getByRole('tab', { name: '설정' }).click();
const name = p.getByLabel('퀴즈 이름');
await name.fill('이름 1');
// hold the save request so an edit can happen while it is on its way
let release!: () => void;
const held = new Promise<void>((r) => (release = r));
await p.route(`${ORIGIN}/api/admin/quizzes/*`, async (route) => {
if (route.request().method() === 'PUT') await held;
await route.continue();
});
await p.keyboard.press('Control+s');
await p.getByText('저장 중…').waitFor();
await name.fill('이름 2');
release();
await p.locator('.toast', { hasText: '저장했어요' }).first().waitFor();
await p.waitForTimeout(200);
expect((await name.inputValue()) === '이름 2', `입력이 사라짐: ${await name.inputValue()}`);
expect(await p.getByText('저장하지 않은 변경이 있어요').isVisible(), '저장 안 됨 표시가 없음');
expect((await p.title()).startsWith('● 저장 안 됨'), `탭 제목: ${await p.title()}`);
expect(db.query<{ name: string }, []>('SELECT name FROM custom_quizzes').get()!.name === '이름 1', '서버에는 보낸 값(이름 1)');
await p.unroute(`${ORIGIN}/api/admin/quizzes/*`);
await p.keyboard.press('Control+s');
await p.getByText('저장됨').waitFor();
expect(db.query<{ name: string }, []>('SELECT name FROM custom_quizzes').get()!.name === '이름 2', '두 번째 저장');
});
expect(errors.length === 0, `페이지 오류: ${errors.join(' | ')}`);
} catch (e) {
console.log(e instanceof Error ? e.message.slice(0, 400) : e);
for (const pg of browser.contexts().flatMap((c) => c.pages())) await pg.screenshot({ path: join(SHOTS, `quiz-fail-${Math.random().toString(36).slice(2, 6)}.png`) }).catch(() => {});
failed = true;
} finally {
await browser.close();
await app.stop();
}
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
process.exit(failed ? 1 : 0);

View File

@@ -11,7 +11,7 @@
"build": "bun run --filter '@mq/web' build",
"typecheck": "tsc -p packages/shared && tsc -p apps/server && tsc -p apps/web",
"test": "bun test --timeout 20000",
"e2e": "bun run build && bun e2e/login.e2e.ts && bun e2e/rooms.e2e.ts && bun e2e/game.e2e.ts && bun e2e/admin.e2e.ts && bun e2e/a11y.e2e.ts && bun e2e/load.ts"
"e2e": "bun run build && bun e2e/login.e2e.ts && bun e2e/rooms.e2e.ts && bun e2e/game.e2e.ts && bun e2e/admin.e2e.ts && bun e2e/quiz.e2e.ts && bun e2e/a11y.e2e.ts && bun e2e/load.ts"
},
"devDependencies": {
"@types/bun": "1.4.2",