fix: 试卷打印的来源编号按题目编号设置显示

Refs: https://github.com/margrop/wrong-notebook/issues/34
This commit is contained in:
margrop
2026-11-22 18:19:58 +08:00
parent a04322668c
commit 84c3cbcbee
10 changed files with 121 additions and 31 deletions

View File

@@ -32,7 +32,7 @@
每道题同时有两个编号:创建时生成的 6 位 ID(如 `oYMCZa`),以及每个用户从 `#1000` 起依次递增的流水号。升级到支持流水号的版本时,已有题目按录入时间自动补齐流水号;删除题目后编号不回收,新题继续往后编。
管理员在“设置 → 通用 → 题目编号显示方式”中选择列表、详情、打印和导入结果中显示哪一种,默认显示 6 位 ID,可随时切换,不改动数据。设置保存在 `config/app-config.json` 的 `questionNumbering` 字段(`shortId` 或 `seqNo`)。无论显示哪一种,错题本搜索和按编号定位都同时支持 6 位 ID 和流水号(可带或不带 `#`);题目链接、MCP 接口和试卷中的来源记录继续使用 6 位 ID。流水号随 JSON 备份导出,恢复时编号未被占用则保留,否则按顺序分配新编号。
管理员在“设置 → 通用 → 题目编号显示方式”中选择列表、详情、打印和导入结果中显示哪一种,默认显示 6 位 ID,可随时切换,不改动数据。设置保存在 `config/app-config.json` 的 `questionNumbering` 字段(`shortId` 或 `seqNo`)。无论显示哪一种,错题本搜索和按编号定位都同时支持 6 位 ID 和流水号(可带或不带 `#`);题目链接和 MCP 接口继续使用 6 位 ID,试卷中的来源记录随题目编号设置显示。流水号随 JSON 备份导出,恢复时编号未被占用则保留,否则按顺序分配新编号。
## AI 配图比对校正

View File

@@ -32,7 +32,7 @@ Choose a rule under **Settings → General** and click **Save grade rule**. Regu
Every question has two numbers: the 6-character ID generated when it is created (such as `oYMCZa`), and a serial number that counts up from `#1000` for each user. When upgrading to a version with serial numbers, existing questions are numbered automatically in the order they were added; numbers of deleted questions are not reused, and new questions continue from the last number.
Admins choose which number is shown in lists, details, printouts and import results in "Settings → General → Question number display". The 6-character ID is the default, and the setting can be switched at any time without changing any data. It is stored in the `questionNumbering` field of `config/app-config.json` (`shortId` or `seqNo`). Whichever is shown, notebook search and locate-by-number accept both the 6-character ID and the serial number (with or without `#`); question links, the MCP interface and source records in exam papers keep using the 6-character ID. Serial numbers are exported with JSON backups; on restore a number is kept if it is free, otherwise the next number is assigned.
Admins choose which number is shown in lists, details, printouts and import results in "Settings → General → Question number display". The 6-character ID is the default, and the setting can be switched at any time without changing any data. It is stored in the `questionNumbering` field of `config/app-config.json` (`shortId` or `seqNo`). Whichever is shown, notebook search and locate-by-number accept both the 6-character ID and the serial number (with or without `#`); question links and the MCP interface keep using the 6-character ID; source records in exam papers follow the question number setting. Serial numbers are exported with JSON backups; on restore a number is kept if it is free, otherwise the next number is assigned.
## AI figure self-check

View File

