Files
wrong-notebook/src/lib/backup/format.ts
margrop 9c4094ab5a feat: 共享错题本随备份导出与恢复
- 备份版本升至 27,导出共享成员邮箱、角色与状态
- 个人备份包含自有错题本中成员录入的题目
- 导入按成员邮箱重建共享关系,已存在时更新角色,缺失成员跳过
- 补充共享备份往返、缺员与旧版兼容集成测试,同步文档
Refs: https://github.com/margrop/wrong-notebook/issues/73
2026-12-03 15:15:14 +08:00

556 lines
19 KiB
TypeScript

import { z } from "zod";
import {
MAX_BACKUP_BANK_QUESTIONS,
MAX_BACKUP_ERROR_ITEMS,
MAX_BACKUP_EXAM_PAPERS,
MAX_BACKUP_EXAM_QUESTIONS,
MAX_BACKUP_PAPER_GROUPS,
MAX_BACKUP_PRACTICE_QUESTIONS,
MAX_BACKUP_PRACTICE_RECORDS,
MAX_BACKUP_QUESTION_BANKS,
MAX_BACKUP_REVIEW_SCHEDULES,
MAX_BACKUP_TAGS,
} from "@/lib/backup/limits";
/**
* 备份文件的格式定义,导出与导入共用。
* 导出侧写出的结构是导入侧可接受结构的超集;旧版本缺失的字段在类型上标为可选。
* 日期字段在导出侧为 Prisma 返回的 Date,JSON 序列化后即为 ISO 字符串,
* 因此类型上同时接受 string 与 Date。
*
* AI 调用次数(AiUsage)与 token 用量(AiCompletion)属于运行统计,不进入备份;
* 外部账号(ExternalAccount)含扩展保存的凭据,也不进入备份。
*/
/** 当前备份文件版本号 */
export const BACKUP_VERSION = 27;
/** 备份文件中的用户对象 */
export interface BackupUser {
id: string;
email: string;
name: string | null;
educationStage: string | null;
enrollmentYear: number | null;
role: string;
/** version 2 起导出 */
confirmBeforeImport?: boolean;
gradeRecognitionMode?: string;
fixedGradeSemester?: string | null;
questionDuplicateThreshold?: number;
masteryThreshold?: number;
enableGeogebra?: boolean;
enableSvgAnimation?: boolean;
themePreference?: string;
/** version 20 起导出;旧版缺失时按试卷处理 */
mobileNavFourth?: string;
}
/** 备份文件中的学科 */
export interface BackupSubject {
id: string;
name: string;
/** 旧版导出文件没有 */
stage?: string | null;
/** 旧版导出文件没有 */
subjectKey?: string | null;
/** 旧版导出文件没有,缺省 default */
tagSet?: string;
userId: string;
createdAt: string | Date;
updatedAt: string | Date;
}
/** 错题本共享关系(version 27 起导出;按成员邮箱重建,避免跨实例用户 ID 不一致) */
export interface BackupNotebookShare {
id: string;
subjectId: string;
memberEmail: string;
memberName?: string | null;
invitedByEmail?: string | null;
/** read 只读 | edit 可编辑 */
role: string;
/** invited 待接受 | active 已生效 */
status: string;
createdAt: string | Date;
updatedAt: string | Date;
}
/** 备份文件中的系统标签(version 3 起导出) */
export interface BackupSystemTag {
id: string;
name: string;
subject: string;
parentId: string | null;
order: number;
code: string | null;
isSystem: boolean;
tagSet: string;
createdAt: string | Date;
updatedAt: string | Date;
}
/** 备份文件中的自定义标签 */
export interface BackupCustomTag {
id: string;
name: string;
subject: string;
parentId: string | null;
order: number;
code: string | null;
isSystem: boolean;
/** 旧版导出文件没有,缺省 default */
tagSet?: string;
userId: string | null;
createdAt: string | Date;
updatedAt: string | Date;
}
/** 备份文件中的错题标签引用 */
export interface BackupErrorItemTag {
id: string;
name: string;
subject: string;
}
/** 备份文件中的错题 */
export interface BackupErrorItem {
id: string;
/** 旧版导出文件没有 */
shortId?: string | null;
/** 用户内的错题流水号;第 15 版起导出,旧版导出文件没有 */
seqNo?: number | null;
userId: string;
subjectId: string | null;
originalImageUrl: string;
ocrText: string | null;
questionText: string | null;
answerText: string | null;
analysis: string | null;
/** AI 生成的解析配图(SVG);第 22 版起导出,旧版备份缺省为无 */
analysisFigureSvg?: string | null;
wrongAnswerText: string | null;
mistakeAnalysis: string | null;
mistakeStatus: string | null;
knowledgePoints: string | null;
source: string | null;
errorType: string | null;
userNotes: string | null;
masteryLevel: number;
gradeSemester: string | null;
paperLevel: string | null;
/** 旧版导出文件没有该字段 */
difficultyStars?: number | null;
/** 旧版导出文件没有该字段 */
hasFigure?: boolean;
/** 旧版导出文件没有该字段 */
figureSvg?: string | null;
/** 识别时裁剪的原配图(PNG data URI);第 17 版起导出 */
figureImage?: string | null;
/** 用户手动上传的清晰配图;第 21 版起导出,旧版备份缺省为无 */
figureUploadImage?: string | null;
/** 配图显示来源;旧版备份缺省为 svg */
figureSource?: string;
/** 旧版备份缺省为 100% */
figureScale?: number;
/** 旧版备份缺省为居中 */
figureAlign?: string;
/** version 4 起导出,旧版备份缺省为按全局留白档位 */
answerSpacePx?: number | null;
/** version 9 起导出,旧版备份缺省为 null */
questionType?: string | null;
/** 多小问结构化内容(JSON);version 26 起导出,旧版备份缺省为 null */
subQuestions?: string | null;
/** 以下字段 version 2 起导出 */
geogebraCommands?: string | null;
svgAnimation?: string | null;
svgAnimationEn?: string | null;
lastPractice?: string | null;
masteryProbability?: number | null;
masteryReason?: string | null;
masterySource?: string | null;
masteryEvaluatedAt?: string | Date | null;
createdAt: string | Date;
updatedAt: string | Date;
tags: BackupErrorItemTag[];
}
/** 备份文件中的复习计划 */
export interface BackupReviewSchedule {
id: string;
errorItemId: string;
scheduledFor: string | Date;
completedAt: string | Date | null;
isCorrect: boolean | null;
createdAt: string | Date;
}
/** 备份文件中的练习记录 */
export interface BackupPracticeRecord {
id: string;
userId: string;
subject: string | null;
difficulty: string | null;
isCorrect: boolean | null;
errorItemId?: string | null;
result?: string | null;
questionText?: string | null;
answerText?: string | null;
analysis?: string | null;
wrongAnswerText?: string | null;
mistakeAnalysis?: string | null;
originalImageUrl?: string | null;
figureSvg?: string | null;
source?: string;
examQuestionId?: string | null;
/** 独立生成题 ID;第 16 版起导出 */
practiceQuestionId?: string | null;
createdAt: string | Date;
}
/** 备份文件中的智能练习生成题(version 16 起导出) */
export interface BackupPracticeQuestion {
id: string;
userId: string;
errorItemId: string | null;
subject: string | null;
difficulty: string | null;
source: string;
questionText: string;
answerText: string;
analysis: string;
figureSvg: string | null;
generatedAt: string | Date;
createdAt: string | Date;
}
/** 备份文件中的试卷题目 */
export interface BackupExamQuestion {
id: string;
order: number;
errorItemId: string | null;
/** version 23 起导出;真题库来源题目 ID 快照,旧版备份缺省为 null */
bankQuestionId?: string | null;
sourceShortId: string;
status: string;
questionText: string | null;
answerText: string | null;
analysis: string | null;
figureSvg: string | null;
/** 来源错题裁剪的原配图快照(PNG data URI);version 19 起导出 */
figureImage?: string | null;
/** 来源错题手动上传的清晰配图快照;version 21 起导出 */
figureUploadImage?: string | null;
/** 配图显示来源;旧版备份缺省为 svg */
figureSource?: string;
/** 旧版备份缺省为 100% */
figureScale?: number;
/** 旧版备份缺省为居中 */
figureAlign?: string;
/** version 4 起导出,旧版备份缺省为按全局留白档位 */
answerSpacePx?: number | null;
/** version 10 起导出,旧版备份缺省为未设分值 */
score?: number | null;
/** version 11 起导出,旧版备份缺省为 null(分组时回退读取关联错题当前题型) */
questionType?: string | null;
/** version 25 起导出,旧版备份缺省为 null(打印定位标记未开启) */
printRegions?: string | null;
error: string | null;
}
/** 备份文件中的试卷(version 2 起导出) */
export interface BackupExamPaper {
id: string;
userId: string;
title: string;
status: string;
scope: string;
difficulty: string;
/** version 8 起导出,旧版缺省 generate */
mode?: string;
/** version 11 起导出,旧版缺省 false(不按题型分大题) */
groupByType?: boolean;
requestedCount: number;
subjectIds: string;
tagNames: string | null;
resultsRecordedAt: string | Date | null;
createdAt: string | Date;
updatedAt: string | Date;
questions: BackupExamQuestion[];
}
/** 自定义题型(version 24 起导出) */
export interface BackupCustomQuestionType {
id: string;
userId: string;
/** 稳定 key,如 custom_1;错题的 questionType 存此值 */
key: string;
nameZh: string;
nameEn: string | null;
instructions: string | null;
order: number;
isActive: boolean;
createdAt: string | Date;
updatedAt: string | Date;
}
/** 卷别分组(version 3 起导出) */
export interface BackupPaperGroup {
id: string;
userId: string;
key: string | null;
name: string;
order: number;
isActive: boolean;
createdAt: string | Date;
updatedAt: string | Date;
}
/** fork 扩展数据(version 7 起导出) */
export interface BackupExtensionEntry {
version: number;
data: unknown;
}
/** 真题库题目(version 14 起导出) */
export interface BackupBankQuestion {
id: string;
externalId: string | null;
stage: string;
subjectKey: string | null;
grade: number | null;
semester: string | null;
questionType: string | null;
difficultyStars: number | null;
text: string;
material: string | null;
optionsJson: string | null;
answer: string | null;
analysis: string | null;
knowledgePoints: string | null;
source: string | null;
figureSvg: string | null;
createdAt: string | Date;
}
/** 全站共享的真题库(version 14 起导出;18 起不再带 userId) */
export interface BackupQuestionBank {
id: string;
name: string;
description: string | null;
stage: string;
subjectKey: string | null;
gradeRange: string | null;
source: string | null;
sourceUrl: string | null;
license: string | null;
formatVersion: number;
questionCount: number;
createdAt: string | Date;
updatedAt: string | Date;
questions: BackupBankQuestion[];
}
/** 备份文件的顶层结构:导出侧写出的结构 */
export interface BackupFile {
version: number;
exportedAt: string;
scope: string;
user: BackupUser;
subjects: BackupSubject[];
/** 错题本共享关系(version 27 起导出) */
notebookShares?: BackupNotebookShare[];
systemTags: BackupSystemTag[];
customTags: BackupCustomTag[];
errorItems: BackupErrorItem[];
reviewSchedules: BackupReviewSchedule[];
practiceRecords: BackupPracticeRecord[];
/** 智能练习生成题(version 16 起导出) */
practiceQuestions: BackupPracticeQuestion[];
examPapers: BackupExamPaper[];
paperGroups: BackupPaperGroup[];
/** 用户自定义题型(version 24 起导出) */
customQuestionTypes: BackupCustomQuestionType[];
/** 全站共享的真题库(version 14 起导出) */
questionBanks: BackupQuestionBank[];
/** 动画讲解的云端语音 */
ttsSpeeches: unknown[];
/** 未处理的识别导入任务(version 5 起导出) */
importTasks: unknown[];
/** 未完成的多题批次(version 6 起导出) */
importBatches: unknown[];
/** fork 扩展数据(version 7 起导出) */
extensions: Record<string, BackupExtensionEntry>;
}
/** 导入侧日期类型:JSON 解析后总是字符串 */
type ImportedDate = string;
/** 导入侧的学科:日期字段为字符串 */
export type ImportedBackupSubject = Omit<BackupSubject, "createdAt" | "updatedAt"> & {
createdAt: ImportedDate;
updatedAt: ImportedDate;
};
/** 导入侧的错题本共享关系 */
export type ImportedBackupNotebookShare = Omit<BackupNotebookShare, "createdAt" | "updatedAt"> & {
createdAt: ImportedDate;
updatedAt: ImportedDate;
};
/** 导入侧的系统标签 */
export type ImportedBackupSystemTag = Omit<BackupSystemTag, "createdAt" | "updatedAt"> & {
createdAt: ImportedDate;
updatedAt: ImportedDate;
};
/** 导入侧的自定义标签 */
export type ImportedBackupCustomTag = Omit<BackupCustomTag, "createdAt" | "updatedAt"> & {
createdAt: ImportedDate;
updatedAt: ImportedDate;
};
/** 导入侧的错题 */
export type ImportedBackupErrorItem = Omit<BackupErrorItem, "masteryEvaluatedAt" | "createdAt" | "updatedAt"> & {
masteryEvaluatedAt?: ImportedDate | null;
createdAt: ImportedDate;
updatedAt: ImportedDate;
};
/** 导入侧的复习计划 */
export type ImportedBackupReviewSchedule = Omit<BackupReviewSchedule, "scheduledFor" | "completedAt" | "createdAt"> & {
scheduledFor: ImportedDate;
completedAt: ImportedDate | null;
createdAt: ImportedDate;
};
/** 导入侧的练习记录 */
export type ImportedBackupPracticeRecord = Omit<BackupPracticeRecord, "createdAt"> & {
createdAt: ImportedDate;
};
/** 导入侧的智能练习生成题 */
export type ImportedBackupPracticeQuestion = Omit<BackupPracticeQuestion, "generatedAt" | "createdAt"> & {
generatedAt: ImportedDate;
createdAt: ImportedDate;
};
/** 导入侧的试卷 */
export type ImportedBackupExamPaper = Omit<BackupExamPaper, "resultsRecordedAt" | "createdAt" | "updatedAt"> & {
resultsRecordedAt: ImportedDate | null;
createdAt: ImportedDate;
updatedAt: ImportedDate;
};
/** 导入侧的自定义题型 */
export type ImportedBackupCustomQuestionType = Omit<BackupCustomQuestionType, "createdAt" | "updatedAt"> & {
createdAt: ImportedDate;
updatedAt: ImportedDate;
};
/** 导入侧的卷别分组 */
export type ImportedBackupPaperGroup = Omit<BackupPaperGroup, "createdAt" | "updatedAt"> & {
createdAt: ImportedDate;
updatedAt: ImportedDate;
};
/** 导入侧的真题库题目 */
export type ImportedBackupBankQuestion = Omit<BackupBankQuestion, "createdAt"> & {
createdAt: ImportedDate;
};
/** 导入侧的真题库 */
export type ImportedBackupQuestionBank = Omit<BackupQuestionBank, "createdAt" | "updatedAt" | "questions"> & {
createdAt: ImportedDate;
updatedAt: ImportedDate;
questions: ImportedBackupBankQuestion[];
};
/**
* 导入侧可接受的备份结构。旧版本缺失的顶层字段标为可选,
* 日期字段在导入侧为字符串(JSON 解析结果),避免拒绝旧版本备份。
*/
export interface ImportableBackupFile {
version: number;
/** 旧版导出文件可能没有 */
exportedAt?: string;
scope?: string;
user: BackupUser;
subjects?: ImportedBackupSubject[];
/** 旧版导出文件没有 */
notebookShares?: ImportedBackupNotebookShare[];
systemTags?: ImportedBackupSystemTag[];
customTags?: ImportedBackupCustomTag[];
errorItems: ImportedBackupErrorItem[];
reviewSchedules?: ImportedBackupReviewSchedule[];
practiceRecords?: ImportedBackupPracticeRecord[];
practiceQuestions?: ImportedBackupPracticeQuestion[];
examPapers?: ImportedBackupExamPaper[];
paperGroups?: ImportedBackupPaperGroup[];
customQuestionTypes?: ImportedBackupCustomQuestionType[];
questionBanks?: ImportedBackupQuestionBank[];
ttsSpeeches?: unknown;
importTasks?: unknown;
importBatches?: unknown;
extensions?: unknown;
/** 允许未知顶层字段(未来版本扩展) */
[key: string]: unknown;
}
const backupIdObjectSchema = z.object({ id: z.string().min(1).max(200) }).passthrough();
const backupTagSchema = backupIdObjectSchema.extend({
name: z.string().max(500).optional(),
subject: z.string().max(100).optional(),
});
const backupNotebookShareSchema = backupIdObjectSchema.extend({
subjectId: z.string().min(1).max(200),
memberEmail: z.string().min(1).max(320),
invitedByEmail: z.string().max(320).optional(),
role: z.string().max(20).optional(),
status: z.string().max(20).optional(),
});
const backupExamPaperSchema = backupIdObjectSchema.extend({
questions: z.array(z.unknown()).max(MAX_BACKUP_EXAM_QUESTIONS).optional(),
});
const backupQuestionBankSchema = backupIdObjectSchema.extend({
questions: z.array(z.unknown()).max(MAX_BACKUP_BANK_QUESTIONS).optional(),
});
/**
* 顶层 schema 保持对未来字段的宽容,但对会进入导入写入器的嵌套数组做结构与数量校验。
* 这样旧版缺字段仍可由 import-parser 补默认值,null 项和超大数组会在入口明确拒绝。
*/
const backupFileSchema = z.object({
version: z.number(),
user: z.record(z.string(), z.unknown()),
errorItems: z.array(backupIdObjectSchema).max(MAX_BACKUP_ERROR_ITEMS),
subjects: z.array(backupIdObjectSchema).max(MAX_BACKUP_TAGS).optional(),
notebookShares: z.array(backupNotebookShareSchema).max(MAX_BACKUP_TAGS).optional(),
systemTags: z.array(backupTagSchema).max(MAX_BACKUP_TAGS).optional(),
customTags: z.array(backupTagSchema).max(MAX_BACKUP_TAGS).optional(),
reviewSchedules: z.array(z.record(z.string(), z.unknown())).max(MAX_BACKUP_REVIEW_SCHEDULES).optional(),
practiceRecords: z.array(z.record(z.string(), z.unknown())).max(MAX_BACKUP_PRACTICE_RECORDS).optional(),
practiceQuestions: z.array(z.record(z.string(), z.unknown())).max(MAX_BACKUP_PRACTICE_QUESTIONS).optional(),
examPapers: z.array(backupExamPaperSchema).max(MAX_BACKUP_EXAM_PAPERS).optional(),
paperGroups: z.array(z.record(z.string(), z.unknown())).max(MAX_BACKUP_PAPER_GROUPS).optional(),
customQuestionTypes: z.array(z.record(z.string(), z.unknown())).max(MAX_BACKUP_TAGS).optional(),
questionBanks: z.array(backupQuestionBankSchema).max(MAX_BACKUP_QUESTION_BANKS).optional(),
importTasks: z.array(z.unknown()).max(MAX_BACKUP_ERROR_ITEMS).optional(),
importBatches: z.array(z.unknown()).max(MAX_BACKUP_EXAM_PAPERS).optional(),
}).passthrough();
export type ParseBackupFileResult =
| { success: true; data: ImportableBackupFile }
| { success: false; error: string };
/** 解析并校验备份文件的顶层结构,失败时返回可读错误 */
export function parseBackupFile(input: unknown): ParseBackupFileResult {
const result = backupFileSchema.safeParse(input);
if (!result.success) {
const issues = result.error.issues
.map((issue) => `${issue.path.join(".") || "root"}: ${issue.message}`)
.join("; ");
return { success: false, error: `Invalid backup file: ${issues}` };
}
return { success: true, data: result.data as unknown as ImportableBackupFile };
}