feat: 数据导出导入包含随机错题试卷、试卷题目及其作答记录

- 导出新增 examPapers(含按顺序排列的题目)
- 导入时把试卷题目重新关联到导入后的错题,错题本 ID 换成新 ID;作答记录关联到对应试卷题目
- 同一用户下标题和创建时间相同的试卷视为已导入,不重复创建
- 导出时仍在生成的题目按失败导入,可在试卷页重新生成
- 导入结果提示显示试卷数量,同步更新 Wiki 与测试

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
margrop
2026-10-24 21:05:46 +08:00
parent c1a57c0cc5
commit 322fef5265
6 changed files with 167 additions and 8 deletions

View File

@@ -6,16 +6,16 @@
| 方式 | 包含内容 | 适用场景 |
| --- | --- | --- |
| 网页 JSON 导出 | 错题本、自定义标签、错题、复习计划、练习记录及部分用户资料 | 个人数据留存、受支持字段的导入 |
| 网页 JSON 导出 | 错题本、自定义标签、错题、复习计划、练习记录、随机错题试卷及部分用户资料 | 个人数据留存、受支持字段的导入 |
| 整站文件备份 | 完整 SQLite 数据库、`config/`、部署配置及需要的证书 | 灾难恢复、迁移整站、升级前回退准备 |
当前 JSON 导出不包含完整用户账户及密码、试卷表或服务端 AI 配置。即使管理员选择导出全部数据,也不能替代整站备份。
当前 JSON 导出不包含完整用户账户及密码或服务端 AI 配置。即使管理员选择导出全部数据,也不能替代整站备份。
## 网页导出与导入
在设置的数据管理入口导出 JSON,并妥善保存。普通用户导入时,导出文件中的用户邮箱必须与当前账户一致;管理员可以使用管理范围的全部数据导入导出。
错题的配图、GeoGebra 演示、中英文 SVG 动画讲解、最近一次举一反三和掌握概率都会随导出文件还原,SVG 在导入时重新净化;没有掌握概率的题目导入后会重新评估。
错题的配图、GeoGebra 演示、中英文 SVG 动画讲解、最近一次举一反三和掌握概率都会随导出文件还原,SVG 在导入时重新净化;没有掌握概率的题目导入后会重新评估。试卷连同题目和每次录入的结果一起还原;导出时仍在生成的题目导入后显示为失败,可在试卷页重新生成。
导入时会合并已有错题本、标签,并按题干相似度处理重复题目。重复题可能在已有题目下新增一次做错记录,因此反复导入同一份文件可能改变练习历史。

View File