@@ -330,6 +330,40 @@ describe('/api/exams', () => {
expect(response.status).toBe(404);
});
it('GET 详情返回来源短 ID 与流水号', async () => {
mocks.examPaper.findUnique.mockResolvedValue({
id: 'p1',
userId: 'user-1',
status: 'ready',
groupByType: false,
questions: [{
id: 'q1',
order: 0,
sourceShortId: 'AbC234',
errorItem: { id: 'ei1', shortId: 'AbC234', seqNo: 42, questionType: null, subject: { name: '数学' } },
practiceRecords: [],
}],
});
const response = await DETAIL(new Request('http://localhost'), params('p1'));
const data = await response.json();
expect(response.status).toBe(200);
expect(data.questions[0].sourceSeqNo).toBe(42);
expect(data.questions[0].sourceShortId).toBe('AbC234');
expect(mocks.examPaper.findUnique).toHaveBeenCalledWith(expect.objectContaining({
include: expect.objectContaining({
questions: expect.objectContaining({
include: expect.objectContaining({
errorItem: expect.objectContaining({
select: expect.objectContaining({ shortId: true, seqNo: true }),
}),
}),
}),
}),
}));
});
it('DELETE 只删除自己的试卷', async () => {
mocks.examPaper.findUnique.mockResolvedValue({ userId: 'user-1' });

View File

@@ -2,9 +2,15 @@ import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import { ExamPrintSheet } from '@/app/exams/[id]/print/exam-print-sheet';
import { LanguageProvider } from '@/contexts/LanguageContext';
import { QuestionNumberingProvider } from '@/contexts/QuestionNumberingContext';
import type { QuestionNumbering } from '@/lib/seq-no/seq-no-format';
import type { ExamPaperDetail } from '@/types/api';
const render = (element: React.ReactElement) => renderToStaticMarkup(<LanguageProvider>{element}</LanguageProvider>);
const render = (element: React.ReactElement, numbering: QuestionNumbering = 'shortId') => renderToStaticMarkup(
<LanguageProvider>
<QuestionNumberingProvider initialNumbering={numbering}>{element}</QuestionNumberingProvider>
</LanguageProvider>
);
function buildPaper(questions: Partial<ExamPaperDetail['questions'][number]>[]): ExamPaperDetail {
return {
@@ -23,6 +29,7 @@ function buildPaper(questions: Partial<ExamPaperDetail['questions'][number]>[]):
order: index,
errorItemId: null,
sourceShortId: `S${index + 1}`,
sourceSeqNo: index + 101,
status: 'ready',
questionText: `题目 ${index + 1}`,
answerText: null,
@@ -64,6 +71,43 @@ describe('ExamPrintSheet 分值打印', () => {
expect(html).toContain('满分 4.5 分');
});
it('来源编号默认按短 ID 显示', () => {
const paper = buildPaper([{}]);
const html = render(
<ExamPrintSheet
paper={paper}
includeAnswers={false}
answerSpace="none"
customSpaces={{}}
uniformPreview={{ scale: null, align: null }}
onSaveFigureScale={NOOP}
onSaveFigureSource={NOOP}
onChangeCustomSpace={() => {}}
/>
);
expect(html).toContain('来源: S1');
expect(html).not.toContain('#101');
});
it('来源编号随题目编号设置显示流水号', () => {
const paper = buildPaper([{}]);
const html = render(
<ExamPrintSheet
paper={paper}
includeAnswers={false}
answerSpace="none"
customSpaces={{}}
uniformPreview={{ scale: null, align: null }}
onSaveFigureScale={NOOP}
onSaveFigureSource={NOOP}
onChangeCustomSpace={() => {}}
/>,
'seqNo',
);
expect(html).toContain('来源: #101');
expect(html).not.toContain('S1');
});
it('未设分值时打印与旧版一致:无满分行、题号后无分值', () => {
const paper = buildPaper([{}, {}]);
const html = render(

View File

@@ -48,7 +48,7 @@ const updateGroupByTypeSchema = z.object({
/**
* GET /api/exams/:id
* 试卷详情,含每题内容、来源短 ID 与历次录入的结果
* 试卷详情,含每题内容、来源编号(按题目编号设置显示)与历次录入的结果
*/
export const GET = withUser(async (
_req: Request,
@@ -63,7 +63,7 @@ export const GET = withUser(async (
questions: {
orderBy: { order: 'asc' },
include: {
errorItem: { select: { id: true, questionType: true, subject: { select: { name: true } } } },
errorItem: { select: { id: true, shortId: true, seqNo: true, questionType: true, subject: { select: { name: true } } } },
practiceRecords: { orderBy: [{ createdAt: 'asc' }, { id: 'asc' }], select: { id: true, result: true, createdAt: true } },
},
},
@@ -90,6 +90,7 @@ export const GET = withUser(async (
questionType: normalizeQuestionType(question.questionType),
errorItemQuestionType: normalizeQuestionType(errorItem?.questionType),
notebookName: errorItem?.subject?.name ?? null,
sourceSeqNo: errorItem?.seqNo ?? null,
attempts: practiceRecords,
})),
});

View File

@@ -6,6 +6,7 @@ import { MarkdownRenderer } from "@/components/markdown-renderer";
import { AnswerSpaceControl } from "@/components/print-preview/answer-space-control";
import { PrintQuestionText } from "@/components/print-preview/print-question-text";
import { useLanguage } from "@/contexts/LanguageContext";
import { useQuestionNo } from "@/contexts/QuestionNumberingContext";
import { stripFigureDescriptions } from "@/lib/question/question-similarity";
import { resolveQuestionAnswerSpacePx } from "@/lib/exam/exam-answer-space";
import type { AnswerSpaceMode } from "@/lib/exam/exam-answer-space";
@@ -52,6 +53,8 @@ function ExamPrintQuestion({
onChangeCustomSpace,
}: ExamPrintQuestionProps) {
const { t } = useLanguage();
const questionNo = useQuestionNo();
const sourceNo = questionNo({ shortId: question.sourceShortId, seqNo: question.sourceSeqNo }) ?? question.sourceShortId;
return (
<section className="exam-question">
<div className="exam-question-head">
@@ -59,7 +62,7 @@ function ExamPrintQuestion({
{displayNumber}.
{typeof question.score === 'number' && `(${formatExamScore(question.score)} ${scoreUnit})`}
</span>
<span className="exam-source">{t.exam.sourceLabel}: {question.sourceShortId}</span>
<span className="exam-source">{t.exam.sourceLabel}: {sourceNo}</span>
</div>
<PrintQuestionText content={question.figureSvg || question.figureImage
? stripFigureDescriptions(question.questionText!)
@@ -130,6 +133,7 @@ export const ExamPrintSheet = forwardRef<HTMLDivElement, ExamPrintSheetProps>(fu
onChangeCustomSpace,
}, ref) {
const { t, language } = useLanguage();
const questionNo = useQuestionNo();
const questions = paper.questions.filter((question) => question.status === "ready" && question.questionText);
// 满分只统计已设分值的题目;全部未设时不显示满分行,打印与旧版一致
const fullScore = summarizeExamScores(questions.map((question) => question.score ?? null)).total;
@@ -153,28 +157,30 @@ export const ExamPrintSheet = forwardRef<HTMLDivElement, ExamPrintSheetProps>(fu
);
// 答案页同样按大题分组,题号与正文一致
const renderAnswerKey = (items: ExamSectionItem<ExamQuestionDetail>[]) => (
items.map((item) => (
<div key={item.question.id} className="exam-question">
<div className="exam-question-head">
<span>{item.displayNumber}.</span>
<span className="exam-source">{t.exam.sourceLabel}: {item.question.sourceShortId}</span>
const renderAnswerKey = (items: ExamSectionItem<ExamQuestionDetail>[]) =>
items.map((item) => {
const sourceNo = questionNo({ shortId: item.question.sourceShortId, seqNo: item.question.sourceSeqNo }) ?? item.question.sourceShortId;
return (
<div key={item.question.id} className="exam-question">
<div className="exam-question-head">
<span>{item.displayNumber}.</span>
<span className="exam-source">{t.exam.sourceLabel}: {sourceNo}</span>
</div>
{item.question.answerText && (
<div>
<span className="exam-label">{t.exam.answerLabel}{t.common.colon}</span>
<MarkdownRenderer content={item.question.answerText} />
</div>
)}
{item.question.analysis && (
<div>
<span className="exam-label">{t.exam.analysisLabel}{t.common.colon}</span>
<MarkdownRenderer content={item.question.analysis} />
</div>
)}
</div>
{item.question.answerText && (
<div>
<span className="exam-label">{t.exam.answerLabel}{t.common.colon}</span>
<MarkdownRenderer content={item.question.answerText} />
</div>
)}
{item.question.analysis && (
<div>
<span className="exam-label">{t.exam.analysisLabel}{t.common.colon}</span>
<MarkdownRenderer content={item.question.analysis} />
</div>
)}
</div>
))
);
);
});
return (
<div ref={ref} className="exam-sheet">

View File

@@ -15,6 +15,7 @@ import { FigureScaleEditor } from "@/components/error-detail/figure-scale-editor
import { ExamQuestionRegenerate } from "@/components/exam/exam-question-regenerate";
import { ExamQuestionScoreInput } from "@/components/exam/exam-question-score-input";
import { useLanguage } from "@/contexts/LanguageContext";
import { useQuestionNo } from "@/contexts/QuestionNumberingContext";
import { stripFigureDescriptions } from "@/lib/question/question-similarity";
import type { FigureAlign } from "@/lib/figure-scale";
import type { ExamMode, ExamQuestionDetail, PracticeResult } from "@/types/api";
@@ -61,6 +62,8 @@ export function ExamQuestionCard({
}: ExamQuestionCardProps) {
const { t } = useLanguage();
const { timeZone } = useTimeZone();
const questionNo = useQuestionNo();
const sourceNo = questionNo({ shortId: question.sourceShortId, seqNo: question.sourceSeqNo }) ?? question.sourceShortId;
const [showAnswer, setShowAnswer] = useState(false);
const isEditing = editingResult !== undefined;
// AI 错误码(如 AI_AUTH_ERROR: ...)映射为界面提示
@@ -79,11 +82,11 @@ export function ExamQuestionCard({
<span className="font-semibold">{displayNumber ?? question.order}.</span>
{question.errorItemId ? (
<Link href={`/error-items/${question.errorItemId}`} className="font-mono text-xs text-primary hover:underline">
{t.exam.source} {question.sourceShortId}
{t.exam.source} {sourceNo}
</Link>
) : (
<span className="font-mono text-xs text-muted-foreground">
{question.sourceShortId} · {t.exam.sourceDeleted}
{sourceNo} · {t.exam.sourceDeleted}
</span>
)}
{question.notebookName && <Badge variant="secondary">{question.notebookName}</Badge>}

View File

@@ -1994,7 +1994,7 @@ export const en = {
answerKey: "Answer Key",
answerLabel: "Answer",
analysisLabel: "Analysis",
sourceLabel: "Source ID",
sourceLabel: "Source",
notReadyHint: "Questions that failed to generate are left out of the printout.",
uniformFigureScale: "Uniform figure scale",
uniformFigureScaleSlider: "Adjust figure scale for all questions",

View File

@@ -1993,7 +1993,7 @@ export const zh = {
answerKey: "参考答案与解析",
answerLabel: "答案",
analysisLabel: "解析",
sourceLabel: "来源 ID",
sourceLabel: "来源",
notReadyHint: "生成失败的题目不会出现在打印稿中。",
uniformFigureScale: "统一配图比例",
uniformFigureScaleSlider: "统一调整全卷配图比例",

View File

@@ -532,6 +532,8 @@ export interface ExamQuestionDetail {
errorItemQuestionType?: QuestionType | null;
error: string | null;
notebookName: string | null;
/** 来源错题流水号,用于按编号设置显示 */
sourceSeqNo?: number | null;
/** 历次录入的结果,按时间正序 */
attempts: ExamQuestionAttempt[];
}