feat(upload): 组内作品唯一 + 小组编号目录 + 按小组打包下载(R190)
需求(管理人员反馈):
① 本科组/教师组同样遵循「小组内只要有一人上传作品,其他人就不能再上传」;
② 作品按「小组编号」建目录存放并保留原始文件名,管理端下载时按小组打包。
后端落地:
- 组锁:新增 getTeamUploadState/assertTeamUploadAllowed,按 (group, teamUid) 取全组
提交记录,**最早提交者为归属人**;其他人上传与分片合并两条路径都返 6006
(data 带 teamLocked/teamOwnerName/teamNumber/folderName)。删除本人作品后自动解锁。
⛔ 必须先按 group 过滤再认 teamUid(team_uid 仅组内唯一)。
- 落盘:works/<group>/<小组编号>/<原始文件名>。目录名走新增 lib/team_folder.js
(唯一 SoT:净化 Windows 非法字符/控制字符/首尾点/设备保留名,限长 60)。
撞名三态:不存在→原名;同一聚合+同一 file_type→原名原子覆盖;否则 (2)(3)。
DB file_path 仍为相对路径 ⇒ 存量平铺文件免迁移。
- 直传与分片合并收敛到同一套 prepareWorkTarget + commitWorkFile:先写同目录临时名
(.upload_*/.merge_*),再 renameSync;失败一律 safeCleanup 后抛。
- status 接口新增 teamLocked/canUpload/teamOwnerName/isTeamOwner/teamFiles/memberCount。
- 管理端:works 列表返回 teamUid/teamNumber/teamFolder(走 resolveTeamLabels 既有口径);
新增 GET /api/admin/team-zip/:group?teamUid= 单组打包(仅本科/教师,其余 400,包内平铺);
batch-download 包内改为 <小组编号>/<原始文件名>。两者共用 _buildZip。
验证:真接口 45/45 + 变异 M1(locked=false ⇒ 15 条断言红,还原后复绿);
已收编为门禁第 58 步。
This commit is contained in:
@@ -16,6 +16,12 @@ const { requireTestPassword } = require('../lib/passwordPolicy');
|
||||
// R107(2026-10-12):身份证号前置校验 —— 把「非 18 位」从 Sequelize 的
|
||||
// `Validation len on id_number failed` 变成可读的行级原因;同源口径见 lib/idCard.js。
|
||||
const { inspectIdNumber } = require('../lib/idCard');
|
||||
// 🔴 R190:小组作品目录命名的**唯一 SoT**。上传落盘(service/upload.js)与本文件的
|
||||
// 批量/单组打包**必须**用同一个函数算目录名,否则「上传写进 A、下载从 B 找」。
|
||||
const {
|
||||
resolveTeamFolderName,
|
||||
teamFolderRelative,
|
||||
} = require('../lib/team_folder');
|
||||
|
||||
/**
|
||||
* 客观题(选择题 / 判断题)每小题固定分值。
|
||||
@@ -1244,11 +1250,26 @@ answeredCount,
|
||||
const isExam = group === 'zhongzhi' || group === 'gaozhi';
|
||||
const contestants = await ctx.model.Contestant.findAll({
|
||||
where: { group },
|
||||
attributes: ['id', 'name', 'id_number', 'phone', 'group', 'word_score', 'ppt_score', 'exam_score'],
|
||||
// team_id 供 resolveTeamLabels 在「aggregation.team_uid 缺失」时兜底
|
||||
attributes: ['id', 'name', 'id_number', 'phone', 'group', 'team_id', 'word_score', 'ppt_score', 'exam_score'],
|
||||
order: [['id', 'ASC']],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 🔴 R190:小组编号 / 小组目录名(口径唯一来源,⛔ 不得在此另算一套)
|
||||
const labelMap = await resolveTeamLabels(ctx, contestants);
|
||||
const teamInfoOf = (contestantId, aggUid) => {
|
||||
const label = labelMap.get(String(contestantId)) || {};
|
||||
const teamUid = label.teamUid === undefined ? null : label.teamUid;
|
||||
const teamNumber = label.teamNumber || null;
|
||||
return {
|
||||
teamUid,
|
||||
teamNumber,
|
||||
// 后端落盘用的目录名;前端只展示,⛔ 不参与拼接
|
||||
teamFolder: resolveTeamFolderName({ teamNumber, teamUid, aggregationUid: aggUid }),
|
||||
};
|
||||
};
|
||||
|
||||
if (!isExam) {
|
||||
const SubmissionModel = group === 'benke' ? ctx.model.BenkeSubmission : ctx.model.JiaoshiSubmission;
|
||||
const rows = await SubmissionModel.findAll({ order: [['upload_time', 'DESC']], raw: true });
|
||||
@@ -1266,7 +1287,8 @@ answeredCount,
|
||||
const byAgg = {};
|
||||
rows.forEach(r => { (byAgg[r.aggregation_uid] = byAgg[r.aggregation_uid] || []).push(r); });
|
||||
return contestants.map(c => {
|
||||
const subs = byAgg[contestantToAgg[c.id]] || [];
|
||||
const aggUid = contestantToAgg[c.id];
|
||||
const subs = byAgg[aggUid] || [];
|
||||
const files = subs.map(s => ({
|
||||
id: s.id,
|
||||
kind: s.file_type || 'word',
|
||||
@@ -1277,7 +1299,16 @@ answeredCount,
|
||||
uploadedAt: s.upload_time,
|
||||
scoreField: s.file_type === 'ppt' ? 'ppt' : 'word',
|
||||
}));
|
||||
return { contestantId: c.id, name: c.name, idNumber: c.id_number, phone: c.phone, group: c.group, files };
|
||||
return {
|
||||
contestantId: c.id,
|
||||
name: c.name,
|
||||
idNumber: c.id_number,
|
||||
phone: c.phone,
|
||||
group: c.group,
|
||||
aggregationUid: aggUid === undefined ? null : aggUid,
|
||||
...teamInfoOf(c.id, aggUid),
|
||||
files,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1304,7 +1335,15 @@ answeredCount,
|
||||
uploadedAt: null,
|
||||
scoreField: 'word',
|
||||
}] : [];
|
||||
return { contestantId: c.id, name: c.name, idNumber: c.id_number, phone: c.phone, group: c.group, files };
|
||||
return {
|
||||
contestantId: c.id,
|
||||
name: c.name,
|
||||
idNumber: c.id_number,
|
||||
phone: c.phone,
|
||||
group: c.group,
|
||||
...teamInfoOf(c.id, null),
|
||||
files,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1608,15 +1647,52 @@ answeredCount,
|
||||
}
|
||||
|
||||
// ==================== 批量下载 ZIP ====================
|
||||
/**
|
||||
* 把「zip 条目清单」打成压缩包(单一打包实现,批量与单组共用)。
|
||||
*
|
||||
* @param {Array<{absPath:string, zipName:string}>} entries - 条目清单
|
||||
* @returns {Promise<string>} zip 绝对路径
|
||||
* @private
|
||||
*/
|
||||
async _buildZip(entries) {
|
||||
const { app } = this;
|
||||
// 使用 archiver 打包。archiver v8 为 ESM,导出 ZipArchive 等类;用 new ZipArchive(...) 实例化
|
||||
const { ZipArchive } = require('archiver');
|
||||
const zipFilePath = path.join(app.baseDir, 'app/public/tmp/zip', `zip_${Date.now()}_${Math.random().toString(36).substring(2, 8)}.zip`);
|
||||
fs.mkdirSync(path.dirname(zipFilePath), { recursive: true });
|
||||
|
||||
const output = fs.createWriteStream(zipFilePath);
|
||||
const archive = new ZipArchive({ zlib: { level: 9 } });
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
output.on('close', resolve);
|
||||
archive.on('error', reject);
|
||||
archive.pipe(output);
|
||||
// 🔴 直接 file() 到目标条目名,⛔ 不再先 copyFileSync 到临时目录再按目录遍历:
|
||||
// 复制步骤既多一次全量磁盘写,也会让「重名文件」在临时目录里互相覆盖。
|
||||
for (const e of entries) {
|
||||
archive.file(e.absPath, { name: e.zipName });
|
||||
}
|
||||
archive.finalize();
|
||||
});
|
||||
|
||||
return zipFilePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量下载某组所有提交文件,打包为 ZIP
|
||||
* 文件重命名为 "组号-学校-姓名-原文件名" 格式
|
||||
*
|
||||
* 🔴 R190 改造:本科/教师组**按小组分文件夹**打包 ——
|
||||
* 旧实现把所有文件平铺在 zip 根下,命名为 `姓名-word-原名`,
|
||||
* 两个文件(Word/PPT)混在一堆同类文件里,评分时无法判断哪两个属于同一小组。
|
||||
* 新结构:`<小组编号>/<原始文件名>`,与管理端「单个小组压缩包」完全同构。
|
||||
* 中职/高职组(Word 答题答案)保持原有平铺命名,不受影响。
|
||||
*
|
||||
* @param {string} group - 组别
|
||||
* @returns {Promise<string>} ZIP 文件路径
|
||||
*/
|
||||
async batchDownloadZip(group) {
|
||||
const { ctx, app } = this;
|
||||
const { app } = this;
|
||||
|
||||
// 获取该组的所有提交记录(考试组与作品组数据形状不同)
|
||||
const isExam = group === 'zhongzhi' || group === 'gaozhi';
|
||||
@@ -1624,14 +1700,32 @@ answeredCount,
|
||||
? await this.getExamSubmissions(group)
|
||||
: await this.getSubmissions(group);
|
||||
|
||||
// 构建临时 ZIP 目录
|
||||
const zipDir = path.join(app.baseDir, 'app/public/tmp/zip', group, String(Date.now()));
|
||||
if (!fs.existsSync(zipDir)) {
|
||||
fs.mkdirSync(zipDir, { recursive: true });
|
||||
// works 列表提供「选手 → 小组目录名」映射(口径与上传落盘同源)
|
||||
const worksList = isExam ? [] : await this.getWorks(group);
|
||||
const folderByContestant = new Map();
|
||||
for (const w of worksList) {
|
||||
folderByContestant.set(String(w.contestantId), w.teamFolder);
|
||||
}
|
||||
|
||||
// 收集所有需要打包的文件
|
||||
const filesToZip = [];
|
||||
const entries = [];
|
||||
const usedNames = new Set();
|
||||
/** 同名条目去重(历史数据里同组两人都传过时会撞名) */
|
||||
const uniqueZipName = (desired) => {
|
||||
if (!usedNames.has(desired)) { usedNames.add(desired); return desired; }
|
||||
const slash = desired.lastIndexOf('/');
|
||||
const dirPart = slash >= 0 ? desired.slice(0, slash + 1) : '';
|
||||
const base = slash >= 0 ? desired.slice(slash + 1) : desired;
|
||||
const dot = base.lastIndexOf('.');
|
||||
const stem = dot > 0 ? base.slice(0, dot) : base;
|
||||
const ext = dot > 0 ? base.slice(dot) : '';
|
||||
for (let i = 2; i <= 99; i += 1) {
|
||||
const cand = `${dirPart}${stem}-${i}${ext}`;
|
||||
if (!usedNames.has(cand)) { usedNames.add(cand); return cand; }
|
||||
}
|
||||
const cand = `${dirPart}${stem}-${Date.now()}${ext}`;
|
||||
usedNames.add(cand);
|
||||
return cand;
|
||||
};
|
||||
|
||||
// 本科/教师组需要 account.name_cn;考试组使用 getExamSubmissions 的 userName
|
||||
for (const item of submissions) {
|
||||
@@ -1639,66 +1733,107 @@ answeredCount,
|
||||
const userName = (isExam ? (item.userName || '未知') : (account.name_cn || '未知')).replace(/[\\/:*?"<>|]/g, '_');
|
||||
|
||||
if (isExam) {
|
||||
// 中职/高职组:收集 Word 答案文件
|
||||
// 中职/高职组:收集 Word 答案文件(保持原平铺命名)
|
||||
if (item.wordFilePath) {
|
||||
const fullPath = path.join(app.baseDir, 'app/public', item.wordFilePath);
|
||||
if (fs.existsSync(fullPath)) {
|
||||
const origName = item.wordFileName || path.basename(fullPath);
|
||||
const targetName = `${userName}-${origName}`;
|
||||
const targetPath = path.join(zipDir, targetName);
|
||||
fs.copyFileSync(fullPath, targetPath);
|
||||
filesToZip.push({ srcPath: fullPath, zipName: targetName });
|
||||
entries.push({ absPath: fullPath, zipName: uniqueZipName(`${userName}-${origName}`) });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 本科/教师组:收集 Word + PPT 作品文件
|
||||
// 本科/教师组:按小组目录归集 Word + PPT
|
||||
const folder = folderByContestant.get(String(item.contestantId)) || '未编组';
|
||||
for (const sub of (item.workSubmissions || [])) {
|
||||
if (sub.file_path) {
|
||||
const fullPath = path.join(app.baseDir, 'app/public', sub.file_path);
|
||||
if (fs.existsSync(fullPath)) {
|
||||
const origName = sub.file_name || path.basename(fullPath);
|
||||
const targetName = `${userName}-${sub.file_type || 'file'}-${origName}`;
|
||||
const targetPath = path.join(zipDir, targetName);
|
||||
fs.copyFileSync(fullPath, targetPath);
|
||||
filesToZip.push({ srcPath: fullPath, zipName: targetName });
|
||||
}
|
||||
}
|
||||
if (!sub.file_path) continue;
|
||||
const fullPath = path.join(app.baseDir, 'app/public', sub.file_path);
|
||||
if (!fs.existsSync(fullPath)) continue;
|
||||
const origName = (sub.file_name || path.basename(fullPath)).replace(/[\\/:*?"<>|]/g, '_');
|
||||
entries.push({ absPath: fullPath, zipName: uniqueZipName(`${folder}/${origName}`) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 创建 ZIP 文件
|
||||
const zipFileName = `${group}_submissions_${Date.now()}.zip`;
|
||||
const zipFilePath = path.join(app.baseDir, 'app/public/tmp/zip', zipFileName);
|
||||
if (entries.length === 0) {
|
||||
const err = new Error('该组暂无已上传的作品文件');
|
||||
err.bizCode = 'EMPTY';
|
||||
throw err;
|
||||
}
|
||||
|
||||
// 使用 archiver 将收集到的文件打包为 ZIP
|
||||
// archiver v8 为 ESM,导出 ZipArchive 等类;用 new ZipArchive(...) 实例化
|
||||
const { ZipArchive } = require('archiver');
|
||||
const output = fs.createWriteStream(zipFilePath);
|
||||
const archive = new ZipArchive({ zlib: { level: 9 } });
|
||||
return await this._buildZip(entries);
|
||||
}
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
output.on('close', resolve);
|
||||
archive.on('error', reject);
|
||||
/**
|
||||
* 单小组作品压缩包(R190)
|
||||
*
|
||||
* 【业务来源】「管理人员下载作品时将这个文件夹进行压缩,直接下载压缩包」
|
||||
* ⇒ 单个小组 = 一个压缩包,包内**平铺**该小组的两个文件(不再套一层目录)。
|
||||
*
|
||||
* @param {string} group - benke / jiaoshi
|
||||
* @param {Object} p
|
||||
* @param {?number} p.teamUid - 队伍号(优先)
|
||||
* @param {?number} p.aggregationUid - 聚合报名 ID(无队伍号时的定位键)
|
||||
* @returns {Promise<{zipFilePath:string, downloadName:string, folderName:string, fileCount:number}>}
|
||||
*/
|
||||
async teamZip(group, { teamUid = null, aggregationUid = null } = {}) {
|
||||
const { app } = this;
|
||||
const works = await this.getWorks(group);
|
||||
|
||||
archive.pipe(output);
|
||||
|
||||
// 将重命名后的文件添加到 ZIP
|
||||
const copiedFiles = fs.readdirSync(zipDir);
|
||||
for (const file of copiedFiles) {
|
||||
const filePath = path.join(zipDir, file);
|
||||
archive.file(filePath, { name: file });
|
||||
// 定位本小组的成员行:有 teamUid 用 teamUid(组内全部成员),否则用 aggregationUid
|
||||
let target;
|
||||
if (teamUid !== null && teamUid !== undefined && String(teamUid) !== '') {
|
||||
const members = works.filter(w => String(w.teamUid) === String(teamUid));
|
||||
if (members.length === 0) {
|
||||
const err = new Error('未找到该小组');
|
||||
err.bizCode = 'NOT_FOUND';
|
||||
throw err;
|
||||
}
|
||||
target = members;
|
||||
} else {
|
||||
const one = works.find(w => String(w.aggregationUid) === String(aggregationUid));
|
||||
if (!one) {
|
||||
const err = new Error('未找到该小组的报名信息');
|
||||
err.bizCode = 'NOT_FOUND';
|
||||
throw err;
|
||||
}
|
||||
target = [one];
|
||||
}
|
||||
|
||||
archive.finalize();
|
||||
});
|
||||
const folderName = target[0].teamFolder || '未编组';
|
||||
const entries = [];
|
||||
const usedNames = new Set();
|
||||
for (const w of target) {
|
||||
for (const f of (w.files || [])) {
|
||||
if (!f.filePath) continue;
|
||||
const abs = path.join(app.baseDir, 'app/public', f.filePath);
|
||||
if (!fs.existsSync(abs)) continue;
|
||||
let name = (f.fileName || path.basename(abs)).replace(/[\\/:*?"<>|]/g, '_');
|
||||
if (usedNames.has(name)) {
|
||||
const dot = name.lastIndexOf('.');
|
||||
const stem = dot > 0 ? name.slice(0, dot) : name;
|
||||
const ext = dot > 0 ? name.slice(dot) : '';
|
||||
let i = 2;
|
||||
while (usedNames.has(`${stem}-${i}${ext}`)) i += 1;
|
||||
name = `${stem}-${i}${ext}`;
|
||||
}
|
||||
usedNames.add(name);
|
||||
entries.push({ absPath: abs, zipName: name });
|
||||
}
|
||||
}
|
||||
|
||||
// 🔴 清理临时目录:best-effort(同源缺陷族,与 controller/upload.js:mergeChunks 同修)。
|
||||
// ZIP 已 finalize 落盘,清理失败绝不能把成功的批量下载判成 500
|
||||
// (common-error.log 实证:/api/admin/batch-download/* 曾因此整体失败)。
|
||||
this.ctx.helper.safeCleanup(zipDir, { label: 'batchZip-tmp' });
|
||||
if (entries.length === 0) {
|
||||
const err = new Error('该小组暂无已上传的作品文件');
|
||||
err.bizCode = 'EMPTY';
|
||||
throw err;
|
||||
}
|
||||
|
||||
return zipFilePath;
|
||||
const zipFilePath = await this._buildZip(entries);
|
||||
return {
|
||||
zipFilePath,
|
||||
downloadName: `${folderName}_作品.zip`,
|
||||
folderName,
|
||||
fileCount: entries.length,
|
||||
};
|
||||
}
|
||||
|
||||
// ==================== 评分管理 ====================
|
||||
|
||||
Reference in New Issue
Block a user