@@ -139,6 +139,49 @@ describe('数据导出后再导入(真实 SQLite)', () => {
expect(mocks.scheduleMasteryEvaluation).toHaveBeenCalledWith([item.id]);
});
it('试卷、试卷题目及其作答记录完整保留,重复导入不新建试卷', async () => {
await database.examPaper.create({
data: {
id: 'paper-1', userId: 'user-1', title: '周测', status: 'generating', scope: 'unmastered', difficulty: 'hard', requestedCount: 2,
subjectIds: JSON.stringify(['math']), tagNames: JSON.stringify(['自定义标签']), resultsRecordedAt: new Date('2026-10-22T00:00:00Z'),
createdAt: new Date('2026-10-21T00:00:00Z'),
questions: { create: [
{ id: 'question-1', order: 0, errorItemId: 'item-1', sourceShortId: 'AbC234', status: 'ready', questionText: '试卷新题', answerText: '答', analysis: '析', figureSvg: figure },
{ id: 'question-2', order: 1, errorItemId: 'item-1', sourceShortId: 'AbC234', status: 'pending' },
] },
},
});
await database.practiceRecord.create({
data: { userId: 'user-1', errorItemId: 'item-1', examQuestionId: 'question-1', result: 'wrong', isCorrect: false, source: 'exam', questionText: '试卷新题' },
});
const backup = await exportBackup();
await clearUserData();
const { stats } = await importBackup(backup);
expect(stats.examPapersCreated).toBe(1);
const item = await database.errorItem.findFirstOrThrow({ where: { userId: 'user-1' } });
const subject = await database.subject.findFirstOrThrow({ where: { userId: 'user-1' } });
const paper = await database.examPaper.findFirstOrThrow({ where: { userId: 'user-1' }, include: { questions: { orderBy: { order: 'asc' } } } });
expect(paper).toMatchObject({
title: '周测', status: 'partial', scope: 'unmastered', difficulty: 'hard', requestedCount: 2,
subjectIds: JSON.stringify([subject.id]), tagNames: JSON.stringify(['自定义标签']),
resultsRecordedAt: new Date('2026-10-22T00:00:00Z'), createdAt: new Date('2026-10-21T00:00:00Z'),
});
expect(paper.questions).toMatchObject([
{ order: 0, errorItemId: item.id, sourceShortId: 'AbC234', status: 'ready', questionText: '试卷新题', figureSvg: figure },
// 导出时仍在生成的题目按失败导入
{ order: 1, errorItemId: item.id, status: 'failed' },
]);
expect(await database.practiceRecord.findFirstOrThrow({ where: { source: 'exam' } })).toMatchObject({ examQuestionId: paper.questions[0].id, errorItemId: item.id });
// 再导入一次:试卷不重复,作答记录关联到已有的试卷题目
const again = await importBackup(backup);
expect(again.stats.examPapersCreated).toBe(0);
expect(await database.examPaper.count({ where: { userId: 'user-1' } })).toBe(1);
const examRecords = await database.practiceRecord.findMany({ where: { source: 'exam' } });
expect(examRecords.map((record) => record.examQuestionId)).toEqual([paper.questions[0].id, paper.questions[0].id]);
});
it('导入时重新净化 SVG,丢弃不合法的暂存练习和掌握概率', async () => {
const backup = await exportBackup();
await clearUserData();

View File

@@ -63,6 +63,13 @@ export async function GET(req: Request) {
where: userFilter,
});
const examPapers = await prisma.examPaper.findMany({
where: userFilter,
include: {
questions: { orderBy: { order: 'asc' } },
},
});
const exportData = {
version: 2,
exportedAt: new Date().toISOString(),
@@ -80,6 +87,7 @@ export async function GET(req: Request) {
errorItems,
reviewSchedules,
practiceRecords,
examPapers,
};
logger.info({
@@ -90,6 +98,7 @@ export async function GET(req: Request) {
errorItemsCount: errorItems.length,
reviewSchedulesCount: reviewSchedules.length,
practiceRecordsCount: practiceRecords.length,
examPapersCount: examPapers.length,
}, 'Data export completed');
const jsonString = JSON.stringify(exportData, null, 2);

View File

@@ -15,6 +15,7 @@ import { sanitizeFigureSvg } from "@/lib/figure-svg";
import { sanitizeSvgAnimation } from "@/lib/svg-animation";
import { parseLastPractice } from "@/lib/last-practice";
import { getDefaultPaperLevel } from "@/lib/paper-level";
import { EXAM_DIFFICULTIES, EXAM_SCOPES, summarizePaperStatus } from "@/lib/exam";
const logger = createLogger('api:import');
@@ -111,8 +112,35 @@ interface ImportData {
originalImageUrl?: string | null;
figureSvg?: string | null;
source?: string;
examQuestionId?: string | null;
createdAt: string;
}>;
examPapers?: Array<{ // version 2 起导出
id: string;
userId: string;
title: string;
status: string;
scope: string;
difficulty: string;
requestedCount: number;
subjectIds: string;
tagNames: string | null;
resultsRecordedAt: string | null;
createdAt: string;
updatedAt: string;
questions: Array<{
id: string;
order: number;
errorItemId: string | null;
sourceShortId: string;
status: string;
questionText: string | null;
answerText: string | null;
analysis: string | null;
figureSvg: string | null;
error: string | null;
}>;
}>;
}
/** Validate and parse a date string, returning undefined if invalid */
@@ -133,6 +161,17 @@ function safeLastPractice(raw: string | null | undefined): string | null {
return practice ? JSON.stringify(practice) : null;
}
/** 试卷的错题本 ID 为 JSON 数组,导入时换成新 ID,找不到的去掉 */
function mapSubjectIds(raw: string | null | undefined, subjectIdMap: Map<string, string>): string {
try {
const ids: unknown = JSON.parse(raw || '[]');
if (!Array.isArray(ids)) return '[]';
return JSON.stringify(ids.flatMap((id) => (typeof id === 'string' && subjectIdMap.has(id) ? [subjectIdMap.get(id)!] : [])));
} catch {
return '[]';
}
}
/** Validate masteryLevel is an integer in range [0, 2] */
function safeMasteryLevel(val: unknown): number {
const n = typeof val === 'number' ? val : parseInt(String(val), 10);
@@ -187,6 +226,7 @@ export async function POST(req: Request) {
tagsCreated: 0,
errorItemsCreated: 0,
reviewSchedulesCreated: 0,
examPapersCreated: 0,
practiceRecordsCreated: 0,
tagsLinked: 0,
duplicateErrorItems: 0,
@@ -402,12 +442,76 @@ export async function POST(req: Request) {
}
}
// 6. 导入 practice records
// 6. 导入试卷:同一用户下标题和创建时间都相同视为已导入过,只建立题目映射
const examQuestionIdMap = new Map<string, string>();
const examQuestionOwnerMap = new Map<string, string>();
for (const paper of (body.examPapers || [])) {
const targetUserId = importAll ? paper.userId : user.id;
const questions = Array.isArray(paper.questions) ? paper.questions : [];
const createdAt = safeParseDate(paper.createdAt);
const existing = createdAt && await tx.examPaper.findFirst({
where: { userId: targetUserId, title: paper.title, createdAt },
select: { questions: { select: { id: true, order: true } } },
});
if (existing) {
for (const question of questions) {
const matched = existing.questions.find((candidate) => candidate.order === question.order);
if (matched) {
examQuestionIdMap.set(question.id, matched.id);
examQuestionOwnerMap.set(question.id, targetUserId);
}
}
continue;
}
// 导出时还在生成的题目不会继续生成,按失败处理,可在试卷页重新生成
const statuses = questions.map((question) => (question.status === 'ready' ? 'ready' : 'failed'));
const created = await tx.examPaper.create({
data: {
userId: targetUserId,
title: String(paper.title || ''),
status: statuses.length > 0 ? summarizePaperStatus(statuses) : 'failed',
scope: (EXAM_SCOPES as readonly string[]).includes(paper.scope) ? paper.scope : 'all',
difficulty: (EXAM_DIFFICULTIES as readonly string[]).includes(paper.difficulty) ? paper.difficulty : 'medium',
requestedCount: Number.isInteger(paper.requestedCount) && paper.requestedCount > 0 ? paper.requestedCount : questions.length,
subjectIds: mapSubjectIds(paper.subjectIds, subjectIdMap),
tagNames: typeof paper.tagNames === 'string' ? paper.tagNames : null,
resultsRecordedAt: safeParseDate(paper.resultsRecordedAt),
createdAt,
updatedAt: safeParseDate(paper.updatedAt),
},
});
for (const [index, question] of questions.entries()) {
const errorItemId = question.errorItemId && errorItemOwnerMap.get(question.errorItemId) === targetUserId
? errorItemIdMap.get(question.errorItemId) : undefined;
const createdQuestion = await tx.examQuestion.create({
data: {
paperId: created.id,
order: Number.isInteger(question.order) ? question.order : index,
errorItemId,
sourceShortId: String(question.sourceShortId || ''),
status: statuses[index],
questionText: question.questionText,
answerText: question.answerText,
analysis: question.analysis,
figureSvg: sanitizeFigureSvg(question.figureSvg),
error: question.error,
},
});
examQuestionIdMap.set(question.id, createdQuestion.id);
examQuestionOwnerMap.set(question.id, targetUserId);
}
stats.examPapersCreated++;
}
// 7. 导入 practice records
for (const record of (body.practiceRecords || [])) {
const targetUserId = importAll ? record.userId : user.id;
const errorItemId = record.errorItemId && errorItemOwnerMap.get(record.errorItemId) === targetUserId
? errorItemIdMap.get(record.errorItemId) : undefined;
const result = isPracticeResult(record.result) ? record.result : undefined;
const examQuestionId = record.examQuestionId && examQuestionOwnerMap.get(record.examQuestionId) === targetUserId
? examQuestionIdMap.get(record.examQuestionId) : undefined;
await tx.practiceRecord.create({
data: {
userId: targetUserId,
@@ -425,6 +529,7 @@ export async function POST(req: Request) {
originalImageUrl: record.originalImageUrl,
figureSvg: sanitizeFigureSvg(record.figureSvg),
source: ['practice', 'manual', 'exam', 'duplicate_import'].includes(record.source || '') ? record.source : 'practice',
examQuestionId,
} : {}),
createdAt: safeParseDate(record.createdAt),
},

View File

@@ -418,12 +418,13 @@ export function SettingsDialog() {
const stats = (response as any).stats;
toast.success(
(t.settings?.importResultDesc || "Imported {subjects} notebooks, {tags} tags, {items} error items, {schedules} review schedules, {records} practice records.")
(t.settings?.importResultDesc || "Imported {subjects} notebooks, {tags} tags, {items} error items, {schedules} review schedules, {records} practice records, {papers} exam papers.")
.replace('{subjects}', String(stats.subjectsCreated))
.replace('{tags}', String(stats.tagsCreated))
.replace('{items}', String(stats.errorItemsCreated))
.replace('{schedules}', String(stats.reviewSchedulesCreated))
.replace('{records}', String(stats.practiceRecordsCreated))
.replace('{papers}', String(stats.examPapersCreated ?? 0))
.replace('{duplicates}', String(stats.duplicateErrorItems ?? 0))
);
@@ -458,12 +459,13 @@ export function SettingsDialog() {
if (result.success) {
const s = result.stats;
toast.success(
(t.settings?.importResultDesc || "Imported {subjects} notebooks, {tags} tags, {items} error items, {schedules} review schedules, {records} practice records.")
(t.settings?.importResultDesc || "Imported {subjects} notebooks, {tags} tags, {items} error items, {schedules} review schedules, {records} practice records, {papers} exam papers.")
.replace('{subjects}', String(s.subjectsCreated))
.replace('{tags}', String(s.tagsCreated))
.replace('{items}', String(s.errorItemsCreated))
.replace('{schedules}', String(s.reviewSchedulesCreated))
.replace('{records}', String(s.practiceRecordsCreated))
.replace('{papers}', String(s.examPapersCreated ?? 0))
.replace('{duplicates}', String(s.duplicateErrorItems ?? 0))
);
setSelectedFile(null);

View File

@@ -544,7 +544,7 @@ export const translations = {
importFailed: "Import failed",
importConfirm: "Are you sure you want to import? This will add new data to your account without deleting existing data.",
importResult: "Import Result",
importResultDesc: "Imported {subjects} notebooks, {tags} tags, {items} error items, {schedules} review schedules, {records} practice records. {duplicates} duplicate questions were skipped and recorded as incorrect attempts.",
importResultDesc: "Imported {subjects} notebooks, {tags} tags, {items} error items, {schedules} review schedules, {records} practice records, {papers} exam papers. {duplicates} duplicate questions were skipped and recorded as incorrect attempts.",
exportAllData: "Export All",
exportAllConfirm: "Export all users' data? This may take a while.",
importAllData: "Import All",
@@ -1570,7 +1570,7 @@ export const translations = {
importFailed: "导入失败",
importConfirm: "确定要导入数据吗?导入操作将添加新数据到您的账户中,不会删除现有数据。",
importResult: "导入结果",
importResultDesc: "已导入 {subjects} 个笔记本、{tags} 个标签、{items} 道错题、{schedules} 条复习计划、{records} 条练习记录。另有 {duplicates} 道重复题目未重复导入,已记录本次相同题目的做错信息。",
importResultDesc: "已导入 {subjects} 个笔记本、{tags} 个标签、{items} 道错题、{schedules} 条复习计划、{records} 条练习记录、{papers} 份试卷。另有 {duplicates} 道重复题目未重复导入,已记录本次相同题目的做错信息。",
exportAllData: "导出全部",
exportAllConfirm: "导出所有用户的数据?这可能需要一些时间。",
importAllData: "导入全部",