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 同步
This commit is contained in:
parent
3daa95c96f
commit
fc58f79b42
@ -4,7 +4,7 @@
|
||||
"jsdoc/check-tag-names": [
|
||||
"warn",
|
||||
{
|
||||
"definedTags": [ "controller", "router", "request", "response" ]
|
||||
"definedTags": [ "controller", "router", "request", "response", "apikey" ]
|
||||
}
|
||||
]
|
||||
},
|
||||
@ -20,6 +20,16 @@
|
||||
"rules": {
|
||||
"no-restricted-modules": "off"
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": [
|
||||
"app/controller/exportTask.js",
|
||||
"app/service/exportTask.js",
|
||||
"app/schedule/cleanupExport.js"
|
||||
],
|
||||
"rules": {
|
||||
"no-restricted-modules": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
43
backend/app.js
Normal file
43
backend/app.js
Normal file
@ -0,0 +1,43 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 应用启动自定义(Boot 类)
|
||||
* - didReady:应用启动完成后,把遗留的「处理中」导出任务重置为「待处理」,交给全局队列重跑
|
||||
* (避免上次进程异常退出导致任务永久卡在处理中)。
|
||||
* - beforeClose:egg-scripts(npm start)优雅退出时,把「处理中」任务重置为「待处理」,
|
||||
* 使其在下一次启动时被重新认领处理(仅对生产环境生效,开发环境 local 不干预,避免刷新即重置)。
|
||||
*/
|
||||
class AppBootHook {
|
||||
constructor(app) {
|
||||
this.app = app;
|
||||
}
|
||||
|
||||
async didReady() {
|
||||
if (this.app.config.env === 'local') return;
|
||||
try {
|
||||
const ExportTask = this.app.model.ExportTask;
|
||||
if (ExportTask) {
|
||||
const [ n ] = await ExportTask.update({ status: 0 }, { where: { status: 1 } });
|
||||
this.app.logger.info('[export] 启动重置处理中任务为待处理,共 ' + (n || 0) + ' 条');
|
||||
}
|
||||
} catch (e) {
|
||||
this.app.logger.error('[export] 启动重置处理中任务失败', e);
|
||||
}
|
||||
}
|
||||
|
||||
async beforeClose() {
|
||||
if (this.app.config.env === 'local') return;
|
||||
try {
|
||||
const ExportTask = this.app.model.ExportTask;
|
||||
if (ExportTask) {
|
||||
// 有进行中的任务:重置为待处理,随后再退出(由 egg-scripts 的 SIGTERM 流程触发)
|
||||
await ExportTask.update({ status: 0 }, { where: { status: 1 } });
|
||||
this.app.logger.info('[export] 优雅退出:已将处理中任务重置为待处理');
|
||||
}
|
||||
} catch (e) {
|
||||
this.app.logger.error('[export] 优雅退出重置任务失败', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = AppBootHook;
|
||||
@ -1674,4 +1674,31 @@ module.exports = {
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'dashboardReport', description: '仪表盘报表数据' },
|
||||
},
|
||||
|
||||
// ---------- 导出任务 export_tasks ----------
|
||||
createExportTaskRequest: {
|
||||
type: { type: 'string', required: true, description: '导出类型:stock_record(出入库记录)/ product(商品)/ order(订单)' },
|
||||
filters: { type: 'object', description: '筛选条件(按类型可选):product_id/warehouse_id/biz_type/direction/bill_type/item_type/bill_no/keyword/start_time/end_time/category_name/status/submit_status/shop_id' },
|
||||
},
|
||||
exportTaskLine: {
|
||||
id: { type: 'integer', description: '任务ID' },
|
||||
principal_id: { type: 'integer', description: '所属主体ID' },
|
||||
type: { type: 'string', description: '导出类型:stock_record/product/order' },
|
||||
type_label: { type: 'string', description: '导出类型中文' },
|
||||
status: { type: 'integer', description: '状态:0待处理 1处理中 2已完成 3失败' },
|
||||
status_label: { type: 'string', description: '状态中文' },
|
||||
sql: { type: 'string', description: '导出所用 SQL(参数化)' },
|
||||
params: { type: 'string', description: '筛选条件 JSON' },
|
||||
total_count: { type: 'integer', description: '总记录数' },
|
||||
processed_count: { type: 'integer', description: '已处理记录数' },
|
||||
progress: { type: 'integer', description: '进度百分比 0-100' },
|
||||
file_path: { type: 'string', description: '导出文件相对路径(按 年/月/日 分目录)' },
|
||||
file_name: { type: 'string', description: '导出文件名' },
|
||||
error_message: { type: 'string', description: '失败原因' },
|
||||
created_by: { type: 'integer', description: '提交人ID' },
|
||||
created_at: { type: 'string', description: '创建时间' },
|
||||
updated_at: { type: 'string', description: '更新时间' },
|
||||
},
|
||||
exportTaskPage: buildPage('exportTaskLine', '导出任务列表'),
|
||||
exportTaskListResponse: buildListResponse('exportTaskPage'),
|
||||
};
|
||||
|
||||
133
backend/app/controller/exportTask.js
Normal file
133
backend/app/controller/exportTask.js
Normal file
@ -0,0 +1,133 @@
|
||||
'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;
|
||||
@ -3,7 +3,7 @@
|
||||
const { Controller } = require('egg');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
const QimenWmsClient = require('../lib/wms/qimenClient');
|
||||
const stock = require('../utils/stock');
|
||||
const { applyStockChange } = require('../utils/stockRecord');
|
||||
|
||||
/** 仓库接口类型:当前系统仅对接类奇门JSON接口 */
|
||||
const API_TYPE_QIMEN = 'qimen';
|
||||
@ -299,9 +299,10 @@ class WarehouseProductController extends Controller {
|
||||
|
||||
/**
|
||||
* 库存同步:将系统库存覆盖为「外部 WMS 库存」(按正品 / 残次品两个维度分别比较)
|
||||
* 对每个维度:系统数量 < 外部 => 已完成入库单(增加系统库存)
|
||||
* 系统数量 > 外部 => 已完成出库单(减少系统库存,仅减总数量不动锁定)
|
||||
* 对每个维度:系统数量 < 外部 => 已完成入库单(增加系统库存)+ 出入库记录(inbound_increase)
|
||||
* 系统数量 > 外部 => 已完成出库单(减少系统库存,仅减总数量不动锁定)+ 出入库记录(inventory_sync_out)
|
||||
* 相等 => 跳过
|
||||
* 出入库单、出入库明细、库存余量变动与出入库记录在同一事务内完成,保证账实一致
|
||||
* @router post /api/warehouses/{id}/inventory/sync
|
||||
* @apikey
|
||||
* @request path integer *id 仓库主键ID
|
||||
@ -358,19 +359,21 @@ class WarehouseProductController extends Controller {
|
||||
|
||||
const transaction = await ctx.model.transaction();
|
||||
try {
|
||||
// 对单个维度(正品 / 残次品)做一次同步:各自生成入/出库单
|
||||
const syncPair = async (product, systemQty, wmsQty, kindLabel, incFn, decFn) => {
|
||||
// 对单个维度(正品 / 残次品)做一次同步:各自生成入/出库单,并写一条出入库记录
|
||||
const syncPair = async (product, systemQty, wmsQty, kindLabel, itemType) => {
|
||||
const diff = wmsQty - systemQty;
|
||||
if (Math.abs(diff) < 1e-9) { skipped += 1; return; } // 相同不处理
|
||||
const billNo = await this.genSyncBillNo(principalId);
|
||||
const qty = Math.abs(diff);
|
||||
const remark = `库存同步(${kindLabel} WMS ${wmsQty} vs 系统 ${systemQty})`;
|
||||
const baseItem = {
|
||||
principal_id: principalId,
|
||||
shop_id: warehouseId,
|
||||
shop_id: null,
|
||||
product_id: product.id,
|
||||
name: product.item_name,
|
||||
code: product.item_code,
|
||||
spec: product.sku_property,
|
||||
inventory_type: itemType === 'CC' ? 'CC' : 'ZP',
|
||||
quantity: qty,
|
||||
total_amount: 0,
|
||||
};
|
||||
@ -383,13 +386,28 @@ class WarehouseProductController extends Controller {
|
||||
status: 4,
|
||||
operator: '库存同步',
|
||||
created_by: ctx.userId,
|
||||
remark: `库存同步(${kindLabel} WMS ${wmsQty} vs 系统 ${systemQty})`,
|
||||
remark,
|
||||
item_total: qty,
|
||||
item_kind: 1,
|
||||
total_amount: 0,
|
||||
}, { transaction });
|
||||
await ctx.model.StockItem.create({ ...baseItem, bill_type: 1, bill_id: order.id }, { transaction });
|
||||
await incFn(ctx, principalId, product.id, qty, transaction);
|
||||
// 增加系统库存并写一条「入库确认增加」出入库记录(与库存变动同事务)
|
||||
await applyStockChange(ctx, {
|
||||
bizType: 'inbound_increase',
|
||||
principalId,
|
||||
warehouseId,
|
||||
productId: product.id,
|
||||
itemCode: product.item_code,
|
||||
itemName: product.item_name,
|
||||
itemType,
|
||||
quantity: qty,
|
||||
billId: order.id,
|
||||
billNo: order.bill_no,
|
||||
createdBy: ctx.userId,
|
||||
remark,
|
||||
transaction,
|
||||
});
|
||||
inboundCount += 1;
|
||||
created.push({ type: 'inbound', kind: kindLabel, id: order.id, bill_no: billNo, product_id: product.id, quantity: qty });
|
||||
} else {
|
||||
@ -402,13 +420,28 @@ class WarehouseProductController extends Controller {
|
||||
customer: '库存同步',
|
||||
operator: '库存同步',
|
||||
created_by: ctx.userId,
|
||||
remark: `库存同步(${kindLabel} WMS ${wmsQty} vs 系统 ${systemQty})`,
|
||||
remark,
|
||||
item_total: qty,
|
||||
item_kind: 1,
|
||||
total_amount: 0,
|
||||
}, { transaction });
|
||||
await ctx.model.StockItem.create({ ...baseItem, bill_type: 2, bill_id: order.id }, { transaction });
|
||||
await decFn(ctx, principalId, product.id, qty, transaction);
|
||||
// 仅减少系统库存总数量(不动锁定),并写一条「库存同步出库」出入库记录(与库存变动同事务)
|
||||
await applyStockChange(ctx, {
|
||||
bizType: 'inventory_sync_out',
|
||||
principalId,
|
||||
warehouseId,
|
||||
productId: product.id,
|
||||
itemCode: product.item_code,
|
||||
itemName: product.item_name,
|
||||
itemType,
|
||||
quantity: qty,
|
||||
billId: order.id,
|
||||
billNo: order.bill_no,
|
||||
createdBy: ctx.userId,
|
||||
remark,
|
||||
transaction,
|
||||
});
|
||||
outboundCount += 1;
|
||||
created.push({ type: 'outbound', kind: kindLabel, id: order.id, bill_no: billNo, product_id: product.id, quantity: qty });
|
||||
}
|
||||
@ -421,9 +454,9 @@ class WarehouseProductController extends Controller {
|
||||
const systemGood = stockRows['ZC'] ? Number(stockRows['ZC'].quantity) : 0;
|
||||
const systemDefect = stockRows['CC'] ? Number(stockRows['CC'].quantity) : 0;
|
||||
// 正品维度
|
||||
await syncPair(product, systemGood, it.wms_good_quantity, '正品', stock.increase, stock.decrease);
|
||||
await syncPair(product, systemGood, it.wms_good_quantity, '正品', 'ZC');
|
||||
// 残次品维度
|
||||
await syncPair(product, systemDefect, it.wms_defect_quantity, '残次品', stock.increaseDefect, stock.decreaseDefect);
|
||||
await syncPair(product, systemDefect, it.wms_defect_quantity, '残次品', 'CC');
|
||||
}
|
||||
await transaction.commit();
|
||||
ctx.body = {
|
||||
|
||||
53
backend/app/model/exportTask.js
Normal file
53
backend/app/model/exportTask.js
Normal file
@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 导出任务表,对应 export_tasks
|
||||
* 全局导出任务池:前端提交导出请求(指定类型与筛选)即写入一条「待处理」任务并立即返回任务ID,
|
||||
* 由定时任务(exportWorker)逐个认领并处理(生成 XLSX 落盘),前端轮询进度,完成后触发浏览器下载。
|
||||
* 文件落盘路径区分 年/月/日:<uploadDir>/exports/YYYY/MM/DD/export_<type>_<id>_<ts>.xlsx
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} exportTask model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, INTEGER, TEXT, DATE } = app.Sequelize;
|
||||
|
||||
const ExportTask = app.model.define('export_task', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID(按主体隔离)' },
|
||||
type: { type: STRING(20), allowNull: false, comment: '导出类型:stock_record 出入库记录 / product 商品 / order 订单' },
|
||||
status: {
|
||||
type: TINYINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '状态:0待处理 1处理中 2已完成 3失败',
|
||||
},
|
||||
sql: { type: TEXT, comment: '实际执行的 MySQL 查询语句(? 占位参数),用于审计与重跑' },
|
||||
params: { type: TEXT, comment: '筛选参数 JSON(与 type 对应)' },
|
||||
file_path: { type: STRING(255), comment: '相对上传根目录的文件路径 exports/YYYY/MM/DD/...' },
|
||||
file_name: { type: STRING(255), comment: '文件名' },
|
||||
total_count: { type: INTEGER.UNSIGNED, defaultValue: 0, comment: '总行数' },
|
||||
processed_count: { type: INTEGER.UNSIGNED, defaultValue: 0, comment: '已处理行数(进度)' },
|
||||
progress: { type: TINYINT.UNSIGNED, defaultValue: 0, comment: '进度百分比 0-100' },
|
||||
error_message: { type: STRING(500), comment: '失败原因' },
|
||||
created_by: { type: BIGINT.UNSIGNED, comment: '提交人ID' },
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
},
|
||||
}, {
|
||||
tableName: 'export_tasks',
|
||||
indexes: [
|
||||
{ fields: [ 'principal_id' ] },
|
||||
{ fields: [ 'status' ] },
|
||||
{ fields: [ 'created_at' ] },
|
||||
],
|
||||
});
|
||||
|
||||
return ExportTask;
|
||||
};
|
||||
@ -137,6 +137,14 @@ module.exports = app => {
|
||||
// 发货单明细(子表商品明细,对应奇门 orderLines):明细锁定校验在控制器内按单据状态判断
|
||||
router.resources('orderDeliveryItems', '/api/order-delivery-items', jwtAuth, principalCheck({ model: 'OrderDeliveryItem' }), controller.orderDeliveryItem);
|
||||
|
||||
// 导出任务(全局任务池):提交即返回任务ID,定时任务逐个处理,前端轮询进度,完成后触发下载
|
||||
// 文件按 年/月/日 分目录存储;列表/提交按主体隔离,详情/下载按任务所属主体鉴权
|
||||
router.get('/api/export-tasks/types', jwtAuth, controller.exportTask.types);
|
||||
router.post('/api/export-tasks', jwtAuth, principalCheck(), controller.exportTask.submit);
|
||||
router.get('/api/export-tasks', jwtAuth, principalCheck(), controller.exportTask.index);
|
||||
router.get('/api/export-tasks/:id', jwtAuth, principalCheck({ model: 'ExportTask' }), controller.exportTask.progress);
|
||||
router.get('/api/export-tasks/:id/download', jwtAuth, principalCheck({ model: 'ExportTask' }), controller.exportTask.download);
|
||||
|
||||
// 文件资源:check/upload 需登录并按主体隔离;raw 为公开读取(URL 含内容 hash,不可枚举)
|
||||
// raw 通配路由需在 resources('files') 之前注册,避免被 /api/files/:id 误匹配
|
||||
router.post('/api/files/check', jwtAuth, principalCheck(), controller.file.check);
|
||||
|
||||
41
backend/app/schedule/cleanupExport.js
Normal file
41
backend/app/schedule/cleanupExport.js
Normal file
@ -0,0 +1,41 @@
|
||||
'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;
|
||||
},
|
||||
};
|
||||
21
backend/app/schedule/exportWorker.js
Normal file
21
backend/app/schedule/exportWorker.js
Normal file
@ -0,0 +1,21 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 导出任务全局队列消费者:每 3 秒运行一次,认领并处理一条「待处理」任务。
|
||||
* type: 'worker' 保证在集群中仅由单一 worker 执行,配合行锁实现「逐个处理」的全局任务池。
|
||||
*/
|
||||
module.exports = {
|
||||
schedule: {
|
||||
cron: '*/3 * * * * *',
|
||||
type: 'worker',
|
||||
disable: false,
|
||||
},
|
||||
|
||||
async task(ctx) {
|
||||
try {
|
||||
await ctx.service.exportTask.processPending();
|
||||
} catch (e) {
|
||||
ctx.logger.error('[export-worker] 调度执行失败', e);
|
||||
}
|
||||
},
|
||||
};
|
||||
224
backend/app/service/exportTask.js
Normal file
224
backend/app/service/exportTask.js
Normal file
@ -0,0 +1,224 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { Service } = require('egg');
|
||||
const ExcelJS = require('exceljs');
|
||||
const { buildExportSql, STATUS_LABELS, TYPE_LABELS, formatDate } = require('../utils/exportDefs');
|
||||
|
||||
/** 任务状态:0待处理 1处理中 2已完成 3失败 */
|
||||
const STATUS = { PENDING: 0, PROCESSING: 1, COMPLETED: 2, FAILED: 3 };
|
||||
|
||||
/** 单批次查询行数(边查边写,控制内存占用并上报进度) */
|
||||
const CHUNK = 2000;
|
||||
|
||||
/**
|
||||
* 解析任务参数(params 以 JSON 字符串存储)
|
||||
* @param {string|Object} s 参数
|
||||
* @return {Object} 解析后的筛选对象
|
||||
*/
|
||||
function safeParse(s) {
|
||||
if (!s) return {};
|
||||
if (typeof s === 'object') return s;
|
||||
try { return JSON.parse(s); } catch { return {}; }
|
||||
}
|
||||
|
||||
/**
|
||||
* 给任务对象补上中文标签(避免前后端枚举漂移)
|
||||
* @param {Object} item 任务纯对象
|
||||
* @return {Object} 带 label 的任务
|
||||
*/
|
||||
function withLabels(item) {
|
||||
item.type_label = TYPE_LABELS[item.type] || item.type;
|
||||
item.status_label = STATUS_LABELS[item.status] != null ? STATUS_LABELS[item.status] : String(item.status);
|
||||
return item;
|
||||
}
|
||||
|
||||
class ExportTaskService extends Service {
|
||||
/**
|
||||
* 提交导出任务:仅构造并落库一条「待处理」记录,立即返回任务ID(实际导出由定时任务处理)
|
||||
* @param {string} type 导出类型
|
||||
* @param {Object} filters 已白名单过滤的筛选条件
|
||||
* @param {number} principalId 主体ID
|
||||
* @param {number} userId 提交人ID
|
||||
* @return {Promise<Object>} 任务实例
|
||||
*/
|
||||
async submit(type, filters, principalId, userId) {
|
||||
const { sql } = buildExportSql(type, filters, principalId);
|
||||
return this.ctx.model.ExportTask.create({
|
||||
principal_id: principalId,
|
||||
type,
|
||||
status: STATUS.PENDING,
|
||||
sql,
|
||||
params: JSON.stringify(filters || {}),
|
||||
created_by: userId || null,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询当前主体的导出任务
|
||||
* @param {number} principalId 主体ID
|
||||
* @param {Object} opts page/pageSize/type/status
|
||||
* @return {Promise<{list: Array, total: number}>}
|
||||
*/
|
||||
async list(principalId, opts) {
|
||||
const { page, pageSize, type, status } = opts;
|
||||
const where = { principal_id: principalId };
|
||||
if (type) where.type = type;
|
||||
if (status !== undefined && status !== null && status !== '') where.status = Number(status);
|
||||
const { count, rows } = await this.ctx.model.ExportTask.findAndCountAll({
|
||||
where,
|
||||
offset: (Number(page) - 1) * Number(pageSize),
|
||||
limit: Number(pageSize),
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
const list = rows.map(r => withLabels(r.get({ plain: true })));
|
||||
return { list, total: count };
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询单个任务(带中文标签)
|
||||
* @param {number} id 任务ID
|
||||
* @return {Promise<Object|null>}
|
||||
*/
|
||||
async progress(id) {
|
||||
const task = await this.ctx.model.ExportTask.findByPk(id);
|
||||
if (!task) return null;
|
||||
return withLabels(task.get({ plain: true }));
|
||||
}
|
||||
|
||||
/**
|
||||
* 认领并处理一条「待处理」任务(全局单_worker队列,靠行锁保证集群下不重复认领)
|
||||
* 业务流程:事务内 FOR UPDATE 锁定最旧待处理任务 → 置为处理中 → 提交;随后分块查询并写 XLSX;
|
||||
* 完成时置已完成;异常时置失败并记录原因。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async processPending() {
|
||||
const ctx = this.ctx;
|
||||
const Model = ctx.model.ExportTask;
|
||||
const transaction = await ctx.model.transaction();
|
||||
let task = null;
|
||||
try {
|
||||
task = await Model.findOne({
|
||||
where: { status: STATUS.PENDING },
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
lock: true,
|
||||
transaction,
|
||||
});
|
||||
if (!task) { await transaction.rollback(); return; }
|
||||
task.status = STATUS.PROCESSING;
|
||||
await task.save({ transaction });
|
||||
await transaction.commit();
|
||||
} catch (e) {
|
||||
await transaction.rollback().catch(() => {});
|
||||
ctx.logger.error('[export-worker] 认领任务失败', e);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await this.run(task, ctx);
|
||||
} catch (e) {
|
||||
ctx.logger.error('[export-worker] 处理任务失败 id=' + task.id, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行导出:分块查询 + 写 XLSX + 实时更新进度,文件按 年/月/日 分目录
|
||||
* @param {Object} task 任务实例
|
||||
* @param {Egg.Context} ctx egg 上下文(含 model / app)
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async run(task, ctx) {
|
||||
const Model = ctx.model.ExportTask;
|
||||
const QueryTypes = ctx.model.QueryTypes;
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
const sheet = workbook.addWorksheet(TYPE_LABELS[task.type] || 'export');
|
||||
try {
|
||||
const filters = safeParse(task.params);
|
||||
const { sql, countSql, columns, replacements } = buildExportSql(task.type, filters, task.principal_id);
|
||||
const [ countRow ] = await ctx.model.query(countSql, { replacements, type: QueryTypes.SELECT });
|
||||
const total = Number(countRow && countRow.cnt) || 0;
|
||||
|
||||
const uploadDir = ctx.app.config.upload.dir;
|
||||
const now = new Date();
|
||||
const y = String(now.getFullYear());
|
||||
const m = String(now.getMonth() + 1).padStart(2, '0');
|
||||
const d = String(now.getDate()).padStart(2, '0');
|
||||
const relDir = [ 'exports', y, m, d ].join('/');
|
||||
fs.mkdirSync(path.join(uploadDir, relDir), { recursive: true });
|
||||
const fileName = `export_${task.type}_${task.id}_${now.getTime()}.xlsx`;
|
||||
const relPath = relDir + '/' + fileName;
|
||||
const absPath = path.join(uploadDir, relPath);
|
||||
|
||||
sheet.columns = columns.map(c => ({ header: c.header, key: c.key, width: 18 }));
|
||||
sheet.getRow(1).font = { bold: true };
|
||||
sheet.views = [{ state: 'frozen', ySplit: 1 }];
|
||||
|
||||
let offset = 0;
|
||||
let processed = 0;
|
||||
if (total > 0) {
|
||||
// 循环分块:offset/CHUNK 为整数,直接内联拼接,无注入风险
|
||||
let finished = false;
|
||||
while (!finished) {
|
||||
const rows = await ctx.model.query(`${sql} LIMIT ${offset}, ${CHUNK}`, {
|
||||
replacements,
|
||||
type: QueryTypes.SELECT,
|
||||
});
|
||||
for (const row of rows) {
|
||||
const vals = {};
|
||||
for (const c of columns) {
|
||||
let v = c.format ? c.format(row[c.key], row) : row[c.key];
|
||||
if (v instanceof Date) v = formatDate(v);
|
||||
vals[c.key] = v;
|
||||
}
|
||||
sheet.addRow(vals);
|
||||
}
|
||||
processed += rows.length;
|
||||
offset += CHUNK;
|
||||
const progress = Math.min(99, Math.floor(processed / total * 100));
|
||||
await Model.update(
|
||||
{ processed_count: processed, progress, file_path: relPath, file_name: fileName },
|
||||
{ where: { id: task.id } }
|
||||
);
|
||||
if (rows.length < CHUNK) finished = true;
|
||||
}
|
||||
}
|
||||
await workbook.xlsx.writeFile(absPath);
|
||||
|
||||
await Model.update(
|
||||
{
|
||||
status: STATUS.COMPLETED,
|
||||
total_count: total,
|
||||
processed_count: total,
|
||||
progress: 100,
|
||||
file_path: relPath,
|
||||
file_name: fileName,
|
||||
},
|
||||
{ where: { id: task.id } }
|
||||
);
|
||||
ctx.logger.info(`[export-worker] 任务完成 id=${task.id} type=${task.type} rows=${total}`);
|
||||
} catch (e) {
|
||||
const msg = (e && e.message) ? e.message : String(e);
|
||||
await Model.update(
|
||||
{ status: STATUS.FAILED, error_message: msg.slice(0, 500) },
|
||||
{ where: { id: task.id } }
|
||||
).catch(() => {});
|
||||
ctx.logger.error('[export-worker] 任务失败 id=' + task.id, e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析任务对应的导出文件绝对路径(校验防止目录穿越)
|
||||
* @param {Object} task 任务实例
|
||||
* @return {Promise<string|null>} 文件绝对路径或 null
|
||||
*/
|
||||
async download(task) {
|
||||
const rel = task.file_path;
|
||||
if (!rel || rel.includes('..') || !/^exports\//.test(rel)) return null;
|
||||
const abs = path.join(this.ctx.app.config.upload.dir, rel);
|
||||
if (!fs.existsSync(abs)) return null;
|
||||
return abs;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ExportTaskService;
|
||||
188
backend/app/utils/exportDefs.js
Normal file
188
backend/app/utils/exportDefs.js
Normal file
@ -0,0 +1,188 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 导出定义与 SQL 构造(纯函数,便于单测与复用)
|
||||
* - EXPORT_TYPES:支持的导出类型(出入库记录 / 商品 / 订单)
|
||||
* - buildExportSql(type, filters, principalId):按类型与筛选条件构造「参数化」SELECT 语句,
|
||||
* 返回 { sql, countSql, columns, replacements };所有用户输入经 ? 占位参数传递,避免 SQL 注入。
|
||||
* - columns:每列 { key(查询字段), header(XLSX 表头), format?(原始值→展示值) },用于生成 XLSX 与中文标签。
|
||||
*/
|
||||
|
||||
/** 支持的导出类型 */
|
||||
const EXPORT_TYPES = {
|
||||
stock_record: { label: '出入库记录', table: 'stock_records' },
|
||||
product: { label: '商品', table: 'products' },
|
||||
order: { label: '订单', table: 'orders' },
|
||||
};
|
||||
|
||||
/** 状态中文(与 export_tasks.status 对齐) */
|
||||
const STATUS_LABELS = { 0: '待处理', 1: '处理中', 2: '已完成', 3: '失败' };
|
||||
|
||||
/** 类型中文 */
|
||||
const TYPE_LABELS = {
|
||||
stock_record: '出入库记录',
|
||||
product: '商品',
|
||||
order: '订单',
|
||||
};
|
||||
|
||||
const BIZ_LABELS = {
|
||||
outbound_lock: '出库推送锁定',
|
||||
outbound_unlock: '出库解锁',
|
||||
outbound_restore: '出库驳回回补',
|
||||
outbound_deduct: '出库确认扣减',
|
||||
inbound_increase: '入库确认增加',
|
||||
order_lock: '订单审核锁定',
|
||||
order_unlock: '订单解锁',
|
||||
order_deduct: '订单发货确认扣减',
|
||||
};
|
||||
|
||||
const ORDER_STATUS = { 1: '待处理', 2: '处理中', 3: '已完成', 4: '已取消' };
|
||||
const SUBMIT_STATUS = { 0: '未上交', 1: '上交中', 2: '已上交', 3: '上交失败' };
|
||||
|
||||
/**
|
||||
* 解析收货人 JSON(orders.receiver 可能为对象或 JSON 字符串)
|
||||
* @param {*} value 原始值
|
||||
* @return {string} 拼接后的「姓名 电话 地址」
|
||||
*/
|
||||
function formatReceiver(value) {
|
||||
if (!value) return '';
|
||||
let obj = value;
|
||||
if (typeof value === 'string') {
|
||||
try { obj = JSON.parse(value); } catch { return value; }
|
||||
}
|
||||
if (obj && typeof obj === 'object') {
|
||||
return [ obj.name, obj.phone, obj.address ].filter(Boolean).join(' ');
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造导出 SQL
|
||||
* @param {string} type 导出类型(见 EXPORT_TYPES)
|
||||
* @param {Object} filters 筛选条件(来自前端,键已做白名单过滤)
|
||||
* @param {number} principalId 主体ID(强制隔离,作为首个 ? 参数)
|
||||
* @return {{sql: string, countSql: string, columns: Array, replacements: Array}}
|
||||
*/
|
||||
function buildExportSql(type, filters, principalId) {
|
||||
const f = filters || {};
|
||||
const def = EXPORT_TYPES[type];
|
||||
if (!def) throw new Error('不支持的导出类型: ' + type);
|
||||
|
||||
const wheres = [ 'principal_id = ?' ];
|
||||
const replacements = [ principalId ];
|
||||
|
||||
function like(val) { return '%' + String(val == null ? '' : val) + '%'; }
|
||||
|
||||
let columns;
|
||||
let select;
|
||||
|
||||
if (type === 'stock_record') {
|
||||
columns = [
|
||||
{ key: 'id', header: 'ID' },
|
||||
{ key: 'created_at', header: '记录时间' },
|
||||
{ key: 'biz_type', header: '业务动作', format: v => BIZ_LABELS[v] || v },
|
||||
{ key: 'direction', header: '方向', format: v => (v === 1 ? '入库' : v === 2 ? '出库' : v) },
|
||||
{ key: 'bill_type', header: '单据类型', format: v => ({ 1: '入库单', 2: '出库单', 3: '发货单' }[v] || v) },
|
||||
{ key: 'bill_no', header: '单据号' },
|
||||
{ key: 'item_code', header: '商品编码' },
|
||||
{ key: 'item_name', header: '商品名称' },
|
||||
{ key: 'item_type', header: '库存类型', format: v => (v === 'CC' ? '残次品' : '正品') },
|
||||
{ key: 'quantity', header: '变动数量' },
|
||||
{ key: 'quantity_before', header: '总数量(前)' },
|
||||
{ key: 'quantity_after', header: '总数量(后)' },
|
||||
{ key: 'lock_quantity', header: '锁定数量' },
|
||||
{ key: 'lock_before', header: '锁定(前)' },
|
||||
{ key: 'lock_after', header: '锁定(后)' },
|
||||
{ key: 'available_before', header: '可用(前)' },
|
||||
{ key: 'available_after', header: '可用(后)' },
|
||||
{ key: 'remark', header: '备注' },
|
||||
];
|
||||
select = columns.map(c => c.key).join(', ');
|
||||
if (f.product_id) { wheres.push('product_id = ?'); replacements.push(Number(f.product_id)); }
|
||||
if (f.warehouse_id) { wheres.push('warehouse_id = ?'); replacements.push(Number(f.warehouse_id)); }
|
||||
if (f.biz_type) { wheres.push('biz_type = ?'); replacements.push(String(f.biz_type)); }
|
||||
if (f.direction) { wheres.push('direction = ?'); replacements.push(Number(f.direction)); }
|
||||
if (f.bill_type) { wheres.push('bill_type = ?'); replacements.push(Number(f.bill_type)); }
|
||||
if (f.item_type) { wheres.push('item_type = ?'); replacements.push(String(f.item_type).toUpperCase()); }
|
||||
if (f.bill_no) { wheres.push('bill_no LIKE ?'); replacements.push(like(f.bill_no)); }
|
||||
if (f.keyword) {
|
||||
wheres.push('(item_code LIKE ? OR item_name LIKE ? OR bill_no LIKE ?)');
|
||||
replacements.push(like(f.keyword), like(f.keyword), like(f.keyword));
|
||||
}
|
||||
if (f.start_time) { wheres.push('created_at >= ?'); replacements.push(String(f.start_time) + ' 00:00:00'); }
|
||||
if (f.end_time) { wheres.push('created_at <= ?'); replacements.push(String(f.end_time) + ' 23:59:59'); }
|
||||
} else if (type === 'product') {
|
||||
columns = [
|
||||
{ key: 'id', header: 'ID' },
|
||||
{ key: 'item_code', header: '商品编码' },
|
||||
{ key: 'item_name', header: '商品名称' },
|
||||
{ key: 'sku_property', header: 'SKU规格' },
|
||||
{ key: 'category_name', header: '分类' },
|
||||
{ key: 'brand_name', header: '品牌' },
|
||||
{ key: 'barcode', header: '条码' },
|
||||
{ key: 'stock_unit', header: '单位' },
|
||||
{ key: 'retail_price', header: '零售价' },
|
||||
{ key: 'cost_price', header: '成本价' },
|
||||
{ key: 'status', header: '状态', format: v => (v === 1 || v === '1' || v === '启用' ? '启用' : '禁用') },
|
||||
{ key: 'remark', header: '备注' },
|
||||
{ key: 'created_at', header: '创建时间' },
|
||||
];
|
||||
select = columns.map(c => c.key).join(', ');
|
||||
if (f.keyword) {
|
||||
wheres.push('(item_code LIKE ? OR item_name LIKE ? OR barcode LIKE ?)');
|
||||
replacements.push(like(f.keyword), like(f.keyword), like(f.keyword));
|
||||
}
|
||||
if (f.category_name) { wheres.push('category_name LIKE ?'); replacements.push(like(f.category_name)); }
|
||||
if (f.status !== undefined && f.status !== null && f.status !== '') { wheres.push('status = ?'); replacements.push(Number(f.status)); }
|
||||
} else if (type === 'order') {
|
||||
columns = [
|
||||
{ key: 'id', header: 'ID' },
|
||||
{ key: 'order_no', header: '订单号' },
|
||||
{ key: 'shop_id', header: '店铺ID' },
|
||||
{ key: 'order_type', header: '订单类型' },
|
||||
{ key: 'status', header: '状态', format: v => ORDER_STATUS[v] || v },
|
||||
{ key: 'wms_status', header: 'WMS状态' },
|
||||
{ key: 'wms_order_no', header: 'WMS单号' },
|
||||
{ key: 'submit_status', header: '上交状态', format: v => SUBMIT_STATUS[v] || v },
|
||||
{ key: 'total_amount', header: '订单金额' },
|
||||
{ key: 'pay_amount', header: '实付金额' },
|
||||
{ key: 'receiver', header: '收货人', format: v => formatReceiver(v) },
|
||||
{ key: 'remark', header: '备注' },
|
||||
{ key: 'created_at', header: '创建时间' },
|
||||
];
|
||||
select = columns.map(c => c.key).join(', ');
|
||||
if (f.keyword) { wheres.push('(order_no LIKE ? OR remark LIKE ?)'); replacements.push(like(f.keyword), like(f.keyword)); }
|
||||
if (f.status !== undefined && f.status !== null && f.status !== '') { wheres.push('status = ?'); replacements.push(Number(f.status)); }
|
||||
if (f.submit_status !== undefined && f.submit_status !== null && f.submit_status !== '') { wheres.push('submit_status = ?'); replacements.push(Number(f.submit_status)); }
|
||||
if (f.shop_id) { wheres.push('shop_id = ?'); replacements.push(Number(f.shop_id)); }
|
||||
if (f.start_time) { wheres.push('created_at >= ?'); replacements.push(String(f.start_time) + ' 00:00:00'); }
|
||||
if (f.end_time) { wheres.push('created_at <= ?'); replacements.push(String(f.end_time) + ' 23:59:59'); }
|
||||
} else {
|
||||
throw new Error('不支持的导出类型: ' + type);
|
||||
}
|
||||
|
||||
const whereSql = wheres.join(' AND ');
|
||||
const sql = `SELECT ${select} FROM ${def.table} WHERE ${whereSql} ORDER BY id DESC`;
|
||||
const countSql = `SELECT COUNT(*) AS cnt FROM ${def.table} WHERE ${whereSql}`;
|
||||
return { sql, countSql, columns, replacements };
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Date 格式化为本地时间字符串 YYYY-MM-DD HH:mm:ss(XLSX 单元格可读)
|
||||
* @param {Date|string|number} value 时间
|
||||
* @return {string}
|
||||
*/
|
||||
function formatDate(value) {
|
||||
const dt = value instanceof Date ? value : new Date(value);
|
||||
if (isNaN(dt.getTime())) return '';
|
||||
const p = n => String(n).padStart(2, '0');
|
||||
return `${dt.getFullYear()}-${p(dt.getMonth() + 1)}-${p(dt.getDate())} ${p(dt.getHours())}:${p(dt.getMinutes())}:${p(dt.getSeconds())}`;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
EXPORT_TYPES,
|
||||
STATUS_LABELS,
|
||||
TYPE_LABELS,
|
||||
buildExportSql,
|
||||
formatDate,
|
||||
};
|
||||
@ -35,6 +35,7 @@ const BIZ_TYPES = {
|
||||
outbound_deduct: { label: '出库确认扣减', direction: 2, billType: 2 },
|
||||
outbound_restore: { label: '出库驳回回补', direction: 2, billType: 2 },
|
||||
inbound_increase: { label: '入库确认增加', direction: 1, billType: 1 },
|
||||
inventory_sync_out: { label: '库存同步出库', direction: 2, billType: 2 },
|
||||
order_lock: { label: '订单审核锁定', direction: 2, billType: 3 },
|
||||
order_unlock: { label: '订单解锁', direction: 2, billType: 3 },
|
||||
order_deduct: { label: '订单发货确认扣减', direction: 2, billType: 3 },
|
||||
@ -50,6 +51,8 @@ const STOCK_ACTIONS = {
|
||||
outbound_deduct: (ctx, principalId, productId, qty, transaction, itemType) => stock.deduct(ctx, principalId, productId, qty, transaction, itemType),
|
||||
outbound_restore: (ctx, principalId, productId, qty, transaction, itemType) => stock.increase(ctx, principalId, productId, qty, transaction, itemType),
|
||||
inbound_increase: (ctx, principalId, productId, qty, transaction, itemType) => stock.increase(ctx, principalId, productId, qty, transaction, itemType),
|
||||
// 库存同步:系统数量多于外部时,仅减少总数量(不动锁定)
|
||||
inventory_sync_out: (ctx, principalId, productId, qty, transaction, itemType) => stock.decrease(ctx, principalId, productId, qty, transaction, itemType),
|
||||
// 发货单(订单):审核锁定 / 解锁 / 发货确认扣减,与出库单同源动作
|
||||
order_lock: (ctx, principalId, productId, qty, transaction, itemType) => stock.lock(ctx, principalId, productId, qty, transaction, itemType),
|
||||
order_unlock: (ctx, principalId, productId, qty, transaction, itemType) => stock.unlock(ctx, principalId, productId, qty, transaction, itemType),
|
||||
|
||||
@ -0,0 +1,52 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 导出任务表(全局任务池):提交即落「待处理」任务,定时任务逐个处理并生成 CSV。
|
||||
* 状态:0待处理 1处理中 2已完成 3失败;文件按 年/月/日 分目录存储。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'export_tasks',
|
||||
{
|
||||
id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
autoIncrement: true,
|
||||
primaryKey: true,
|
||||
},
|
||||
principal_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
type: { type: Sequelize.STRING(20), allowNull: false, comment: '导出类型:stock_record/product/order' },
|
||||
status: { type: Sequelize.TINYINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '0待处理 1处理中 2已完成 3失败' },
|
||||
sql: { type: Sequelize.TEXT, comment: '实际执行的 MySQL 查询语句(? 占位参数)' },
|
||||
params: { type: Sequelize.TEXT, comment: '筛选参数 JSON' },
|
||||
file_path: { type: Sequelize.STRING(255), comment: '相对上传根目录的文件路径' },
|
||||
file_name: { type: Sequelize.STRING(255), comment: '文件名' },
|
||||
total_count: { type: Sequelize.INTEGER.UNSIGNED, defaultValue: 0, comment: '总行数' },
|
||||
processed_count: { type: Sequelize.INTEGER.UNSIGNED, defaultValue: 0, comment: '已处理行数' },
|
||||
progress: { type: Sequelize.TINYINT.UNSIGNED, defaultValue: 0, comment: '进度百分比' },
|
||||
error_message: { type: Sequelize.STRING(500), comment: '失败原因' },
|
||||
created_by: { type: Sequelize.BIGINT.UNSIGNED, comment: '提交人ID' },
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
},
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '导出任务(全局任务池)表' }
|
||||
);
|
||||
|
||||
await queryInterface.addIndex('export_tasks', { fields: [ 'principal_id' ], name: 'idx_et_principal' });
|
||||
await queryInterface.addIndex('export_tasks', { fields: [ 'status' ], name: 'idx_et_status' });
|
||||
await queryInterface.addIndex('export_tasks', { fields: [ 'created_at' ], name: 'idx_et_created' });
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable('export_tasks');
|
||||
},
|
||||
};
|
||||
806
backend/package-lock.json
generated
806
backend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
Loading…
x
Reference in New Issue
Block a user