- 新增 export_tasks 表与模型(迁移 20260916000000),记录导出类型、状态、进度、 文件名与错误信息 - app/service/exportTask.js:生成 CSV(exceljs)并落盘到 upload/exports/<主体>/<年>/<月>/<日> - app/schedule/exportWorker.js 定时执行待处理任务,cleanupExport.js 清理过期文件 - 接口:POST /api/export-tasks 提交、GET /api/export-tasks 列表与进度、 GET /api/export-tasks/:id/download 下载 - app/utils/exportDefs.js 定义各导出类型的数据源;warehouseProduct / stockRecord 补充 库存相关数据 - 契约补 exportTask 系列与 apikey 安全定义;.eslintrc 放行相关文件与 apikey 标签 - package-lock 同步
42 lines
1.3 KiB
JavaScript
42 lines
1.3 KiB
JavaScript
'use strict';
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
/**
|
|
* 定时清理导出文件与记录:每日凌晨 2:30 执行,删除超过 90 天且已终态(完成/失败)的导出任务,
|
|
* 同时删除其落盘文件(路径以 exports/ 开头,防止穿越),释放磁盘与数据库空间。
|
|
*/
|
|
module.exports = {
|
|
schedule: {
|
|
cron: '0 30 2 * * *',
|
|
type: 'worker',
|
|
disable: false,
|
|
},
|
|
|
|
async task(ctx) {
|
|
const keepDays = 90;
|
|
const Op = ctx.app.Sequelize.Op;
|
|
const threshold = new Date(Date.now() - keepDays * 24 * 60 * 60 * 1000);
|
|
const rows = await ctx.model.ExportTask.findAll({
|
|
where: {
|
|
created_at: { [Op.lt]: threshold },
|
|
status: { [Op.in]: [ 2, 3 ] },
|
|
},
|
|
});
|
|
|
|
const uploadDir = ctx.app.config.upload.dir;
|
|
let deleted = 0;
|
|
for (const r of rows) {
|
|
if (r.file_path && !r.file_path.includes('..') && /^exports\//.test(r.file_path)) {
|
|
const abs = path.join(uploadDir, r.file_path);
|
|
try { fs.unlinkSync(abs); } catch (e) { ctx.logger.warn('[export-cleanup] 删除文件失败 ' + abs, e.message); }
|
|
}
|
|
await r.destroy();
|
|
deleted += 1;
|
|
}
|
|
ctx.logger.info(`[export-cleanup] 已清理 ${keepDays} 天前的导出记录 ${deleted} 条`);
|
|
return deleted;
|
|
},
|
|
};
|