정답 자동 채우기: 채우는 중에 이지선다로 바꾸거나 다른 파일을 열면 '채우는 중'이 남아 만들기·추가 버튼이 계속 막히던 것 — 대상이 없어지거나 화면이 바뀌면 기다림을 풂. 1,000곡까지만 묻고 나머지를 빈 정답으로 '채웠어요' 처리하던 것 — 1,000곡씩 나눠 전부 묻고(fillAnswers), 실패한 요청·빠진 답의 곡은 '못 채워서 적힌 정답만 써요'로 따로 표시. 단위 테스트(2,500곡 나누기, 실패 구분, 화면 바뀐 뒤 중단), e2e quiz(요청 중 이지선다 전환, 502 실패 표시)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -25,6 +25,7 @@ import {
|
||||
} from '@mq/shared/lite';
|
||||
import { toast } from '../../store/toast';
|
||||
import { apiCall } from '../../net/api';
|
||||
import { fillAnswers, type FilledAnswers } from './fillAnswers';
|
||||
import { ConfirmSheet } from '../../components/ui';
|
||||
import { Seg } from '../../components/RoomSettings';
|
||||
|
||||
@@ -97,6 +98,7 @@ export function QuizFileImport({
|
||||
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 });
|
||||
setFailed(new Set());
|
||||
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];
|
||||
@@ -117,21 +119,37 @@ export function QuizFileImport({
|
||||
// 정답 자동 채우기: the songs whose 정답 / 가수 정답 cells were empty, answered by the server
|
||||
const toFill = useMemo(() => (duel ? [] : (parsed?.rows ?? []).filter((r) => r.item && (r.fill.title || r.fill.artist))), [parsed, duel]);
|
||||
const fillKey = (it: { title: string; artist: string }) => `${it.title}\u0000${it.artist}`;
|
||||
const [filled, setFilled] = useState<Record<string, { titleAnswers: string[]; artistAnswers: string[] }>>({});
|
||||
const [filled, setFilled] = useState<Record<string, FilledAnswers>>({});
|
||||
const [failed, setFailed] = useState<Set<string>>(new Set());
|
||||
const [filling, setFilling] = useState(false);
|
||||
useEffect(() => {
|
||||
const want = [...new Map(toFill.map((r) => [fillKey(r.item!), { title: r.item!.title, artist: r.item!.artist }])).values()].filter((x) => !filled[fillKey(x)]);
|
||||
if (!want.length) return;
|
||||
const want = [...new Map(toFill.map((r) => [fillKey(r.item!), { title: r.item!.title, artist: r.item!.artist }])).values()].filter(
|
||||
(x) => !filled[fillKey(x)] && !failed.has(fillKey(x)),
|
||||
);
|
||||
// nothing to ask (all done, or switched to 이지선다 / another file): never leave the buttons waiting
|
||||
if (!want.length) return setFilling(false);
|
||||
let live = true;
|
||||
let warned = false;
|
||||
setFilling(true);
|
||||
apiCall<{ answers: { titleAnswers: string[]; artistAnswers: string[] }[] }>('POST', '/api/admin/quizzes/answers', { songs: want.slice(0, 1000) })
|
||||
.then((r) => live && setFilled((cur) => ({ ...cur, ...Object.fromEntries(want.map((x, i) => [fillKey(x), r.answers[i] ?? { titleAnswers: [], artistAnswers: [] }])) })))
|
||||
.catch((e: Error) => live && toast(`정답 자동 채우기를 못 했어요(적힌 정답만 써요): ${e.message}`, 'error'))
|
||||
.finally(() => live && setFilling(false));
|
||||
void fillAnswers(
|
||||
want,
|
||||
async (songs) => (await apiCall<{ answers: FilledAnswers[] }>('POST', '/api/admin/quizzes/answers', { songs })).answers,
|
||||
(done, bad, error) => {
|
||||
if (done.length) setFilled((cur) => ({ ...cur, ...Object.fromEntries(done.map(([x, a]) => [fillKey(x), a])) }));
|
||||
if (bad.length) setFailed((cur) => new Set([...cur, ...bad.map(fillKey)]));
|
||||
if (bad.length && !warned) {
|
||||
warned = true;
|
||||
toast(`${bad.length}곡은 정답 자동 채우기를 못 했어요(적힌 정답만 써요)${error ? `: ${error.message}` : ''}`, 'error');
|
||||
}
|
||||
},
|
||||
() => live,
|
||||
).finally(() => live && setFilling(false));
|
||||
return () => {
|
||||
live = false;
|
||||
setFilling(false);
|
||||
};
|
||||
}, [toFill]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const fillFailed = toFill.filter((r) => failed.has(fillKey(r.item!))).length;
|
||||
const items = useMemo(() => {
|
||||
const fill = new Map(toFill.map((r) => [r.item!, r.fill]));
|
||||
return (parsed?.items ?? []).map((it) => {
|
||||
@@ -270,7 +288,14 @@ export function QuizFileImport({
|
||||
<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>}
|
||||
{toFill.length > 0 && <span className="muted"> · 정답 칸이 빈 곡 {toFill.length}곡{filling ? ' (자동으로 채우는 중…)' : ' (자동으로 채웠어요)'}</span>}
|
||||
{toFill.length > 0 && (
|
||||
<span className="muted">
|
||||
{' '}
|
||||
· 정답 칸이 빈 곡 {toFill.length}곡
|
||||
{filling ? ' (자동으로 채우는 중…)' : fillFailed ? '' : ' (자동으로 채웠어요)'}
|
||||
</span>
|
||||
)}
|
||||
{!filling && fillFailed > 0 && <span className="warn-text"> · {fillFailed}곡은 자동으로 못 채워서 적힌 정답만 써요</span>}
|
||||
</div>
|
||||
{blankCount > 0 && (
|
||||
<div className="stack" style={{ gap: 4 }}>
|
||||
|
||||
53
apps/web/src/pages/admin/fillAnswers.test.ts
Normal file
53
apps/web/src/pages/admin/fillAnswers.test.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { FILL_CHUNK, fillAnswers, type FillSong } from './fillAnswers';
|
||||
|
||||
const songs = (n: number): FillSong[] => Array.from({ length: n }, (_, i) => ({ title: `곡 ${i}`, artist: '가수' }));
|
||||
|
||||
test('a 2,500-song file is asked in requests of 1,000 and every song gets its answers', async () => {
|
||||
const sizes: number[] = [];
|
||||
const done: string[] = [];
|
||||
await fillAnswers(
|
||||
songs(2500),
|
||||
async (c) => (sizes.push(c.length), c.map((s) => ({ titleAnswers: [`${s.title}!`], artistAnswers: [] }))),
|
||||
(ok, failed) => (done.push(...ok.map(([s, a]) => `${s.title}=${a.titleAnswers[0]}`)), expect(failed).toEqual([])),
|
||||
);
|
||||
expect(sizes).toEqual([FILL_CHUNK, FILL_CHUNK, 500]);
|
||||
expect(done).toHaveLength(2500);
|
||||
expect(done[2499]).toBe('곡 2499=곡 2499!');
|
||||
});
|
||||
|
||||
test('a failed request marks only its songs as failed; a short answer list is not "filled"', async () => {
|
||||
let n = 0;
|
||||
const failed: FillSong[] = [];
|
||||
const ok: FillSong[] = [];
|
||||
const errors: string[] = [];
|
||||
await fillAnswers(
|
||||
songs(2100),
|
||||
async (c) => {
|
||||
if (n++ === 0) throw new Error('502');
|
||||
return c.slice(0, c.length - 1).map(() => ({ titleAnswers: [], artistAnswers: [] }));
|
||||
},
|
||||
(d, f, e) => (ok.push(...d.map(([s]) => s)), failed.push(...f), e && errors.push(e.message)),
|
||||
);
|
||||
expect(errors).toEqual(['502']);
|
||||
expect(ok).toHaveLength(999 + 99);
|
||||
expect(failed.map((s) => s.title)).toEqual([...songs(1000).map((s) => s.title), '곡 1999', '곡 2099']);
|
||||
});
|
||||
|
||||
test('nothing more is asked or reported once the screen moved on', async () => {
|
||||
let live = true;
|
||||
const calls: number[] = [];
|
||||
const reported: number[] = [];
|
||||
await fillAnswers(
|
||||
songs(3000),
|
||||
async (c) => {
|
||||
calls.push(c.length);
|
||||
live = false; // e.g. switched to 이지선다 while the first request was out
|
||||
return c.map(() => ({ titleAnswers: [], artistAnswers: [] }));
|
||||
},
|
||||
(d) => reported.push(d.length),
|
||||
() => live,
|
||||
);
|
||||
expect(calls).toEqual([1000]);
|
||||
expect(reported).toEqual([]);
|
||||
});
|
||||
39
apps/web/src/pages/admin/fillAnswers.ts
Normal file
39
apps/web/src/pages/admin/fillAnswers.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* 정답 자동 채우기 (파일로 만들기·파일에서 가져오기, docs/13): asks the server for the answers of songs whose 정답 /
|
||||
* 가수 정답 cells were empty, in requests of at most CHUNK songs (the server's limit), so a 5,000-song file is filled whole.
|
||||
* A request that fails marks only its own songs as failed; the others still get their answers.
|
||||
*/
|
||||
export interface FillSong {
|
||||
title: string;
|
||||
artist: string;
|
||||
}
|
||||
export interface FilledAnswers {
|
||||
titleAnswers: string[];
|
||||
artistAnswers: string[];
|
||||
}
|
||||
|
||||
export const FILL_CHUNK = 1000;
|
||||
|
||||
export async function fillAnswers(
|
||||
songs: FillSong[],
|
||||
call: (chunk: FillSong[]) => Promise<FilledAnswers[]>,
|
||||
onChunk: (done: [FillSong, FilledAnswers][], failed: FillSong[], error: Error | null) => void,
|
||||
isLive: () => boolean = () => true,
|
||||
): Promise<void> {
|
||||
for (let i = 0; i < songs.length && isLive(); i += FILL_CHUNK) {
|
||||
const chunk = songs.slice(i, i + FILL_CHUNK);
|
||||
try {
|
||||
const got = await call(chunk);
|
||||
if (!isLive()) return;
|
||||
// a short answer list leaves the rest unanswered (failed), never "filled" with nothing
|
||||
onChunk(
|
||||
chunk.flatMap((s, k) => (got[k] ? [[s, got[k]!] as [FillSong, FilledAnswers]] : [])),
|
||||
chunk.filter((_, k) => !got[k]),
|
||||
null,
|
||||
);
|
||||
} catch (e) {
|
||||
if (!isLive()) return;
|
||||
onChunk([], chunk, e as Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -198,6 +198,39 @@ try {
|
||||
await p.getByText('저장됨').waitFor();
|
||||
expect(db.query<{ n: number }, [number]>('SELECT COUNT(*) n FROM custom_quiz_items WHERE quiz_id = ?').get(quizId)!.n === 4, '가져온 곡 저장');
|
||||
});
|
||||
await step('정답 자동 채우기: 빈 정답 칸은 서버가 채움, 채우는 중에 이지선다로 바꿔도 만들기 버튼이 막히지 않음, 실패는 "채웠어요"로 안 보임', async () => {
|
||||
const csv = new TextEncoder().encode('링크,제목,가수,정답\nhttps://youtu.be/9hzKkTpXDwM,사랑을 했다(LOVE SCENARIO),아이콘,\nhttps://youtu.be/Yz-Af4p_Vv8,광(狂),SG워너비,\n');
|
||||
const openFile = async () => {
|
||||
await p.goto(`${ORIGIN}/admin/quizzes`);
|
||||
await p.getByRole('button', { name: /^파일로 만들기/ }).click();
|
||||
await p.getByLabel('퀴즈 파일').setInputFiles({ name: '빈 정답.csv', mimeType: 'text/csv', buffer: Buffer.from(csv) });
|
||||
};
|
||||
// 1. the request hangs: switching to 이지선다 must not leave the button waiting
|
||||
let release!: () => void;
|
||||
const hold = new Promise<void>((r) => (release = r));
|
||||
await p.route(`${ORIGIN}/api/admin/quizzes/answers`, async (route) => (await hold, route.continue().catch(() => {})));
|
||||
await openFile();
|
||||
await p.getByText('자동으로 채우는 중').waitFor();
|
||||
expect(await p.getByRole('button', { name: '2곡으로 만들기' }).isDisabled(), '채우는 중에는 만들기를 기다림');
|
||||
await p.getByRole('radio', { name: /이지선다/ }).click();
|
||||
const duelBtn = p.getByRole('button', { name: '2곡으로 이지선다 만들기' });
|
||||
await duelBtn.waitFor();
|
||||
for (let i = 0; i < 20 && (await duelBtn.isDisabled()); i++) await p.waitForTimeout(100);
|
||||
expect(await duelBtn.isEnabled(), '이지선다로 바꾼 뒤 만들기 버튼이 막힘(요청이 끝나지 않은 채)');
|
||||
release();
|
||||
await p.unroute(`${ORIGIN}/api/admin/quizzes/answers`);
|
||||
// 2. back to 일반: filled from the server, shown under the title
|
||||
await p.getByRole('radio', { name: /일반 퀴즈/ }).click();
|
||||
await p.getByText('(자동으로 채웠어요)').waitFor();
|
||||
await p.getByText('또는 LOVE SCENARIO, 사랑을 했다 LOVE SCENARIO').waitFor();
|
||||
// 3. the server fails: those songs say so, never "채웠어요"
|
||||
await p.route(`${ORIGIN}/api/admin/quizzes/answers`, (route) => route.fulfill({ status: 502, contentType: 'application/json', body: '{"error":"잠깐 끊김"}' }));
|
||||
await openFile();
|
||||
await p.getByText('2곡은 자동으로 못 채워서 적힌 정답만 써요').waitFor();
|
||||
expect((await p.getByText('(자동으로 채웠어요)').count()) === 0, '실패했는데 채웠다고 보임');
|
||||
expect(await p.getByRole('button', { name: '2곡으로 만들기' }).isEnabled(), '실패 뒤 만들기 버튼이 막힘');
|
||||
await p.unroute(`${ORIGIN}/api/admin/quizzes/answers`);
|
||||
});
|
||||
await step('재생목록으로 엑셀 만들기 → 검토(DB 곡·확인 필요·같은 영상은 빠진 곡) → 받은 엑셀을 파일로 만들기: 자동은 DB 하이라이트, 처음부터는 0초', async () => {
|
||||
await p.goto(`${ORIGIN}/admin/quizzes`);
|
||||
await p.getByRole('button', { name: /재생목록으로 엑셀 만들기/ }).click();
|
||||
|
||||
Reference in New Issue
Block a user