merge: 共享题库导入支持同时写入错题本

This commit is contained in:
margrop
2026-11-29 05:09:27 +08:00
3 changed files with 180 additions and 7 deletions

View File

@@ -0,0 +1,125 @@
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import type { Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { SharedBankPicker } from '@/components/banks/shared-bank-picker';
import { LanguageProvider } from '@/contexts/LanguageContext';
import { apiClient } from '@/lib/api-client';
import { toast } from '@/lib/feedback';
import type { Notebook } from '@/types/api';
vi.mock('@/lib/api-client', () => ({ apiClient: { post: vi.fn() } }));
vi.mock('@/lib/frontend-logger', () => ({ frontendLogger: { warn: vi.fn(), error: vi.fn() } }));
vi.mock('@/lib/feedback', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
const index = {
format: 'wrong-notebook-question-bank-index',
version: 1,
updatedAt: '2026-11-29',
packages: [
{ id: 'p1', title: '小学数学题库', stage: 'primary', subject: 'math', count: 1, source: 'test', license: 'MIT', file: 'banks/a.json' },
],
};
const bankFile = {
format: 'wrong-notebook-question-bank',
version: 1,
meta: { id: 'p1', title: '小学数学题库', stage: 'primary', subject: 'math', source: 'test', license: 'MIT' },
questions: [{ text: '1 + 1 = ?', answer: '2' }],
};
const notebook: Notebook = {
id: 'nb1',
name: '我的错题本',
userId: 'u1',
createdAt: '2026-11-01T00:00:00.000Z',
updatedAt: '2026-11-01T00:00:00.000Z',
};
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
vi.stubGlobal('fetch', vi.fn(async (url: string) => ({
ok: true,
json: async () => (String(url).includes('index.json') ? index : bankFile),
})));
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(async () => {
await act(async () => root.unmount());
container.remove();
vi.unstubAllGlobals();
});
async function flushUntil(predicate: () => boolean) {
for (let i = 0; i < 50; i += 1) {
if (predicate()) return;
await act(async () => { await Promise.resolve(); });
}
throw new Error('等待渲染超时');
}
async function render(notebooks: Notebook[]) {
await act(async () => root.render(
<LanguageProvider>
<SharedBankPicker existingNames={[]} notebooks={notebooks} onImported={vi.fn()} />
</LanguageProvider>,
));
await flushUntil(() => container.textContent?.includes('小学数学题库') ?? false);
}
function findImportButton() {
const button = [...container.querySelectorAll('button')].find((item) => item.textContent?.trim() === '导入');
if (!button) throw new Error('未找到导入按钮');
return button;
}
describe('共享题库导入', () => {
it('勾选同时写入错题本后提交目标错题本', async () => {
vi.mocked(apiClient.post).mockResolvedValue({ bank: { name: '小学数学题库', questionCount: 1 }, errorItemsCreated: 1, duplicates: 0 });
await render([notebook]);
const checkbox = container.querySelector<HTMLInputElement>('input[type="checkbox"]')!;
await act(async () => checkbox.click());
expect(container.textContent).toContain('目标错题本');
await act(async () => findImportButton().click());
await flushUntil(() => vi.mocked(apiClient.post).mock.calls.length > 0);
expect(apiClient.post).toHaveBeenCalledWith(
'/api/question-banks',
expect.objectContaining({ addToErrorItems: true, notebookId: 'nb1' }),
expect.objectContaining({ timeout: 300_000 }),
);
});
it('不勾选时只导入题库,不写入错题本', async () => {
vi.mocked(apiClient.post).mockResolvedValue({ bank: { name: '小学数学题库', questionCount: 1 }, errorItemsCreated: 0, duplicates: 0 });
await render([notebook]);
await act(async () => findImportButton().click());
await flushUntil(() => vi.mocked(apiClient.post).mock.calls.length > 0);
expect(apiClient.post).toHaveBeenCalledWith(
'/api/question-banks',
expect.objectContaining({ addToErrorItems: false, notebookId: undefined }),
expect.objectContaining({ timeout: 300_000 }),
);
});
it('勾选但无错题本时提示选择目标错题本', async () => {
await render([]);
const checkbox = container.querySelector<HTMLInputElement>('input[type="checkbox"]')!;
await act(async () => checkbox.click());
await act(async () => findImportButton().click());
expect(toast.error).toHaveBeenCalledWith('勾选「同时写入错题本」后需选择目标错题本。');
expect(apiClient.post).not.toHaveBeenCalled();
});
});

View File

@@ -71,7 +71,7 @@ export default function BanksPage() {
{isAdmin ? (
<>
<BankImportPanel notebooks={notebooks} onImported={fetchBanks} />
<SharedBankPicker existingNames={banks.map((bank) => bank.name)} onImported={fetchBanks} />
<SharedBankPicker existingNames={banks.map((bank) => bank.name)} notebooks={notebooks} onImported={fetchBanks} />
</>
) : (
<p className="text-sm text-muted-foreground">{t.banks.adminManagedHint}</p>

View File

@@ -14,6 +14,7 @@ import { bankPackageUrl, parseBankFile, parseBankIndex } from "@/lib/question-ba
import { DEFAULT_BANK_INDEX_URL } from "@/lib/question-bank/types";
import type { BankIndexPackage } from "@/lib/question-bank/types";
import type { BankImportResult } from "@/lib/question-bank/types";
import type { Notebook } from "@/types/api";
const STAGE_KEYS: Record<string, "primary" | "juniorHigh" | "seniorHigh" | "university"> = {
primary: "primary",
@@ -25,17 +26,27 @@ const STAGE_KEYS: Record<string, "primary" | "juniorHigh" | "seniorHigh" | "univ
interface SharedBankPickerProps {
/** 已导入的题库名称;同名题库的按钮显示为「已导入」 */
existingNames: string[];
/** 勾选「同时写入错题本」时的目标错题本列表 */
notebooks: Notebook[];
onImported: () => void;
}
/** 从共享题库仓库读取索引并逐包导入;只进入真题库,不写入错题 */
export function SharedBankPicker({ existingNames, onImported }: SharedBankPickerProps) {
/** 从共享题库仓库读取索引并逐包导入;可选同时把整包题目写入自己的错题本 */
export function SharedBankPicker({ existingNames, notebooks, onImported }: SharedBankPickerProps) {
const { t } = useLanguage();
const importedNames = new Set(existingNames.map((name) => name.trim()));
const [packages, setPackages] = useState<BankIndexPackage[]>([]);
const [loading, setLoading] = useState(true);
const [failed, setFailed] = useState(false);
const [importingId, setImportingId] = useState<string | null>(null);
const [addToErrorItems, setAddToErrorItems] = useState(false);
const [notebookId, setNotebookId] = useState(notebooks[0]?.id ?? "");
// 错题本异步加载:首个错题本到达后补齐默认目标,避免勾选后仍提示未选择
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect -- 依赖异步加载的错题本列表
if (!notebookId && notebooks[0]) setNotebookId(notebooks[0].id);
}, [notebooks, notebookId]);
const loadIndex = useCallback(async () => {
setLoading(true);
@@ -60,6 +71,10 @@ export function SharedBankPicker({ existingNames, onImported }: SharedBankPicker
}, [loadIndex]);
const handleImport = async (item: BankIndexPackage) => {
if (addToErrorItems && !notebookId) {
toast.error(t.banks.notebookRequired);
return;
}
setImportingId(item.id);
try {
const response = await fetch(bankPackageUrl(DEFAULT_BANK_INDEX_URL, item.file), { cache: "no-store", signal: AbortSignal.timeout(30_000) });
@@ -70,11 +85,20 @@ export function SharedBankPicker({ existingNames, onImported }: SharedBankPicker
const result = await apiClient.post<BankImportResult>("/api/question-banks", {
file: raw,
name: parsed.data.meta.title,
addToErrorItems: false,
addToErrorItems,
notebookId: addToErrorItems ? notebookId : undefined,
}, { timeout: 300_000, recoverable: true });
toast.success((t.banks.imported || "Imported {name} with {count} questions.")
.replace("{name}", result.bank.name)
.replace("{count}", String(result.bank.questionCount)));
const message = addToErrorItems
? (t.banks.importedWithItems || "Imported {name} with {count} questions; {items} added, {duplicates} duplicates.")
.replace("{name}", result.bank.name)
.replace("{count}", String(result.bank.questionCount))
.replace("{items}", String(result.errorItemsCreated))
.replace("{duplicates}", String(result.duplicates))
: (t.banks.imported || "Imported {name} with {count} questions.")
.replace("{name}", result.bank.name)
.replace("{count}", String(result.bank.questionCount));
toast.success(message);
setAddToErrorItems(false);
onImported();
} catch (err) {
const rawMessage = getApiErrorMessage(err);
@@ -98,6 +122,30 @@ export function SharedBankPicker({ existingNames, onImported }: SharedBankPicker
</CardHeader>
<CardContent className="space-y-4">
<p className="text-sm text-muted-foreground">{t.banks.sharedHint}</p>
<div className="space-y-2 text-sm">
<label className="flex items-center gap-2">
<input
type="checkbox"
checked={addToErrorItems}
onChange={(event) => setAddToErrorItems(event.target.checked)}
/>
{t.banks.addToErrorItems}
</label>
{addToErrorItems && (
<label className="flex flex-wrap items-center gap-2">
<span className="font-medium">{t.banks.targetNotebook}</span>
<select
value={notebookId}
onChange={(event) => setNotebookId(event.target.value)}
className="rounded-md border border-border bg-background px-3 py-2"
>
{notebooks.map((notebook) => (
<option key={notebook.id} value={notebook.id}>{notebook.name}</option>
))}
</select>
</label>
)}
</div>
{loading ? (
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />