fix(admin): 复核页选择题选项渲染修复 + 阅卷导出 Word + 评分两位小数(R28)

针对测试人员反馈的四项:
1) 复核明细「选择题大量空白」:options 为 text 列存 JSON 字符串,原先被原样透传,
   前端 v-for 对字符串逐字符迭代(op.key/op.text 皆 undefined)⇒ 每字符渲染一行。
   新增 parseOptions()(仅 string 才 JSON.parse,失败降级 null)。
2) 选项与答案不随机:仅题目用 RAND() 抽题,normalizeQuestion 无 shuffle,字母无歧义。
3) 评分精度:DECIMAL(6,1) -> DECIMAL(6,2),migration 026 覆盖 17 列(与 025 同范围),
   lib/decimal_score.js 与 11 个 model 注释同步;汇总收敛 round2(×100/100)。
4) 阅卷导出:GET /api/admin/big-answers/:group/export?ids=
   单选考生 -> 直接 .docx;多位/全部 -> 每位考生单独 .docx 打包 .zip。
   路由为 3 段,注册在 :group 通配段之前。

验证:verify_big_question 51 PASS/1 FAIL(唯一 FAIL=测试人员新数据,非本次改动)、
verify_score_leak_all_channels 24/24、verify_question_no_answer_leak 4/3/0/1。
This commit is contained in:
2026-09-28 15:50:46 +08:00
parent 37d07907a1
commit 2ab0991310
16 changed files with 330 additions and 34 deletions

View File

