oms/backend/app/controller/exportTask.js
liufumingren fc58f79b42 feat(backend): 新增商品导出任务
- 新增 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 同步
2026-09-14 22:14:23 +08:00

134 lines
4.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const fs = require('fs');
const { Controller } = require('egg');
const { parsePagination, buildPageResult } = require('../lib/pagination');
const { EXPORT_TYPES } = require('../utils/exportDefs');
/**
* @controller ExportTaskController 导出任务(全局任务池)
*
* 提交导出(指定类型 + 筛选)→ 立即返回任务ID;定时任务逐个处理并生成 XLSX;
* 前端轮询进度,完成后触发浏览器下载(文件按 年/月/日 分目录存储)。
* 所有任务按主体隔离(principal_id 由 principalCheck 中间件写入 ctx.state.principalId)。
*/
class ExportTaskController extends Controller {
/**
* @summary 导出类型选项
* @router get /api/export-tasks/types
* @apikey
* @response 200 baseResponse success
*/
async types() {
const { ctx } = this;
const list = Object.keys(EXPORT_TYPES).map(k => ({ value: k, label: EXPORT_TYPES[k].label }));
ctx.body = { code: 0, message: 'success', data: list };
}
/**
* @summary 提交导出任务
* @description 仅落库一条「待处理」任务并立即返回任务ID,实际导出由定时任务异步处理
* @router post /api/export-tasks
* @apikey
* @request body createExportTaskRequest *body
* @response 200 baseResponse success
*/
async submit() {
const { ctx } = this;
const { type, filters } = ctx.request.body;
if (!EXPORT_TYPES[type]) {
ctx.status = 400;
ctx.body = { code: 400, message: '不支持的导出类型' };
return;
}
const clean = {};
if (filters && typeof filters === 'object') {
const allowed = [
'product_id', 'warehouse_id', 'biz_type', 'direction', 'bill_type', 'item_type',
'bill_no', 'keyword', 'category_name', 'status', 'submit_status', 'shop_id',
'start_time', 'end_time',
];
for (const k of allowed) {
const v = filters[k];
if (v !== undefined && v !== null && v !== '') clean[k] = v;
}
}
const task = await ctx.service.exportTask.submit(type, clean, ctx.state.principalId, ctx.userId);
ctx.body = { code: 0, message: 'success', data: { id: task.id, type, status: task.status } };
}
/**
* @summary 导出任务列表(按主体隔离)
* @router get /api/export-tasks
* @apikey
* @request query integer page 页码
* @request query integer pageSize 每页条数
* @request query string type 按类型筛选
* @request query integer status 按状态筛选(0待处理 1处理中 2已完成 3失败)
* @response 200 exportTaskListResponse success
*/
async index() {
const { ctx } = this;
const { page, pageSize } = parsePagination(ctx.query);
const { list, total } = await ctx.service.exportTask.list(ctx.state.principalId, {
page,
pageSize,
type: ctx.query.type,
status: ctx.query.status,
});
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, total, { page, pageSize }) };
}
/**
* @summary 导出任务进度
* @router get /api/export-tasks/:id
* @apikey
* @response 200 baseResponse success
*/
async progress() {
const { ctx } = this;
const task = await ctx.service.exportTask.progress(Number(ctx.params.id));
if (!task) {
ctx.status = 404;
ctx.body = { code: 404, message: '任务不存在' };
return;
}
ctx.body = { code: 0, message: 'success', data: task };
}
/**
* @summary 下载导出文件
* @description 仅「已完成」任务可下载;文件按 年/月/日 分目录存储,流式为 xlsx
* @router get /api/export-tasks/:id/download
* @apikey
* @response 200 baseResponse success
*/
async download() {
const { ctx } = this;
const task = await ctx.model.ExportTask.findByPk(ctx.params.id);
if (!task) {
ctx.status = 404;
ctx.body = { code: 404, message: '任务不存在' };
return;
}
if (task.status !== 2) {
ctx.status = 400;
ctx.body = { code: 400, message: '任务尚未完成,无法下载' };
return;
}
const abs = await ctx.service.exportTask.download(task);
if (!abs) {
ctx.status = 404;
ctx.body = { code: 404, message: '导出文件不存在' };
return;
}
const fallback = `export_${task.id}.xlsx`;
const name = task.file_name || fallback;
ctx.set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
ctx.set('Content-Disposition', `attachment; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(name)}`);
ctx.body = fs.createReadStream(abs);
}
}
module.exports = ExportTaskController;