@@ -1739,6 +1739,49 @@ class AdminController extends Controller {
}
}
/**
* 导出考生大题答卷为 Word(2026-09-28 需求:阅卷评分需将「试题 + 考生答案」导出)
* GET /api/admin/big-answers/:group/export?ids=1,2,3
* · 传 ids → 导出指定考生的答卷;不传 → 该组**全部已抽题**考生
* · 命中 1 位 → 直接返回 .docx
* · 命中多位 → 返回「每人一个独立 .docx」打包的 .zip(⛔ 不塞进同一个 Word)
*
* ⚠️ 与 `PUT /big-answers/:group/:uid/scores` 方法不同、段数不同,不会互相吞并。
* ⚠️ 只调 ctx.attachment(原名):koa 自动做 RFC5987 编码;自行 encodeURIComponent 会
* 双重编码导致中文文件名乱码(同源缺陷族,见 exportBigQuestions 注释)。
*/
async exportBigAnswers() {
const { ctx, service } = this;
if (!this._ensureAdmin()) return;
try {
const { group } = ctx.params;
if (!this._validateGroup(group)) return;
const result = await service.bigQuestion.exportAnswers(group, ctx.query.ids);
if (!result.ok) {
const httpStatus = result.code === 'NOT_FOUND' ? 404 : 400;
ctx.body = ctx.helper.error(httpStatus, result.message);
return;
}
ctx.set(
'Content-Type',
result.isZip
? 'application/zip'
: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
);
ctx.attachment(result.fileName);
// 前端需知道本次导出了几位考生(响应体是二进制,读不到)
ctx.set('X-Export-Count', String(result.count));
ctx.body = result.buffer;
} catch (err) {
ctx.logger.error('导出考生大题答卷失败:', err);
ctx.body = ctx.helper.error(500, '导出考生大题答卷失败');
}
}
/**
* 新增大题
* POST /api/admin/big-questions/:group

View File

@@ -1,16 +1,17 @@
'use strict';
/**
* 分数列类型工厂(2026-09-23:大题人工评分允许小数点后一位)
* 分数列类型工厂(2026-09-28:大题人工评分精确到小数点后**两位**)
*
* 用法(在 model 文件内):
* const decimalScore = require('../lib/decimal_score')(app);
* ...
* word_score: decimalScore('word_score', 'Word题/综合大题得分(可含 1 位小数)'),
* word_score: decimalScore('word_score', 'Word题/综合大题得分(可含 2 位小数)'),
*
* ⚠️ 三处必须同时成立,小数才不会被截断或变形:
* ① DB 列 = DECIMAL
* → database/migrations/025-scores-decimal-one-place.sql
* → database/migrations/025-scores-decimal-one-place.sql(INT(11) → DECIMAL(6,1))
* → database/migrations/026-scores-decimal-two-places.sql((6,1) → (6,2) ← 现行)
* ② model 声明 = DECIMAL(本文件)
* → 若仍写 INTEGER,Sequelize 读取时会走 INTEGER.parse(parseInt),
* 把 7.5 **静默截成 7**,且不报任何错
@@ -27,7 +28,9 @@ module.exports = app => {
return function decimalScore(field, comment, extra = {}) {
return Object.assign({
type: DECIMAL(6, 1), // 上限 99999.9,足够覆盖总分/单题分
// 上限 9999.99,足够覆盖总分 / 单题分;两位小数满足阅卷评分精度
// ⚠️ 改这里必须同步 database/migrations/026-scores-decimal-two-places.sql
type: DECIMAL(6, 2),
allowNull: true,
comment,
get() {

View File

@@ -10,7 +10,7 @@
module.exports = app => {
const { STRING, INTEGER, BOOLEAN, DATE } = app.Sequelize;
// 分数列统一走共享工厂(DECIMAL(6,1) + Number 兜底,见 app/lib/decimal_score.js)
// 分数列统一走共享工厂(DECIMAL(6,2) + Number 兜底,见 app/lib/decimal_score.js)
const decimalScore = require('../lib/decimal_score')(app);
const Account = app.model.define('account', {

View File

@@ -10,7 +10,7 @@
module.exports = app => {
const { STRING, INTEGER, DATE } = app.Sequelize;
// 分数列统一走共享工厂(DECIMAL(6,1) + Number 兜底,见 app/lib/decimal_score.js)
// 分数列统一走共享工厂(DECIMAL(6,2) + Number 兜底,见 app/lib/decimal_score.js)
const decimalScore = require('../lib/decimal_score')(app);
const BenkeSubmission = app.model.define('benke_submission', {
@@ -74,7 +74,7 @@ module.exports = app => {
comment: '上传时间',
},
// 评分
score: decimalScore('score', '评分(可含 1 位小数)', { defaultValue: null }),
score: decimalScore('score', '评分(可含 2 位小数)', { defaultValue: null }),
// 记录创建时间
created_at: {
type: DATE,

View File

@@ -14,7 +14,7 @@
module.exports = app => {
const { STRING, INTEGER, DATE, TEXT } = app.Sequelize;
// 分数列统一走共享工厂(DECIMAL(6,1) + Number 兜底,见 app/lib/decimal_score.js)
// 分数列统一走共享工厂(DECIMAL(6,2) + Number 兜底,见 app/lib/decimal_score.js)
const decimalScore = require('../lib/decimal_score')(app);
return app.model.define('BigQuestion', {

View File

@@ -14,7 +14,7 @@
module.exports = app => {
const { STRING, INTEGER, DATE, TEXT } = app.Sequelize;
// 分数列统一走共享工厂(DECIMAL(6,1) + Number 兜底,见 app/lib/decimal_score.js)
// 分数列统一走共享工厂(DECIMAL(6,2) + Number 兜底,见 app/lib/decimal_score.js)
const decimalScore = require('../lib/decimal_score')(app);
return app.model.define('BigQuestionAnswer', {
@@ -69,10 +69,10 @@ module.exports = app => {
allowNull: true,
comment: '第3小问作答(上限 2000 字)',
},
score_1: decimalScore('score_1', '第1小问得分(0-10,可含 1 位小数)'),
score_2: decimalScore('score_2', '第2小问得分(0-10,可含 1 位小数)'),
score_3: decimalScore('score_3', '第3小问得分(0-10,可含 1 位小数)'),
total_score: decimalScore('total_score', '三小问得分合计(可含 1 位小数)'),
score_1: decimalScore('score_1', '第1小问得分(0-10,可含 2 位小数)'),
score_2: decimalScore('score_2', '第2小问得分(0-10,可含 2 位小数)'),
score_3: decimalScore('score_3', '第3小问得分(0-10,可含 2 位小数)'),
total_score: decimalScore('total_score', '三小问得分合计(可含 2 位小数)'),
submit_time: {
type: DATE,
allowNull: true,

View File

@@ -10,7 +10,7 @@
module.exports = app => {
const { STRING, INTEGER, BOOLEAN, DATE } = app.Sequelize;
// 分数列统一走共享工厂(DECIMAL(6,1) + Number 兜底,见 app/lib/decimal_score.js)
// 分数列统一走共享工厂(DECIMAL(6,2) + Number 兜底,见 app/lib/decimal_score.js)
const decimalScore = require('../lib/decimal_score')(app);
const Contestant = app.model.define('contestant', {
@@ -70,10 +70,10 @@ module.exports = app => {
score: decimalScore('score', '选手总分(exam_score + word_score)'),
// 卷面分(选择题+判断题自动计算)
exam_score: decimalScore('exam_score', '卷面考试成绩'),
// 综合大题 / Word 题分数(管理员手动打分,可含 1 位小数)
word_score: decimalScore('word_score', 'Word题/综合大题得分(可含 1 位小数)'),
// 综合大题 / Word 题分数(管理员手动打分,可含 2 位小数)
word_score: decimalScore('word_score', 'Word题/综合大题得分(可含 2 位小数)'),
// PPT分数(本科/教师组管理员手动打分)
ppt_score: decimalScore('ppt_score', 'PPT得分(本科/教师组,可含 1 位小数)'),
ppt_score: decimalScore('ppt_score', 'PPT得分(本科/教师组,可含 2 位小数)'),
// 所属团队 ID(外键关联 teams 表)
team_id: {
type: INTEGER,

View File

@@ -11,7 +11,7 @@
module.exports = app => {
const { STRING, INTEGER, DATE, TEXT, JSON: JSON_TYPE } = app.Sequelize;
// 分数列统一走共享工厂(DECIMAL(6,1) + Number 兜底,见 app/lib/decimal_score.js)
// 分数列统一走共享工厂(DECIMAL(6,2) + Number 兜底,见 app/lib/decimal_score.js)
const decimalScore = require('../lib/decimal_score')(app);
const ExamSubmission = app.model.define('exam_submission', {

View File

@@ -10,7 +10,7 @@
module.exports = app => {
const { STRING, INTEGER, TEXT, BOOLEAN, DATE } = app.Sequelize;
// 分数列统一走共享工厂(DECIMAL(6,1) + Number 兜底,见 app/lib/decimal_score.js)
// 分数列统一走共享工厂(DECIMAL(6,2) + Number 兜底,见 app/lib/decimal_score.js)
const decimalScore = require('../lib/decimal_score')(app);
const GaozhiSubmission = app.model.define('gaozhi_submission', {
@@ -57,7 +57,7 @@ module.exports = app => {
comment: '是否判为正确',
},
// 得分
score: decimalScore('score', '得分(可含 1 位小数)', { defaultValue: null }),
score: decimalScore('score', '得分(可含 2 位小数)', { defaultValue: null }),
// Word 文件存储路径
word_file_path: {
type: STRING(500),

View File

@@ -10,7 +10,7 @@
module.exports = app => {
const { STRING, INTEGER, DATE } = app.Sequelize;
// 分数列统一走共享工厂(DECIMAL(6,1) + Number 兜底,见 app/lib/decimal_score.js)
// 分数列统一走共享工厂(DECIMAL(6,2) + Number 兜底,见 app/lib/decimal_score.js)
const decimalScore = require('../lib/decimal_score')(app);
const JiaoshiSubmission = app.model.define('jiaoshi_submission', {
@@ -74,7 +74,7 @@ module.exports = app => {
comment: '上传时间',
},
// 评分
score: decimalScore('score', '评分(可含 1 位小数)', { defaultValue: null }),
score: decimalScore('score', '评分(可含 2 位小数)', { defaultValue: null }),
// 记录创建时间
created_at: {
type: DATE,

View File

@@ -11,7 +11,7 @@
module.exports = app => {
const { STRING, INTEGER, DATE } = app.Sequelize;
// 分数列统一走共享工厂(DECIMAL(6,1) + Number 兜底,见 app/lib/decimal_score.js)
// 分数列统一走共享工厂(DECIMAL(6,2) + Number 兜底,见 app/lib/decimal_score.js)
const decimalScore = require('../lib/decimal_score')(app);
const WorkSubmission = app.model.define('work_submission', {

View File

@@ -10,7 +10,7 @@
module.exports = app => {
const { STRING, INTEGER, TEXT, BOOLEAN, DATE } = app.Sequelize;
// 分数列统一走共享工厂(DECIMAL(6,1) + Number 兜底,见 app/lib/decimal_score.js)
// 分数列统一走共享工厂(DECIMAL(6,2) + Number 兜底,见 app/lib/decimal_score.js)
const decimalScore = require('../lib/decimal_score')(app);
const ZhongzhiSubmission = app.model.define('zhongzhi_submission', {
@@ -57,7 +57,7 @@ module.exports = app => {
comment: '是否判为正确',
},
// 得分
score: decimalScore('score', '得分(可含 1 位小数)', { defaultValue: null }),
score: decimalScore('score', '得分(可含 2 位小数)', { defaultValue: null }),
// Word 文件存储路径
word_file_path: {
type: STRING(500),

View File

@@ -152,6 +152,8 @@ module.exports = app => {
router.put('/api/admin/big-questions/:group/:id', adminAuth, controller.admin.updateBigQuestion);
router.delete('/api/admin/big-questions/:group/:id', adminAuth, controller.admin.deleteBigQuestion);
router.get('/api/admin/big-answers/:group', adminAuth, controller.admin.getBigAnswers);
// 考生答卷导出(R28):3 段路径,与上方 2 段列表、下方 PUT /:uid/scores 均不冲突
router.get('/api/admin/big-answers/:group/export', adminAuth, controller.admin.exportBigAnswers);
router.put('/api/admin/big-answers/:group/:uid/scores', adminAuth, controller.admin.setBigAnswerScores);
// 备赛资料管理

View File

@@ -2083,6 +2083,21 @@ class AdminService extends Service {
// ---- 4) 拼装逐题明细 ----
const norm = v => String(v == null ? '' : v).trim().toLowerCase();
// 【R28 修复】options 在 DB 里是 text 列、存的是 JSON 字符串。
// 若原样透传给前端,`v-for="op in row.options"` 会按**字符**迭代 ⇒ 每个字符渲染成一行
// 空内容(op.key / op.text 皆 undefined),表现即「选择题大量换行导致空白」。
// 写法与 admin.js:1370 既有口径同源:仅在 typeof === 'string' 时 parse,失败降级 null。
const parseOptions = raw => {
if (raw == null) return null;
if (Array.isArray(raw)) return raw;
if (typeof raw !== 'string') return null;
try {
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : null;
} catch (e) {
return null;
}
};
const objective = subs.map(s => {
const t = s.question_type;
const n = Number(s.question_uid);
@@ -2097,7 +2112,7 @@ class AdminService extends Service {
questionType: t,
questionUid: n,
question: q ? q.question : null,
options: q ? (q.options || null) : null,
options: q ? parseOptions(q.options) : null,
// 原始值:选择 'A'/'AB';判断 'true'/'false'(由前端做「正确/错误」展示映射,后端不丢事实)
correctAnswer: correct,
maxScore: q && q.score != null ? Number(q.score) : null,
@@ -2121,9 +2136,9 @@ class AdminService extends Service {
return a.questionUid - b.questionUid;
});
// 小数按 1 位收敛(与 DECIMAL(6,1) 及全站评分口径一致,避免 0.30000000000000004)
const round1 = v => Math.round(v * 10) / 10;
const autoScore = round1(objective.reduce((sum, o) => sum + (o.score || 0), 0));
// 小数按 2 位收敛(与 DECIMAL(6,2) 及全站评分口径一致,避免 0.30000000000000004)
const round2 = v => Math.round(v * 100) / 100;
const autoScore = round2(objective.reduce((sum, o) => sum + (o.score || 0), 0));
// ---- 5) 综合大题(题干取抽题快照,保证考生当时所见可举证) ----
let bigQuestion = null;
@@ -2171,7 +2186,7 @@ class AdminService extends Service {
correctCount: objective.filter(o => o.isCorrect === true).length,
autoScore,
wordScore: contestant.word_score == null ? 0 : Number(contestant.word_score),
totalScore: round1(autoScore + (contestant.word_score == null ? 0 : Number(contestant.word_score))),
totalScore: round2(autoScore + (contestant.word_score == null ? 0 : Number(contestant.word_score))),
},
// 固化题序存在与否决定上图顺序的可解释性,一并上报(便于核对与排障)
questionOrderFixed: rank.size > 0,

View File

@@ -360,13 +360,14 @@ class BigQuestionService extends Service {
}
const n = Number(raw);
if (!Number.isFinite(n) || n < 0 || n > per) {
return { ok: false, code: 'INVALID_SCORE', message: `第 ${i + 1} 小问得分须为 0-${per} 的数值(可含一位小数)` };
return { ok: false, code: 'INVALID_SCORE', message: `第 ${i + 1} 小问得分须为 0-${per} 的数值(可含两位小数)` };
}
// 2026-09-23:人工评分允许小数点后一位 ⇒ 收敛到 1 位小数,⛔ 不可用 Math.round 抹成整数
parsed.push(Math.round(n * 10) / 10);
// 2026-09-28:评分精确到小数点后**两位**(测试人员反馈)⇒ 收敛到 2 位小数,
// ⛔ 不可用 Math.round 抹成整数(会丢掉 8.25 这类分数)
parsed.push(Math.round(n * 100) / 100);
}
// 浮点求和再收敛一次,避免 0.1+0.2=0.30000000000000004 之类脏值落库/回显
const total = Math.round(parsed.reduce((a, b) => a + b, 0) * 10) / 10;
const total = Math.round(parsed.reduce((a, b) => a + b, 0) * 100) / 100;
await record.update({
score_1: parsed[0],
@@ -529,6 +530,140 @@ class BigQuestionService extends Service {
};
}
/**
* 导出「试题 + 考生作答」阅卷用 Word(2026-09-28 测试人员需求)
*
* 与 exportQuestions 的区别(⛔ 勿混淆):
* · exportQuestions = 导出**题库题目**(供留存 / 打印 / 分发),不含任何考生信息;
* · exportAnswers = 导出**考生答卷**(供离线阅卷 / 打印 / 归档),内容 =
* 考生身份 + 抽题时刻题干快照 + 三小问作答 + 逐问得分 + 合计。
*
* 粒度(测试人员明确要求,勿改):
* · 命中 1 位考生 → 直接返回 .docx;
* · 命中多位 / 不传 ids(该组全部已抽题考生)→ **每人一个独立 .docx** 再打包为 .zip;
* · ⛔ 绝不把多位考生塞进同一个 Word —— 否则无法分别打印 / 分发 / 归档。
*
* 只读操作:不写库、不改任何状态。
*
* @param {string} group
* @param {Array<number>|string} [ids] - 考生 ID(contestantId)数组或逗号分隔串
* @returns {Promise<Object>} { ok:true, fileName, buffer, count, isZip? } 或 { ok:false, code, message }
*/
async exportAnswers(group, ids) {
if (!this.isEnabledGroup(group)) {
return { ok: false, code: 'GROUP_NOT_ENABLED', message: '该组别未启用综合大题' };
}
const all = await this.listAnswersForAdmin(group);
let picked = all;
if (ids !== undefined && ids !== null && ids !== '') {
const raw = Array.isArray(ids) ? ids : String(ids).split(',');
const idList = raw
.map(v => Number(String(v).trim()))
.filter(v => Number.isInteger(v) && v > 0);
if (!idList.length) {
return { ok: false, code: 'INVALID_IDS', message: '导出的考生 ID 列表非法' };
}
const wanted = new Set(idList);
picked = all.filter(x => wanted.has(Number(x.contestantId)));
if (!picked.length) {
return { ok: false, code: 'NOT_FOUND', message: '选中的考生不属于该组别或已不存在' };
}
}
// 只导出「已抽题」考生:未抽题者没有题面与作答,导出只会得到空白页
const exportable = picked.filter(x => x.drawn);
if (!exportable.length) {
return { ok: false, code: 'NOT_FOUND', message: '该范围内没有已抽取大题的考生,无可导出的答卷' };
}
const docx = require('../lib/docx');
const groupLabel = GROUP_LABELS[group] || group;
const pad = n => String(n).padStart(2, '0');
const fmtTime = v => {
if (!v) return '未提交';
const d = new Date(v);
if (isNaN(d.getTime())) return String(v);
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} `
+ `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
};
// 评分统一显示两位小数(与 DECIMAL(6,2) 口径一致)
const fmtScore = v => (v == null || v === '' ? '(未评分)' : Number(v).toFixed(2));
const files = [];
for (const s of exportable) {
const snap = s.questionSnapshot || {};
const prompts = Array.isArray(snap.sub_prompts) ? snap.sub_prompts : [];
const per = snap.score_per_sub != null ? Number(snap.score_per_sub) : null;
const answers = [s.answer1, s.answer2, s.answer3];
const scores = [s.score1, s.score2, s.score3];
const blocks = [];
// ---- 抬头:身份信息(阅卷核对用,与成绩复核同口径) ----
blocks.push({
type: 'p',
align: 'center',
runs: [{ text: `${groupLabel}综合大题阅卷表`, bold: true, size: 32 }],
});
blocks.push({ type: 'p', runs: [{ text: `姓名:${s.name || '--'}  身份证号:${s.idNumber || '--'}  手机号:${s.phone || '--'}` }] });
blocks.push({ type: 'p', runs: [{ text: `抽到题目:${snap.title || '--'}(${s.bigQuestionUid || '--'})` }] });
blocks.push({ type: 'p', runs: [{ text: `提交时间:${fmtTime(s.submitTime)}  已答小问:${s.answeredCount} / ${SUB_QUESTION_COUNT}` }] });
// ---- 试题(抽题时刻快照:题目后续被改不影响存证) ----
blocks.push({ type: 'p', runs: [] });
blocks.push({ type: 'p', runs: [{ text: '【试题】(抽题时刻快照,防纠纷)', bold: true, size: 26 }] });
blocks.push(...docx.htmlToBlocks(snap.description || ''));
// ---- 三小问:小问题目 + 考生作答 + 得分 ----
for (let i = 0; i < SUB_QUESTION_COUNT; i++) {
blocks.push({ type: 'p', runs: [] });
blocks.push({
type: 'p',
runs: [{
text: `【第 ${i + 1} 小问】${prompts[i] ? ':' + prompts[i] : ''}${per != null ? `(${per} 分)` : ''}`,
bold: true,
size: 26,
}],
});
const a = String(answers[i] || '').trim();
blocks.push({ type: 'p', runs: [{ text: '考生作答:', bold: true }] });
blocks.push(...docx.textToBlocks(a || '(未作答)'));
blocks.push({ type: 'p', runs: [{ text: `得分:${fmtScore(scores[i])}${per != null ? ` / ${Number(per).toFixed(2)}` : ''} 分` }] });
}
// ---- 合计 ----
blocks.push({ type: 'p', runs: [] });
blocks.push({
type: 'p',
runs: [{
text: `本大题合计:${fmtScore(s.bigScore)}${per != null ? ` / ${(per * SUB_QUESTION_COUNT).toFixed(2)}` : ''} 分`,
bold: true,
}],
});
blocks.push({ type: 'p', runs: [{ text: `(导出时间:${fmtTime(new Date())})` }] });
const buffer = await docx.buildDocx(blocks);
files.push({
name: `${groupLabel}_${safeFilePart(s.name || '考生')}_${safeFilePart(s.idNumber || s.contestantId)}.docx`,
buffer,
});
}
if (files.length === 1) {
return { ok: true, fileName: files[0].name, buffer: files[0].buffer, count: 1 };
}
const buffer = await docx.zipDocxFiles(files);
return {
ok: true,
isZip: true,
fileName: `${groupLabel}_大题答卷_${files.length}人.zip`,
buffer,
count: files.length,
};
}
/**
* 新建大题
* @param {string} group