Compare commits

...

13 Commits

Author SHA1 Message Date
liufumingren
da56253d4a feat(shops): 店铺视频号授权支持 + 部署优化
- shops.js: 视频号授权需传 appId/toUserName,新增授权请求/响应调试缓存
- index.js: SPH 运单查询添加调试缓存
- deploy-remote.cjs: 健康检查优化(30次→5次/10s),失败自动回滚 current.md
- config.default.js: 数据库连接池 20→225
2026-08-01 03:45:26 +08:00
liufumingren
315e366c4c feat(inventory): 新增库存异步导出功能
- systemMethods 层:export 提交异步任务 + exportTaskProgress 查询进度
- systems 层:exportInventoryList 导出实现(支持按 stock_id 聚合/按 storage_id 明细)
- 导出任务通过 Redis 缓存管理进度状态(TTL 30min)
2026-08-01 03:45:16 +08:00
liufumingren
bd6013d7b8 fix(order): 拣货/波次/复核/打包/自动出库修复与增强
- pick.js: 修复拣货车绑定逻辑,禁止已绑定任务直接换车
- wave.js: 修复波次拣货车查询(移除 current_task_id)
- recheckOrder.js: 新增 batchQuickRecheckByWave 按波次批量快速复核
- order_packing.js: 时间字段统一格式化输出
- order_auto_outbound.js: 修复仓库去重逻辑
2026-08-01 03:45:06 +08:00
liufumingren
5378fcd137 refactor(print): 打印模块重构
- 新增 systems/order_print.js 订单打印业务层(getPrintDataByWaybillCodes 等)
- print.js 删除 retry 补偿相关代码(normalizeRetrySendPayload/getRetryEligibility)
- order/print.js 新增 getPrintDataByWaybillCodes 方法
- printer_data_builder.js 新增 appendExtraCustomLines + extraCustomLines 参数支持
- polo_api_client.js 添加调试缓存
- 删除 print_retry_compensation 定时任务测试
2026-08-01 03:44:53 +08:00
liufumingren
3736d306bd feat(express): 快递运单创建链路改造
- order_express model 新增 logistics_code/name/delivery_order_code/source_order_codes/store_id 字段
- express.js 业务层改造:创建运单号时写入快照字段
- express_platform.js 适配新字段
- pendingOrder.js 运单分配+拆子单号改造:支持 dispatch 表查询、已取消订单校验、主单号前置检查、step 4 配送中拆单
2026-08-01 03:44:14 +08:00
liufumingren
45b59ea35c feat(camera): 新增摄像头 OSD 叠加功能
- 新增 camera model username/password 字段
- 新增 osd_client.js OSD 客户端库
- 工作台打包时自动叠加 OSD 信息到摄像头(带 Redis 缓存去重)
- 新增迁移脚本:摄像头用户名密码字段
2026-08-01 03:44:02 +08:00
liufumingren
edc164298d feat(waybill): 新增面单/运单管理模块
- 新增 systems/waybill.js 业务层:运单列表查询/详情/导出
- 新增 systemMethods/waybill/warehouse.js 入口层
- 新增 6 个迁移脚本:面单列表索引、store_id 列、物流编码/名称回填、发货单号列、货主ID回填、发货字段回填
- 更新 waybill-module-design.md 设计文档
2026-08-01 03:43:47 +08:00
liufumingren
76e25db7da feat(apiApp): 新增仓库 API 应用管理模块
- 新增 systems/apiApp.js 业务层:CRUD + AppKey/Secret 自动生成 + 仓库隔离
- 新增 systemMethods/apiApp.js 入口层:list/detail/create/update/delete/regenerateSecret
- 注册 methods/system.json API 文档 + changes 变更记录
- 新增迁移脚本:wms_permission 固定 ID 464-470 + 客服组主管及以上角色授权
2026-08-01 03:39:41 +08:00
liufumingren
635e86f984 chore: 提交当前所有变更,准备开始 allocateSubOrderNumber step=4 改造 2026-07-29 13:57:04 +08:00
liufumingren
fb2c00027e refactor(storage.receiving): 导出功能 storeId 改为从 ctx.user.store_id 获取 warehouseId;新增导出相关接口文档 2026-07-27 17:46:56 +08:00
liufumingren
000597fecc fix(order.recheckOrder): waybill_code 加入散单复核列表响应字段 2026-07-27 17:46:42 +08:00
liufumingren
d11ed3b2a2 feat(order.pendingOrder): 新增 allocateSubOrderNumber 子单号异步分配接口与进度查询 2026-07-27 17:46:26 +08:00
liufumingren
f9fbf96ce5 feat(order.packing): 新增 has_video/video_enable 录像筛选与响应字段;运单号改为 express 表解析;setEndTime 增加开始时间校验;forceRecord 优化错误处理 2026-07-27 17:46:03 +08:00
58 changed files with 11666 additions and 1282 deletions

102
app/lib/osd_client.js Normal file
View File

@ -0,0 +1,102 @@
'use strict';
/**
* OSD(屏幕菜单叠加)客户端模块。
* 负责组装 RTSP URL 并调用打印服务设置摄像头 OSD 文字叠加。
*
* 使用方式:
* const osdClient = new (require('../lib/osd_client'))(ctx);
* await osdClient.setOsd({ camera, warehouseId, text, x, y });
*/
class OsdClient {
constructor(ctx) {
this.ctx = ctx;
this.logger = ctx.logger || console;
}
/**
* 组装摄像头 RTSP 地址
* 格式: rtsp://{username}:{password}@{ip}:554/stream{channelId}
*
* @param {Object} camera - 摄像头记录(含 ip/username/password/channel_id)
* @return {string} RTSP URL
*/
buildRtspUrl(camera) {
const ip = camera.ip;
if (!ip) {
throw new Error('摄像头未配置IP地址,无法组装RTSP地址');
}
const username = camera.username || 'admin';
const password = camera.password || '';
const channelId = camera.channel_id;
const rtspPort = 554;
return `rtsp://${username}:${password}@${ip}:${rtspPort}/stream${channelId}`;
}
/**
* 发送 OSD 叠加指令到打印服务
*
* @param {Object} options - 配置选项
* @param {Object} options.camera - 摄像头记录
* @param {Object} [options.server] - 关联的录像服务器(fallback 认证信息)
* @param {number} options.warehouseId - 仓库ID
* @param {string} options.text - OSD 叠加文字
* @param {number} [options.x] - X 坐标(-1 到 1,默认 -0.9)
* @param {number} [options.y] - Y 坐标(-1 到 1,默认 0.8)
* @return {Promise<Object>} 打印服务响应 { status, data, error }
*/
async setOsd(options = {}) {
const { ctx } = this;
const { camera, warehouseId, text, x, y } = options;
if (!camera) throw new Error('摄像头信息不能为空');
if (!text) throw new Error('OSD文字不能为空');
if (warehouseId === undefined || warehouseId === null) throw new Error('仓库ID不能为空');
const rtspUrl = this.buildRtspUrl(camera);
const printServiceUrl = ctx.app.config.printService.url;
const requestData = {
warehouse_id: String(warehouseId),
rtspUrl,
text,
x: x !== undefined ? x : -0.9,
y: y !== undefined ? y : 0.8,
};
const targetUrl = `${printServiceUrl}/camera/setOSD`;
ctx.logger.info('[OSD] 发送设置请求', { url: targetUrl, body: requestData });
let response = null;
let error = null;
try {
const res = await ctx.curl(targetUrl, {
method: 'POST',
contentType: 'json',
data: requestData,
dataType: 'json',
timeout: 10000,
});
response = {
status: res.status,
headers: res.headers,
data: res.data,
};
ctx.logger.info('[OSD] 打印服务回信', { status: res.status, data: res.data });
} catch (err) {
error = err.message;
ctx.logger.warn('[OSD] 打印服务请求失败', { camera_id: camera.id, error: err.message });
}
return {
success: !error && response && response.status >= 200 && response.status < 300,
error,
response,
request: requestData,
};
}
}
module.exports = OsdClient;

View File

@ -49,6 +49,9 @@ class PoloApiClient {
.map(key => `${key}=${encodeURIComponent(signMap[key])}`)
.join('&');
console.log('查询菠萝派平台数据,接口URL:', config.interface_url, '入参bizcontent:', JSON.stringify(bizcontent));
await this.ctx.app.setCacheAsync('PoloApiquery', '查询菠萝派平台数据,接口URL:' + config.interface_url + ',入参bizcontent:' + formBody, 3600);
const response = await this.ctx.curl(String(config.interface_url || ''), {
method: 'POST',
headers: {

View File

@ -556,6 +556,23 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options =
return [ headerLine, ...detailLines ];
}
/**
* 向已有的自定义区文本追加额外行。
* @param {string} customText 已有的自定义区文本。
* @param {Array<string>} extraLines 额外文本行数组。
* @param {string} [lineBreak='\n'] 换行符。
* @return {string} 追加后的文本。
*/
function appendExtraCustomLines(customText, extraLines, lineBreak = '\n') {
const safeLines = Array.isArray(extraLines) ? extraLines.filter(line => String(line || '').trim() !== '') : [];
if (safeLines.length === 0) {
return customText;
}
const prefix = safeLines.join(lineBreak);
const base = String(customText || '').trim();
return base ? `${prefix}${lineBreak}${base}` : prefix;
}
/**
* 将自定义文本行按平台换行符合并为字符串。
* @param {Array<string>} lines 文本行数组。
@ -1237,7 +1254,7 @@ function sanitizeTemplatePrivateFields(value, warnings, currentKey = '') {
* @param {Object} policyConfig 策略配置对象。
* @param {string} customDataTemplateURL 自定义区模板地址默认值。
*/
function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, warnings, policyConfig, customDataTemplateURL) {
function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, warnings, policyConfig, customDataTemplateURL, extraCustomLines = []) {
if (platform !== 'kuaishou') {
return;
}
@ -1278,9 +1295,13 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
}
);
const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, {
lineBreak: LINE_BREAK_MAP.LF,
});
const customProductInfo = appendExtraCustomLines(
mergeWaybillCustomLines(customProductInfoLines, {
lineBreak: LINE_BREAK_MAP.LF,
}),
extraCustomLines,
LINE_BREAK_MAP.LF
);
for (const document of documents) {
if (!isPlainObject(document)) {
@ -1382,7 +1403,7 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde
* @param {Object} orderDelivery 订单对象。
* @param {Object} policyConfig 策略配置对象。
*/
function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig) {
function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig, extraCustomLines = []) {
if (platform !== 'pdd') {
return;
}
@ -1423,10 +1444,14 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
}
);
const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, {
lineBreak: LINE_BREAK_MAP.CR,
trailingLineBreak: true,
});
const customProductInfo = appendExtraCustomLines(
mergeWaybillCustomLines(customProductInfoLines, {
lineBreak: LINE_BREAK_MAP.CR,
trailingLineBreak: true,
}),
extraCustomLines,
LINE_BREAK_MAP.CR
);
/**
* 判断内容对象是否属于拼多多自定义区。
@ -1560,7 +1585,7 @@ function resolveDouyinParams(orderExpress) {
* @param {Object} orderDelivery 订单对象。
* @param {Object} policyConfig 策略配置对象。
*/
function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig) {
function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig, extraCustomLines = []) {
if (platform !== 'douyin') {
return;
}
@ -1610,7 +1635,11 @@ function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderD
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
}
);
const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { lineBreak: '\n' });
const customProductInfo = appendExtraCustomLines(
mergeWaybillCustomLines(customProductInfoLines, { lineBreak: '\n' }),
extraCustomLines,
'\n'
);
for (const document of documents) {
if (!isPlainObject(document)) {
@ -1700,7 +1729,8 @@ function applyCainiaoExpressFieldMapping(
orderDelivery,
policyConfig,
customControlTemplateURL,
warnings
warnings,
extraCustomLines = []
) {
if (platform !== 'cainiao') {
return;
@ -1743,9 +1773,13 @@ function applyCainiaoExpressFieldMapping(
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
}
);
const customControlText = mergeWaybillCustomLines(customProductInfoLines, {
lineBreak: LINE_BREAK_MAP.CR,
});
const customControlText = appendExtraCustomLines(
mergeWaybillCustomLines(customProductInfoLines, {
lineBreak: LINE_BREAK_MAP.CR,
}),
extraCustomLines,
LINE_BREAK_MAP.CR
);
for (const document of documents) {
if (!isPlainObject(document)) {
@ -1904,7 +1938,8 @@ function applyXhsExpressFieldMapping(
orderExpress,
orderDelivery,
policyConfig,
warnings
warnings,
extraCustomLines = []
) {
if (platform !== 'xhs') {
return;
@ -1944,9 +1979,13 @@ function applyXhsExpressFieldMapping(
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
}
);
const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, {
lineBreak: LINE_BREAK_MAP.LF,
});
const customProductInfo = appendExtraCustomLines(
mergeWaybillCustomLines(customProductInfoLines, {
lineBreak: LINE_BREAK_MAP.LF,
}),
extraCustomLines,
LINE_BREAK_MAP.LF
);
for (const document of documents) {
if (!isPlainObject(document)) {
@ -2000,7 +2039,8 @@ function applySphExpressFieldMapping(
skeleton,
orderExpress,
orderDelivery,
policyConfig
policyConfig,
extraCustomLines = []
) {
if (platform !== 'sph') {
return;
@ -2054,9 +2094,13 @@ function applySphExpressFieldMapping(
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
}
);
const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, {
lineBreak: LINE_BREAK_MAP.LF,
}).replace(/\n/g, '<br>');
const customProductInfo = appendExtraCustomLines(
mergeWaybillCustomLines(customProductInfoLines, {
lineBreak: LINE_BREAK_MAP.LF,
}).replace(/\n/g, '<br>'),
extraCustomLines,
'<br>'
);
task.customInfo = isPlainObject(task.customInfo) ? task.customInfo : {};
task.customInfo.data = isPlainObject(task.customInfo.data) ? task.customInfo.data : {};
@ -2137,7 +2181,8 @@ function applyJdExpressFieldMapping(
orderDelivery,
policyConfig,
templateSample,
warnings
warnings,
extraCustomLines = []
) {
if (platform !== 'jd') {
return;
@ -2220,10 +2265,14 @@ function applyJdExpressFieldMapping(
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
}
);
const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, {
lineBreak: LINE_BREAK_MAP.LF,
trailingLineBreak: true,
});
const customProductInfo = appendExtraCustomLines(
mergeWaybillCustomLines(customProductInfoLines, {
lineBreak: LINE_BREAK_MAP.LF,
trailingLineBreak: true,
}),
extraCustomLines,
LINE_BREAK_MAP.LF
);
content.customData = isPlainObject(content.customData) ? content.customData : {};
content.customData.GoodsInfo = customProductInfo;
@ -2243,6 +2292,7 @@ function buildPlatformRequestSkeleton(input = {}) {
const baseResult = buildBaseData(input, normalized.platform, normalized.meta);
const options = isPlainObject(input.options) ? input.options : {};
const extraCustomLines = Array.isArray(options.extraCustomLines) ? options.extraCustomLines : [];
const policyConfig = resolvePolicyConfig(input);
const orderExpressForCompose = isPlainObject(input.order_express)
? { ...input.order_express }
@ -2335,7 +2385,8 @@ function buildPlatformRequestSkeleton(input = {}) {
orderDeliveryForCompose,
policyConfig,
cainiaoCustomControlTemplateURL,
warnings
warnings,
extraCustomLines
);
applyKuaishouExpressFieldMapping(
@ -2345,7 +2396,8 @@ function buildPlatformRequestSkeleton(input = {}) {
orderDeliveryForCompose,
warnings,
policyConfig,
customDataTemplateURL
customDataTemplateURL,
extraCustomLines
);
applyPddExpressFieldMapping(
@ -2353,7 +2405,8 @@ function buildPlatformRequestSkeleton(input = {}) {
skeleton,
orderExpressForCompose,
orderDeliveryForCompose,
policyConfig
policyConfig,
extraCustomLines
);
applyDouyinExpressFieldMapping(
@ -2361,7 +2414,8 @@ function buildPlatformRequestSkeleton(input = {}) {
skeleton,
orderExpressForCompose,
orderDeliveryForCompose,
policyConfig
policyConfig,
extraCustomLines
);
applyJdExpressFieldMapping(
@ -2371,7 +2425,8 @@ function buildPlatformRequestSkeleton(input = {}) {
orderDeliveryForCompose,
policyConfig,
templateSample,
warnings
warnings,
extraCustomLines
);
applyXhsExpressFieldMapping(
@ -2380,7 +2435,8 @@ function buildPlatformRequestSkeleton(input = {}) {
orderExpressForCompose,
orderDeliveryForCompose,
policyConfig,
warnings
warnings,
extraCustomLines
);
applySphExpressFieldMapping(
@ -2388,7 +2444,8 @@ function buildPlatformRequestSkeleton(input = {}) {
skeleton,
orderExpressForCompose,
orderDeliveryForCompose,
policyConfig
policyConfig,
extraCustomLines
);
return {

View File

@ -0,0 +1,267 @@
'use strict';
module.exports = app => {
const { STRING, BIGINT, INTEGER, TINYINT, TEXT, DATE, DECIMAL } = app.Sequelize;
/**
* 售后工单业务类型定义
* 外部可通过 require('./app/model/after_sale_work_order').BUSINESS_TYPES 访问
* 增删业务类型或子类型只需修改此常量,无需 ALTER TABLE
*/
const BUSINESS_TYPES = {
waybill: {
label: '运单',
table: 'wms_order_express',
subtypes: {
intercept: '拦截',
urge: '催件',
damage: '破损',
lost: '丢件',
wrong_info: '信息错误',
},
},
order_delivery: {
label: '发货订单',
table: 'wms_order_delivery',
subtypes: {
mis_shipment: '错发',
missing_item: '少发',
wrong_sku: '错品',
quality_issue: '质量问题',
delivery_delay: '发货延迟',
},
},
entry_order: {
label: '入库单',
table: 'wms_entry_order',
subtypes: {
shortage: '少货',
damage: '破损',
wrong_sku: '错品',
quality_issue: '质量问题',
},
},
order_stockout: {
label: '出库单/退货出库单',
table: 'wms_order_stockout',
subtypes: {
return_issue: '退货异常',
wrong_outbound: '错发',
shortage: '少发',
},
},
receiving: {
label: '收货单',
table: 'wms_receiving',
subtypes: {
shortage: '少货',
damage: '破损',
quality_issue: '质量问题',
},
},
other: {
label: '其他',
table: null,
subtypes: {
general: '通用',
},
},
};
/**
* 根据 business_type 获取关联表名
* @param {string} businessType 业务类型
* @returns {string|null} 关联表名
*/
function getBusinessTable(businessType) {
return BUSINESS_TYPES[businessType]?.table || null;
}
/**
* 校验 business_type + business_sub_type 组合是否合法
* @param {string} businessType 业务类型
* @param {string} businessSubType 业务子类型
* @returns {boolean} 是否合法
*/
function isValidSubType(businessType, businessSubType) {
const def = BUSINESS_TYPES[businessType];
return def && Object.prototype.hasOwnProperty.call(def.subtypes, businessSubType);
}
const AfterSaleWorkOrder = app.model.define('after_sale_work_order', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键ID',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID',
},
store_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '货主ID',
},
work_order_no: {
type: STRING(50),
allowNull: false,
comment: '售后工单号,唯一',
},
business_type: {
type: STRING(50),
allowNull: false,
comment: '关联业务类型',
},
business_sub_type: {
type: STRING(50),
allowNull: false,
comment: '关联业务子类型',
},
business_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '关联业务单据主键ID(多态关联)',
},
business_no: {
type: STRING(100),
allowNull: true,
comment: '关联业务单据号(冗余)',
},
direction: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '记账方向:0=未确定 1=入库 2=出库',
},
status: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '工单状态:0=待处理 1=处理中 2=已完成 3=已关闭 9=已取消',
},
priority: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 50,
comment: '优先级:1~100,数字越大优先级越高',
},
title: {
type: STRING(200),
allowNull: false,
comment: '工单标题/摘要',
},
description: {
type: TEXT,
allowNull: true,
comment: '问题描述',
},
creator_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '创建人ID,关联 account.id;0 表示 AI 自动接待',
},
creator_snapshot: {
type: TEXT,
allowNull: true,
comment: '创建人信息快照(JSON格式);AI创建时记录模型/会话信息',
},
assignee_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '当前处理人ID,关联 account.id',
},
parent_work_order_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '父工单ID,自关联本表;非空时表示子工单',
},
current_step: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 1,
comment: '当前进度,值为当前正在处理的 step_order 序号',
},
claim_needed: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '是否需要理赔:0=不需要 1=需要',
},
claim_amount: {
type: DECIMAL(12, 2),
allowNull: true,
defaultValue: 0.00,
comment: '理赔金额(元)',
},
claim_status: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '理赔状态:0=未理赔 1=已理赔(单笔结清) 2=月结',
},
resolution: {
type: TEXT,
allowNull: true,
comment: '处理结果说明',
},
resolved_at: {
type: DATE,
allowNull: true,
comment: '解决时间',
},
created_at: {
type: DATE,
allowNull: false,
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
comment: '更新时间',
},
deleted_at: {
type: DATE,
allowNull: true,
comment: '软删除时间',
},
}, {
tableName: 'wms_after_sale_work_order',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: true,
deletedAt: 'deleted_at',
comment: '售后工单主表',
});
AfterSaleWorkOrder.associate = () => {
// 自关联:父工单 → 子工单
AfterSaleWorkOrder.hasMany(app.model.AfterSaleWorkOrder, {
foreignKey: 'parent_work_order_id',
sourceKey: 'id',
as: 'children',
});
AfterSaleWorkOrder.belongsTo(app.model.AfterSaleWorkOrder, {
foreignKey: 'parent_work_order_id',
targetKey: 'id',
as: 'parent',
});
// 关联进度步骤表
AfterSaleWorkOrder.hasMany(app.model.AfterSaleWorkOrderStep, {
foreignKey: 'work_order_id',
sourceKey: 'id',
as: 'steps',
});
};
// 挂载业务类型常量及辅助函数到 Model
AfterSaleWorkOrder.BUSINESS_TYPES = BUSINESS_TYPES;
AfterSaleWorkOrder.getBusinessTable = getBusinessTable;
AfterSaleWorkOrder.isValidSubType = isValidSubType;
return AfterSaleWorkOrder;
};

View File

@ -0,0 +1,99 @@
'use strict';
module.exports = app => {
const { STRING, BIGINT, TINYINT, TEXT, DATE } = app.Sequelize;
const AfterSaleWorkOrderStep = app.model.define('after_sale_work_order_step', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键ID',
},
work_order_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '工单ID,关联 wms_after_sale_work_order.id',
},
step_order: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 1,
comment: '步骤序号(从1开始递增)',
},
step_name: {
type: STRING(100),
allowNull: false,
comment: '步骤名称',
},
step_status: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '步骤状态:0=待开始 1=进行中 2=已完成 3=已跳过',
},
operator_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '操作员工ID,关联 account.id',
},
operator_snapshot: {
type: TEXT,
allowNull: true,
comment: '操作人信息快照(JSON格式)',
},
action: {
type: STRING(100),
allowNull: true,
comment: '操作动作描述',
},
remark: {
type: TEXT,
allowNull: true,
comment: '处理备注',
},
started_at: {
type: DATE,
allowNull: true,
comment: '步骤开始时间',
},
completed_at: {
type: DATE,
allowNull: true,
comment: '步骤完成时间',
},
created_at: {
type: DATE,
allowNull: false,
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
comment: '更新时间',
},
deleted_at: {
type: DATE,
allowNull: true,
comment: '软删除时间',
},
}, {
tableName: 'wms_after_sale_work_order_step',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: true,
deletedAt: 'deleted_at',
comment: '售后工单进度步骤表',
});
AfterSaleWorkOrderStep.associate = () => {
AfterSaleWorkOrderStep.belongsTo(app.model.AfterSaleWorkOrder, {
foreignKey: 'work_order_id',
targetKey: 'id',
as: 'workOrder',
});
};
return AfterSaleWorkOrderStep;
};

View File

@ -55,6 +55,16 @@ module.exports = app => {
allowNull: true,
comment: '码流类型(auto/main/sub)',
},
username: {
type: STRING(100),
allowNull: true,
comment: '摄像头登录用户名',
},
password: {
type: STRING(100),
allowNull: true,
comment: '摄像头登录密码',
},
custom_name: {
type: STRING(100),
allowNull: true,

View File

@ -39,7 +39,7 @@ module.exports = app => {
is_galaxy_receive: {
type: ENUM('Y', 'N'),
allowNull: true,
comment: '是否星河签收',
comment: '是否揽收',
},
is_back: {
type: ENUM('Y', 'N'),
@ -122,6 +122,21 @@ module.exports = app => {
allowNull: true,
comment: '仓库ID',
},
store_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '货主ID',
},
delivery_order_code: {
type: STRING(50),
allowNull: true,
comment: '发货单号',
},
source_order_codes: {
type: TEXT,
allowNull: true,
comment: '来源订单号集合',
},
package_material_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,

View File

@ -50,12 +50,6 @@ module.exports = app => {
defaultValue: null,
comment: '录制存储单位:KB/MB/GB/TB',
},
remote_play_url: {
type: STRING(500),
allowNull: true,
defaultValue: null,
comment: '远程播放地址',
},
recording_directory: {
type: STRING(500),
allowNull: true,

View File

@ -222,14 +222,66 @@ class orderServer extends MainService {
return this.fail('订单已同步,不可取消,已转为拦截处理');
}
await existingOrder.update({
// 检查是否在波次中,若在波次中需清除波次关联
const existingWaveId = Number(existingOrder.wave_id || 0);
const updateValues = {
status: 'cancel',
outbound_status: 'fin',
step: 4,
updated_at: new Date(),
}, {
transaction,
});
};
if (existingWaveId > 0) {
updateValues.wave_id = 0;
updateValues.wave_no = '';
}
await existingOrder.update(updateValues, { transaction });
// 波次清理:删除波次索引、更新波次统计
if (existingWaveId > 0) {
try {
await ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({
warehouseId: info.warehouseId,
orderIds: [existingOrder.id],
transaction,
});
const { Op } = this.app.Sequelize;
const WaveBatch = ctx.model.WaveBatch;
if (WaveBatch) {
await WaveBatch.decrement('total_orders', {
by: 1,
where: {
wave_id: existingWaveId,
warehouse_id: info.warehouseId,
total_orders: { [Op.gt]: 0 },
},
transaction,
});
const wave = await WaveBatch.findOne({
where: { wave_id: existingWaveId, warehouse_id: info.warehouseId },
attributes: ['wave_id', 'total_orders', 'wave_status'],
raw: true,
transaction,
});
if (wave) {
const totalOrders = Number(wave.total_orders);
const normalizedTotalOrders = Number.isFinite(totalOrders) ? totalOrders : 0;
if (normalizedTotalOrders <= 0) {
await WaveBatch.update(
{ total_orders: 0, wave_status: -1, update_time: new Date() },
{ where: { wave_id: existingWaveId, warehouse_id: info.warehouseId }, transaction }
);
}
}
}
} catch (waveErr) {
ctx.logger.warn('[QimenOrderCancel] 清理波次关联失败,不影响订单取消', waveErr);
}
}
// 释放储位分配锁定库存(wms_storage / wms_stock_warehouse)
await this.releaseStorageLockForCancel({
@ -240,6 +292,19 @@ class orderServer extends MainService {
await transaction.commit();
// 波次策略扫描清理(不影响主流程)
if (existingWaveId > 0) {
try {
ctx.service.systemMethods.order.wave.enqueueWaveStrategyQuickScanPostOrderChange(
info.warehouseId,
[existingOrder.id],
{ triggerScan: true, source: 'qimenCancel' }
);
} catch (scanErr) {
ctx.logger.warn('[QimenOrderCancel] 波次策略扫描触发失败,不影响主流程', scanErr);
}
}
// 写入取消操作日志(不影响主流程)
try {
if (ctx.model && ctx.model.OperationLog) {

View File

@ -0,0 +1,117 @@
'use strict';
const MainService = require('../main');
/**
* 仓库 API 应用管理 Service
* 管理当前仓库的外部 API 应用(AppKey/Secret 生成、IP 白名单、限流等)。
* 仓库隔离:所有操作自动按 ctx.user.store_id 过滤。
*/
class ApiAppService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = '';
const _noNeedLog = '';
const _noNeedAuth = '';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 查询当前仓库的 API 应用列表(分页)。
* @param {Object} data 查询参数。
* @return {Promise<Object>} 分页结果。
*/
async list(data) {
try {
const result = await this.service.systems.apiApp.list(data || {});
return this.success('获取成功', result);
} catch (e) { return this.fail(e.message); }
}
/**
* 查询单个 API 应用详情。
* @param {Object} data 查询参数。
* @param {number|string} data.id 应用 ID。
* @return {Promise<Object>} 应用详情。
*/
async detail(data) {
try {
const { id } = data || {};
if (!id) return this.fail('ID不能为空');
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id || 0);
const defaultTypeId = await this.service.systems.apiApp.getDefaultInterfaceTypeId();
const record = await ctx.model.ApiApp.findOne({
attributes: [
'id', 'app_name', 'warehouse_id', 'self_app_key', 'self_app_secret',
'self_ip_whitelist', 'callback_url', 'interface_type_id',
'rate_limit', 'sign_method', 'is_enabled', 'created_at', 'updated_at',
],
where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: defaultTypeId },
raw: true,
});
if (!record) return this.fail('API应用不存在');
record.self_app_secret = record.self_app_secret
? String(record.self_app_secret).substring(0, 8) + '****'
: '';
return this.success('获取成功', record);
} catch (e) { return this.fail(e.message); }
}
/**
* 创建 API 应用,自动生成 AppKey 和 AppSecret。
* @param {Object} data 创建参数。
* @return {Promise<Object>} 创建结果(含完整 secret)。
*/
async create(data) {
try {
const result = await this.service.systems.apiApp.create(data || {});
return this.success('创建成功', result);
} catch (e) { return this.fail(e.message); }
}
/**
* 更新 API 应用。
* @param {Object} data 更新参数。
* @return {Promise<Object>} 更新结果。
*/
async update(data) {
try {
const { id, ...fields } = data || {};
if (!id) return this.fail('ID不能为空');
const result = await this.service.systems.apiApp.update(id, fields);
return this.success('更新成功', result);
} catch (e) { return this.fail(e.message); }
}
/**
* 删除/停用 API 应用。
* @param {Object} data 删除参数。
* @return {Promise<Object>} 删除结果。
*/
async delete(data) {
try {
const { id } = data || {};
if (!id) return this.fail('ID不能为空');
await this.service.systems.apiApp.delete(id);
return this.success('删除成功');
} catch (e) { return this.fail(e.message); }
}
/**
* 重新生成 AppSecret。
* @param {Object} data 参数。
* @return {Promise<Object>} 新 secret。
*/
async regenerateSecret(data) {
try {
const { id } = data || {};
if (!id) return this.fail('ID不能为空');
const result = await this.service.systems.apiApp.regenerateSecret(id);
return this.success('重新生成成功', result);
} catch (e) { return this.fail(e.message); }
}
}
module.exports = ApiAppService;

View File

@ -6,9 +6,9 @@ class CameraService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,detail';
const _noNeedRight = 'list,detail,setOsd';
const _noNeedLog = '*';
const _noNeedAuth = 'list,detail';
const _noNeedAuth = 'list,detail,setOsd';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -41,6 +41,12 @@ class CameraService extends MainService {
} catch (e) { return this.fail(e.message); }
}
async setOsd(data) {
try {
return this.success('设置成功', await this.service.systems.camera.setOsd(data));
} catch (e) { return this.fail(e.message); }
}
async delete(data) {
try {
const { id } = data || {};

View File

@ -2288,6 +2288,14 @@ class indexService extends MainService {
const accessToken = String(shopPlain.access_token || '').trim();
const expressList = await this.service.systems.express.getExpressList(true);
const expressNameMap = buildExpressNameMap(expressList, 'SPH');
await this.app.setCacheAsync('SPHquery', JSON.stringify({
interface_url: 'https://api.polyapi.com/OpenAPI/do',
appkey: this.app.config.poloApi.appKey,
app_secret: this.app.config.poloApi.appSecret,
platid,
version: '1.5',
token: accessToken,
}), 3600);
const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', {
}, {
interface_url: 'https://api.polyapi.com/OpenAPI/do',
@ -2297,7 +2305,7 @@ class indexService extends MainService {
version: '1.5',
token: accessToken,
});
console.log('请求的店铺的platformCode', platformCode, '接口响应', JSON.stringify(responseData));
await this.app.setCacheAsync('SPHrequest', JSON.stringify(responseData), 3600);
const parsed = formatDyWaybillSearchResponse(responseData, expressNameMap);
list = parsed.list;
break;

View File

@ -53,6 +53,18 @@ const SYNC_ORDER_IDS_PROGRESS_MAP = Object.freeze({
unknown: 0,
});
const ALLOCATE_SUB_ORDER_TASK_CACHE_KEY_PREFIX = 'order:pending:allocate_sub_order:request:';
const ALLOCATE_SUB_ORDER_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2;
const ALLOCATE_SUB_ORDER_PROGRESS_MAP = Object.freeze({
submitted: 5,
running: 50,
success: 100,
partial: 80,
failed: 100,
not_found: 0,
unknown: 0,
});
/**
* 中国行政区划反向查询表。
*
@ -528,9 +540,9 @@ class PendingOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -2003,6 +2015,12 @@ class PendingOrderService extends OrderBaseService {
};
await this.setAllocateExpressTaskProgress(taskId, taskPayload);
// 捕获 warehouseId 供 setImmediate 异步回调使用,
// 避免 Qimen 等链路中 withPatchedCtxUser 补丁已撤销导致 getCurrentWarehouseId() 返回 0。
const capturedWarehouseId = Number(
this.ctx && this.ctx.user && this.ctx.user.store_id || 0
);
// 后台异步执行
setImmediate(async () => {
try {
@ -2014,6 +2032,7 @@ class PendingOrderService extends OrderBaseService {
const result = await service.systems.express.createWaybillCodePipeline(orders, {
awaitTasks: true,
warehouseId: capturedWarehouseId,
});
await this.setAllocateExpressTaskProgress(taskId, {
@ -5691,7 +5710,7 @@ class PendingOrderService extends OrderBaseService {
const where = this.buildOrderWhere([ orderId ], warehouseId);
const order = await model.findOne({
where,
attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id' ],
attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id', 'sys_logistics_code', 'sys_logistics_name', 'delivery_order_code', 'source_order_codes' ],
raw: true,
});
@ -5746,7 +5765,12 @@ class PendingOrderService extends OrderBaseService {
order_id: orderId,
waybill_code: waybillCode,
logistics_interface_name: logisticsInterfaceName,
logistics_code: String(order.sys_logistics_code || '').trim() || null,
logistics_name: String(order.sys_logistics_name || '').trim() || null,
delivery_order_code: String(order.delivery_order_code || '').trim() || null,
source_order_codes: String(order.source_order_codes || '').trim() || null,
warehouse_id: Number(order.warehouse_id) || warehouseId,
store_id: order.store_id != null ? Number(order.store_id) : null,
business_key: nextBusinessKey,
status: 1,
create_at: new Date(),
@ -5917,6 +5941,715 @@ class PendingOrderService extends OrderBaseService {
}
}
// ========== allocateSubOrderNumber 子单号分配 ==========
/**
* 分配子单号(异步任务模式)。
*
* 为指定订单按 business_key(从 2 开始)逐个子单号分配运单号。
* 将所有 business_key 全量传入 createWaybillCodePipeline,
* 由 pipeline 内部事务 + UNIQUE(order_id,business_key,status,warehouse_id) 索引
* 保证并发安全:已分配(status=1)自动跳过,未分配 INSERT status=0 占位后分配。
*
* @param {Object} data 请求体。
* @param {number|string} data.order_id 订单ID(必填)。
* @param {number} data.sub_order_count 子单号数量(必填,>=1)。
* @return {Promise<Object>} 统一 success 包装,立即返回 task_id。
*/
async allocateSubOrderNumber(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
// 1. 参数校验
const orderId = Number(requestData.order_id);
if (!Number.isInteger(orderId) || orderId <= 0) {
throw new Error('order_id 必须为正整数');
}
const subOrderCount = Number(requestData.sub_order_count);
if (!Number.isInteger(subOrderCount) || subOrderCount < 1) {
throw new Error('sub_order_count 必须为正整数且 >= 1');
}
// 2. 查询订单并校验状态
// 先查 current 表;若不存在再查 dispatch 表(配送中订单可能已被定时任务迁移到 dispatch)
let model = await this.getOrderModel('order', warehouseId);
const where = this.buildOrderWhere([ orderId ], warehouseId);
let order = await model.findOne({
where,
attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'status' ],
raw: true,
});
if (!order) {
model = await this.getOrderModelByTableType('dispatch', warehouseId);
order = await model.findOne({
where,
attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'status' ],
raw: true,
});
}
if (!order) {
throw new Error(`订单 ${orderId} 不存在或不属于当前仓库`);
}
if (order.status === PENDING_CANCEL_STATUS) {
throw new Error(`订单 ${orderId} 已取消,不允许分配子单号`);
}
const allowedSteps = new Set([ 1, 2, 3, 4 ]);
if (!allowedSteps.has(order.step)) {
throw new Error(`订单 ${orderId} 当前步骤为 ${order.step},仅允许待处理(step 1/2/3)或配送中(step 4)的订单分配子单号`);
}
// 仅待处理阶段(step 1/2/3)校验 outbound_status;配送中(step 4)不校验
if (order.step !== 4 && order.outbound_status === PENDING_OUTBOUND_STATUS) {
throw new Error(`订单 ${orderId} 已标记待出库,不允许分配子单号`);
}
// 3. 计算 business_key 列表(从 2 开始)
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel) {
throw new Error('OrderExpress 模型未加载');
}
// 3.1 校验主单号:必须已有 business_key=1 且 status=1 的主单号,才能拆子单号
const { Op } = this.app.Sequelize;
const mainWaybill = await orderExpressModel.findOne({
where: {
order_id: orderId,
warehouse_id: Number(order.warehouse_id) || warehouseId,
business_key: 1,
status: 1,
},
attributes: [ 'id' ],
raw: true,
});
if (!mainWaybill) {
throw new Error(`订单 ${orderId} 尚未分配主单号,请先分配主单号后再拆子单号`);
}
const businessKeys = [];
for (let i = 0; i < subOrderCount; i++) {
businessKeys.push(2 + i);
}
// 4. 预查已有的已分配运单号(status=1),仅用于初始 details 展示与全部跳过优化
const existingCompleted = await orderExpressModel.findAll({
where: {
order_id: orderId,
warehouse_id: Number(order.warehouse_id) || warehouseId,
status: 1,
business_key: { [Op.in]: businessKeys },
},
attributes: [ 'business_key', 'waybill_code' ],
raw: true,
});
const completedBusinessKeyMap = new Map();
if (Array.isArray(existingCompleted)) {
for (const row of existingCompleted) {
completedBusinessKeyMap.set(Number(row.business_key), String(row.waybill_code || '').trim());
}
}
// 5. 生成任务ID,立即返回
const taskId = `sub_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
const taskPayload = {
task_id: taskId,
order_id: orderId,
status: 'submitted',
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.submitted,
message: '子单号分配任务已提交',
result: {
total_count: businessKeys.length,
skip_count: completedBusinessKeyMap.size,
pending_count: businessKeys.length - completedBusinessKeyMap.size,
business_keys: businessKeys,
skipped_business_keys: businessKeys.filter(bk => completedBusinessKeyMap.has(bk)),
pending_business_keys: businessKeys.filter(bk => !completedBusinessKeyMap.has(bk)),
details: businessKeys.map(bk => ({
business_key: bk,
status: completedBusinessKeyMap.has(bk) ? 'skipped' : 'pending',
waybill_code: completedBusinessKeyMap.get(bk) || null,
})),
},
error: '',
};
await this.setAllocateSubOrderTaskProgress(taskId, taskPayload);
// 6. 如果全部已分配,跳过 pipeline 直接完成
if (completedBusinessKeyMap.size === businessKeys.length) {
await this.setAllocateSubOrderTaskProgress(taskId, {
...taskPayload,
status: 'success',
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.success,
message: '子单号分配完成(全部已分配,无待处理项)',
});
return this.success('ok', {
...taskPayload,
status: 'success',
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.success,
message: '子单号分配完成(全部已分配,无待处理项)',
update_time: Date.now(),
});
}
// 7. 后台异步执行分配(全量 business_key 传入 pipeline,由其内部事务保证去重与并发安全)
const orderWarehouseId = Number(order.warehouse_id) || warehouseId;
setImmediate(async () => {
try {
await this.setAllocateSubOrderTaskProgress(taskId, {
...taskPayload,
status: 'running',
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.running,
message: '子单号分配处理中',
});
// 全量传入(含已分配的),pipeline 内部 createWaybillCode 事务会跳过 status=1 的记录
const ordersForPipeline = businessKeys.map(bk => ({
order_id: orderId,
business_key: bk,
sys_platform_code: order.sys_platform_code,
logistics_code: order.logistics_code,
sys_platform_name: order.sys_platform_name,
logistics_name: order.logistics_name,
store_id: order.store_id,
warehouse_id: Number(order.warehouse_id) || warehouseId,
}));
const pipelineResult = await this.service.systems.express.createWaybillCodePipeline(
ordersForPipeline,
{ awaitTasks: true }
);
// 回查最终分配结果
const updatedDetails = await this.buildSubOrderDetails(orderId, orderWarehouseId, businessKeys);
const successCount = updatedDetails.filter(d => d.status === 'allocated' || d.status === 'skipped').length;
const isPartial = successCount < businessKeys.length;
await this.setAllocateSubOrderTaskProgress(taskId, {
...taskPayload,
status: isPartial ? 'partial' : 'success',
progress: isPartial ? ALLOCATE_SUB_ORDER_PROGRESS_MAP.partial : ALLOCATE_SUB_ORDER_PROGRESS_MAP.success,
message: isPartial
? `子单号分配部分完成(${successCount}/${businessKeys.length})`
: '子单号分配完成',
result: {
...taskPayload.result,
pipeline_result: pipelineResult,
details: updatedDetails,
},
});
// 写入操作日志(成功)
try {
await this.writeAllocateSubOrderLog(orderId, orderWarehouseId, {
action: isPartial ? 'SUCCESS_PARTIAL' : 'SUCCESS',
subOrderCount: businessKeys.length,
successCount,
details: updatedDetails,
});
} catch (logErr) {
this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入成功操作日志失败: %s',
logErr && logErr.message ? logErr.message : logErr);
}
} catch (error) {
const errorMessage = error && error.message ? error.message : String(error);
await this.setAllocateSubOrderTaskProgress(taskId, {
...taskPayload,
status: 'failed',
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.failed,
message: '子单号分配失败',
error: errorMessage,
});
// 写错误信息到 order_flag(尝试 current 和 dispatch 两张表)
try {
await this.writeAllocateSubOrderErrorFlag(orderId, orderWarehouseId, errorMessage);
} catch (flagErr) {
this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入 order_flag 失败: %s',
flagErr && flagErr.message ? flagErr.message : flagErr);
}
// 写入操作日志(失败)
try {
await this.writeAllocateSubOrderLog(orderId, orderWarehouseId, {
action: 'FAILED',
errorMessage,
});
} catch (logErr) {
this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入失败操作日志失败: %s',
logErr && logErr.message ? logErr.message : logErr);
}
}
});
return this.success('ok', {
...taskPayload,
update_time: Date.now(),
});
}
/**
* 写入子单号分配的 order_flag 错误信息。
* 尝试更新 current 和 dispatch 两张表,任一成功即返回。
*
* @param {number} orderId 订单ID。
* @param {number} warehouseId 仓库ID。
* @param {string} errorMessage 错误信息。
* @return {Promise<void>} 无返回值。
*/
async writeAllocateSubOrderErrorFlag(orderId, warehouseId, errorMessage) {
const flag = `[子单号分配失败] ${errorMessage}`.substring(0, 500);
const where = this.buildOrderWhere([ orderId ], warehouseId);
const updatePayload = { order_flag: flag, updated_at: new Date() };
// 尝试 current 表
try {
const currentModel = await this.getOrderModel('order', warehouseId);
if (currentModel && typeof currentModel.update === 'function') {
const [ affected ] = await currentModel.update(updatePayload, { where });
if (Number(affected) > 0) return;
}
} catch (err) {
this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] current 表写入 order_flag 失败: %s',
err && err.message ? err.message : err);
}
// 尝试 dispatch 表
try {
const dispatchModel = await this.getOrderModelByTableType('dispatch', warehouseId);
if (dispatchModel && typeof dispatchModel.update === 'function') {
await dispatchModel.update(updatePayload, { where });
}
} catch (err) {
this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] dispatch 表写入 order_flag 失败: %s',
err && err.message ? err.message : err);
}
}
/**
* 写入子单号分配的操作日志。
*
* @param {number} orderId 订单ID。
* @param {number} warehouseId 仓库ID。
* @param {Object} opts 日志详情。
* @param {string} opts.action 操作动作(SUCCESS/SUCCESS_PARTIAL/FAILED)。
* @param {number} [opts.subOrderCount] 子单总数。
* @param {number} [opts.successCount] 成功数。
* @param {string} [opts.errorMessage] 错误信息。
* @param {Array<Object>} [opts.details] 分配详情。
* @return {Promise<void>} 无返回值。
*/
async writeAllocateSubOrderLog(orderId, warehouseId, opts = {}) {
const operator = this.getOrderLogOperator();
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
const now = new Date();
// 状态中文映射
const STATUS_CN = { allocated: '成功', failed: '失败', skipped: '跳过', pending: '处理中' };
const detailSummary = Array.isArray(opts.details)
? opts.details.slice(0, 10).map(d => {
const cn = STATUS_CN[d.status] || d.status;
let seg = `子单${d.business_key}:${cn}`;
if (d.status === 'failed' && d.note) {
seg += `(${d.note})`;
}
return seg;
}).join(', ')
: '';
let message = `子单号分配${opts.action === 'FAILED' ? '失败' : '完成'}`;
if (opts.action === 'SUCCESS_PARTIAL') {
message = `子单号分配部分完成(${opts.successCount}/${opts.subOrderCount})`;
}
if (opts.errorMessage) {
message += ` - ${opts.errorMessage}`;
}
if (detailSummary) {
message += ` | ${detailSummary}`;
}
const logRow = {
business_type: 'order',
business_id: String(orderId),
operation_code: '子单号分配',
operator_id: operator.id,
operator_name: operator.name,
external_log_type: 'NONE',
warehouse_id: logWarehouseId || null,
platform_code: 'SYSTEM',
message: message.substring(0, 1000),
created_at: now,
};
if (this.ctx.model && this.ctx.model.OperationLog) {
await this.ctx.model.OperationLog.create(logRow);
} else if (this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog) {
await this.ctx.service.systems.operationLog.createOperationLog(logRow);
}
}
/**
* 查询子单号分配任务进度。
*
* 可按 task_id 或 business_key 查询。
* 若传入 business_key,返回该 business_key 对应的分配详情。
*
* @param {Object} data 请求体。
* @param {string} data.task_id 任务ID。
* @param {string} data.taskId 任务ID(驼峰写法)。
* @param {number} [data.business_key] 子单号业务ID(可选,按业务ID过滤)。
* @param {number} [data.businessKey] 子单号业务ID(可选,驼峰写法)。
* @return {Promise<Object>} 统一 success 包装。
*/
async allocateSubOrderNumberProgress(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const taskId = String(requestData.task_id || requestData.taskId || '').trim();
const businessKey = Number(requestData.business_key || requestData.businessKey);
if (!taskId) {
return this.success('ok', {
task_id: '',
status: 'not_found',
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.not_found,
message: '任务不存在',
result: null,
error: '',
update_time: Date.now(),
});
}
const cachedTask = await this.getAllocateSubOrderTaskProgress(taskId);
if (!cachedTask) {
return this.success('ok', {
task_id: taskId,
status: 'not_found',
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.not_found,
message: '任务不存在',
result: null,
error: '',
update_time: Date.now(),
});
}
// 如果传入了 business_key,过滤出该业务ID对应的详情
let filteredResult = cachedTask.result;
if (Number.isInteger(businessKey) && businessKey > 0 && cachedTask.result) {
const details = Array.isArray(cachedTask.result.details) ? cachedTask.result.details : [];
const matchedDetail = details.find(d => Number(d.business_key) === businessKey);
filteredResult = {
...cachedTask.result,
filtered_business_key: businessKey,
matched_detail: matchedDetail || null,
};
}
return this.success('ok', {
...cachedTask,
result: filteredResult,
update_time: cachedTask.update_time || Date.now(),
});
}
// ========== allocateSubOrderNumber 缓存工具方法 ==========
/**
* 获取子单号分配任务缓存键。
*
* @param {string} taskId 任务ID。
* @return {string} 缓存键。
*/
getAllocateSubOrderTaskCacheKey(taskId = '') {
const normalizedTaskId = String(taskId || '').trim();
if (!normalizedTaskId) {
return '';
}
return `${ALLOCATE_SUB_ORDER_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
}
/**
* 写入子单号分配任务进度。
*
* @param {string} taskId 任务ID。
* @param {Object} payload 任务状态与结果。
* @return {Promise<void>}
*/
async setAllocateSubOrderTaskProgress(taskId = '', payload = {}) {
const cacheKey = this.getAllocateSubOrderTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
return;
}
const safePayload = this.isPlainObject(payload) ? payload : {};
const progressPayload = {
task_id: String(taskId || '').trim(),
order_id: safePayload.order_id || null,
status: String(safePayload.status || 'unknown').trim(),
progress: Number(safePayload.progress || 0),
message: String(safePayload.message || ''),
result: safePayload.result || null,
error: String(safePayload.error || ''),
update_time: Date.now(),
};
try {
await this.app.setCacheAsync(cacheKey, progressPayload, ALLOCATE_SUB_ORDER_TASK_CACHE_TTL_SECONDS);
} catch (error) {
this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入任务进度缓存失败: %s', error && error.message ? error.message : error);
}
}
/**
* 读取子单号分配任务进度。
*
* @param {string} taskId 任务ID。
* @return {Promise<Object|null>} 任务缓存结果。
*/
async getAllocateSubOrderTaskProgress(taskId = '') {
const cacheKey = this.getAllocateSubOrderTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
return null;
}
try {
const cached = await this.app.getCacheAsync(cacheKey);
if (!this.isPlainObject(cached)) {
return null;
}
return cached;
} catch (error) {
this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 读取任务进度缓存失败: %s', error && error.message ? error.message : error);
return null;
}
}
/**
* 回查子单号分配结果详情(pipeline 执行后调用)。
*
* 根据 order_express 表最终状态判断每个 business_key 的结果:
* - status=1 且 waybill_code 非空 → allocated(本次分配成功或之前已分配)
* - status=0 → pipeline 占位但 API 未完成 → failed
* - 无记录 → failed(pipeline 未处理到)
*
* @param {number} orderId 订单ID。
* @param {number} warehouseId 仓库ID。
* @param {number[]} businessKeys 全部 business_key 列表。
* @return {Promise<Array<Object>>} 每个 business_key 的分配详情。
*/
async buildSubOrderDetails(orderId, warehouseId, businessKeys) {
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel) {
return businessKeys.map(bk => ({
business_key: bk,
status: 'unknown',
waybill_code: null,
note: 'OrderExpress 模型未加载',
}));
}
const { Op } = this.app.Sequelize;
const allRecords = await orderExpressModel.findAll({
where: {
order_id: orderId,
warehouse_id: warehouseId,
business_key: { [Op.in]: businessKeys },
},
attributes: [ 'business_key', 'waybill_code', 'status' ],
raw: true,
});
const recordMap = new Map();
if (Array.isArray(allRecords)) {
for (const row of allRecords) {
// 同一 business_key 可能有多条(status 不同),优先取 status=1 的
const existing = recordMap.get(Number(row.business_key));
if (!existing || Number(row.status) === 1) {
recordMap.set(Number(row.business_key), row);
}
}
}
// 兜底:如果 order_express 中一条记录都没有,尝试从订单表的 order_flag 获取异常信息
let orderFlagNote = '';
if (recordMap.size === 0) {
try {
const orderWhere = this.buildOrderWhere([ orderId ], warehouseId);
// 查 current 表
let orderModel = await this.getOrderModel('order', warehouseId);
let orderRow = await orderModel.findOne({
where: orderWhere,
attributes: [ 'order_flag' ],
raw: true,
});
// 查 dispatch 表兜底
if (!orderRow) {
orderModel = await this.getOrderModelByTableType('dispatch', warehouseId);
orderRow = await orderModel.findOne({
where: orderWhere,
attributes: [ 'order_flag' ],
raw: true,
});
}
if (orderRow && orderRow.order_flag) {
orderFlagNote = `(订单异常: ${String(orderRow.order_flag).trim()})`;
}
} catch (err) {
// 查 order_flag 失败不影响主流程
this.ctx.logger.warn('[pendingOrder.buildSubOrderDetails] 查询 order_flag 失败: %s',
err && err.message ? err.message : err);
}
}
return businessKeys.map(bk => {
const record = recordMap.get(bk);
if (record && Number(record.status) === 1 && String(record.waybill_code || '').trim()) {
return {
business_key: bk,
status: 'allocated',
waybill_code: String(record.waybill_code || '').trim(),
note: '子单号分配成功',
};
}
if (record && Number(record.status) === 0) {
return {
business_key: bk,
status: 'failed',
waybill_code: null,
note: '运单占位已创建但 API 未返回运单号(status=0)',
};
}
const baseNote = '未找到分配的运单记录';
return {
business_key: bk,
status: 'failed',
waybill_code: null,
note: orderFlagNote ? `${baseNote}${orderFlagNote}` : baseNote,
};
});
}
/**
* 批量设置订单为已打印状态。
*
* 将给定订单 ID 列表中属于当前仓库的订单的 print_status 更新为 'fin'。
* 先查 current 表(wms_order_delivery_{warehouseId}),再查 dispatch 表
* (wms_order_delivery_{warehouseId}_dispatch)兜底。
* 仅允许 step 在 [1,2,3] 且 status 不为 'cancel' 的订单操作,已打印(print_status='fin')的订单会被静默跳过。
*
* @param {Object} data 请求体。
* @param {Array<number|string>|number|string} [data.order_ids] 订单ID集合(下划线写法)。
* @param {Array<number|string>|number|string} [data.orderIds] 订单ID集合(驼峰别名)。
* @param {Array<number|string>|number|string} [data.ids] 订单ID集合(简写别名)。
* @return {Promise<Object>} 统一 success 包装的更新结果。
*/
async batchMarkPrinted(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
const operator = this.getOrderLogOperator();
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
throw new Error('未识别到当前仓库上下文');
}
const rawIds = requestData.order_ids !== undefined ? requestData.order_ids
: requestData.orderIds !== undefined ? requestData.orderIds
: requestData.ids;
const orderIds = this.normalizeIdsInput(rawIds);
if (orderIds.length === 0) {
throw new Error('order_ids 参数不能为空或格式错误');
}
const { Op } = this.app.Sequelize;
const now = new Date();
const buildWhere = () => ({
step: { [Op.in]: [ 1, 2, 3 ] },
status: { [Op.ne]: 'cancel' },
print_status: { [Op.ne]: 'fin' },
});
// 1. 先查 current 表
const currentModel = await this.getOrderModel('order', warehouseId);
const currentWhere = {
...this.buildOrderWhere(orderIds, warehouseId),
...buildWhere(),
};
const [ currentAffected ] = await currentModel.update(
{ print_status: 'fin', updated_at: now },
{ where: currentWhere }
);
let updatedCount = Number(currentAffected || 0);
// 2. 查询 current 表中已存在的订单 ID,计算出未命中的 ID
const currentFoundRows = await currentModel.findAll({
attributes: [ 'id' ],
where: this.buildOrderWhere(orderIds, warehouseId),
raw: true,
});
const currentFoundIds = new Set(
(Array.isArray(currentFoundRows) ? currentFoundRows : []).map(row => Number(row.id))
);
const missingIds = orderIds.filter(id => !currentFoundIds.has(id));
// 3. dispatch 表兜底
if (missingIds.length > 0) {
try {
const dispatchModel = await this.ctx.model.OrderDeliveryFactory.getDispatchModel(warehouseId);
if (dispatchModel && typeof dispatchModel.update === 'function') {
const dispatchWhere = {
id: { [Op.in]: missingIds },
warehouse_id: warehouseId,
...buildWhere(),
};
const [ dispatchAffected ] = await dispatchModel.update(
{ print_status: 'fin', updated_at: now },
{ where: dispatchWhere }
);
updatedCount += Number(dispatchAffected || 0);
}
} catch (dispatchErr) {
this.ctx.logger.warn('[PendingOrderService.batchMarkPrinted] dispatch 表更新失败,不影响 current 表结果', dispatchErr);
}
}
// 写入操作日志(不影响主流程)
try {
const opLogService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog;
if (opLogService && typeof opLogService.createOperationLogs === 'function') {
const logPayloads = orderIds.map(orderId => ({
businessType: 'order',
businessId: String(orderId),
operationCode: 'ORDER_BATCH_MARK_PRINTED',
operator,
extras: {
warehouseId: logWarehouseId,
orderId,
message: `批量标记已打印:订单 ${orderId}`,
},
beforeChanges: null,
}));
await opLogService.createOperationLogs(logPayloads);
}
} catch (logErr) {
this.ctx.logger.warn('[PendingOrderService.batchMarkPrinted] 写入操作日志失败,不影响业务', logErr);
}
return this.success('ok', {
updated_count: updatedCount,
ids: orderIds,
});
}
}
module.exports = PendingOrderService;

View File

@ -11,9 +11,9 @@ class OrderPrintService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData';
const _noNeedLog = 'getWavePrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData';
const _noNeedAuth = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData';
const _noNeedRight = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes';
const _noNeedLog = 'getWavePrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes';
const _noNeedAuth = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -120,6 +120,36 @@ class OrderPrintService extends OrderBaseService {
});
}
/**
* 按运单号数组拉取平台打印中间态数据。
*
* method 层仅负责参数解构与边界校验,具体业务查询与打印数据组装由 systems 层实现。
* 仓库ID统一从当前上下文获取,无需调用方传入。
*
* @param {Object} data 请求体。
* @param {Array<string>} data.waybill_codes 运单号数组。
* @return {Promise<Object>} 统一 success 包装的平台打印中间态结果。
*/
async getPrintDataByWaybillCodes(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const {
waybill_codes: waybillCodes,
} = requestData;
if (!Array.isArray(waybillCodes) || waybillCodes.length === 0) {
throw new Error('waybill_codes 必填,且必须为非空数组');
}
const result = await this.service.systems.orderPrint.getPrintDataByWaybillCodes({
waybillCodes,
});
return this.success('ok', {
data: result,
code: 200,
});
}
/**
* 按分组解锁波次平台打印锁。
*

View File

@ -10,9 +10,9 @@ class RecheckOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,queryRecheckOrderSingleList';
const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck';
const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,queryRecheckOrderSingleList';
const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList';
const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave';
const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -79,6 +79,7 @@ class RecheckOrderService extends OrderBaseService {
match_type: matchType,
list_type: 'group',
waybill_no: keyword,
wave_id: orderWaveId,
picker_id: pickerInfo.picker_id,
picker_name: pickerInfo.picker_name,
task_id: groupTaskId,
@ -2293,21 +2294,7 @@ class RecheckOrderService extends OrderBaseService {
async unbindCartForTask(taskId, warehouseId, operatorUserId) {
const { ctx } = this;
// 1. 清空波次拣货任务的车绑定信息
await ctx.model.query(
`UPDATE wms_wave_pick_task
SET current_cart_id = NULL,
current_cart_code_snapshot = NULL,
update_time = NOW()
WHERE id = :taskId
AND warehouse_id = :warehouseId`,
{
replacements: { taskId, warehouseId },
type: ctx.model.QueryTypes.UPDATE,
}
);
// 2. 停用拣货车绑定记录
// 停用拣货车绑定记录
await ctx.model.query(
`UPDATE wms_pick_task_cart_binding
SET is_active = 0,
@ -2322,21 +2309,6 @@ class RecheckOrderService extends OrderBaseService {
type: ctx.model.QueryTypes.UPDATE,
}
);
// 3. 释放拣货车(清空当前任务和绑定用户)
await ctx.model.query(
`UPDATE wms_pick_cart
SET current_task_id = NULL,
bind_user_id = NULL,
last_seen_time = NOW(),
update_time = NOW()
WHERE warehouse_id = :warehouseId
AND current_task_id = :taskId`,
{
replacements: { taskId, warehouseId },
type: ctx.model.QueryTypes.UPDATE,
}
);
}
/**
@ -2596,16 +2568,44 @@ class RecheckOrderService extends OrderBaseService {
/**
* 通过车号查找匹配的拣货任务行。
* 匹配优先级:
* 1. wms_wave_pick_task.current_cart_code_snapshot(任务主表车号快照)
* 2. wms_wave_pick_task_order.cart_code_snapshot(任务订单行车号快照,仅散单模式有数据)
* 3. wms_pick_task_cart_binding(车任务绑定表,所有模式均有记录,回退兜底)
* 1. wms_pick_task_cart_binding(车任务绑定表,unbind_time IS NULL,权威数据源)
* 2. wms_wave_pick_task.current_cart_code_snapshot / wms_wave_pick_task_order.cart_code_snapshot(快照回退兜底)
* @param {string} cartCode 车号。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object|null>} 任务行,未找到返回 null。
*/
const findTaskByCartCode = async (cartCode, warehouseId) => {
// 第一优先级:任务主表车号快照 + 任务订单行车号快照
const primaryRows = await ctx.model.query(
// 第一优先级:车任务绑定表(权威活跃绑定数据源,unbind_time IS NULL 表示未解绑)
const bindingRows = await ctx.model.query(
`
SELECT
t.id AS task_id,
t.task_no,
t.pick_mode,
t.status,
t.review_status,
t.current_cart_code_snapshot
FROM wms_pick_task_cart_binding b
INNER JOIN wms_wave_pick_task t
ON t.id = b.task_id
WHERE b.cart_code_snapshot = :cartCode
AND b.warehouse_id = :warehouseId
AND b.unbind_time IS NULL
ORDER BY b.create_time DESC, b.id DESC
LIMIT 1
`,
{
replacements: { warehouseId, cartCode },
type: ctx.model.QueryTypes.SELECT,
}
);
if (Array.isArray(bindingRows) && bindingRows.length > 0) {
return bindingRows[0];
}
// 第二优先级(回退兜底):任务主表 + 任务订单行快照
const snapshotRows = await ctx.model.query(
`
SELECT
t.id AS task_id,
@ -2634,36 +2634,7 @@ class RecheckOrderService extends OrderBaseService {
}
);
if (Array.isArray(primaryRows) && primaryRows.length > 0) {
return primaryRows[0];
}
// 第二优先级(回退):车任务绑定表(覆盖小团购等无 wms_wave_pick_task_order 记录的场景)
const bindingRows = await ctx.model.query(
`
SELECT
t.id AS task_id,
t.task_no,
t.pick_mode,
t.status,
t.review_status,
t.current_cart_code_snapshot
FROM wms_pick_task_cart_binding b
INNER JOIN wms_wave_pick_task t
ON t.id = b.task_id
WHERE b.cart_code_snapshot = :cartCode
AND b.warehouse_id = :warehouseId
AND b.is_active = 1
ORDER BY b.create_time DESC, b.id DESC
LIMIT 1
`,
{
replacements: { warehouseId, cartCode },
type: ctx.model.QueryTypes.SELECT,
}
);
return (Array.isArray(bindingRows) && bindingRows.length > 0) ? bindingRows[0] : null;
return (Array.isArray(snapshotRows) && snapshotRows.length > 0) ? snapshotRows[0] : null;
};
const taskRow = await findTaskByCartCode(cartCode, warehouseId);
@ -3176,7 +3147,8 @@ class RecheckOrderService extends OrderBaseService {
o.weight_type,
o.status,
o.create_at,
o.recheck_time
o.recheck_time,
(SELECT oe.waybill_code FROM order_express oe WHERE oe.order_id = o.id AND oe.delete_at IS NULL LIMIT 1) AS waybill_code
FROM ${orderTableName} o
${whereClause}
ORDER BY o.id ASC
@ -3219,6 +3191,7 @@ class RecheckOrderService extends OrderBaseService {
items_total: Number(row?.items_total || 0),
items_weight: row?.items_weight != null ? Number(row.items_weight) : null,
weight_type: this.formatWeightTypeLabel(row?.weight_type),
waybill_code: String(row?.waybill_code || '').trim(),
status: Number(row?.status || 0),
create_at: row?.create_at || null,
recheck_time: row?.recheck_time || null,
@ -3659,6 +3632,200 @@ class RecheckOrderService extends OrderBaseService {
};
}
/**
* 规范波次 ID 入参,兼容 wave_ids、waveIds、wave_id 等写法。
* @param {Object} data 请求体。
* @return {number[]} 波次 ID 列表。
*/
normalizeWaveIds(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const rawIds = requestData.wave_ids;
const sourceIds = [];
if (Array.isArray(rawIds)) {
sourceIds.push(...rawIds);
} else if (typeof rawIds === 'string') {
sourceIds.push(...rawIds.split(','));
} else if (rawIds !== undefined && rawIds !== null && rawIds !== '') {
sourceIds.push(rawIds);
} else if (requestData.waveIds !== undefined && requestData.waveIds !== null && requestData.waveIds !== '') {
const val = requestData.waveIds;
if (Array.isArray(val)) sourceIds.push(...val);
else if (typeof val === 'string') sourceIds.push(...val.split(','));
else sourceIds.push(val);
} else if (requestData.wave_id !== undefined && requestData.wave_id !== null && requestData.wave_id !== '') {
sourceIds.push(requestData.wave_id);
}
const normalizedIds = [];
for (const value of sourceIds) {
const normalizedId = Number(String(value).trim());
if (Number.isFinite(normalizedId) && normalizedId > 0) {
normalizedIds.push(normalizedId);
}
}
return Array.from(new Set(normalizedIds));
}
/**
* 按波次批量快捷复核:传入波次 IDs 列表,对每个波次下所有有效订单执行前置检查
* (已分配储位、已分配快递、已同步且未被拦截),必要时自动完成拣货(含库存锁定校验与扣减、
* 库存流水写入、拣货任务状态同步)后标记复核(含复核任务记录、任务复核状态更新、车任务解绑、
* 操作日志)。每个订单在独立事务中执行,支持部分失败,不满足条件的订单跳过并返回原因。
*
* @param {Object} data 请求体。
* @param {number[]|string} [data.wave_ids] 波次 ID 列表,支持数组或以逗号分隔的字符串。
* @param {number[]|string} [data.waveIds] 波次 ID 列表别名(驼峰写法)。
* @param {number} [data.wave_id] 单个波次 ID。
* @return {Promise<Object>} 处理结果,包含 success/failed 列表及计数。
*/
async batchQuickRecheckByWave(data = {}) {
const { ctx } = this;
const warehouseId = this.getWarehouseId();
const waveIds = this.normalizeWaveIds(data);
if (waveIds.length === 0) {
this.ctx.throw(400, '波次ID列表不能为空');
}
// ── 1. 批量查询所有波次下的订单 ──
const orderModel = await this.getOrderModel('order', warehouseId);
const orderRows = await orderModel.findAll({
where: {
wave_id: { [this.app.Sequelize.Op.in]: waveIds },
warehouse_id: warehouseId,
},
attributes: [
'id', 'delivery_order_code', 'pre_delivery_order_code',
'storage_status', 'post_status', 'sync_status', 'status', 'intercept_status',
'pick_status', 'recheck_status', 'wave_id', 'wave_no',
],
raw: true,
});
// 按 wave_id 分组
const waveOrderMap = new Map();
for (const row of orderRows) {
const wid = Number(row.wave_id);
if (!waveOrderMap.has(wid)) {
waveOrderMap.set(wid, []);
}
waveOrderMap.get(wid).push(row);
}
// ── 2. 前置条件检查:逐波次、逐订单校验 ──
const allSuccessOrders = [];
const allFailedOrders = [];
for (const waveId of waveIds) {
const waveOrders = waveOrderMap.get(waveId) || [];
if (waveOrders.length === 0) {
allFailedOrders.push({
wave_id: waveId,
reason: '波次下无订单',
});
continue;
}
const validOrders = [];
for (const order of waveOrders) {
const orderId = Number(order.id);
const interceptStatus = String(order.intercept_status || '').trim();
if (interceptStatus === 'intercepted' || interceptStatus === 'intercepted_at_warehouse') {
allFailedOrders.push({
order_id: orderId,
wave_id: waveId,
delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(),
reason: '已拦截',
});
continue;
}
const storageStatus = String(order.storage_status || '').trim();
if (storageStatus !== 'fin') {
allFailedOrders.push({
order_id: orderId,
wave_id: waveId,
delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(),
reason: '未分配储位',
});
continue;
}
const postStatus = String(order.post_status || '').trim();
if (postStatus !== 'fin') {
allFailedOrders.push({
order_id: orderId,
wave_id: waveId,
delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(),
reason: '没有分配快递',
});
continue;
}
const syncStatus = String(order.sync_status || '').trim();
if (syncStatus !== 'fin') {
allFailedOrders.push({
order_id: orderId,
wave_id: waveId,
delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(),
reason: '没有同步',
});
continue;
}
validOrders.push(order);
}
// ── 3. 逐订单在独立事务中执行拣货完成 + 复核标记 ──
for (const order of validOrders) {
const orderId = Number(order.id);
try {
await ctx.model.transaction(async transaction => {
// 3a. 若未完成拣货,先执行拣货完成流程
const pickStatus = String(order.pick_status || '').trim();
if (pickStatus !== 'fin') {
await this._completePickForOrder(orderId, warehouseId, transaction);
// 更新内存中的 pick_status,避免后续 _markRecheckForOrder 因旧值误判
order.pick_status = 'fin';
}
// 3b. 标记复核
await this._markRecheckForOrder(order, warehouseId, transaction);
});
allSuccessOrders.push({
order_id: orderId,
wave_id: Number(order.wave_id) || waveId,
delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(),
});
} catch (error) {
ctx.logger.warn(
`[batchQuickRecheckByWave] 订单复核失败, orderId=${orderId}, waveId=${waveId}, error=${error.message}`
);
allFailedOrders.push({
order_id: orderId,
wave_id: waveId,
delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(),
reason: `复核失败: ${error.message}`,
});
}
}
}
return {
success: allSuccessOrders,
failed: allFailedOrders,
success_count: allSuccessOrders.length,
failed_count: allFailedOrders.length,
};
}
/**
* 完成单个订单的拣货流程(内部方法,在事务中执行)。
* 包含:更新拣货任务订单状态、订单拣货状态、拣货记录状态、扣减库存锁定数量与可用数量、写库存流水。
@ -4292,6 +4459,31 @@ class RecheckOrderService extends OrderBaseService {
`[batchQuickRecheck] 解绑车任务失败(复核已成功), taskId=${taskId}, orderId=${orderId}, error=${unbindError.message}`
);
}
// 更新 wms_wave_pick_task 任务状态:status=3(已完成),review_status=3(复核通过)
const operatorName = String(operator.name || '').trim();
const taskStatusSetClauses = [
'status = 3',
'review_status = 3',
'review_finish_time = :now',
'review_time = :now',
'update_time = NOW()',
];
if (operatorUserId > 0) {
taskStatusSetClauses.push('review_user_id = :operatorUserId');
taskStatusSetClauses.push('review_user_name = :operatorName');
}
await ctx.model.query(
`UPDATE wms_wave_pick_task
SET ${taskStatusSetClauses.join(',\n ')}
WHERE id = :taskId
AND warehouse_id = :warehouseId`,
{
replacements: { taskId, warehouseId, operatorUserId, operatorName, now },
type: ctx.model.QueryTypes.UPDATE,
transaction,
}
);
}
/**
@ -4306,21 +4498,6 @@ class RecheckOrderService extends OrderBaseService {
async _unbindCartForTaskInTransaction(taskId, warehouseId, operatorUserId, transaction) {
const { ctx } = this;
// 清空波次拣货任务的车绑定信息
await ctx.model.query(
`UPDATE wms_wave_pick_task
SET current_cart_id = NULL,
current_cart_code_snapshot = NULL,
update_time = NOW()
WHERE id = :taskId
AND warehouse_id = :warehouseId`,
{
replacements: { taskId, warehouseId },
type: ctx.model.QueryTypes.UPDATE,
transaction,
}
);
// 停用拣货车绑定记录
await ctx.model.query(
`UPDATE wms_pick_task_cart_binding
@ -4337,26 +4514,6 @@ class RecheckOrderService extends OrderBaseService {
transaction,
}
);
// 释放拣货车
await ctx.model.query(
`UPDATE wms_pick_cart
SET status = 'idle',
current_task_id = NULL,
update_time = NOW()
WHERE id IN (
SELECT cart_id
FROM wms_pick_task_cart_binding
WHERE task_id = :taskId
AND warehouse_id = :warehouseId
)
AND warehouse_id = :warehouseId`,
{
replacements: { taskId, warehouseId },
type: ctx.model.QueryTypes.UPDATE,
transaction,
}
);
}
/**

View File

@ -11347,7 +11347,7 @@ class WaveService extends OrderBaseService {
: 0;
const cartRows = await this.ctx.model.query(`
SELECT id, cart_code, current_task_id
SELECT id, cart_code
FROM wms_pick_cart
WHERE id = :cartId
AND warehouse_id = :warehouseId
@ -11367,9 +11367,31 @@ class WaveService extends OrderBaseService {
throw new Error(`拣货车不存在或已停用: ${cartId}`);
}
const activeTaskId = Number(cartRow.current_task_id || 0);
if (activeTaskId > 0 && activeTaskId !== taskId) {
throw new Error(`拣货车已被任务占用: ${cartId}`);
// 通过绑定表判断车是否被其他活跃任务占用(不依赖 wms_pick_cart.current_task_id)
const bindingRows = await this.ctx.model.query(`
SELECT b.task_id
FROM wms_pick_task_cart_binding b
INNER JOIN wms_wave_pick_task t ON t.id = b.task_id
WHERE b.cart_id = :cartId
AND b.warehouse_id = :warehouseId
AND b.is_active = 1
AND t.status IN (0, 1)
LIMIT 1
FOR UPDATE
`, {
replacements: {
cartId,
warehouseId,
},
type: this.ctx.model.QueryTypes.SELECT,
transaction,
});
const activeBindingTaskId = Number(
(Array.isArray(bindingRows) && bindingRows.length > 0 ? bindingRows[0]?.task_id : 0)
);
if (activeBindingTaskId > 0 && activeBindingTaskId !== taskId) {
throw new Error(`拣货车已被活动任务占用: ${cartId}`);
}
await this.bulkInsertRows('wms_pick_task_cart_binding', [{
@ -11385,25 +11407,6 @@ class WaveService extends OrderBaseService {
unbind_time: null,
}], transaction);
await this.ctx.model.query(`
UPDATE wms_pick_cart
SET
current_task_id = :taskId,
bind_user_id = :operatorId,
last_bind_time = NOW(),
last_seen_time = NOW()
WHERE id = :cartId
AND warehouse_id = :warehouseId
`, {
replacements: {
taskId,
operatorId,
cartId,
warehouseId,
},
transaction,
});
await this.ctx.model.query(`
UPDATE wms_wave_pick_task
SET
@ -12171,8 +12174,6 @@ class WaveService extends OrderBaseService {
SET
status = 9,
wave_count = 0,
current_cart_id = NULL,
current_cart_code_snapshot = NULL,
${hasCancelledAtColumn ? 'cancelled_at = NOW(),' : ''}
update_time = NOW()
WHERE id = :taskId
@ -12204,23 +12205,6 @@ class WaveService extends OrderBaseService {
transaction,
});
await this.ctx.model.query(`
UPDATE wms_pick_cart
SET
current_task_id = NULL,
bind_user_id = NULL,
last_seen_time = NOW(),
update_time = NOW()
WHERE warehouse_id = :warehouseId
AND current_task_id = :taskId
`, {
replacements: {
taskId,
warehouseId,
},
transaction,
});
await this.bulkInsertRows('wms_wave_pick_action_log', [{
task_id: taskId,
warehouse_id: warehouseId,

View File

@ -138,7 +138,7 @@ class PrintService extends MainService {
return {
status: 'sent',
send_status: 'sent',
print_status: 'printed',
print_status: 'unknown',
sent_time: sentTime,
print_time: sentTime,
fail_code: null,
@ -170,55 +170,6 @@ class PrintService extends MainService {
};
}
/**
* 规范化补打所需的已落库发送数据。
* @param {Object|string} recordData 打印记录 data 字段。
* @return {{success:boolean,data?:Object,error?:string}} 解析结果。
*/
normalizeRetrySendPayload(recordData) {
let normalizedRecordData = recordData;
if (typeof normalizedRecordData === 'string') {
try {
normalizedRecordData = JSON.parse(normalizedRecordData);
} catch (error) {
return {
success: false,
error: '打印记录 data 不是有效 JSON',
};
}
}
if (!normalizedRecordData || typeof normalizedRecordData !== 'object' || Array.isArray(normalizedRecordData)) {
return {
success: false,
error: '打印记录 data 结构不合法',
};
}
const printer = String(normalizedRecordData.printer || '').trim();
const component = String(normalizedRecordData.component || '').trim();
const type = String(normalizedRecordData.type || '').trim();
const payloadData = normalizedRecordData.data;
const orderIds = this.normalizeOrderIds(normalizedRecordData.order_ids);
if (!printer || !type || !payloadData || typeof payloadData !== 'object' || Array.isArray(payloadData)) {
return {
success: false,
error: '打印记录 data 缺少 printer/type/data',
};
}
return {
success: true,
data: {
printer,
component,
type,
order_ids: orderIds,
data: JSON.parse(JSON.stringify(payloadData)),
},
};
}
/**
* 规范化订单ID数组,过滤非法值并去重。
* @param {Array<number|string>} orderIds 原始订单ID数组。
@ -421,39 +372,6 @@ class PrintService extends MainService {
}
}
/**
* 判断记录是否满足失败补打条件。
* @param {Object} record 打印记录。
* @param {boolean} force 是否强制补打(最小实现默认不放宽规则)。
* @return {{canRetry:boolean,reason:string}} 判断结果。
*/
getRetryEligibility(record = {}, force = false) {
const normalizedRecord = record && typeof record === 'object' ? record : {};
const status = String(normalizedRecord.status || '').trim();
const printStatus = String(normalizedRecord.print_status || '').trim();
if (status === 'sent' && [ 'unknown', 'printed' ].includes(printStatus)) {
return {
canRetry: false,
reason: `状态为 sent/${printStatus},按规则跳过`,
};
}
const canRetry = status === 'failed' || [ 'print_failed', 'timeout' ].includes(printStatus);
if (canRetry) {
return {
canRetry: true,
reason: '',
};
}
const forceTip = force ? '(force 已开启,当前最小实现仍不放宽状态限制)' : '';
return {
canRetry: false,
reason: `状态不允许补打:status=${status || 'unknown'},print_status=${printStatus || 'unknown'}${forceTip}`,
};
}
/**
* 获取打印任务编码冲突重试配置。
* @return {{maxRetries:number,baseDelayMs:number,jitterMs:number}} 归一化后的重试配置。
@ -1082,6 +1000,7 @@ class PrintService extends MainService {
timestamp,
count,
printId: printRecord.id,
...(customizeOrderIds.length > 0 ? { order_ids: customizeOrderIds } : {}),
};
const sendStartAt = Date.now();
const res = await this.service.systems.print.index.sendToComputer({ warehouse: warehouseId, computerId, data: printData });
@ -1142,175 +1061,6 @@ class PrintService extends MainService {
return this.fail(res.error, { code: 504, printId: printRecord.id });
}
/**
* 失败项补打:仅重试失败记录,原记录保持不变。
* @param {Object} data 补打参数。
* @param {Array<number|string>} data.print_ids 需要补打的打印记录 ID 列表。
* @param {boolean} [data.force=false] 是否强制补打(最小实现默认不放宽状态规则)。
* @param {number|string} [data.warehouse_id] 显式指定仓库 ID(用于定时任务等无登录上下文场景)。
* @return {Promise<Object>} 统一返回结构。
*/
async retryFailed(data = {}) {
const { ctx } = this;
const requestData = data && typeof data === 'object' ? data : {};
const {
print_ids: rawPrintIds,
force = false,
warehouse_id: rawWarehouseId,
} = requestData;
const normalizedWarehouseId = Number(rawWarehouseId);
const userWarehouseId = Number(ctx.user && ctx.user.store_id);
const warehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0
? normalizedWarehouseId
: (Number.isInteger(userWarehouseId) && userWarehouseId > 0 ? userWarehouseId : 0);
if (!warehouseId) {
return this.fail('warehouse_id 参数缺失,且当前上下文无可用仓库信息', { code: 400 });
}
if (!Array.isArray(rawPrintIds) || rawPrintIds.length === 0) {
return this.fail('print_ids 参数不能为空数组', { code: 400 });
}
const printIds = Array.from(new Set(rawPrintIds
.map(item => Number(item))
.filter(item => Number.isInteger(item) && item > 0)));
if (printIds.length === 0) {
return this.fail('print_ids 参数不合法,必须包含正整数 ID', { code: 400 });
}
const sourceRecords = await ctx.model.PrintRecord.findAll({
where: {
id: printIds,
warehouse_id: warehouseId,
},
raw: true,
});
const sourceRecordMap = new Map(sourceRecords.map(item => [ Number(item.id), item ]));
const retried = [];
const skipped = [];
let successCount = 0;
let failedCount = 0;
for (const printId of printIds) {
const sourceRecord = sourceRecordMap.get(printId);
if (!sourceRecord) {
skipped.push({
print_id: printId,
reason: '记录不存在或不属于当前仓库',
});
continue;
}
const eligibility = this.getRetryEligibility(sourceRecord, Boolean(force));
if (!eligibility.canRetry) {
skipped.push({
print_id: printId,
reason: eligibility.reason,
});
continue;
}
const payloadResult = this.normalizeRetrySendPayload(sourceRecord.data);
if (!payloadResult.success) {
skipped.push({
print_id: printId,
reason: payloadResult.error,
});
continue;
}
const sendPayload = payloadResult.data;
const taskCode = await this.reserveUniquePrintTaskCode();
if (sendPayload.data.task && typeof sendPayload.data.task === 'object' && !Array.isArray(sendPayload.data.task)) {
sendPayload.data.task.taskID = taskCode;
}
const newPrintRecord = await ctx.model.PrintRecord.create(this.buildPendingPrintRecordPayload({
warehouse_id: sourceRecord.warehouse_id,
computer_id: sourceRecord.computer_id,
printer: sourceRecord.printer,
type: sourceRecord.type,
request_code: sourceRecord.request_code,
wave_id: sourceRecord.wave_id,
wave_no: sourceRecord.wave_no,
platform_code: sourceRecord.platform_code,
platform_name: sourceRecord.platform_name,
sys_logistics_code: sourceRecord.sys_logistics_code,
sys_logistics_name: sourceRecord.sys_logistics_name,
retry_of_print_id: sourceRecord.id,
data: sendPayload,
}));
try {
const sendResult = await this.service.systems.print.index.sendToComputer({
warehouse: warehouseId,
computerId: sourceRecord.computer_id,
data: {
...sendPayload,
printId: newPrintRecord.id,
},
});
if (sendResult.status !== 'success') {
const failedMessage = sendResult.error || '打印服务返回失败';
await newPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({
errorMessage: failedMessage,
failCode: 'SEND_FAILED',
}));
retried.push({
source_print_id: sourceRecord.id,
new_print_id: newPrintRecord.id,
task_code: taskCode,
status: 'failed',
});
failedCount += 1;
continue;
}
const providerTaskId = String(
sendResult && (sendResult.taskId || sendResult.task_id || sendResult.providerTaskId || sendResult.id)
? (sendResult.taskId || sendResult.task_id || sendResult.providerTaskId || sendResult.id)
: ''
).trim();
await this.bindTaskCodeToPrintRecordWithRetry({
printRecordId: newPrintRecord.id,
taskCode,
provider: providerTaskId,
});
retried.push({
source_print_id: sourceRecord.id,
new_print_id: newPrintRecord.id,
task_code: taskCode,
status: 'sent',
});
successCount += 1;
} catch (error) {
await newPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({
errorMessage: error && error.message ? error.message : `${error}`,
failCode: 'SEND_FAILED',
}));
retried.push({
source_print_id: sourceRecord.id,
new_print_id: newPrintRecord.id,
task_code: taskCode,
status: 'failed',
});
failedCount += 1;
}
}
return this.success('失败项补打处理完成', {
code: 200,
success_count: successCount,
failed_count: failedCount,
skipped_count: skipped.length,
retried,
skipped,
});
}
/**
* 校验快递打印请求的必要参数。
* @param {Object} payload 校验参数。
@ -1797,6 +1547,142 @@ class PrintService extends MainService {
return this.notifyLock(data);
}
/**
* 当 batchOrderIds 为空时,尝试通过 wave_id 从数据库反查订单 ID 列表作为兜底。
*
* 适用于前端未回传 order_ids 的场景(如团购打印),确保打印成功后仍能标记订单为已打印。
*
* @param {Object} payload 查询参数。
* @param {number|string} payload.warehouseId 仓库ID。
* @param {number|null} payload.waveId 波次ID。
* @return {Promise<Array<number>>} 订单ID列表;查询失败或参数无效时返回空数组。
*/
async resolveBatchOrderIdsByWaveFallback(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const warehouseId = Number(normalizedPayload.warehouseId || 0);
const waveId = Number(normalizedPayload.waveId || 0);
if (!Number.isInteger(warehouseId) || warehouseId <= 0 || !Number.isInteger(waveId) || waveId <= 0) {
return [];
}
try {
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
this.ctx.logger.warn('[print.markWavePrintStatus] OrderDeliveryFactory 不可用');
return [];
}
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId);
if (!orderDeliveryModel || typeof orderDeliveryModel.findAll !== 'function') {
this.ctx.logger.warn('[print.markWavePrintStatus] orderDeliveryModel 不可用');
return [];
}
const rows = await orderDeliveryModel.findAll({
attributes: [ 'id' ],
where: {
wave_id: waveId,
warehouse_id: warehouseId,
status: { [this.app.Sequelize.Op.ne]: 'cancel' },
},
raw: true,
});
const orderIds = (Array.isArray(rows) ? rows : [])
.map(row => Number(row && row.id))
.filter(id => Number.isInteger(id) && id > 0);
if (orderIds.length > 0) {
this.ctx.logger.info('[print.markWavePrintStatus] wave_id=%d 查询到 %d 个订单', waveId, orderIds.length);
}
return orderIds;
} catch (error) {
this.ctx.logger.warn('[print.markWavePrintStatus] 查询失败 wave_id=%d reason=%s',
waveId, error && error.message ? error.message : `${error}`);
return [];
}
}
/**
* 标记/取消标记整个波次的订单打印状态。
*
* 仅操作当前仓库下、状态非取消的订单。
* 仓库隔离:从 ctx.user.store_id 获取仓库 ID。
*
* @param {Object} data 入参。
* @param {number|string} data.wave_id 波次ID(必填)。
* @param {string} [data.status='printed'] 目标状态:'printed' 标记已打印,'unprinted' 取消已打印标记。
* @return {Promise<Object>} 统一返回结构。
*/
async markWavePrintStatus(data = {}) {
const { ctx } = this;
const requestData = data && typeof data === 'object' ? data : {};
const waveId = Number(requestData.wave_id || 0);
const targetStatus = String(requestData.status || 'printed').trim().toLowerCase();
if (!Number.isInteger(waveId) || waveId <= 0) {
return this.fail('wave_id 参数必填,且必须为正整数', { code: 400 });
}
if (![ 'printed', 'unprinted' ].includes(targetStatus)) {
return this.fail('status 参数不合法,仅支持 printed / unprinted', { code: 400 });
}
const warehouseId = Number(ctx.user && ctx.user.store_id || 0);
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
return this.fail('无法获取当前仓库ID,请确认已登录', { code: 400 });
}
const orderIds = await this.resolveBatchOrderIdsByWaveFallback({ warehouseId, waveId });
if (orderIds.length === 0) {
return this.fail(`波次 ${waveId} 在当前仓库下没有可操作的订单`, { code: 404 });
}
const printStatus = targetStatus === 'printed' ? 'fin' : 'none';
try {
const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
return this.fail('OrderDeliveryFactory 不可用', { code: 500 });
}
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId);
if (!orderDeliveryModel || typeof orderDeliveryModel.update !== 'function') {
return this.fail('OrderDeliveryModel 不可用', { code: 500 });
}
const updateResult = await orderDeliveryModel.update({
print_status: printStatus,
updated_at: new Date(),
}, {
where: {
id: { [this.app.Sequelize.Op.in]: orderIds },
warehouse_id: warehouseId,
status: { [this.app.Sequelize.Op.ne]: 'cancel' },
},
});
const affectedRows = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0;
this.ctx.logger.info('[print.markWavePrintStatus] 波次打印状态标记完成 wave_id=%d target=%s affected=%d/%d',
waveId, targetStatus, affectedRows, orderIds.length);
return this.success('ok', {
code: 0,
wave_id: waveId,
status: targetStatus,
print_status: printStatus,
total_orders: orderIds.length,
affected_orders: affectedRows,
order_ids: orderIds,
});
} catch (error) {
this.ctx.logger.error('[print.markWavePrintStatus] 更新失败 wave_id=%d reason=%s',
waveId, error && error.message ? error.message : `${error}`);
return this.fail(`波次打印状态更新失败:${error && error.message ? error.message : '未知错误'}`, { code: 500 });
}
}
/**
* 在打印发送成功后批量锁定订单。
*
@ -2129,6 +2015,16 @@ class PrintService extends MainService {
for (let batchIndex = 0; batchIndex < orderBatches.length; batchIndex++) {
const batchOrders = orderBatches[batchIndex];
const batchOrderIds = this.collectOrderIdsFromPlatformGroup(platformGroup, batchOrders);
// 兜底:前端未回传 order_ids 时,通过 wave_id 反查当前波次全部订单ID
if (batchOrderIds.length === 0 && waveId) {
const fallbackIds = await this.resolveBatchOrderIdsByWaveFallback({
warehouseId: normalizedPayload.warehouseId,
waveId,
});
if (fallbackIds.length > 0) {
batchOrderIds.push(...fallbackIds);
}
}
const currentPrinterName = printerNameResult.data;
const batchSummary = {
...groupSummary,
@ -2487,7 +2383,7 @@ class PrintService extends MainService {
result: 'idempotent',
print_task_code: normalizedPrintTaskCode,
print_record_id: printRecordId,
print_status: 'printed',
print_status: 'unknown',
});
}
@ -2497,7 +2393,7 @@ class PrintService extends MainService {
result: 'ignored',
print_task_code: normalizedPrintTaskCode,
print_record_id: printRecordId,
print_status: 'printed',
print_status: 'unknown',
});
}
@ -2507,7 +2403,7 @@ class PrintService extends MainService {
const updatePayload = normalizedResult === 'success'
? {
status: 'sent',
print_status: 'printed',
print_status: 'unknown',
error_message: null,
fail_code: null,
print_time: normalizedPrintTime,
@ -2550,7 +2446,7 @@ class PrintService extends MainService {
result: 'updated',
print_task_code: normalizedPrintTaskCode,
print_record_id: printRecordId,
print_status: updatePayload.print_status,
print_status: 'unknown',
});
}

View File

@ -39,7 +39,7 @@ class PrintComputerService extends MainService {
/**
* 设置录制电脑(会先取消同仓库下其他录制电脑)。
* @param {Object} data { id, recording_size_value, recording_size_unit, remote_play_url, recording_directory }
* @param {Object} data { id, recording_size_value, recording_size_unit, recording_directory }
* @return {Promise<Object>} 设置结果
*/
async setRecording(data) {

View File

@ -2,6 +2,9 @@
const MainService = require('../../main');
const STORAGE_INVENTORY_EXPORT_TASK_CACHE_KEY_PREFIX = 'storage_inventory_export_task_';
const STORAGE_INVENTORY_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
/**
* 系统方法层:storage.inventory(库存操作接口包装层)。
* 职责:统一包装库存操作接口,调用底层 systems/storage/inventory service。
@ -10,9 +13,9 @@ class InventoryMethodService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list';
const _noNeedLog = 'list';
const _noNeedAuth = 'list,quickPutaway';
const _noNeedRight = 'list,export,exportTaskProgress';
const _noNeedLog = 'list,export,exportTaskProgress';
const _noNeedAuth = 'list,quickPutaway,export,exportTaskProgress';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -75,6 +78,228 @@ class InventoryMethodService extends MainService {
const result = await service.systems.storage.inventory.quickPutaway({ receiving_id });
return this.success('ok', result);
}
/**
* 提交库存导出异步任务(入参与 list 一致,复用相同的 where/sort/group_by_batch 语义)。
*
* @param {Object} data 请求体
* @param {Object} [data.where] 查询条件(与 list 完全一致)
* @param {Object} [data.sort] 排序参数 { sortField, sortOrder }(与 list 完全一致)
* @param {boolean} [data.group_by_batch=false] 是否按批次导出,默认 false
* - false:按 stock_id + 库位聚合导出库存汇总
* - true:按 storage_id 逐条导出库存明细
* @return {Promise<Object>} 统一 success 包装,data 为导出任务信息
*/
async export(data = {}) {
const { service } = this;
const groupByBatch = data.group_by_batch === true || data.group_by_batch === 'true';
// 与 list 一致:prepareWhereContext 会设置 ctx.whereParsed,systems 层从中读取条件
this.prepareWhereContext(data);
const { sort = {} } = data;
const sortField = sort.sortField || sort.sort_field;
const sortOrder = sort.sortOrder || sort.sort_order;
const sortParams = {
...(sortField ? { sortField } : {}),
...(sortOrder ? { sortOrder } : {}),
};
const taskId = this.generateExportTaskId();
const taskPayload = {
task_id: taskId,
status: 'submitted',
progress: 0,
message: '导出任务已提交',
result: null,
error: '',
};
await this.setExportTaskProgress(taskId, taskPayload);
setImmediate(async () => {
try {
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'running',
progress: 10,
message: '导出任务执行中',
result: null,
error: '',
});
const result = await service.systems.storage.inventory.exportInventoryList(sortParams, groupByBatch);
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'success',
progress: 100,
message: '导出任务完成',
result,
error: '',
});
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'failed',
progress: 100,
message: '导出任务失败',
result: null,
error: errorMessage,
});
}
});
return this.success('ok', {
...taskPayload,
update_time: Date.now(),
});
}
/**
* 查询库存导出任务进度。
* @param {Object} data 请求体
* @param {string} [data.task_id] 任务ID(下划线写法)
* @param {string} [data.taskId] 任务ID(驼峰写法)
* @return {Promise<Object>} 统一 success 包装
*/
async exportTaskProgress(data = {}) {
const taskId = this.normalizeExportTaskId(data);
if (!taskId) {
return this.success('ok', {
task_id: '',
status: 'not_found',
progress: 0,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const cachedTask = await this.getExportTaskProgress(taskId);
if (!cachedTask) {
return this.success('ok', {
task_id: taskId,
status: 'not_found',
progress: 0,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
const downloadUrl = String(
safeResult.url
|| safeResult.cndUrl
|| safeResult.cosUrl
|| safeResult.fileKey
|| ''
);
return this.success('ok', {
task_id: taskId,
...cachedTask,
download_url: downloadUrl,
});
}
// ==================== 导出任务辅助方法 ====================
/**
* 生成库存导出任务ID。
* @return {string} 导出任务ID
*/
generateExportTaskId() {
const warehouseId = this.ctx?.user?.store_id || 'unknown';
const timestamp = Date.now();
const randomToken = Math.random().toString(36).slice(2, 10);
return `storage_inventory_export_${warehouseId}_${timestamp}_${randomToken}`;
}
/**
* 归一化导出任务ID。
* @param {Object} data 请求体
* @param {string} [data.task_id] 任务ID(下划线写法)
* @param {string} [data.taskId] 任务ID(驼峰写法)
* @return {string} 归一化后的任务ID
*/
normalizeExportTaskId(data = {}) {
const normalizedData = this.isPlainObject(data) ? data : {};
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
}
/**
* 获取导出任务缓存键。
* @param {string} taskId 任务ID
* @return {string} 缓存键
*/
getExportTaskCacheKey(taskId = '') {
const normalizedTaskId = String(taskId || '').trim();
if (!normalizedTaskId) {
return '';
}
return `${STORAGE_INVENTORY_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
}
/**
* 写入导出任务进度缓存。
* @param {string} taskId 任务ID
* @param {Object} payload 任务状态载荷
* @return {Promise<void>} 无返回值
*/
async setExportTaskProgress(taskId = '', payload = {}) {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
return;
}
const safePayload = this.isPlainObject(payload) ? payload : {};
const progressPayload = {
task_id: String(taskId || '').trim(),
status: String(safePayload.status || 'submitted').trim() || 'submitted',
progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0,
message: String(safePayload.message || ''),
result: safePayload.result ?? null,
error: String(safePayload.error || ''),
update_time: Date.now(),
};
try {
await this.app.setCacheAsync(cacheKey, progressPayload, STORAGE_INVENTORY_EXPORT_TASK_CACHE_TTL_SECONDS);
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[storage.inventory.export] 写入导出任务缓存失败: ${errorMessage}`);
}
}
/**
* 读取导出任务进度缓存。
* @param {string} taskId 任务ID
* @return {Promise<Object|null>} 任务缓存
*/
async getExportTaskProgress(taskId = '') {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
return null;
}
try {
const cached = await this.app.getCacheAsync(cacheKey);
if (!this.isPlainObject(cached)) {
return null;
}
return cached;
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[storage.inventory.export] 读取导出任务缓存失败: ${errorMessage}`);
return null;
}
}
}
module.exports = InventoryMethodService;

View File

@ -13,9 +13,9 @@ class configService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress';
const _noNeedLog = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail,export,exportTaskProgress';
const _noNeedAuth = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress';
const _noNeedRight = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress';
const _noNeedLog = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress';
const _noNeedAuth = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -333,39 +333,19 @@ class configService extends MainService {
}
/**
* 提交收货单导出任务(复用 getStoreReceivingList 的筛选语义与排序规则)。
* 提交收货单导出任务(仓库维度,复用 getReceivingList 的筛选语义与排序规则)。
* 导出分为两个 sheet:Sheet1=收货单列表,Sheet2=收货单明细。
* @param {Object} data 请求体
* @param {Object} [data.where] 筛选条件(与 getStoreReceivingList 一致)
* @param {Object} [data.where] 筛选条件(与 getReceivingList 一致)
* @param {Object} [data.sort] 排序参数
* @return {Promise<Object>} 统一成功包装响应,data 为导出任务信息
*/
async export(data = {}) {
const { ctx, app, service } = this;
// 从平台激活上下文获取 store_id
const platformRows = await app.model.query(
'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' +
'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' +
'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1',
{
replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' },
type: app.Sequelize.QueryTypes.SELECT,
}
);
if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) {
return this.fail('未获取到货主平台激活上下文,请先切换至货主角色');
}
const storeId = platformRows[0].store_id;
const { service } = this;
const { sort = {} } = data;
const { where } = this.prepareWhereContext(data, {
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
quickWhere: { bucket: 'quick' },
},
});
@ -394,7 +374,6 @@ class configService extends MainService {
const result = await service.systems.storage.receiving.exportReceivingList({
where,
storeId,
sort,
onProgress: async progress => {
const safeProgress = this.isPlainObject(progress) ? progress : {};
@ -490,13 +469,15 @@ class configService extends MainService {
/**
* 生成收货单导出任务ID。
* @param {string} [prefix=''] 任务类型前缀(如 'store')
* @return {string} 导出任务ID
*/
generateExportTaskId() {
generateExportTaskId(prefix = '') {
const storeId = this.ctx?.user?.store_id || 'unknown';
const timestamp = Date.now();
const randomToken = Math.random().toString(36).slice(2, 10);
return `receiving_export_${storeId}_${timestamp}_${randomToken}`;
const typePrefix = prefix ? `${prefix}_` : '';
return `receiving_${typePrefix}export_${storeId}_${timestamp}_${randomToken}`;
}
/**
@ -579,5 +560,121 @@ class configService extends MainService {
}
}
/**
* 提交货主侧收货单导出任务(复用 getStoreReceivingList 的筛选语义与排序规则)。
* 以当前平台激活的货主 store_id 为维度导出。导出分为两个 sheet:Sheet1=收货单列表,Sheet2=收货单明细。
* @param {Object} data 请求体
* @param {Object} [data.where] 筛选条件(与 getStoreReceivingList 一致)
* @param {Object} [data.sort] 排序参数
* @return {Promise<Object>} 统一成功包装响应,data 为导出任务信息
*/
async storeExport(data = {}) {
const { ctx, app, service } = this;
// 从平台激活上下文获取 store_id
const platformRows = await app.model.query(
'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' +
'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' +
'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1',
{
replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' },
type: app.Sequelize.QueryTypes.SELECT,
}
);
if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) {
return this.fail('未获取到货主平台激活上下文,请先切换至货主角色');
}
const storeId = platformRows[0].store_id;
const { sort = {} } = data;
const { where } = this.prepareWhereContext(data, {
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
const taskId = this.generateExportTaskId('store');
const taskPayload = {
task_id: taskId,
status: 'submitted',
progress: 0,
message: '货主侧收货单导出任务已提交',
result: null,
error: '',
};
await this.setExportTaskProgress(taskId, taskPayload);
setImmediate(async () => {
try {
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'running',
progress: 5,
message: '货主侧收货单导出任务执行中',
result: null,
error: '',
});
const result = await service.systems.storage.receiving.exportStoreReceivingList({
where,
storeId,
sort,
onProgress: async progress => {
const safeProgress = this.isPlainObject(progress) ? progress : {};
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: safeProgress.status || 'running',
progress: safeProgress.progress,
message: safeProgress.message || '货主侧收货单导出任务执行中',
result: safeProgress.result || null,
error: '',
});
},
});
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'success',
progress: 100,
message: '货主侧收货单导出任务完成',
result,
error: '',
});
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'failed',
progress: 100,
message: '货主侧收货单导出任务失败',
result: null,
error: errorMessage,
});
}
});
return this.success('ok', {
...taskPayload,
update_time: Date.now(),
});
}
/**
* 查询货主侧收货单导出任务进度。
* 复用 exportTaskProgress 的缓存查询逻辑,任务 ID 前缀不同。
* @param {Object} data 请求体
* @param {string} [data.task_id] 任务ID(下划线写法)
* @param {string} [data.taskId] 任务ID(驼峰写法)
* @return {Promise<Object>} 统一成功包装响应
*/
async storeExportTaskProgress(data = {}) {
return this.exportTaskProgress(data);
}
}
module.exports = configService;

View File

@ -0,0 +1,307 @@
'use strict';
const MainService = require('../../main');
const WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX = 'waybill_export_task_';
/**
* 运单号仓库侧入口层。
* 负责鉴权声明、参数校验,委托 systems/waybill.js 执行业务逻辑。
*
* 所有方法均需登录但无需细粒度鉴权(与订单列表保持一致)。
*/
class WaybillWarehouseService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,detail,export,exportTaskProgress';
const _noNeedLog = '';
const _noNeedAuth = 'list,detail,export,exportTaskProgress';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 运单列表查询(仓库侧)。
* 支持分页、多条件筛选、排序。
*
* @param {Object} data 请求参数。
* @param {Object} [data.where] 筛选条件。
* @param {Object} [data.pagination] 分页参数 { page, pageSize }。
* @param {Object} [data.sort] 排序参数 { field, order }。
* @return {Promise<Object>} 运单列表与分页信息。
*/
async list(data) {
try {
const { where, pagination, sort } = data || {};
const result = await this.service.systems.waybill.list({
where: where || {},
pagination: pagination || {},
sort: sort || {},
});
return this.success('获取成功', result);
} catch (e) {
return this.fail(e.message);
}
}
/**
* 运单详情查询(仓库侧)。
* 支持按运单ID或运单号查询。
*
* @param {Object} data 请求参数。
* @param {number} [data.id] 运单记录ID。
* @param {string} [data.waybillCode] 运单号(与 id 二选一,waybillCode 优先)。
* @return {Promise<Object>} 运单详情(含订单/打印/打包信息)。
*/
async detail(data) {
try {
const { id, waybillCode } = data || {};
if (!id && !waybillCode) {
return this.fail('运单ID或运单号不能为空');
}
const result = await this.service.systems.waybill.detail({
id,
waybillCode,
});
return this.success('获取成功', result);
} catch (e) {
return this.fail(e.message);
}
}
/**
* 运单导出(仓库侧)。异步任务模式,提交后通过 exportTaskProgress 查询进度。
*
* @param {Object} data 请求参数。
* @param {Object} [data.where] 筛选条件(同 list)。
* @param {Object} [data.sort] 排序参数(同 list)。
* @param {string[]} [data.exportFields] 需要导出的字段列表。
* @return {Promise<Object>} 任务提交结果,含 task_id。
*/
async export(data) {
try {
const { where, sort, exportFields } = data || {};
const taskId = this.generateExportTaskId();
const taskPayload = {
task_id: taskId,
status: 'submitted',
progress: 0,
current_count: 0,
total_count: 0,
message: '导出任务已提交',
result: null,
error: '',
};
await this.setExportTaskProgress(taskId, taskPayload);
setImmediate(async () => {
try {
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'running',
progress: 5,
current_count: 0,
total_count: 0,
message: '导出任务执行中',
result: null,
error: '',
});
const result = await this.service.systems.waybill.export({
where: where || {},
sort: sort || {},
exportFields,
onProgress: async progress => {
const safeProgress = this.isPlainObject(progress) ? progress : {};
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: safeProgress.status || 'running',
progress: safeProgress.progress || 0,
current_count: safeProgress.currentCount || safeProgress.current_count || 0,
total_count: safeProgress.totalCount || safeProgress.total_count || 0,
message: safeProgress.message || '导出任务执行中',
result: safeProgress.result || null,
error: '',
});
},
});
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'success',
progress: 100,
current_count: result.current_count || 0,
total_count: result.total_count || 0,
message: '导出任务完成',
result,
error: '',
});
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'failed',
progress: 100,
message: '导出任务失败',
result: null,
error: errorMessage,
});
}
});
return this.success('ok', {
...taskPayload,
update_time: Date.now(),
});
} catch (e) {
return this.fail(e.message);
}
}
/**
* 查询运单导出任务进度。
*
* @param {Object} data 请求参数。
* @param {string} [data.task_id] 任务ID(下划线写法)。
* @param {string} [data.taskId] 任务ID(驼峰写法)。
* @return {Promise<Object>} 任务进度信息。
*/
async exportTaskProgress(data = {}) {
try {
const taskId = this.normalizeExportTaskId(data);
if (!taskId) {
return this.success('ok', {
task_id: '',
status: 'not_found',
progress: 0,
current_count: 0,
total_count: 0,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const cachedTask = await this.getExportTaskProgress(taskId);
if (!cachedTask) {
return this.success('ok', {
task_id: taskId,
status: 'not_found',
progress: 0,
current_count: 0,
total_count: 0,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
const downloadUrl = String(
safeResult.url
|| safeResult.cndUrl
|| safeResult.cdnUrl
|| safeResult.cosUrl
|| safeResult.fileKey
|| ''
);
return this.success('ok', {
task_id: taskId,
...cachedTask,
download_url: downloadUrl,
});
} catch (e) {
return this.fail(e.message);
}
}
// ==================== 导出任务辅助方法 ====================
/**
* 生成运单导出任务ID。
* @return {string} 任务ID。
*/
generateExportTaskId() {
const warehouseId = this.ctx?.user?.store_id || 'unknown';
const timestamp = Date.now();
const randomToken = Math.random().toString(36).slice(2, 10);
return `waybill_export_${warehouseId}_${timestamp}_${randomToken}`;
}
/**
* 规范导出任务ID。
* @param {Object} data 请求体。
* @return {string} 规范后的任务ID。
*/
normalizeExportTaskId(data = {}) {
const normalizedData = this.isPlainObject(data) ? data : {};
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
}
/**
* 获取运单导出任务缓存键。
* @param {string} taskId 任务ID。
* @return {string} 缓存键。
*/
getExportTaskCacheKey(taskId = '') {
const normalizedTaskId = String(taskId || '').trim();
if (!normalizedTaskId) {
return '';
}
return `${WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
}
/**
* 写入运单导出任务进度缓存。
* @param {string} taskId 任务ID。
* @param {Object} payload 任务状态。
* @return {Promise<void>} 无返回值。
*/
async setExportTaskProgress(taskId = '', payload = {}) {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
return;
}
const safePayload = this.isPlainObject(payload) ? payload : {};
const normalizeCount = value => {
const numericValue = Number(value);
return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0;
};
const progressPayload = {
task_id: String(taskId || '').trim(),
status: String(safePayload.status || 'submitted').trim() || 'submitted',
progress: Number.isFinite(Number(safePayload.progress))
? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress))))
: 0,
current_count: normalizeCount(safePayload.current_count),
total_count: normalizeCount(safePayload.total_count),
message: String(safePayload.message || ''),
result: safePayload.result ?? null,
error: String(safePayload.error || ''),
};
await this.app.setCacheAsync(cacheKey, progressPayload);
}
/**
* 读取运单导出任务进度缓存。
* @param {string} taskId 任务ID。
* @return {Promise<Object|null>} 任务状态对象或 null。
*/
async getExportTaskProgress(taskId = '') {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
return null;
}
return await this.app.getCacheAsync(cacheKey);
}
}
module.exports = WaybillWarehouseService;

View File

@ -0,0 +1,320 @@
'use strict';
const { randomBytes } = require('node:crypto');
const { Service } = require('egg');
class ApiAppService extends Service {
/**
* 生成唯一的 AppKey。
* 格式:AK{yyyyMMddHHmmss}{random8}
* @return {string} AppKey
*/
generateAppKey() {
const now = new Date();
const timestamp = [
now.getFullYear(),
String(now.getMonth() + 1).padStart(2, '0'),
String(now.getDate()).padStart(2, '0'),
String(now.getHours()).padStart(2, '0'),
String(now.getMinutes()).padStart(2, '0'),
String(now.getSeconds()).padStart(2, '0'),
].join('');
return `AK${timestamp}${randomBytes(4).toString('hex')}`;
}
/**
* 生成 AppSecret。
* @return {string} 64 字符十六进制密钥。
*/
generateAppSecret() {
return randomBytes(32).toString('hex');
}
/**
* 获取默认的仓库渠道接口类型 ID。
* 查找 interface_type 中 interface_code = 'OPEN_API_WAREHOUSE' 的记录。
* @return {Promise<number>} 接口类型 ID,找不到时返回 0。
*/
async getDefaultInterfaceTypeId() {
const row = await this.ctx.model.InterfaceType.findOne({
attributes: [ 'id' ],
where: { interface_code: 'OPEN_API_WAREHOUSE', is_enabled: 1 },
raw: true,
});
return row ? Number(row.id) : 0;
}
/**
* 查询当前仓库的 API 应用列表(分页)。
* @param {Object} data 查询参数。
* @param {number} [data.page=1] 页码。
* @param {number} [data.pageSize=20] 每页数量。
* @param {string} [data.app_name] 应用名称(模糊搜索)。
* @param {number} [data.is_enabled] 启用状态。
* @return {Promise<Object>} 分页结果。
*/
async list(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id || 0);
const page = Math.max(1, Number(data.page) || 1);
const pageSize = Math.min(100, Math.max(1, Number(data.pageSize) || 20));
// 仅查询仓库开放接口类型的应用,排除货主/奇门等类型
const where = {
warehouse_id: warehouseId,
interface_type_id: await this.getDefaultInterfaceTypeId(),
};
if (data.app_name) {
where.app_name = { [this.app.Sequelize.Op.like]: `%${String(data.app_name).trim()}%` };
}
if (data.is_enabled !== undefined && data.is_enabled !== null && data.is_enabled !== '') {
where.is_enabled = Number(data.is_enabled);
}
const total = await ctx.model.ApiApp.count({ where });
const list = await ctx.model.ApiApp.findAll({
attributes: [
'id', 'app_name', 'warehouse_id', 'self_app_key', 'self_app_secret',
'self_ip_whitelist', 'callback_url', 'interface_type_id',
'rate_limit', 'sign_method', 'is_enabled', 'created_at', 'updated_at',
],
where,
offset: (page - 1) * pageSize,
limit: pageSize,
order: [[ 'id', 'DESC' ]],
raw: true,
});
// 脱敏:只返回 secret 前 8 位
const maskedList = list.map(item => ({
...item,
self_app_secret: item.self_app_secret
? String(item.self_app_secret).substring(0, 8) + '****'
: '',
}));
return {
list: maskedList,
pagination: {
page,
pageSize,
total,
totalPages: Math.ceil(total / pageSize),
hasNext: page * pageSize < total,
hasPrevious: page > 1,
},
};
}
/**
* 创建仓库 API 应用,自动生成 AppKey 和 AppSecret。
* @param {Object} data 创建参数。
* @param {string} data.app_name 应用名称(必填)。
* @param {number|string} [data.interface_type_id] 接口类型 ID,不传则查 WH_CHANNEL。
* @param {Array<string>} [data.self_ip_whitelist] IP 白名单。
* @param {string} [data.callback_url] 回调地址。
* @param {number} [data.rate_limit=1000] 速率限制。
* @param {string} [data.sign_method='md5'] 签名方法。
* @return {Promise<Object>} 创建结果(含完整 secret,仅创建时返回)。
*/
async create(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id || 0);
if (!warehouseId) {
throw new Error('无法获取当前仓库ID');
}
const appName = String(data.app_name || '').trim();
if (!appName) {
throw new Error('应用名称不能为空');
}
if (appName.length > 200) {
throw new Error('应用名称不能超过200个字符');
}
const interfaceTypeId = data.interface_type_id
? Number(data.interface_type_id)
: await this.getDefaultInterfaceTypeId();
const appKey = this.generateAppKey();
const appSecret = this.generateAppSecret();
const payload = {
app_name: appName,
warehouse_id: warehouseId,
interface_type_id: interfaceTypeId,
self_app_key: appKey,
self_app_secret: appSecret,
self_ip_whitelist: Array.isArray(data.self_ip_whitelist) ? data.self_ip_whitelist : null,
callback_url: String(data.callback_url || '').trim() || null,
rate_limit: Number(data.rate_limit) || 1000,
sign_method: [ 'md5', 'hmac', 'sha256' ].includes(String(data.sign_method || '').trim())
? String(data.sign_method).trim()
: 'md5',
is_enabled: 1,
};
const record = await ctx.model.ApiApp.create(payload);
this.ctx.logger.info('[apiApp] 创建仓库API应用成功', {
warehouseId,
appId: record.id,
appName,
appKey,
});
return {
id: record.id,
app_name: record.app_name,
warehouse_id: record.warehouse_id,
interface_type_id: record.interface_type_id,
self_app_key: record.self_app_key,
self_app_secret: record.self_app_secret,
self_ip_whitelist: record.self_ip_whitelist,
callback_url: record.callback_url,
rate_limit: record.rate_limit,
sign_method: record.sign_method,
is_enabled: record.is_enabled,
created_at: record.created_at,
updated_at: record.updated_at,
};
}
/**
* 更新仓库 API 应用。
* @param {number|string} id 应用 ID。
* @param {Object} data 更新字段。
* @param {string} [data.app_name] 应用名称。
* @param {Array<string>} [data.self_ip_whitelist] IP 白名单。
* @param {string} [data.callback_url] 回调地址。
* @param {number} [data.rate_limit] 速率限制。
* @param {string} [data.sign_method] 签名方法。
* @param {number} [data.is_enabled] 启用状态。
* @return {Promise<Object>} 更新后的记录(脱敏)。
*/
async update(id, data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id || 0);
const record = await ctx.model.ApiApp.findOne({
where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: await this.getDefaultInterfaceTypeId() },
});
if (!record) {
throw new Error('API应用不存在或不属于当前仓库');
}
const updatableFields = [ 'app_name', 'self_ip_whitelist', 'callback_url', 'rate_limit', 'sign_method', 'is_enabled' ];
for (const field of updatableFields) {
if (data[field] !== undefined && data[field] !== null) {
if (field === 'sign_method') {
const val = String(data[field]).trim();
if (![ 'md5', 'hmac', 'sha256' ].includes(val)) {
throw new Error('签名方法仅支持 md5/hmac/sha256');
}
record[field] = val;
} else if (field === 'is_enabled') {
record[field] = Number(data[field]);
} else if (field === 'rate_limit') {
const val = Number(data[field]);
record[field] = val > 0 && val <= 100000 ? val : record[field];
} else if (field === 'app_name') {
const val = String(data[field]).trim();
if (!val) throw new Error('应用名称不能为空');
if (val.length > 200) throw new Error('应用名称不能超过200个字符');
record[field] = val;
} else {
record[field] = data[field];
}
}
}
await record.save();
this.ctx.logger.info('[apiApp] 更新仓库API应用成功', {
warehouseId,
appId: record.id,
});
return {
id: record.id,
app_name: record.app_name,
warehouse_id: record.warehouse_id,
interface_type_id: record.interface_type_id,
self_app_key: record.self_app_key,
self_app_secret: record.self_app_secret
? String(record.self_app_secret).substring(0, 8) + '****'
: '',
self_ip_whitelist: record.self_ip_whitelist,
callback_url: record.callback_url,
rate_limit: record.rate_limit,
sign_method: record.sign_method,
is_enabled: record.is_enabled,
created_at: record.created_at,
updated_at: record.updated_at,
};
}
/**
* 删除仓库 API 应用(软删除:is_enabled=0)。
* @param {number|string} id 应用 ID。
* @return {Promise<void>} 无返回值。
*/
async delete(id) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id || 0);
const record = await ctx.model.ApiApp.findOne({
where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: await this.getDefaultInterfaceTypeId() },
});
if (!record) {
throw new Error('API应用不存在或不属于当前仓库');
}
record.is_enabled = 0;
await record.save();
this.ctx.logger.info('[apiApp] 停用仓库API应用成功', {
warehouseId,
appId: record.id,
});
}
/**
* 重新生成 AppSecret。
* @param {number|string} id 应用 ID。
* @return {Promise<Object>} 包含新 secret 的结果(仅此次返回完整 secret)。
*/
async regenerateSecret(id) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id || 0);
const record = await ctx.model.ApiApp.findOne({
where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: await this.getDefaultInterfaceTypeId() },
});
if (!record) {
throw new Error('API应用不存在或不属于当前仓库');
}
const newSecret = this.generateAppSecret();
record.self_app_secret = newSecret;
await record.save();
this.ctx.logger.info('[apiApp] 重新生成AppSecret成功', {
warehouseId,
appId: record.id,
});
return {
id: record.id,
app_name: record.app_name,
self_app_key: record.self_app_key,
self_app_secret: newSecret,
};
}
}
module.exports = ApiAppService;

View File

@ -24,10 +24,10 @@ class CameraService extends Service {
include: [{
model: ctx.model.CameraServer,
as: 'server',
attributes: ['id', 'name', 'brand', 'public_ip', 'internal_ip', 'public_port', 'internal_port', 'status'],
attributes: [ 'id', 'name', 'brand', 'public_ip', 'internal_ip', 'public_port', 'internal_port', 'status' ],
required: false,
}],
order: [['created_at', 'DESC']],
order: [[ 'created_at', 'DESC' ]],
offset: (page - 1) * pageSize,
limit: pageSize,
});
@ -42,7 +42,7 @@ class CameraService extends Service {
include: [{
model: ctx.model.CameraServer,
as: 'server',
attributes: ['id', 'name', 'brand', 'public_ip', 'internal_ip', 'public_port', 'internal_port', 'status'],
attributes: [ 'id', 'name', 'brand', 'public_ip', 'internal_ip', 'public_port', 'internal_port', 'status' ],
required: false,
}],
});
@ -67,6 +67,8 @@ class CameraService extends Service {
model: data.model || null,
serial_number: data.serial_number || null,
stream_type: data.stream_type || null,
username: data.username || null,
password: data.password || null,
custom_name: data.custom_name || null,
status: data.status !== undefined ? parseInt(data.status) : 1,
remark: data.remark || null,
@ -87,6 +89,8 @@ class CameraService extends Service {
if (data.model !== undefined) fields.model = data.model;
if (data.serial_number !== undefined) fields.serial_number = data.serial_number;
if (data.stream_type !== undefined) fields.stream_type = data.stream_type;
if (data.username !== undefined) fields.username = data.username;
if (data.password !== undefined) fields.password = data.password;
if (data.custom_name !== undefined) {
if (data.custom_name !== null && String(data.custom_name).trim() === '') {
throw new Error('自定义名称不能为空');
@ -101,6 +105,65 @@ class CameraService extends Service {
return record;
}
/**
* 设置摄像头 OSD 文字叠加
* @param {Object} data - 配置选项
* @param {number} data.id - 摄像头ID
* @param {string} data.text - OSD 叠加文字
* @param {number} [data.x] - X 坐标(-1 到 1,默认 -0.9)
* @param {number} [data.y] - Y 坐标(-1 到 1,默认 0.8)
* @return {Promise<Object>} 打印服务响应
*/
async setOsd(data) {
const { ctx } = this;
const { id, text, x, y } = data || {};
const warehouseId = ctx.user.store_id;
if (!id) throw new Error('摄像头ID不能为空');
if (!text) throw new Error('OSD叠加文字不能为空');
// 查询摄像头及关联服务器
const camera = await ctx.model.Camera.findOne({
where: { id: parseInt(id), warehouse_id: warehouseId },
include: [{
model: ctx.model.CameraServer,
as: 'server',
attributes: [ 'id', 'name', 'username', 'password', 'public_ip', 'internal_ip' ],
required: false,
}],
});
if (!camera) throw new Error('摄像头不存在或无权操作');
const OsdClient = require('../../lib/osd_client');
const osdClient = new OsdClient(ctx);
const result = await osdClient.setOsd({
camera,
warehouseId,
text,
x,
y,
});
if (result.error) {
throw new Error(`打印服务请求失败: ${result.error}`);
}
if (!result.response || result.response.status !== 200) {
const status = result.response ? result.response.status : '无响应';
const resData = result.response && result.response.data;
const msg = (resData && resData.message) || (resData && typeof resData === 'string' ? resData : '') || '未知错误';
throw new Error(`打印服务返回异常(${status}): ${msg}`);
}
return {
camera_id: camera.id,
rtsp_url: result.request.rtspUrl,
osd_text: text,
position: { x: result.request.x, y: result.request.y },
print_service_response: result.response,
};
}
async delete(id) {
const { ctx } = this;
const warehouseId = ctx.user.store_id;
@ -110,7 +173,7 @@ class CameraService extends Service {
// 检查是否被工作台绑定
const boundWorkbenches = await ctx.model.Workbench.findAll({
where: { warehouse_id: warehouseId },
attributes: ['id', 'name'],
attributes: [ 'id', 'name' ],
});
for (const wb of boundWorkbenches) {
const deviceIds = Array.isArray(wb.device_ids) ? wb.device_ids : [];

View File

@ -635,6 +635,10 @@ class ExpressService extends Service {
status: {
[Op.ne]: 'cancel',
},
// 保护配送中(step=4)订单不被回退为异常状态
step: {
[Op.ne]: 4,
},
},
transaction,
});
@ -658,6 +662,76 @@ class ExpressService extends Service {
}
}
/**
* 补写 dispatch 表订单的 order_flag 异常信息。
* dispatch 表中的配送中订单(step=4)不应回退 step,仅记录异常标记。
*
* @param {Array<Object>} dispatchOrderDeliveryRows dispatch 表中的订单行。
* @param {Map<string, Array<number>>} failedOrdersByReason 失败原因与订单 ID 映射。
* @param {Object} transaction 数据库事务。
* @return {Promise<void>} 无返回值。
*/
async writeDispatchOrderFlags(dispatchOrderDeliveryRows = [], failedOrdersByReason = new Map(), transaction) {
if (!failedOrdersByReason || typeof failedOrdersByReason.forEach !== 'function') {
return;
}
const { Op } = this.app.Sequelize;
const dispatchOrderIdSet = new Set(
(Array.isArray(dispatchOrderDeliveryRows) ? dispatchOrderDeliveryRows : [])
.map(row => Number(row && row.id))
.filter(id => Number.isFinite(id) && id > 0)
);
if (dispatchOrderIdSet.size === 0) {
return;
}
this.ctx.logger.info('[ExpressService.writeDispatchOrderFlags] 入口 dispatchOrderIds=%s failedReasons=%d',
Array.from(dispatchOrderIdSet).join(','), failedOrdersByReason.size);
// 找到同时属于 dispatch 表且失败的订单
const dispatchFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!dispatchFactory || typeof dispatchFactory.getDispatchModel !== 'function') {
this.ctx.logger.warn('[ExpressService.writeDispatchOrderFlags] dispatchFactory 不可用');
return;
}
const currentWarehouseId = this.getCurrentWarehouseId();
if (!currentWarehouseId) return;
for (const [ exceptionText, orderIds ] of failedOrdersByReason.entries()) {
const failedDispatchIds = (Array.isArray(orderIds) ? orderIds : [])
.map(id => Number(id))
.filter(id => dispatchOrderIdSet.has(id));
if (failedDispatchIds.length === 0) continue;
this.ctx.logger.info('[ExpressService.writeDispatchOrderFlags] 准备写入 order_flag: ids=%s reason=%s',
failedDispatchIds.join(','), exceptionText);
try {
const dispatchModel = await dispatchFactory.getDispatchModel(currentWarehouseId);
if (dispatchModel && typeof dispatchModel.update === 'function') {
await dispatchModel.update({
order_flag: exceptionText,
updated_at: new Date(),
}, {
where: {
id: { [Op.in]: failedDispatchIds },
status: { [Op.ne]: 'cancel' },
},
transaction,
});
this.ctx.logger.info('[ExpressService.writeDispatchOrderFlags] 写入成功 ids=%s', failedDispatchIds.join(','));
}
} catch (err) {
this.ctx.logger.warn('[ExpressService.writeDispatchOrderFlags] 写入 dispatch order_flag 失败: %s',
err && err.message ? err.message : err);
}
}
}
/**
* 将运单异步后处理失败订单批量回写为错误状态。
*
@ -703,6 +777,10 @@ class ExpressService extends Service {
status: {
[Op.ne]: 'cancel',
},
// 保护配送中(step=4)订单不被回退为异常状态
step: {
[Op.ne]: 4,
},
},
});
}
@ -2342,6 +2420,7 @@ class ExpressService extends Service {
* @param {Object} [options] 可选配置。
* @param {boolean} [options.awaitTasks=false] 是否等待所有异步任务完成后再返回。
* @param {Function} [options.onBatchComplete] 单批完成回调 ({ processed, total })。
* @param {number} [options.warehouseId] 仓库ID覆盖值,用于 setImmediate 等异步上下文中 ctx.user 不可用的场景。
* @return {Promise<Object>} 处理结果,包含 orders、waybill_codes 和 skippedOrders。
*/
async createWaybillCodePipeline(orders = [], options = {}) {
@ -2358,7 +2437,7 @@ class ExpressService extends Service {
waveIds: orderList.slice(0, 50).map(order => Number(order && order.wave_id)).filter(waveId => Number.isFinite(waveId) && waveId > 0),
});
const warehouseId = this.getCurrentWarehouseId();
const warehouseId = Number(options.warehouseId) > 0 ? Number(options.warehouseId) : this.getCurrentWarehouseId();
const orderDeliveryModel = await this.getWaybillAsyncOrderDeliveryModel(warehouseId);
@ -2370,23 +2449,52 @@ class ExpressService extends Service {
throw new Error('订单主表模型未初始化');
}
// 【step1】先按订单ID和业务键筛选 wms_order_express,找出已存在的快递记录,避免重复创建。
const orders_arr = await orderDeliveryModel.findAll({
// 【step1】先按订单ID和业务键筛选,找出已存在的快递记录,避免重复创建。
// 先从 current 表查;若存在未覆盖的 order_id,再从 dispatch 表补查(配送中订单可能已迁移)
const inputOrderIds = orderList.map(order => Number(order && order.order_id)).filter(orderId => Number.isFinite(orderId) && orderId > 0);
const currentOrders = await orderDeliveryModel.findAll({
where: {
id: orderList.map(order => Number(order && order.order_id)).filter(orderId => Number.isFinite(orderId) && orderId > 0),
id: inputOrderIds,
warehouse_id: warehouseId,
step: {
[Op.in]: [ 1, 2, 3 ],
[Op.in]: [ 1, 2, 3, 4 ],
},
},
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id' ],
raw: true,
});
// 补查 dispatch 表:获取 current 表未覆盖的 order_id
const currentCoveredIds = new Set((Array.isArray(currentOrders) ? currentOrders : []).map(o => Number(o.id)));
const uncoveredIds = inputOrderIds.filter(id => !currentCoveredIds.has(id));
let dispatchOrders = [];
if (uncoveredIds.length > 0) {
const dispatchModel = this.ctx.model && this.ctx.model.OrderDeliveryFactory
? await this.ctx.model.OrderDeliveryFactory.getDispatchModel(warehouseId)
: null;
if (dispatchModel && typeof dispatchModel.findAll === 'function') {
dispatchOrders = await dispatchModel.findAll({
where: {
id: uncoveredIds,
warehouse_id: warehouseId,
step: {
[Op.in]: [ 4 ],
},
},
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id' ],
raw: true,
});
}
}
const orders_arr = [ ...(Array.isArray(currentOrders) ? currentOrders : []), ...dispatchOrders ];
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 订单筛选结果', {
traceId,
warehouseId,
inputOrderCount: orderList.length,
matchedOrderCount: Array.isArray(orders_arr) ? orders_arr.length : 0,
currentCount: (Array.isArray(currentOrders) ? currentOrders : []).length,
dispatchCount: dispatchOrders.length,
matchedOrderCount: orders_arr.length,
});
// 【step1.5】过滤已分配运单号(status=1)且传入 business_key=1 的订单,避免重复分配。
@ -2438,14 +2546,26 @@ class ExpressService extends Service {
return { message: '所有订单均已分配运单号,无需处理' };
}
// orders_arr和orderList合并
const ordersWithExpress = filteredOrdersArr.map(order => {
const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id));
return {
...order,
business_key: matchedExpress ? matchedExpress.business_key : 1,
};
});
// orders_arr和orderList合并:同一 order_id 在 orderList 中可能有多条(不同 business_key),
// 需要展开为多条 ordersWithExpress,不能用 find() 只取第一条
const ordersWithExpress = [];
for (const order of filteredOrdersArr) {
const matchingExpresses = orderList.filter(express => Number(order.id) === Number(express.order_id));
if (matchingExpresses.length > 0) {
for (const express of matchingExpresses) {
ordersWithExpress.push({
...order,
business_key: express.business_key || 1,
});
}
} else {
// 兜底:orderList 中无对应记录,business_key 默认为 1
ordersWithExpress.push({
...order,
business_key: 1,
});
}
}
const platformList = await this.service.systems.platform.getPlatformList(true, true);
const printPlatformCodeMap = await this.loadWaybillPrintPlatformCodeMap(platformList);
const requestPlatformCodeMap = await this.loadWaybillAsyncRequestPlatformCodeMap(platformList);
@ -2750,7 +2870,69 @@ class ExpressService extends Service {
include: orderDeliveryInclude,
transaction,
});
const orderDeliveryMap = this.buildWaybillOrderDeliveryMap(orderDeliveryRows);
// 补查 dispatch 表:配送中订单可能已迁移,current 表未覆盖的从 dispatch 补齐
const currentCoveredOrderIds = new Set(
(Array.isArray(orderDeliveryRows) ? orderDeliveryRows : []).map(row => Number(row && row.id))
);
const uncoveredOrderIds = normalizedOrders
.map(o => o.order_id)
.filter(id => !currentCoveredOrderIds.has(id));
let dispatchOrderDeliveryRows = [];
if (uncoveredOrderIds.length > 0) {
ctx.logger.info('[ExpressService.createWaybillCode] dispatch 补查 uncoveredOrderIds=%s',
[ ...new Set(uncoveredOrderIds) ].join(','));
const dispatchModel = orderDeliveryFactory && typeof orderDeliveryFactory.getDispatchModel === 'function'
? await orderDeliveryFactory.getDispatchModel(currentWarehouseId)
: null;
if (dispatchModel && typeof dispatchModel.findAll === 'function') {
// dispatch 表 items 关联可能不同,去掉 include 避免关联查询报错
dispatchOrderDeliveryRows = await dispatchModel.findAll({
attributes: WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES,
where: {
id: { [Op.in]: uncoveredOrderIds },
},
transaction,
});
ctx.logger.info('[ExpressService.createWaybillCode] dispatch 补查结果 count=%d',
dispatchOrderDeliveryRows.length);
// 补查 dispatch 表的商品明细(物流 API 需要 items 信息)
if (dispatchOrderDeliveryRows.length > 0) {
const dispatchItemsFactory = ctx.model && ctx.model.OrderItemsFactory;
const dispatchItemsModel = dispatchItemsFactory && typeof dispatchItemsFactory.getDispatchModel === 'function'
? await dispatchItemsFactory.getDispatchModel(currentWarehouseId)
: null;
if (dispatchItemsModel && typeof dispatchItemsModel.findAll === 'function') {
const dispatchOrderIds = dispatchOrderDeliveryRows.map(row => Number(row.id)).filter(id => id > 0);
const dispatchItems = await dispatchItemsModel.findAll({
where: { order_id: { [Op.in]: dispatchOrderIds } },
attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'source_order_code' ],
raw: true,
transaction,
});
// 将 items 以 Sequelize include 格式附加到 dispatch 行上
if (Array.isArray(dispatchItems) && dispatchItems.length > 0) {
const itemsByOrderId = new Map();
for (const item of dispatchItems) {
const oid = Number(item.order_id);
if (!itemsByOrderId.has(oid)) itemsByOrderId.set(oid, []);
itemsByOrderId.get(oid).push(item);
}
for (const row of dispatchOrderDeliveryRows) {
const oid = Number(row.id);
row.orderItems = itemsByOrderId.get(oid) || [];
}
}
}
}
} else {
ctx.logger.warn('[ExpressService.createWaybillCode] dispatch 模型不可用');
}
}
const allOrderDeliveryRows = [ ...(Array.isArray(orderDeliveryRows) ? orderDeliveryRows : []), ...dispatchOrderDeliveryRows ];
const orderDeliveryMap = this.buildWaybillOrderDeliveryMap(allOrderDeliveryRows);
const existingCompletedRows = await orderExpressModel.findAll({
where: {
@ -2787,7 +2969,7 @@ class ExpressService extends Service {
const {
relationGroupMap,
missingOrderIds,
} = this.buildWaybillCreateRelationGroups(pendingOrders, orderDeliveryRows, currentWarehouseId);
} = this.buildWaybillCreateRelationGroups(pendingOrders, allOrderDeliveryRows, currentWarehouseId);
const relationWhereList = Array.from(relationGroupMap.values()).map(group => ({
store_id: group.store_id,
@ -2828,6 +3010,16 @@ class ExpressService extends Service {
// 【step5】事务内统一回写失败订单异常,避免成功与失败状态分离。
await this.writeWaybillOrderExceptions(orderDeliveryModel, failedOrdersByReason, transaction);
// 补写 dispatch 表 order_flag:dispatch 订单的异常信息需单独写(current 表写不到)
if (dispatchOrderDeliveryRows.length > 0 && failedOrdersByReason.size > 0) {
try {
await this.writeDispatchOrderFlags(dispatchOrderDeliveryRows, failedOrdersByReason, transaction);
} catch (dispatchFlagErr) {
ctx.logger.warn('[ExpressService.createWaybillCode] 补写 dispatch order_flag 失败: %s',
dispatchFlagErr && dispatchFlagErr.message ? dispatchFlagErr.message : dispatchFlagErr);
}
}
if (balanceWarnings.length > 0) {
ctx.logger.warn('[ExpressService.createWaybillCode] 余额不足但允许超额分配: %s', balanceWarnings.join(';'));
}
@ -2896,17 +3088,28 @@ class ExpressService extends Service {
.filter(orderId => Number.isFinite(orderId) && orderId > 0)));
if (successOrderIds.length > 0) {
await orderDeliveryModel.update({
step: 2,
updated_at: new Date(),
}, {
where: {
id: {
[Op.in]: successOrderIds,
// 仅对非配送中(step != 4)的订单更新 step 为 2;配送中订单保持 step 不变
const step4OrderIdSet = new Set();
for (const orderId of successOrderIds) {
const orderRow = orderDeliveryMap.get(orderId);
if (orderRow && Number(orderRow.step) === 4) {
step4OrderIdSet.add(orderId);
}
}
const stepUpdatableIds = successOrderIds.filter(id => !step4OrderIdSet.has(id));
if (stepUpdatableIds.length > 0) {
await orderDeliveryModel.update({
step: 2,
updated_at: new Date(),
}, {
where: {
id: {
[Op.in]: stepUpdatableIds,
},
},
},
transaction,
});
transaction,
});
}
}
}
@ -2931,12 +3134,24 @@ class ExpressService extends Service {
continue;
}
ctx.logger.info('[DEBUG] rowsToCreate order', JSON.stringify({
order_id: order.order_id,
store_id: order.store_id,
has_delivery: !!order.order_delivery,
delivery_store_id: order.order_delivery && order.order_delivery.store_id,
delivery_doc: order.order_delivery && order.order_delivery.delivery_order_code,
}));
rowsToCreate.push({
order_id: order.order_id,
business_key: order.business_key,
status: 0,
retry_count: 0,
warehouse_id: this.getCurrentWarehouseId(),
store_id: order.store_id || null,
logistics_code: (listByWarehousePlatformCode && listByWarehousePlatformCode.sys_express_code) || '',
delivery_order_code: (orderDeliveryMap.get(order.order_id) && orderDeliveryMap.get(order.order_id).delivery_order_code) || null,
source_order_codes: (orderDeliveryMap.get(order.order_id) && orderDeliveryMap.get(order.order_id).source_order_codes) || null,
});
}

View File

@ -614,6 +614,17 @@ class ExpressPlatformService extends MainService {
},
});
const ExpressList = await this.service.systems.express.loadExpressList();
const sysExpressName = (ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}).name || '';
const orderDataMap = new Map();
for (const order_tmp of normalizedOrders) {
const od = order_tmp && order_tmp.order_delivery;
if (!od) continue;
orderDataMap.set(`${od.id}_${order_tmp.business_key}`, {
delivery_order_code: od.delivery_order_code || '',
source_order_codes: od.source_order_codes || '',
store_id: od.store_id || 0,
});
}
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
const allocatedWaybillMap = new Map();
if (orderExpressModel && typeof orderExpressModel.findAll === 'function') {
@ -690,6 +701,7 @@ class ExpressPlatformService extends MainService {
const order_bizcontent = {
orders: orders.map(order_tmp => {
const order = order_tmp.order_delivery;
console.log('order', order);
const expressListItem = ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {};
let playload = {
object_Id: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串
@ -729,6 +741,7 @@ class ExpressPlatformService extends MainService {
inputsite: listByWarehousePlatformCode.site_code || '',
sitecode: listByWarehousePlatformCode.site_code || '',
shipperno: listByWarehousePlatformCode.shipperno || '',
customercode: listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '',
sender: {
company: listByWarehousePlatformCode.shop_name || '',
name: listByWarehousePlatformCode.sender_name || '',
@ -743,7 +756,7 @@ class ExpressPlatformService extends MainService {
receiver: {
name: order.name || '',
company: order.company || '',
phone: order.sys_platform_code === 'KS' ? undefined : (order.mobile || order.tel || ''),
phone: order.sys_platform_code === 'KS' || order.sys_platform_code === 'KS' ? undefined : (order.mobile || order.tel || ''),
mobile: order.mobile || order.tel || '',
country: order.country_code || 'CN',
province: order.province || '',
@ -766,6 +779,9 @@ class ExpressPlatformService extends MainService {
labelformat: listByWarehousePlatformCode.labelformat || '',
extraInfo: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)?.polyapi_extra_info || '',
};
console.log("matchedPlatform.platid",matchedPlatform.platid);
console.log("startPlayload",playload);
if (Number(matchedPlatform.platid) === 673) {
playload.BizVersion = '2';
playload.brandno = listByWarehousePlatformCode.brandno || '';
@ -779,6 +795,7 @@ class ExpressPlatformService extends MainService {
providercode,
numpackage,
businessplat,
oaid,
ordertype,
businessType,
codpaymoney,
@ -789,6 +806,7 @@ class ExpressPlatformService extends MainService {
ordersource,
shipperno,
sitecode,
customercode,
goods,
sender = {},
receiver = {},
@ -836,6 +854,8 @@ class ExpressPlatformService extends MainService {
sitecode,
customername,
goods,
oaid,
customercode: customercode || shipperno || listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '',
sender: {
name: senderName,
phone: senderPhoneRaw,
@ -870,7 +890,8 @@ class ExpressPlatformService extends MainService {
if (!order.extend_props.ewaybill_order_code) {
throw new Error('订单数据错误,参数不全缺失extend_props.ewaybill_order_code,请复制次信息给ERP方反馈');
}
playload.oaid = order.extend_props.ewaybill_order_code;
playload.oaid = order.extend_props.ewaybill_order_code||order.oaid||undefined;
playload.transtype = '0';
playload.Mallmaskid = order.buyer_nick;
playload.mainsubpaymode = '1';
@ -897,6 +918,8 @@ class ExpressPlatformService extends MainService {
api: 'Differ.JH.Logistics.PostOrder',
response: JSON.stringify(result),
});
console.log("分配运单号结果",result);
if (result && result.code !== '10000') {
const postOrderErrorMessage = String(
result.submessage || result.message || '菠萝派平台接口调用失败'
@ -931,9 +954,12 @@ class ExpressPlatformService extends MainService {
encryptprintinfo: item.encryptprintinfo,
...this.buildOrderExpressVerPatch([ item.ver ]),
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: listByWarehousePlatformCode.logistics_name || '',
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
@ -963,9 +989,12 @@ class ExpressPlatformService extends MainService {
encryptprintinfo: item.encryptprintinfo,
...this.buildOrderExpressVerPatch([ item.ver ]),
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: listByWarehousePlatformCode.logistics_name || '',
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
@ -981,8 +1010,8 @@ class ExpressPlatformService extends MainService {
case 'JD':{
const batchPrintSipshopid = String(listByWarehousePlatformCode.platform_shop_id || '0');
const batchPrintOrders = (result.results || []).map(item => ({
orderno: String(item.orderno || ''),
logisticno: String(item.logisticno || item.waybill_code || ''),
orderno: String(item.orderno),
logisticno: String(item.logisticno),
outputformat: 'JH_PDF',
labelformat: 'JH_A4',
printobjecttype: 'JH_Label',
@ -1007,18 +1036,18 @@ class ExpressPlatformService extends MainService {
cargoname: '',
senddata: '',
weight: '',
eCustomerCode: '',
remark: '',
carrier: batchPrintSipshopid,
selleruserid: '',
printno: '',
printno: "",
iscloudprint: 'false',
needprintdetail: 'false',
extenddata: '',
providercode: String(item.procode || item.realcpcode || item.logisticcompanycode || ''),
packageno: '',
fontsize: '',
platorderno: String(item.plattradeno || item.platorderno || item.orderno || ''),
sipshopid: batchPrintSipshopid,
platorderno: "",
sipshopid: 0,
}));
console.log('京东批量打印请求参数', JSON.stringify({
api: 'Differ.JH.Logistics.BatchPrintOrder',
@ -1076,9 +1105,12 @@ class ExpressPlatformService extends MainService {
encryptedtoken,
...this.buildOrderExpressVerPatch([ item && item.ver ]),
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: listByWarehousePlatformCode.logistics_name || '',
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
@ -1110,9 +1142,12 @@ class ExpressPlatformService extends MainService {
encryptprintinfo: item.encryptprintinfo,
...this.buildOrderExpressVerPatch([ item.ver ]),
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: listByWarehousePlatformCode.logistics_name || '',
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
@ -1174,9 +1209,12 @@ class ExpressPlatformService extends MainService {
encryptedtoken,
...this.buildOrderExpressVerPatch([ ver ]),
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: listByWarehousePlatformCode.logistics_name || '',
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
@ -1206,9 +1244,12 @@ class ExpressPlatformService extends MainService {
encryptprintinfo: item.encryptprintinfo,
...this.buildOrderExpressVerPatch([ item.ver ]),
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: listByWarehousePlatformCode.logistics_name || '',
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
@ -1239,9 +1280,12 @@ class ExpressPlatformService extends MainService {
encryptedtoken: item.encryptedtoken,
...this.buildOrderExpressVerPatch([ item.ver ]),
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: listByWarehousePlatformCode.logistics_name || '',
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
@ -1614,6 +1658,18 @@ class ExpressPlatformService extends MainService {
const normalizedTemplateUrl = isValidCainiaoTemplateUrl(listByWarehousePlatformCode.template_url)
? String(listByWarehousePlatformCode.template_url).trim()
: DEFAULT_CAINIAO_TEMPLATE_URL;
const ExpressList = await this.service.systems.express.loadExpressList();
const sysExpressName = (ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}).name || '';
const orderDataMap = new Map();
for (const order_tmp of normalizedOrders) {
const od = order_tmp && order_tmp.order_delivery;
if (!od) continue;
orderDataMap.set(`${od.id}_${order_tmp.business_key}`, {
delivery_order_code: od.delivery_order_code || '',
source_order_codes: od.source_order_codes || '',
store_id: od.store_id || 0,
});
}
if (!appKey || !appSecret) {
throw new Error('淘宝接口配置缺失');
}
@ -1839,9 +1895,12 @@ class ExpressPlatformService extends MainService {
encryptprintinfo: encryptPrintInfo,
...orderExpressVerPatch,
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
delivery_order_code: orderDataMap.get(`${orderId}_${businessKey}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${orderId}_${businessKey}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${orderId}_${businessKey}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: listByWarehousePlatformCode.logistics_name || '',
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
@ -2201,6 +2260,18 @@ class ExpressPlatformService extends MainService {
} = data && typeof data === 'object' ? data : {};
const normalizedOrders = Array.isArray(orders) ? orders : [];
const normalizedExtData = this.normalizePddExtData(listByWarehousePlatformCode.ext_data);
const ExpressList = await this.service.systems.express.loadExpressList();
const sysExpressName = (ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}).name || '';
const orderDataMap = new Map();
for (const order_tmp of normalizedOrders) {
const od = order_tmp && order_tmp.order_delivery;
if (!od) continue;
orderDataMap.set(`${od.id}_${order_tmp.business_key}`, {
delivery_order_code: od.delivery_order_code || '',
source_order_codes: od.source_order_codes || '',
store_id: od.store_id || 0,
});
}
console.log('拼多多平台接口入参', data);
@ -2374,9 +2445,12 @@ class ExpressPlatformService extends MainService {
parsedPrintData && parsedPrintData.data && parsedPrintData.data.ver,
]),
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
delivery_order_code: orderDataMap.get(`${orderId}_${businessKey}`)?.delivery_order_code || null,
source_order_codes: orderDataMap.get(`${orderId}_${businessKey}`)?.source_order_codes || null,
store_id: orderDataMap.get(`${orderId}_${businessKey}`)?.store_id || null,
logistics_code: listByWarehousePlatformCode.sys_express_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: listByWarehousePlatformCode.logistics_name || '',
logistics_name: sysExpressName || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,

View File

@ -55,21 +55,26 @@ class OrderAutoOutboundService extends MainService {
raw: true,
});
for (const contract of contracts) {
result.push({
storeId: store.id,
warehouseId: contract.warehouse_id,
rules: autoOutboundRules,
});
}
// 始终将 store.id 自身的仓库加入扫描(store.id 即 warehouse_id)
const scannedWarehouseIds = new Set();
result.push({
storeId: store.id,
warehouseId: store.id,
rules: autoOutboundRules,
});
scannedWarehouseIds.add(store.id);
// 兜底:仓库自身没有 StoreWarehouse 合同关系时,直接用 store.id 作为 warehouseId
if (contracts.length === 0) {
result.push({
storeId: store.id,
warehouseId: store.id,
rules: autoOutboundRules,
});
// 追加外部合同中的仓库(去重)
for (const contract of contracts) {
const contractWarehouseId = contract.warehouse_id;
if (!scannedWarehouseIds.has(contractWarehouseId)) {
result.push({
storeId: store.id,
warehouseId: contractWarehouseId,
rules: autoOutboundRules,
});
scannedWarehouseIds.add(contractWarehouseId);
}
}
}

View File

@ -48,7 +48,7 @@ class OrderPackingService extends Service {
* @param {Object} where 筛选条件对象
* @param {Object} [where.status] 任务状态:0=待处理 1=打包中 2=已完成 3=异常
* @param {Object} [where.pack_mode] 打包模式:1=散单 2=团购
* @param {Object} [where.waybill_code] 运单号(模糊匹配)
* @param {Object} [where.waybill_code] 运单号(通过 wms_order_express 解析 order_id 后过滤,支持 eq/like)
* @param {Object} [where.wave_no] 波次号(模糊匹配)
* @param {Object} [where.order_id] 订单ID(精确匹配)
* @param {Object} [where.workbench_id] 工作台ID(精确匹配)
@ -98,11 +98,33 @@ class OrderPackingService extends Service {
}
}
// 运单号模糊匹配
// 运单号筛选:通过 wms_order_express 表解析 order_id,再按 order_id 过滤(wms_pack_task.waybill_code 通常为空)
if (where.waybill_code) {
const waybillValue = where.waybill_code?.value ?? where.waybill_code;
const waybillOperator = (where.waybill_code?.operator || 'like').toLowerCase();
if (waybillValue && String(waybillValue).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(waybillValue).trim()}%` };
const trimmedValue = String(waybillValue).trim();
const expressWhere = {
warehouse_id: warehouseId,
delete_at: null,
};
if (waybillOperator === 'eq') {
expressWhere.waybill_code = trimmedValue;
} else {
expressWhere.waybill_code = { [Op.like]: `%${trimmedValue}%` };
}
const expressRecords = await ctx.model.OrderExpress.findAll({
where: expressWhere,
attributes: [ 'order_id' ],
raw: true,
});
const matchedOrderIds = [ ...new Set(expressRecords.map(r => r.order_id).filter(Boolean)) ];
if (matchedOrderIds.length > 0) {
queryWhere.order_id = { [Op.in]: matchedOrderIds };
} else {
// 无匹配运单号 → 强制返回空结果
queryWhere.id = -1;
}
}
}
@ -250,6 +272,34 @@ class OrderPackingService extends Service {
}
}
// has_video 筛选:1=有视频 2=无视频
if (where.has_video !== undefined && where.has_video !== null) {
const hasVideoValue = Number(where.has_video?.value ?? where.has_video);
if (hasVideoValue === 1) {
queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []),
app.Sequelize.literal('EXISTS (SELECT 1 FROM wms_pack_task_video WHERE pack_task_id = pack_task.id AND deleted_at IS NULL)'),
];
} else if (hasVideoValue === 2) {
queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []),
app.Sequelize.literal('NOT EXISTS (SELECT 1 FROM wms_pack_task_video WHERE pack_task_id = pack_task.id AND deleted_at IS NULL)'),
];
}
}
// video_enable 筛选:1=录像可用 2=录像不可用
if (where.video_enable !== undefined && where.video_enable !== null) {
const videoEnableValue = Number(where.video_enable?.value ?? where.video_enable);
if (videoEnableValue === 1) {
queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []),
app.Sequelize.literal("EXISTS (SELECT 1 FROM wms_pack_task_video WHERE pack_task_id = pack_task.id AND deleted_at IS NULL AND video_url != '' AND status != 'failed')"),
];
} else if (videoEnableValue === 2) {
queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []),
app.Sequelize.literal("NOT EXISTS (SELECT 1 FROM wms_pack_task_video WHERE pack_task_id = pack_task.id AND deleted_at IS NULL AND video_url != '' AND status != 'failed')"),
];
}
}
// 开始打包时间范围
if (where.start_time_start) {
const startTimeStart = where.start_time_start?.value ?? where.start_time_start;
@ -309,12 +359,21 @@ class OrderPackingService extends Service {
const recordingComputerId = await this._getRecordingComputerId(warehouseId);
const list = rows.map(row => {
const plain = row.get({ plain: true });
const rawVideos = plain.videos || [];
const { app: appCtx } = this;
return {
...plain,
start_time: plain.start_time ? appCtx.formatDate(plain.start_time) : null,
end_time: plain.end_time ? appCtx.formatDate(plain.end_time) : null,
create_time: plain.create_time ? appCtx.formatDate(plain.create_time) : null,
update_time: plain.update_time ? appCtx.formatDate(plain.update_time) : null,
deleted_at: plain.deleted_at ? appCtx.formatDate(plain.deleted_at) : null,
workbench_name: plain.workbench?.name || null,
workbench_type: plain.workbench?.type || null,
workbench_barcode: plain.workbench?.barcode || null,
videos: (plain.videos || []).map(v => ({
has_video: rawVideos.length > 0 ? 1 : 2,
video_enable: rawVideos.some(v => v.video_url && v.status !== 'failed') ? 1 : 2,
videos: rawVideos.map(v => ({
id: v.id,
video_url: this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url),
status: v.status || null,
@ -411,12 +470,21 @@ class OrderPackingService extends Service {
const plain = record.get({ plain: true });
const recordingComputerId = await this._getRecordingComputerId(warehouseId);
const rawVideos = plain.videos || [];
const { app: appCtx } = this;
const data = {
...plain,
start_time: plain.start_time ? appCtx.formatDate(plain.start_time) : null,
end_time: plain.end_time ? appCtx.formatDate(plain.end_time) : null,
create_time: plain.create_time ? appCtx.formatDate(plain.create_time) : null,
update_time: plain.update_time ? appCtx.formatDate(plain.update_time) : null,
deleted_at: plain.deleted_at ? appCtx.formatDate(plain.deleted_at) : null,
workbench_name: plain.workbench?.name || null,
workbench_type: plain.workbench?.type || null,
workbench_barcode: plain.workbench?.barcode || null,
videos: (plain.videos || []).map(v => ({
has_video: rawVideos.length > 0 ? 1 : 2,
video_enable: rawVideos.some(v => v.video_url && v.status !== 'failed') ? 1 : 2,
videos: rawVideos.map(v => ({
id: v.id,
video_url: this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url),
status: v.status || null,
@ -472,7 +540,14 @@ class OrderPackingService extends Service {
return { code: 404, message: '打包任务不存在或无权访问', data: null };
}
const updates = { end_time: new Date(end_time) };
const newEndTime = new Date(end_time);
// 结束时间不能早于开始时间
if (record.start_time && newEndTime < new Date(record.start_time)) {
return { code: 400, message: '结束时间不能早于开始时间', data: null };
}
const updates = { end_time: newEndTime };
// 若任务状态不是已完成(2),同步更新为已完成
if (record.status !== 2) {
@ -486,7 +561,7 @@ class OrderPackingService extends Service {
message: '结束时间设置成功',
data: {
id: record.id,
end_time: updates.end_time,
end_time: this.app.formatDate(updates.end_time),
status: updates.status,
},
};
@ -546,30 +621,37 @@ class OrderPackingService extends Service {
// 5. 通知打印服务推送强制录制任务
const printServiceUrl = ctx.app.config.printService.url;
const requestData = { pack_task_id: Number(id) };
let printServiceResponse = null;
let printServiceError = null;
try {
await ctx.curl(`${printServiceUrl}/record/force`, {
const res = await ctx.curl(`${printServiceUrl}/record/force`, {
method: 'POST',
contentType: 'json',
data: {
pack_task_id: Number(id),
warehouse_id: warehouseId,
computer_id: recordingComputer.id,
camera_ids: packTask.device_ids || [],
},
data: requestData,
dataType: 'json',
timeout: 10000,
});
printServiceResponse = {
status: res.status,
headers: res.headers,
data: res.data,
};
} catch (err) {
printServiceError = err.message;
ctx.logger.warn(`通知打印服务强制录制 pack_task_id=${id} 失败: ${err.message}`);
return { code: 500, message: `通知打印服务失败: ${err.message}`, data: null };
}
return {
code: 200,
message: '强制录制任务已推送',
code: printServiceError ? 500 : 200,
message: printServiceError ? `通知打印服务失败: ${printServiceError}` : '强制录制任务已推送',
data: {
pack_task_id: Number(id),
computer_id: recordingComputer.id,
print_service_url: `${printServiceUrl}/record/force`,
print_service_request: requestData,
print_service_response: printServiceResponse,
print_service_error: printServiceError,
},
};
}

View File

@ -890,6 +890,344 @@ class OrderPrintSystemService extends OrderBaseService {
* @param {Array<number>} payload.validWaveIds 有效波次ID列表。
* @return {Array<Object>} 规范化后的分组规则列表。
*/
/**
* 按运单号数组拉取平台打印中间态数据。
*
* 与 getOrderPrintData 输出相同的 waveGroups 结构,但入参改为运单号数组。
* 支持子单号(business_key > 1):
* - 主面单:与现有逻辑一致
* - 子面单:使用主订单的订单数据构建打印数据,但在自定义区追加 "子单号【{business_key}】-{主单号}" 行
*
* 仓库ID统一从当前上下文获取。
*
* @param {Object} params 请求参数。
* @param {Array<string>} params.waybillCodes 运单号数组。
* @return {Promise<Object>} 平台打印中间态结果。
*/
async getPrintDataByWaybillCodes(params = {}) {
const requestParams = this.isPlainObject(params) ? params : {};
const { waybillCodes } = requestParams;
if (!Array.isArray(waybillCodes) || waybillCodes.length === 0) {
throw new Error('waybill_codes 必填,且必须为非空数组');
}
const normalizedWaybillCodes = Array.from(new Set(
waybillCodes.map(code => String(code || '').trim()).filter(Boolean)
));
if (normalizedWaybillCodes.length === 0) {
throw new Error('waybill_codes 必填,且必须为非空数组');
}
const normalizedWarehouseId = this.getContextWarehouseId();
// 1. 按运单号查询运单记录(不限制 business_key,支持子单号)
const waybillRows = await this.queryWaybillsByCodes(normalizedWaybillCodes, normalizedWarehouseId);
if (waybillRows.length === 0) {
return {
summary: { total_waves: 0, total_orders: 0, total_platforms: 0 },
waveGroups: [],
wave_ids: [],
ext: {
missing_waybill_codes: normalizedWaybillCodes,
filtered_waybill_codes: [],
},
};
}
const foundWaybillCodeSet = new Set(waybillRows.map(r => String(r.waybill_code || '').trim()));
const missingWaybillCodes = normalizedWaybillCodes.filter(code => !foundWaybillCodeSet.has(code));
// 2. 提取所有涉及的订单ID,查询订单
const orderIdSet = new Set(waybillRows.map(r => Number(r.order_id)).filter(id => id > 0));
const orderIds = Array.from(orderIdSet);
const orderRows = await this.queryOrdersByIds(orderIds, normalizedWarehouseId);
const orderRowMap = new Map(orderRows.map(row => [ Number(row.id), row ]));
// 过滤未找到订单的运单
const validWaybillRows = waybillRows.filter(row => orderRowMap.has(Number(row.order_id)));
const invalidWaybillCodes = waybillRows
.filter(row => !orderRowMap.has(Number(row.order_id)))
.map(row => ({
waybill_code: String(row.waybill_code || '').trim(),
reason: '关联订单未找到或不属于当前仓库',
}));
if (validWaybillRows.length === 0) {
return {
summary: { total_waves: 0, total_orders: 0, total_platforms: 0 },
waveGroups: [],
wave_ids: [],
ext: {
missing_waybill_codes: missingWaybillCodes,
filtered_waybill_codes: invalidWaybillCodes,
},
};
}
// 3. 过滤 post_status !== 'fin' 的订单
const validOrderIdSet = new Set(
orderRows
.filter(row => String(row.post_status || '').trim() === 'fin')
.map(row => Number(row.id))
);
const finalWaybillRows = validWaybillRows.filter(row => validOrderIdSet.has(Number(row.order_id)));
const filteredWaybillCodes = validWaybillRows
.filter(row => !validOrderIdSet.has(Number(row.order_id)))
.map(row => ({
waybill_code: String(row.waybill_code || '').trim(),
reason: '关联订单快递未完全分配',
}));
if (finalWaybillRows.length === 0) {
return {
summary: { total_waves: 0, total_orders: 0, total_platforms: 0 },
waveGroups: [],
wave_ids: [],
ext: {
missing_waybill_codes: missingWaybillCodes,
filtered_waybill_codes: [ ...invalidWaybillCodes, ...filteredWaybillCodes ],
},
};
}
// 4. 收集有效订单行
const validOrderRows = Array.from(
new Map(orderRows.filter(row => validOrderIdSet.has(Number(row.id))).map(row => [ Number(row.id), row ])).values()
);
// 4b. 对命中的所有运单行做平台增强(主单和子单各自走自己的增强,密文/签名/参数按运单独立)
const waybillRowsForEnrich = finalWaybillRows.map(row => ({ ...row }));
const cainiaoEnrichedWaybillRows = await this.enrichCainiaoOrderExpressRows(
validOrderRows, waybillRowsForEnrich, normalizedWarehouseId
);
const jdEnrichedWaybillRows = await this.enrichJdOrderExpressRows(
validOrderRows, cainiaoEnrichedWaybillRows, normalizedWarehouseId
);
const enrichedWaybillRows = await this.enrichPddDyOrderExpressRows(
validOrderRows, jdEnrichedWaybillRows, normalizedWarehouseId
);
// 构建 order_id → 增强后运单列表的映射(同一订单可能有多个运单)
const enrichedWaybillMap = new Map();
for (const row of enrichedWaybillRows) {
const oid = Number(row.order_id);
if (!enrichedWaybillMap.has(oid)) {
enrichedWaybillMap.set(oid, []);
}
enrichedWaybillMap.get(oid).push(row);
}
// 4c. 获取每个订单的主运单(business_key=1),用于子面单自定义区追加主运单号
const mainWaybillMap = await this.getMainWaybillMapByOrderIds(orderIds, normalizedWarehouseId);
// 5. 获取策略配置
const policyConfigMap = await this.getPolicyConfigMapByStore(validOrderRows, normalizedWarehouseId);
// 6. 拣货明细、波次序号等辅助数据
const pickingCandidateRows = validOrderRows.filter(orderRow => {
const storeId = Number(orderRow.store_id || 0);
const policyConfig = policyConfigMap.get(storeId) || {};
return this.shouldLoadPickingDetails(policyConfig);
});
const printOrderRowMap = await this.buildPrintOrderRowMapWithPicking(pickingCandidateRows, normalizedWarehouseId);
const validOrderWaveIds = Array.from(new Set(validOrderRows
.map(row => Number(row.wave_id || 0))
.filter(waveId => Number.isInteger(waveId) && waveId > 0)));
const waveRows = await this.queryWavesByIds(normalizedWarehouseId, validOrderWaveIds);
const orderIdsForIndex = validOrderRows.map(row => Number(row.id)).filter(id => id > 0);
const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds(
orderIdsForIndex, normalizedWarehouseId, validOrderWaveIds
);
const waveTotalOrderCountMap = await this.queryWaveTotalOrderCountMap(validOrderWaveIds, normalizedWarehouseId);
const templateSampleCache = new Map();
// 7. 为每个运单构建打印数据
const orderPrintList = [];
for (const enrichedRow of enrichedWaybillRows) {
const orderId = Number(enrichedRow.order_id);
const orderRow = orderRowMap.get(orderId);
if (!orderRow) continue;
const effectiveOrderRow = printOrderRowMap.get(orderId) || orderRow;
const waveOrderIndexInfo = waveOrderIndexMap.get(orderId) || {};
const waveIdForCount = Number(effectiveOrderRow.wave_id || orderRow.wave_id || waveOrderIndexInfo.wave_id || 0);
const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0);
const waveIndex = Number(waveOrderIndexInfo.wave_index || 0);
const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0);
const effectiveOrderRowWithWaveIndex = {
...effectiveOrderRow,
wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0,
wave_index: waveIndex > 0 ? waveIndex : 0,
platforms_index: platformsIndex > 0 ? platformsIndex : 0,
};
const storeId = Number(orderRow.store_id || 0);
const policyConfig = policyConfigMap.get(storeId) || {};
const platformCode = this.resolvePrintPlatformCode(effectiveOrderRow, enrichedRow);
const templateSample = this.loadTemplateSampleByPlatform(platformCode, templateSampleCache);
// 子面单:自定义区首行追加子单号标识
const businessKey = Number(enrichedRow.business_key || 1);
const mainWaybill = mainWaybillMap.get(orderId);
const mainWaybillCode = mainWaybill ? String(mainWaybill.waybill_code || '').trim() : '';
const isChildWaybill = businessKey > 1 && mainWaybillCode;
const extraCustomLines = isChildWaybill
? [ `子单号【${businessKey}】-${mainWaybillCode}` ]
: [];
orderPrintList.push(await this.buildOrderPlatformPrintItem({
orderRow: effectiveOrderRowWithWaveIndex,
orderExpress: enrichedRow,
policyConfig,
platformCode,
templateSample,
extraCustomLines,
}));
}
// 8. 分组输出
// 分离有波次和无波次的打印条目
const wavedItems = orderPrintList.filter(item => Number(item && item.wave_id || 0) > 0);
const noWaveItems = orderPrintList.filter(item => Number(item && item.wave_id || 0) === 0);
const waveGroups = this.groupOrderPrintItemsByWaveAndPlatform({
waveRows,
hitWaveIds: validOrderWaveIds,
orderPrintList: wavedItems,
});
// 无波次条目按平台直接分组
if (noWaveItems.length > 0) {
const noWavePlatforms = this.groupOrderPrintItemsByPlatform(noWaveItems);
waveGroups.push({
wave_id: 0,
wave_no: '',
order_count: noWaveItems.length,
platforms: noWavePlatforms,
});
// 将 0 加入 wave_ids 表示有无波次条目
if (!validOrderWaveIds.includes(0)) {
validOrderWaveIds.push(0);
}
}
const totalPlatforms = waveGroups.reduce((sum, waveGroup) => {
return sum + Number(waveGroup && waveGroup.platforms && waveGroup.platforms.length || 0);
}, 0);
return {
summary: {
total_waves: waveGroups.length,
total_orders: orderPrintList.length,
total_platforms: totalPlatforms,
},
waveGroups,
wave_ids: validOrderWaveIds,
ext: {
missing_waybill_codes: missingWaybillCodes,
filtered_waybill_codes: [ ...invalidWaybillCodes, ...filteredWaybillCodes ],
},
};
}
/**
* 按运单号数组查询运单记录(不限制 business_key,支持子单号)。
*
* @param {string[]} waybillCodes 运单号数组。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Array<Object>>} 运单记录数组。
*/
async queryWaybillsByCodes(waybillCodes = [], warehouseId) {
if (!Array.isArray(waybillCodes) || waybillCodes.length === 0) {
return [];
}
const normalizedCodes = Array.from(new Set(
waybillCodes.map(code => String(code || '').trim()).filter(Boolean)
));
if (normalizedCodes.length === 0) {
return [];
}
const rows = await this.ctx.model.OrderExpress.findAll({
attributes: [
'id',
'order_id',
'business_key',
'waybill_code',
'logistics_code',
'logistics_name',
'logistics_interface_id',
'logistics_interface_name',
'platform_code',
'warehouse_id',
'printinfo',
'signature',
'encryptprintinfo',
'ver',
],
where: {
waybill_code: {
[Op.in]: normalizedCodes,
},
warehouse_id: warehouseId,
},
order: [[ 'order_id', 'ASC' ], [ 'business_key', 'ASC' ], [ 'id', 'ASC' ]],
raw: true,
});
return Array.isArray(rows) ? rows : [];
}
/**
* 按订单ID列表获取主运单映射(business_key=1)。
*
* @param {number[]} orderIds 订单ID数组。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Map<number, Object>>} order_id → 主运单记录。
*/
async getMainWaybillMapByOrderIds(orderIds = [], warehouseId) {
const map = new Map();
if (!Array.isArray(orderIds) || orderIds.length === 0) {
return map;
}
const normalizedOrderIds = Array.from(new Set(
orderIds.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0)
));
if (normalizedOrderIds.length === 0) {
return map;
}
const rows = await this.ctx.model.OrderExpress.findAll({
attributes: [ 'id', 'order_id', 'business_key', 'waybill_code' ],
where: {
order_id: { [Op.in]: normalizedOrderIds },
warehouse_id: warehouseId,
business_key: 1,
},
raw: true,
});
for (const row of rows) {
map.set(Number(row.order_id), row);
}
return map;
}
/**
* 规范化"按分组解锁"规则。
*
* @param {Object} payload 规则入参。
* @param {Array<Object>} payload.groups 分组条件原始列表。
* @param {string} payload.groupType 分组类型。
* @param {string} payload.unlockScope 解锁范围。
* @param {Array<number>} payload.validWaveIds 有效波次ID列表。
* @return {Array<Object>} 规范化后的分组规则列表。
*/
normalizeUnlockGroupRules(payload = {}) {
const requestPayload = this.isPlainObject(payload) ? payload : {};
const groups = Array.isArray(requestPayload.groups) ? requestPayload.groups : [];
@ -1527,6 +1865,7 @@ class OrderPrintSystemService extends OrderBaseService {
* 返回 business_key=1 的主运单,按 order_id、business_key、id 升序排列。
*
* @param {number[]} orderIds 订单 ID 列表。
* @param warehouseId
* @return {Promise<Array<Object>>} 匹配的运单记录数组,字段包含 id、order_id、business_key、waybill_code、
* logistics_code、logistics_name、logistics_interface_id、logistics_interface_name、platform_code、
* warehouse_id、printinfo、signature、encryptprintinfo、ver。
@ -2648,6 +2987,7 @@ ${waveFilterSql}
const policyConfig = this.isPlainObject(requestPayload.policyConfig) ? requestPayload.policyConfig : {};
const templateSample = this.isPlainObject(requestPayload.templateSample) ? requestPayload.templateSample : {};
const platformCode = String(requestPayload.platformCode || '').trim();
const extraCustomLines = Array.isArray(requestPayload.extraCustomLines) ? requestPayload.extraCustomLines : [];
// 查最匹配的包材名称(基于 items_hash)
let suggestedPackageMaterialName = '';
@ -2714,9 +3054,17 @@ ${waveFilterSql}
taskId: requestId,
documentId,
packageMaterialName: suggestedPackageMaterialName,
extraCustomLines,
},
});
const printData = this.extractSinglePlatformPrintData(printPayload);
// 子面单场景:同一运单号可能对应多个 business_key,注入 business_key 到返回文档中供调用方区分
if (printData && typeof printData === 'object' && !Array.isArray(printData)) {
const expressBusinessKey = Number(orderExpress.business_key || 1);
if (expressBusinessKey > 1) {
printData.business_key = expressBusinessKey;
}
}
return {
wave_id: waveId,
wave_no: String(orderRow.wave_no || '').trim(),

View File

@ -2376,11 +2376,44 @@ class PickSystemService extends Service {
const targetCartId = Number(targetCartRow.cart_id || 0);
const targetCartCode = String(targetCartRow.cart_code || '').trim();
const previousCartId = Number(taskRow && taskRow.current_cart_id || 0);
const bindType = previousCartId > 0 && previousCartId !== targetCartId ? 2 : 1;
const transaction = await ctx.model.transaction();
try {
// 检查任务是否已有活跃的车绑定(正常绑定流程,不支持换车,需先解绑)
const taskActiveBindingRows = await ctx.model.query(`
SELECT
b.id,
b.cart_id,
t.current_cart_code_snapshot AS cart_code
FROM wms_pick_task_cart_binding b
INNER JOIN wms_wave_pick_task t
ON t.id = b.task_id
WHERE b.task_id = :taskId
AND b.warehouse_id = :warehouseId
AND b.is_active = 1
ORDER BY b.id DESC
LIMIT 1
`, {
replacements: {
taskId,
warehouseId,
},
type: ctx.model.QueryTypes.SELECT,
transaction,
});
const taskActiveBinding = Array.isArray(taskActiveBindingRows) && taskActiveBindingRows.length > 0
? taskActiveBindingRows[0]
: null;
if (taskActiveBinding) {
throw this.createBusinessError('任务已绑定拣货车,请先解绑后再重新绑定', 409, {
task_id: taskId,
cart_id: Number(taskActiveBinding.cart_id || 0),
cart_code: String(taskActiveBinding.cart_code || '').trim() || null,
});
}
// 检查车是否已有活跃的任务绑定
const cartActiveBindingRows = await ctx.model.query(`
SELECT
b.id,
@ -2404,58 +2437,29 @@ class PickSystemService extends Service {
transaction,
});
const activeBinding = Array.isArray(cartActiveBindingRows) && cartActiveBindingRows.length > 0
const cartActiveBinding = Array.isArray(cartActiveBindingRows) && cartActiveBindingRows.length > 0
? cartActiveBindingRows[0]
: null;
const bindingTaskId = Number(activeBinding && activeBinding.task_id || 0);
const bindingTaskStatus = Number(activeBinding && activeBinding.task_status || 0);
if (bindingTaskId > 0 && bindingTaskId !== taskId && [ 0, 1 ].includes(bindingTaskStatus)) {
throw this.createBusinessError('该拣货车已绑定其他活动任务,无法重复绑定', 409, {
task_id: bindingTaskId,
task_no: String(activeBinding && activeBinding.task_no || '').trim() || null,
cart_id: targetCartId,
cart_code: targetCartCode,
});
if (cartActiveBinding) {
const boundTaskId = Number(cartActiveBinding.task_id || 0);
const boundTaskStatus = Number(cartActiveBinding.task_status || 0);
if (boundTaskId === taskId) {
throw this.createBusinessError('该任务已绑定此拣货车,无需重复绑定', 409, {
task_id: taskId,
cart_id: targetCartId,
cart_code: targetCartCode,
});
}
if ([ 0, 1 ].includes(boundTaskStatus)) {
throw this.createBusinessError('该拣货车已绑定其他活动任务,请先解绑后再重新绑定', 409, {
task_id: boundTaskId,
task_no: String(cartActiveBinding.task_no || '').trim() || null,
cart_id: targetCartId,
cart_code: targetCartCode,
});
}
}
if (previousCartId > 0 && previousCartId !== targetCartId) {
await ctx.model.query(`
UPDATE wms_pick_cart
SET current_task_id = NULL,
bind_user_id = NULL,
update_time = NOW()
WHERE id = :previousCartId
AND warehouse_id = :warehouseId
AND current_task_id = :taskId
`, {
replacements: {
previousCartId,
warehouseId,
taskId,
},
transaction,
});
}
await ctx.model.query(`
UPDATE wms_pick_task_cart_binding
SET is_active = 0,
unbind_user_id = :operatorId,
unbind_time = NOW(),
update_time = NOW()
WHERE warehouse_id = :warehouseId
AND is_active = 1
AND (task_id = :taskId OR cart_id = :cartId)
`, {
replacements: {
operatorId,
warehouseId,
taskId,
cartId: targetCartId,
},
transaction,
});
await ctx.model.query(`
INSERT INTO wms_pick_task_cart_binding (
task_id,
@ -2474,7 +2478,7 @@ class PickSystemService extends Service {
:cartCode,
:warehouseId,
:operatorId,
:bindType,
1,
1,
NOW(),
NOW(),
@ -2487,7 +2491,6 @@ class PickSystemService extends Service {
cartCode: targetCartCode,
warehouseId,
operatorId,
bindType,
},
transaction,
});
@ -2509,25 +2512,6 @@ class PickSystemService extends Service {
transaction,
});
await ctx.model.query(`
UPDATE wms_pick_cart
SET current_task_id = :taskId,
bind_user_id = :operatorId,
last_bind_time = NOW(),
last_seen_time = NOW(),
update_time = NOW()
WHERE id = :cartId
AND warehouse_id = :warehouseId
`, {
replacements: {
taskId,
operatorId,
cartId: targetCartId,
warehouseId,
},
transaction,
});
await transaction.commit();
const latestCartRow = await this.getPickCartById(targetCartId, warehouseId);
@ -2654,8 +2638,24 @@ class PickSystemService extends Service {
throw this.createBusinessError('cart_code 必填', 400);
}
await this.assertPickCartCodeUnique(nextCartCode, warehouseId, cartId);
if (nextStatus === 0 && Number(cartRow.current_task_id || 0) > 0) {
throw this.createBusinessError('拣货车已绑定任务,无法停用', 400);
if (nextStatus === 0) {
// 通过绑定表检查车是否被活动任务占用
const activeBindingRows = await ctx.model.query(`
SELECT b.id
FROM wms_pick_task_cart_binding b
INNER JOIN wms_wave_pick_task t ON t.id = b.task_id
WHERE b.cart_id = :cartId
AND b.warehouse_id = :warehouseId
AND b.is_active = 1
AND t.status IN (0, 1)
LIMIT 1
`, {
replacements: { cartId, warehouseId },
type: ctx.model.QueryTypes.SELECT,
});
if (Array.isArray(activeBindingRows) && activeBindingRows.length > 0) {
throw this.createBusinessError('拣货车已绑定活动任务,无法停用', 400);
}
}
await ctx.model.query(`

View File

@ -154,7 +154,7 @@ class PrintComputerService extends Service {
* 设置录制电脑。
* 会将同仓库下其他已设为录制的电脑取消,再设置当前电脑为录制。
* @param {number} id 电脑ID
* @param {Object} data { recording_size_value, recording_size_unit, remote_play_url, recording_directory }
* @param {Object} data { recording_size_value, recording_size_unit, recording_directory }
* @return {Promise<Object>} 更新后的记录
*/
async setRecording(id, data) {
@ -176,11 +176,6 @@ class PrintComputerService extends Service {
throw new Error(`存储单位不合法,支持:${VALID_UNITS.join('/')}`);
}
const url = String(data.remote_play_url || '').trim();
if (!/^https?:\/\/.+/.test(url)) {
throw new Error('远程播放地址必须以 http:// 或 https:// 开头');
}
const directory = String(data.recording_directory || '').trim();
if (!directory) {
throw new Error('录制目录不能为空');
@ -198,7 +193,6 @@ class PrintComputerService extends Service {
is_recording: false,
recording_size_value: null,
recording_size_unit: null,
remote_play_url: null,
recording_directory: null,
},
{
@ -215,7 +209,6 @@ class PrintComputerService extends Service {
is_recording: true,
recording_size_value: sizeValue,
recording_size_unit: unit,
remote_play_url: url,
recording_directory: directory,
});
@ -261,7 +254,6 @@ class PrintComputerService extends Service {
is_recording: false,
recording_size_value: null,
recording_size_unit: null,
remote_play_url: null,
recording_directory: null,
});

View File

@ -696,6 +696,8 @@ class ShopsService extends Service {
'callbackurl',
{ required: true, maxLength: 500 }
);
const appId = data.appId || '';
const toUserName = data.toUserName || '';
const shop = await this.findShopById(shopId, { allowDeleted: false });
const shopPlain = typeof shop.get === 'function' ? shop.get({ plain: true }) : shop;
const platformCode = await this.ensureShopPrintPlatformExists(shopPlain.platform_code);
@ -719,6 +721,16 @@ class ShopsService extends Service {
if (platName === '电商京东') {
requestData.VenderID = shopPlain.id;
}
if (platName === '视频号') {
if(!appId || !toUserName) {
throw this.createError('视频号授权需要提供 appId 和 toUserName', 400);
}
requestData.appId = appId;
requestData.toUserName = toUserName;
delete requestData.RedirectCodeUrl;
}
// 缓存最后一次授权查询请求数据,便于排查问题
await this.app.setCacheAsync('last_query_auth_polo', JSON.stringify(requestData), 3600);
const respone = await ctx.curl(authUrl, {
method: 'POST',
@ -726,6 +738,7 @@ class ShopsService extends Service {
timeout: 5000,
data: requestData,
});
await this.app.setCacheAsync('last_respone_auth_polo', JSON.stringify(respone), 3600);
if (respone.data && respone.data.code === 0) {
const sessionKey = respone.data.data || null;
if (sessionKey) {

View File

@ -1686,6 +1686,293 @@ class InventoryService extends Service {
}
}
/**
* 导出库存列表(异步任务内部调用,生成 Excel 并上传)。
*
* where 条件通过 ctx.whereParsed 读取(与 getInventoryList 完全一致),
* 调用方需先执行 prepareWhereContext 设置 ctx.whereParsed。
*
* 支持两种导出模式:
* - stock_location:按 stock_id + space_id(库位)聚合,汇总数量
* - storage:按 storage_id 逐条导出明细
*
* @param {Object} sortParams 排序参数 { sortField, sortOrder }
* @param {boolean} groupByBatch 是否按批次导出(false=聚合,true=逐条明细)
* @return {Promise<Object>} 导出上传结果(含 url/fileKey 等)
*/
async exportInventoryList(sortParams = {}, groupByBatch = false) {
const { ctx, app } = this;
const { Op, fn, col, literal } = app.Sequelize;
const warehouseId = ctx.user.store_id;
const { sortField = 'id', sortOrder = 'DESC' } = sortParams;
const pageSize = 500;
let page = 1;
let hasNext = true;
const rows = [];
// 构建基础 where 条件(与 getInventoryList 完全一致)
const baseWhere = {
[Op.and]: [
{ warehouse_id: warehouseId },
{ is_enabled: 1 },
{ delete_at: null },
],
};
// 动态 where 条件(与 getInventoryList 一致:从 ctx.whereParsed 读取)
const parsed = ctx.whereParsed;
if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) {
baseWhere[Op.and].push(...parsed.dynamicConditions);
}
if (groupByBatch) {
// ────── group_by_batch=true:按 storage_id 逐条导出明细 ──────
while (hasNext) {
const { rows: pageRows } = await ctx.model.Storage.findAndCountAll({
where: baseWhere,
attributes: [
'id', 'stock_id', 'space_id', 'batch_no', 'inventory_type',
'quantity', 'locked_quantity', 'available_quantity',
'production_date', 'expiry_date', 'inbound_time', 'inbound_order_no',
'supplier_batch_no', 'store_id', 'warehouse_id',
'created_at', 'updated_at',
],
order: [[ sortField, sortOrder ]],
offset: (page - 1) * pageSize,
limit: pageSize,
include: [
{
model: ctx.model.StockWarehouse,
as: 'stock',
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ],
required: false,
},
{
model: ctx.model.LocationSpace,
as: 'space',
attributes: [ 'id', 'space_code', 'custom_name' ],
required: false,
},
],
raw: true,
nest: true,
});
if (pageRows.length === 0) {
hasNext = false;
break;
}
// 收集 store_id 批量查询货主名称
const storeIds = [ ...new Set(pageRows.map(r => Number(r.store_id)).filter(Boolean)) ];
const storeMap = new Map();
if (storeIds.length > 0) {
try {
const storeRows = await ctx.model.StoreWarehouse.findAll({
attributes: [ 'store_id', 'store_remask' ],
where: { store_id: { [Op.in]: storeIds }, warehouse_id: warehouseId },
raw: true,
});
for (const sr of storeRows) {
storeMap.set(Number(sr.store_id), sr.store_remask || '');
}
} catch (_e) { /* ignore */ }
}
for (const row of pageRows) {
rows.push({
storage_id: row.id,
stock_id: row.stock_id,
item_code: row.stock?.item_code || '',
item_name: row.stock?.item_name || '',
sku_property: row.stock?.sku_property || '',
stock_unit: row.stock?.stock_unit || '',
store_name: storeMap.get(Number(row.store_id)) || '',
space_code: row.space?.space_code || '',
space_name: row.space?.custom_name || '',
batch_no: row.batch_no || '',
inventory_type: row.inventory_type || '',
quantity: row.quantity,
locked_quantity: row.locked_quantity,
available_quantity: row.available_quantity,
production_date: row.production_date ? app.formatDate(row.production_date) : '',
expiry_date: row.expiry_date ? app.formatDate(row.expiry_date) : '',
inbound_time: row.inbound_time ? app.formatDate(row.inbound_time) : '',
inbound_order_no: row.inbound_order_no || '',
supplier_batch_no: row.supplier_batch_no || '',
created_at: row.created_at ? app.formatDate(row.created_at) : '',
updated_at: row.updated_at ? app.formatDate(row.updated_at) : '',
});
}
hasNext = pageRows.length >= pageSize;
page += 1;
}
} else {
// ────── group_by_batch=false(默认):按 stock_id + space_id 聚合 ──────
const groupFields = [ 'stock_id', 'space_id' ];
while (hasNext) {
const pageRows = await ctx.model.Storage.findAll({
where: baseWhere,
attributes: [
'stock_id',
'space_id',
[ fn('MIN', col('wms_storage.store_id')), 'store_id' ],
[ fn('SUM', col('wms_storage.quantity')), 'quantity' ],
[ fn('SUM', col('wms_storage.locked_quantity')), 'locked_quantity' ],
[ fn('SUM', col('wms_storage.available_quantity')), 'available_quantity' ],
[ fn('COUNT', col('wms_storage.id')), 'batch_count' ],
[ fn('MAX', col('wms_storage.inbound_time')), 'last_inbound_time' ],
[ fn('MIN', col('wms_storage.created_at')), 'first_created_at' ],
[ fn('MAX', col('wms_storage.updated_at')), 'last_updated_at' ],
],
group: groupFields,
order: [[ literal('last_inbound_time'), sortOrder ]],
offset: (page - 1) * pageSize,
limit: pageSize,
include: [
{
model: ctx.model.StockWarehouse,
as: 'stock',
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ],
required: false,
},
{
model: ctx.model.LocationSpace,
as: 'space',
attributes: [ 'id', 'space_code', 'custom_name' ],
required: false,
},
],
raw: true,
nest: true,
});
if (pageRows.length === 0) {
hasNext = false;
break;
}
// 收集 store_id 批量查询货主名称
const storeIds = [ ...new Set(pageRows.map(r => Number(r.store_id)).filter(Boolean)) ];
const storeMap = new Map();
if (storeIds.length > 0) {
try {
const storeRows = await ctx.model.StoreWarehouse.findAll({
attributes: [ 'store_id', 'store_remask' ],
where: { store_id: { [Op.in]: storeIds }, warehouse_id: warehouseId },
raw: true,
});
for (const sr of storeRows) {
storeMap.set(Number(sr.store_id), sr.store_remask || '');
}
} catch (_e) { /* ignore */ }
}
for (const row of pageRows) {
rows.push({
stock_id: row.stock_id,
space_id: row.space_id,
item_code: row.stock?.item_code || '',
item_name: row.stock?.item_name || '',
sku_property: row.stock?.sku_property || '',
stock_unit: row.stock?.stock_unit || '',
store_name: storeMap.get(Number(row.store_id)) || '',
space_code: row.space?.space_code || '',
space_name: row.space?.custom_name || '',
quantity: row.quantity,
locked_quantity: row.locked_quantity,
available_quantity: row.available_quantity,
batch_count: row.batch_count,
last_inbound_time: row.last_inbound_time ? app.formatDate(row.last_inbound_time) : '',
created_at: row.first_created_at ? app.formatDate(row.first_created_at) : '',
updated_at: row.last_updated_at ? app.formatDate(row.last_updated_at) : '',
});
}
hasNext = pageRows.length >= pageSize;
page += 1;
}
}
// ── 批量填充商品条码和图片(复用 loadStockAttachments 缓存查询)──
if (rows.length > 0) {
const stockIds = [ ...new Set(
rows.map(r => Number(r.stock_id || 0)).filter(Boolean)
) ];
const { barcodesByStockId, imagesByStockId } = await loadStockAttachments(ctx, stockIds);
for (const row of rows) {
const sid = Number(row.stock_id || 0);
row.barcodes = sid ? (barcodesByStockId.get(sid) || []).join(', ') : '';
row.image_url = sid ? ((imagesByStockId.get(sid) || [])[0] || '') : '';
}
}
// 生成 Excel
const now = new Date();
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}${String(now.getMilliseconds()).padStart(3, '0')}`;
const modeLabel = groupByBatch ? '库存明细' : '库存汇总';
const sheetName = groupByBatch ? '库存明细' : '库存汇总(按商品+库位)';
const columns = groupByBatch
? [
{ header: '库存记录ID', key: 'storage_id' },
{ header: '商品编码', key: 'item_code' },
{ header: '商品名称', key: 'item_name' },
{ header: '规格', key: 'sku_property' },
{ header: '库存单位', key: 'stock_unit' },
{ header: '货主', key: 'store_name' },
{ header: '库位编码', key: 'space_code' },
{ header: '库位名称', key: 'space_name' },
{ header: '条码', key: 'barcodes' },
{ header: '图片', key: 'image_url' },
{ header: '批次号', key: 'batch_no' },
{ header: '库存类型', key: 'inventory_type' },
{ header: '数量', key: 'quantity' },
{ header: '锁定数量', key: 'locked_quantity' },
{ header: '可用数量', key: 'available_quantity' },
{ header: '生产日期', key: 'production_date' },
{ header: '过期日期', key: 'expiry_date' },
{ header: '入库时间', key: 'inbound_time' },
{ header: '入库单号', key: 'inbound_order_no' },
{ header: '供应商批次号', key: 'supplier_batch_no' },
{ header: '创建时间', key: 'created_at' },
{ header: '更新时间', key: 'updated_at' },
]
: [
{ header: '商品编码', key: 'item_code' },
{ header: '商品名称', key: 'item_name' },
{ header: '规格', key: 'sku_property' },
{ header: '库存单位', key: 'stock_unit' },
{ header: '货主', key: 'store_name' },
{ header: '条码', key: 'barcodes' },
{ header: '图片', key: 'image_url' },
{ header: '库位编码', key: 'space_code' },
{ header: '库位名称', key: 'space_name' },
{ header: '总库存', key: 'quantity' },
{ header: '锁定库存', key: 'locked_quantity' },
{ header: '可用库存', key: 'available_quantity' },
{ header: '批次数', key: 'batch_count' },
{ header: '最近入库时间', key: 'last_inbound_time' },
{ header: '创建时间', key: 'created_at' },
{ header: '更新时间', key: 'updated_at' },
];
return await ctx.service.systems.excel.generateAndUpload({
filename: `${modeLabel}导出_${dateToken}.xlsx`,
dir: `exports/storage/inventory/${warehouseId}`,
category: 'document',
sheets: [{
name: sheetName,
columns,
rows,
}],
});
}
/**
* 生成入库单号。
* 格式:SCRK + 年月日 + 4位流水号

View File

@ -4727,14 +4727,14 @@ class ReceivingService extends Service {
const { Op } = Sequelize;
const safeOptions = options && typeof options === 'object' ? options : {};
const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {};
const storeId = Number(safeOptions.storeId);
const warehouseId = Number(ctx.user && ctx.user.store_id);
const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {};
const progressHandler = typeof safeOptions.onProgress === 'function'
? safeOptions.onProgress
: async () => {};
if (!storeId) {
throw new Error('货主ID不能为空,无法导出');
if (!warehouseId) {
throw new Error('用户未绑定仓库,无法导出');
}
const sortField = sort.sortField || 'created_at';
@ -4744,24 +4744,27 @@ class ReceivingService extends Service {
];
const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at';
// 构建 where 条件(与 getStoreReceivingList 一致)
// 构建 where 条件(与 getReceivingList 一致,按仓库维度)
const queryOptions = {
where: { [Op.and]: [{ store_id: storeId }] },
where: { [Op.and]: [{ warehouse_id: warehouseId }] },
};
const normalizedWhere = { ...where };
const parsed = parseWhereConditions({
where: normalizedWhere,
app,
specialFieldMap: {
quickWhere: { bucket: 'quick' },
},
});
let parsedResult = ctx.whereParsed;
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
const parsed = parseWhereConditions({
where: normalizedWhere,
app,
specialFieldMap: {
quickWhere: { bucket: 'quick' },
},
});
if (!parsed.ok) {
throw new Error(`筛选条件解析失败: ${parsed.reason}`);
if (!parsed.ok) {
throw new Error(`筛选条件解析失败: ${parsed.reason}`);
}
parsedResult = parsed.result;
}
const parsedResult = parsed.result;
const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ];
const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
@ -5089,7 +5092,438 @@ class ReceivingService extends Service {
const stat = await fsp.stat(filePath);
const randomToken = crypto.randomBytes(6).toString('hex');
const uploadKey = `exports/receiving/${storeId}/${Date.now()}_${randomToken}.xlsx`;
const uploadKey = `exports/receiving/${warehouseId}/${Date.now()}_${randomToken}.xlsx`;
const uploadStream = fs.createReadStream(filePath);
uploadStream.filename = filename;
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
uploadStream.fileSize = stat.size;
const uploadResult = await uploadService.uploadFile(uploadStream, {
key: uploadKey,
category: 'document',
mimetype: 'xls,xlsx,csv',
});
let fileRecord = null;
if (typeof uploadService.uploadSuccessNotify === 'function') {
fileRecord = await uploadService.uploadSuccessNotify({
url: uploadResult.fileName,
fileKey: uploadResult.fileName,
fileName: filename,
fileType: 'document',
mimeType: uploadStream.mimeType,
fileSize: stat.size,
userId: ctx.userId,
description: `收货单导出(仓库${warehouseId}),共${totalCount}条收货单`,
});
}
// 清理临时文件
try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (_) { /* ignore */ }
const uploadInfo = fileRecord || uploadResult;
const fileUrl = typeof uploadInfo === 'object' && uploadInfo.url
? uploadInfo.url
: (typeof uploadResult === 'object' ? uploadResult.fileName : '');
await progressHandler({
status: 'running',
progress: 100,
message: '导出完成',
result: { url: fileUrl, fileKey: uploadKey, total: totalCount },
});
return {
url: fileUrl,
fileKey: uploadKey,
total: totalCount,
totalDetails: allReceivingIds.reduce((sum, rid) => sum + (detailsMap.get(rid) || []).length, 0),
};
}
/**
* 导出货主侧收货单列表(双 sheet:收货单列表 + 收货单明细)。
* 复用 getStoreReceivingList 的筛选与排序语义,以货主 store_id 过滤,分页拉取全量数据后生成 Excel 并上传。
* @param {Object} options 导出选项
* @param {Object} [options.where] 筛选条件(与 getStoreReceivingList 一致)
* @param {number} options.storeId 货主ID
* @param {Object} [options.sort] 排序参数
* @param {Function} [options.onProgress] 进度回调
* @return {Promise<Object>} 上传结果与统计信息
*/
async exportStoreReceivingList(options = {}) {
const { ctx, app } = this;
const { Sequelize } = app;
const { Op } = Sequelize;
const safeOptions = options && typeof options === 'object' ? options : {};
const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {};
const storeId = Number(safeOptions.storeId);
const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {};
const progressHandler = typeof safeOptions.onProgress === 'function'
? safeOptions.onProgress
: async () => {};
if (!storeId) {
throw new Error('货主ID不能为空,无法导出');
}
const sortField = sort.sortField || 'created_at';
const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
const validSortFields = [
'id', 'receiving_number', 'status', 'created_at', 'updated_at', 'store_id', 'warehouse_id',
];
const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at';
// 构建 where 条件(与 getStoreReceivingList 一致,按货主维度)
const queryOptions = {
where: { [Op.and]: [{ store_id: storeId }] },
};
const normalizedWhere = { ...where };
let parsedResult = ctx.whereParsed;
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
const parsed = parseWhereConditions({
where: normalizedWhere,
app,
specialFieldMap: {
quickWhere: { bucket: 'quick' },
},
});
if (!parsed.ok) {
throw new Error(`筛选条件解析失败: ${parsed.reason}`);
}
parsedResult = parsed.result;
}
const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ];
const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|| normalizedWhere.quickWhere;
if (quickWhereRaw && quickWhereRaw.value && String(quickWhereRaw.value).trim() !== '') {
const quickValue = String(quickWhereRaw.value).trim();
dynamicConditions.push({
[Op.or]: {
store_name: { [Op.like]: `%${quickValue}%` },
receiving_number: { [Op.like]: `%${quickValue}%` },
tracking_number: { [Op.like]: `%${quickValue}%` },
creator_snapshot: { [Op.like]: `%${quickValue}%` },
license_plate: { [Op.like]: `%${quickValue}%` },
},
});
}
if (dynamicConditions.length > 0) {
queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions });
}
// ---- 分页拉取收货单列表 ----
const RECEIVING_EXPORT_PAGE_SIZE = 200;
const RECEIVING_ITEMS_FETCH_BATCH_SIZE = 50;
const totalCount = await ctx.model.Receiving.count({
where: queryOptions.where,
distinct: true,
});
await progressHandler({
status: 'running',
progress: totalCount > 0 ? 10 : 85,
message: totalCount > 0 ? `已命中 ${totalCount} 条收货单,开始导出` : '未命中数据,开始生成空文件',
});
const allReceivingOrders = [];
let page = 1;
let fetchedCount = 0;
while (fetchedCount < totalCount) {
const rows = await ctx.model.Receiving.findAll({
where: queryOptions.where,
order: [[ actualSortField, sortOrder ]],
limit: RECEIVING_EXPORT_PAGE_SIZE,
offset: (page - 1) * RECEIVING_EXPORT_PAGE_SIZE,
raw: true,
});
if (!Array.isArray(rows) || rows.length === 0) {
break;
}
allReceivingOrders.push(...rows);
fetchedCount += rows.length;
page += 1;
await progressHandler({
status: 'running',
progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)),
message: `正在拉取收货单列表,已完成 ${fetchedCount}/${totalCount}`,
});
}
// ---- 批量拉取收货单明细 ----
const allReceivingIds = allReceivingOrders.map(r => Number(r.id)).filter(Boolean);
/** @type {Map<number, Array<Object>>} receiving_id → details */
const detailsMap = new Map();
if (allReceivingIds.length > 0) {
const batchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE;
const totalBatches = Math.ceil(allReceivingIds.length / batchSize);
for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += batchSize) {
const batchIds = allReceivingIds.slice(batchIdx, batchIdx + batchSize);
const details = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id: { [Op.in]: batchIds } },
order: [[ 'receiving_id', 'ASC' ], [ 'id', 'ASC' ]],
raw: true,
});
for (const detail of details) {
const rid = Number(detail.receiving_id);
if (!detailsMap.has(rid)) {
detailsMap.set(rid, []);
}
detailsMap.get(rid).push(detail);
}
const currentBatch = Math.floor(batchIdx / batchSize) + 1;
await progressHandler({
status: 'running',
progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)),
message: `正在拉取收货单明细,已完成批次 ${currentBatch}/${totalBatches}`,
});
}
}
await progressHandler({
status: 'running',
progress: 55,
message: '正在生成 Excel 文件...',
});
// ---- 生成 Excel(流式写入,两个 Sheet) ----
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-receiving-store-export-'));
const now = new Date();
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
const filename = `收货单导出(货主)_${dateToken}.xlsx`;
const filePath = path.join(tempDir, filename);
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
filename: filePath,
useStyles: false,
useSharedStrings: false,
});
const normalizeCellValue = value => {
if (value === null || value === undefined) return '';
if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString();
return value;
};
const statusLabelMap = {
receiving: '收货中',
completed: '已完成',
cancelled: '已作废',
};
const detailStatusLabelMap = {
all_matched: '全部匹配',
partial_matched: '部分匹配',
unmatched: '未匹配',
};
const storageStatusLabelMap = {
none: '未入库',
waiting: '等待入库',
partial: '部分入库',
all: '全部入库',
};
const deliveryMethodLabelMap = {
truck: '货车',
express: '快递',
air_freight: '空运',
sea_freight: '海运',
other: '其他',
};
const loadingMethodLabelMap = {
with_pallet: '带托盘',
without_pallet: '不带托盘',
};
// Sheet 1: 收货单列表
const sheet1 = workbook.addWorksheet('收货单列表');
const receivingColumns = [
{ header: '收货单ID', key: 'id', width: 10 },
{ header: '收货单号', key: 'receiving_number', width: 22 },
{ header: '货主', key: 'store_name', width: 20 },
{ header: '收货状态', key: 'status_label', width: 12 },
{ header: '明细匹配状态', key: 'detail_status_label', width: 14 },
{ header: '入库状态', key: 'storage_status_label', width: 12 },
{ header: '来货方式', key: 'delivery_method_label', width: 12 },
{ header: '车牌号', key: 'license_plate', width: 14 },
{ header: '快递单号', key: 'tracking_number', width: 22 },
{ header: '装卸方式', key: 'loading_method_label', width: 12 },
{ header: '总商品种类', key: 'total_items', width: 12 },
{ header: '总数量', key: 'total_quantity', width: 12 },
{ header: '总箱数', key: 'total_boxes', width: 10 },
{ header: '总托盘数', key: 'total_pallets', width: 10 },
{ header: '审核状态', key: 'is_review_label', width: 10 },
{ header: '创建人', key: 'creator_name', width: 14 },
{ header: '备注', key: 'remark', width: 30 },
{ header: '收货开始时间', key: 'receiving_start_time', width: 20 },
{ header: '收货结束时间', key: 'receiving_end_time', width: 20 },
{ header: '创建时间', key: 'created_at', width: 20 },
{ header: '更新时间', key: 'updated_at', width: 20 },
];
sheet1.columns = receivingColumns;
for (const row of allReceivingOrders) {
let creatorName = '';
try {
if (row.creator_snapshot) {
const snapshot = JSON.parse(row.creator_snapshot);
creatorName = snapshot.name || '';
}
} catch (_) { /* ignore */ }
sheet1.addRow({
id: row.id,
receiving_number: normalizeCellValue(row.receiving_number),
store_name: normalizeCellValue(row.store_name),
status_label: statusLabelMap[row.status] || row.status || '',
detail_status_label: detailStatusLabelMap[row.detail_status] || row.detail_status || '',
storage_status_label: storageStatusLabelMap[row.storage_status] || row.storage_status || '',
delivery_method_label: deliveryMethodLabelMap[row.delivery_method] || row.delivery_method || '',
license_plate: normalizeCellValue(row.license_plate),
tracking_number: normalizeCellValue(row.tracking_number),
loading_method_label: loadingMethodLabelMap[row.loading_method] || row.loading_method || '',
total_items: row.total_items,
total_quantity: row.total_quantity,
total_boxes: row.total_boxes,
total_pallets: row.total_pallets,
is_review_label: row.is_review === 1 ? '已审核' : '未审核',
creator_name: creatorName,
remark: normalizeCellValue(row.remark),
receiving_start_time: normalizeCellValue(row.receiving_start_time),
receiving_end_time: normalizeCellValue(row.receiving_end_time),
created_at: normalizeCellValue(row.created_at),
updated_at: normalizeCellValue(row.updated_at),
}).commit();
}
sheet1.commit();
await progressHandler({
status: 'running',
progress: 70,
message: '正在写入收货单明细...',
});
// Sheet 2: 收货单明细
const sheet2 = workbook.addWorksheet('收货单明细');
const detailColumns = [
{ header: '收货单号', key: 'receiving_number', width: 22 },
{ header: '收货单ID', key: 'receiving_id', width: 12 },
{ header: '明细ID', key: 'detail_id', width: 10 },
{ header: '商品名称', key: 'product_name', width: 28 },
{ header: '商品条码', key: 'barcode', width: 20 },
{ header: '系统商品ID', key: 'system_product_id', width: 14 },
{ header: '实际收货数量', key: 'actual_quantity', width: 14 },
{ header: '箱数', key: 'box_quantity', width: 10 },
{ header: '托盘数', key: 'pallet_quantity', width: 10 },
{ header: '收货状态', key: 'receiving_status_label', width: 12 },
{ header: '入库状态', key: 'storage_status_label', width: 12 },
{ header: '已入库数量', key: 'stored_quantity', width: 12 },
{ header: '批次号', key: 'batch_number', width: 16 },
{ header: '生产日期', key: 'production_date', width: 14 },
{ header: '到期日期', key: 'expiry_date', width: 14 },
{ header: '备注', key: 'remark', width: 30 },
{ header: '创建时间', key: 'created_at', width: 20 },
];
sheet2.columns = detailColumns;
const receivingCodeMap = new Map();
for (const row of allReceivingOrders) {
receivingCodeMap.set(Number(row.id), row.receiving_number || '');
}
const detailReceivingStatusLabelMap = {
pending: '待收货',
receiving: '收货中',
completed: '已完成',
cancelled: '已作废',
};
const detailStorageStatusLabelMap = {
none: '未入库',
waiting: '等待入库',
partial: '部分入库',
all: '全部入库',
};
const itemBatchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE;
let itemWrittenCount = 0;
const totalReceivingOrders = allReceivingIds.length;
for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += itemBatchSize) {
const batchIds = allReceivingIds.slice(batchIdx, batchIdx + itemBatchSize);
for (const rid of batchIds) {
const receivingNumber = receivingCodeMap.get(rid) || '';
const details = detailsMap.get(rid) || [];
for (const detail of details) {
sheet2.addRow({
receiving_number: receivingNumber,
receiving_id: rid,
detail_id: detail.id,
product_name: normalizeCellValue(detail.product_name),
barcode: normalizeCellValue(detail.barcode),
system_product_id: normalizeCellValue(detail.system_product_id),
actual_quantity: detail.actual_quantity,
box_quantity: detail.box_quantity,
pallet_quantity: detail.pallet_quantity,
receiving_status_label: detailReceivingStatusLabelMap[detail.receiving_status] || detail.receiving_status || '',
storage_status_label: detailStorageStatusLabelMap[detail.storage_status] || detail.storage_status || '',
stored_quantity: detail.stored_quantity,
batch_number: normalizeCellValue(detail.batch_number),
production_date: normalizeCellValue(detail.production_date),
expiry_date: normalizeCellValue(detail.expiry_date),
remark: normalizeCellValue(detail.remark),
created_at: normalizeCellValue(detail.created_at),
}).commit();
}
itemWrittenCount += 1;
}
const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1;
const totalBatches = Math.ceil(totalReceivingOrders / itemBatchSize);
await progressHandler({
status: 'running',
progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)),
message: `正在写入收货单明细,已完成 ${itemWrittenCount}/${totalReceivingOrders} 条收货单`,
});
}
sheet2.commit();
await workbook.commit();
await progressHandler({
status: 'running',
progress: 92,
message: '正在上传文件...',
});
// ---- 上传文件 ----
const uploadService = ctx?.service?.systems?.upload;
if (!uploadService || typeof uploadService.uploadFile !== 'function') {
throw new Error('上传服务不可用');
}
const stat = await fsp.stat(filePath);
const randomToken = crypto.randomBytes(6).toString('hex');
const uploadKey = `exports/receiving/store/${storeId}/${Date.now()}_${randomToken}.xlsx`;
const uploadStream = fs.createReadStream(filePath);
uploadStream.filename = filename;
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

View File

@ -1,6 +1,11 @@
'use strict';
const MainService = require('../main');
const ExcelJS = require('exceljs');
const fs = require('fs');
const fsp = require('fs').promises;
const path = require('path');
const os = require('os');
/**
* 业务逻辑层:waybill(运单号快速查询)。
@ -131,6 +136,895 @@ class WaybillService extends MainService {
],
};
}
/**
* 运单列表查询(仓库侧)。
* 按仓库维度查询运单号列表,支持分页、多条件筛选、排序。
* 核心查询仅使用 wms_order_express 单表(利用快照字段),
* 主单号通过 SELF JOIN 同 order_id 下 business_key=1 的记录获取。
*
* @param {Object} [options={}] 查询参数。
* @param {Object} [options.where] 筛选条件,支持 waybillCode / mainWaybillCode / orderId / orderNo / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / packageMaterialId / hasWeighingWeight / keyword / createdAtStart / createdAtEnd。
* @param {Object} [options.pagination] 分页参数 { page, pageSize },默认 page=1, pageSize=20。
* @param {Object} [options.sort] 排序参数 { field, order },默认 create_at desc。
* @return {Promise<Object>} 运单列表与分页信息 { list, pagination }。
*/
async list({ where = {}, pagination = {}, sort = {} } = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
// 仓库隔离
const warehouseId = Number(ctx.user && ctx.user.store_id);
if (!warehouseId) {
this.throwError('用户未绑定仓库,无法查询运单');
}
// 分页参数
const page = Math.max(Number(pagination.page) || 1, 1);
const pageSize = Math.min(Math.max(Number(pagination.pageSize) || 20, 1), 500);
// 排序参数
const allowedSortFields = [ 'create_at', 'weighing_weight', 'id' ];
const sortField = allowedSortFields.includes(sort.field) ? sort.field : 'create_at';
const sortOrder = sort.order === 'asc' ? 'ASC' : 'DESC';
// 构建查询条件
const queryWhere = { warehouse_id: warehouseId };
// 主单号查询:先通过主单号定位 order_id,再查该 order 下所有运单
if (where.mainWaybillCode && String(where.mainWaybillCode).trim()) {
const mainCode = String(where.mainWaybillCode).trim();
const mainRecord = await ctx.model.OrderExpress.findOne({
where: {
waybill_code: mainCode,
business_key: 1,
warehouse_id: warehouseId,
},
attributes: [ 'order_id' ],
raw: true,
});
if (mainRecord) {
queryWhere.order_id = mainRecord.order_id;
} else {
// 主单号不存在,直接返回空结果
return {
list: [],
pagination: { page, pageSize, total: 0, totalPages: 0 },
};
}
}
// 运单号模糊搜索
if (where.waybillCode && String(where.waybillCode).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(where.waybillCode).trim()}%` };
}
// 订单ID等值
if (where.orderId !== undefined && where.orderId !== null && String(where.orderId).trim() !== '') {
queryWhere.order_id = Number(where.orderId);
}
// 订单号模糊搜索
// TODO: 快照字段 delivery_order_code 未落库,暂跳过订单号筛选;快照列就绪后取消注释
// if (where.orderNo && String(where.orderNo).trim()) {
// queryWhere.delivery_order_code = { [Op.like]: `%${String(where.orderNo).trim()}%` };
// }
// 物流公司编码等值
if (where.logisticsCode && String(where.logisticsCode).trim()) {
queryWhere.logistics_code = String(where.logisticsCode).trim();
}
// 物流接口ID等值
if (where.logisticsInterfaceId !== undefined && where.logisticsInterfaceId !== null && String(where.logisticsInterfaceId).trim() !== '') {
queryWhere.logistics_interface_id = Number(where.logisticsInterfaceId);
}
// 平台编码等值
if (where.platformCode && String(where.platformCode).trim()) {
queryWhere.platform_code = String(where.platformCode).trim();
}
// 运单状态等值
if (where.status !== undefined && where.status !== null && String(where.status).trim() !== '') {
queryWhere.status = Number(where.status);
}
// 是否退回
if (where.isBack && String(where.isBack).trim()) {
queryWhere.is_back = String(where.isBack).trim();
}
// 是否拦截
if (where.isIntercept && String(where.isIntercept).trim()) {
queryWhere.is_intercept = String(where.isIntercept).trim();
}
// 是否揽收
if (where.isGalaxyReceive && String(where.isGalaxyReceive).trim()) {
queryWhere.is_galaxy_receive = String(where.isGalaxyReceive).trim();
}
// 运单类型:主单号 / 子单号
if (where.waybillType && String(where.waybillType).trim()) {
const type = String(where.waybillType).trim();
if (type === 'main' || type === '1') {
queryWhere.business_key = 1;
} else if (type === 'child' || type === '2') {
queryWhere.business_key = { [Op.gt]: 1 };
}
}
// 货主ID等值
if (where.storeId !== undefined && where.storeId !== null && String(where.storeId).trim() !== '') {
queryWhere.store_id = Number(where.storeId);
}
// 包材ID等值
if (where.packageMaterialId !== undefined && where.packageMaterialId !== null && String(where.packageMaterialId).trim() !== '') {
queryWhere.package_material_id = Number(where.packageMaterialId);
}
// 是否已称重
if (where.hasWeighingWeight !== undefined && where.hasWeighingWeight !== null && String(where.hasWeighingWeight).trim() !== '') {
const hasWeight = String(where.hasWeighingWeight).trim();
if (hasWeight === 'true') {
queryWhere.weighing_weight = { [Op.gt]: 0 };
} else if (hasWeight === 'false') {
queryWhere.weighing_weight = { [Op.eq]: 0 };
}
}
// 关键词模糊搜索
if (where.keyword && String(where.keyword).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(where.keyword).trim()}%` };
}
// 创建时间范围
if (where.createdAtStart && String(where.createdAtStart).trim()) {
const startDate = this.normalizeDate(String(where.createdAtStart).trim(), false);
if (startDate) {
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate };
}
}
if (where.createdAtEnd && String(where.createdAtEnd).trim()) {
const endDate = this.normalizeDate(String(where.createdAtEnd).trim(), true);
if (endDate) {
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: endDate };
}
}
// 核心查询:仅查 wms_order_express 单表
// TODO: warehouse_name_snapshot / store_id_snapshot / store_name_snapshot / delivery_order_code
// 快照列未落库,暂时只查已有字段;快照列就绪后替换为快照直读
const { count, rows } = await ctx.model.OrderExpress.findAndCountAll({
where: queryWhere,
attributes: [
'id', 'waybill_code', 'order_id', 'business_key', 'status',
'warehouse_id', 'store_id',
'logistics_code', 'logistics_name',
'logistics_interface_id', 'logistics_interface_name',
'platform_code',
'is_back', 'is_intercept', 'is_galaxy_receive',
'weighing_weight',
'package_material_id', 'package_material_name_snapshot',
'create_at',
],
order: [[ sortField, sortOrder ]],
limit: pageSize,
offset: (page - 1) * pageSize,
raw: true,
});
if (rows.length === 0) {
return {
list: [],
pagination: { page, pageSize, total: count, totalPages: Math.ceil(count / pageSize) },
};
}
// 提取所有唯一的 order_id
const orderIds = [ ...new Set(rows.map(r => r.order_id).filter(Boolean)) ];
// SELF JOIN:查询同 order_id 下 business_key=1 的主单号
const mainWaybillMap = new Map();
if (orderIds.length > 0) {
const mainRecords = await ctx.model.OrderExpress.findAll({
where: {
order_id: { [Op.in]: orderIds },
business_key: 1,
},
attributes: [ 'order_id', 'waybill_code' ],
raw: true,
});
for (const rec of mainRecords) {
if (!mainWaybillMap.has(rec.order_id)) {
mainWaybillMap.set(rec.order_id, rec.waybill_code);
}
}
}
// 提取运单号列表,用于查询打印信息
const waybillCodes = rows.map(r => r.waybill_code).filter(Boolean);
// 查询货主备注名称(store_warehouse.store_remask)
const storeRemarkMap = new Map();
const storeWarehouseKeys = rows
.filter(r => r.store_id && r.warehouse_id)
.map(r => `${r.store_id}:${r.warehouse_id}`);
const uniqueKeys = [ ...new Set(storeWarehouseKeys) ];
if (uniqueKeys.length > 0 && ctx.model.StoreWarehouse) {
const swConditions = uniqueKeys.map(key => {
const [ storeId, whId ] = key.split(':');
return { store_id: Number(storeId), warehouse_id: Number(whId) };
});
const swRows = await ctx.model.StoreWarehouse.findAll({
where: { [Op.or]: swConditions },
attributes: [ 'store_id', 'warehouse_id', 'store_remask' ],
raw: true,
});
for (const sw of swRows) {
storeRemarkMap.set(`${sw.store_id}:${sw.warehouse_id}`, sw.store_remask || '');
}
}
// 查询打印记录(次数和最近打印时间)
const printInfoMap = new Map();
if (waybillCodes.length > 0) {
const printRecords = await ctx.model.ExpressPrintRecord.findAll({
where: { express_no: { [Op.in]: waybillCodes } },
attributes: [
'express_no',
[ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'print_count' ],
[ app.Sequelize.fn('MAX', app.Sequelize.col('print_time')), 'last_print_at' ],
],
group: [ 'express_no' ],
raw: true,
});
for (const pr of printRecords) {
printInfoMap.set(pr.express_no, {
print_count: Number(pr.print_count) || 0,
last_print_at: pr.last_print_at || null,
});
}
}
// 组装响应列表
const list = rows.map(row => {
const wbCode = row.waybill_code || '';
const mainCode = mainWaybillMap.get(row.order_id) || wbCode;
const printInfo = printInfoMap.get(wbCode) || { print_count: 0, last_print_at: null };
return {
id: row.id,
waybill_code: wbCode,
main_waybill_code: mainCode,
waybill_type: Number(row.business_key) === 1 ? '主单号' : '子单号',
order_id: row.order_id,
// TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.delivery_order_code
order_no: '',
warehouse_id: row.warehouse_id,
// TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.warehouse_name_snapshot
warehouse_name: '',
store_id: row.store_id || 0,
// TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.store_name_snapshot
store_name: '',
store_remark_name: storeRemarkMap.get(`${row.store_id}:${row.warehouse_id}`) || '',
business_key: row.business_key,
status: row.status,
status_text: row.status === 1 ? '已分配' : '未分配',
logistics_code: row.logistics_code || '',
logistics_name: row.logistics_name || '',
logistics_interface_id: row.logistics_interface_id || 0,
logistics_interface_name: row.logistics_interface_name || '',
platform_code: row.platform_code || '',
is_back: row.is_back || 'N',
is_intercept: row.is_intercept || 'N',
is_galaxy_receive: row.is_galaxy_receive || 'N',
weighing_weight: row.weighing_weight || 0,
weighing_weight_display: row.weighing_weight > 0 ? `${(row.weighing_weight / 1000).toFixed(2)} kg` : '0 kg',
package_material_id: row.package_material_id || 0,
package_material_name: row.package_material_name_snapshot || '',
print_count: printInfo.print_count,
last_print_at: printInfo.last_print_at ? this.app.formatDate(printInfo.last_print_at) : null,
create_at: row.create_at ? this.app.formatDate(row.create_at) : null,
};
});
return {
list,
pagination: {
page,
pageSize,
total: count,
totalPages: Math.ceil(count / pageSize),
},
};
}
/**
* 运单详情查询(仓库侧)。
* 查询单个运单的完整信息,包含关联订单、兄弟运单、打印记录、打包信息。
*
* @param {Object} options 查询参数。
* @param {number} [options.id] 运单记录ID。
* @param {string} [options.waybillCode] 运单号(与 id 二选一,waybillCode 优先)。
* @return {Promise<Object>} 运单详情。
* @throws {Error} 当运单不存在或参数无效时抛出业务错误。
*/
async detail({ id, waybillCode } = {}) {
const { ctx } = this;
// 仓库隔离
const warehouseId = Number(ctx.user && ctx.user.store_id);
if (!warehouseId) {
this.throwError('用户未绑定仓库,无法查询运单');
}
// 构建查询条件
const expressWhere = { warehouse_id: warehouseId };
if (waybillCode && String(waybillCode).trim()) {
expressWhere.waybill_code = String(waybillCode).trim();
} else if (id !== undefined && id !== null && String(id).trim() !== '') {
expressWhere.id = Number(id);
} else {
this.throwError('运单ID或运单号不能为空');
}
// 查询运单主记录
const record = await ctx.model.OrderExpress.findOne({
where: expressWhere,
raw: true,
});
if (!record) {
this.throwError('未找到该运单');
}
const orderId = record.order_id;
// 查询同订单下所有运单(兄弟运单)
const siblingWaybills = await ctx.model.OrderExpress.findAll({
where: { order_id: orderId, warehouse_id: warehouseId },
attributes: [ 'id', 'waybill_code', 'business_key' ],
order: [[ 'business_key', 'ASC' ]],
raw: true,
});
const mainWaybillRecord = siblingWaybills.find(s => Number(s.business_key) === 1);
const mainWaybillCode = mainWaybillRecord ? mainWaybillRecord.waybill_code : (record.waybill_code || '');
const siblingList = siblingWaybills.map(s => ({
waybill_code: s.waybill_code || '',
business_key: s.business_key,
waybill_type: Number(s.business_key) === 1 ? '主单号' : '子单号',
}));
// 通过 OrderDeliveryFactory 多表遍历查询订单信息
const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory;
let orderInfo = null;
if (orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') {
const tableOrders = [
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) },
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findOne !== 'function') {
continue;
}
const row = await model.findOne({
where: { id: orderId, warehouse_id: warehouseId },
attributes: [
'id', 'delivery_order_code', 'warehouse_id', 'store_id',
'wave_id', 'wave_no', 'order_type', 'store_name',
],
raw: true,
});
if (row) {
orderInfo = {
order_id: row.id,
order_no: row.delivery_order_code || '',
warehouse_id: row.warehouse_id,
// TODO: 快照列未落库,暂时填空;快照就绪后替换为 record.warehouse_name_snapshot
warehouse_name: '',
store_id: row.store_id || 0,
store_name: row.store_name || '',
wave_id: row.wave_id || 0,
wave_no: row.wave_no || '',
order_type: row.order_type || 'delivery',
};
break;
}
} catch (_err) {
continue;
}
}
}
// 若遍历失败,用已有信息兜底
// TODO: 快照列未落库,暂用空值兜底;快照就绪后替换为 record.xxx_snapshot
if (!orderInfo) {
orderInfo = {
order_id: orderId,
order_no: '',
warehouse_id: record.warehouse_id,
warehouse_name: '',
store_id: 0,
store_name: '',
wave_id: 0,
wave_no: '',
order_type: 'delivery',
};
}
// 查询打印记录
let printRecords = [];
if (record.waybill_code) {
printRecords = await ctx.model.ExpressPrintRecord.findAll({
where: { express_no: record.waybill_code },
attributes: [
'id', 'printer_name', 'template_id', 'platform',
'print_time',
],
order: [[ 'print_time', 'DESC' ]],
raw: true,
});
}
// 组装详情响应
return {
id: record.id,
waybill_code: record.waybill_code || '',
main_waybill_code: mainWaybillCode,
waybill_type: Number(record.business_key) === 1 ? '主单号' : '子单号',
business_key: record.business_key,
sibling_waybills: siblingList,
order: orderInfo,
logistics: {
logistics_code: record.logistics_code || '',
logistics_name: record.logistics_name || '',
logistics_interface_id: record.logistics_interface_id || 0,
logistics_interface_name: record.logistics_interface_name || '',
platform_code: record.platform_code || '',
},
status_info: {
status: record.status,
status_text: record.status === 1 ? '已分配' : '未分配',
is_back: record.is_back || 'N',
is_intercept: record.is_intercept || 'N',
is_galaxy_receive: record.is_galaxy_receive || 'N',
},
weight: {
weighing_weight: record.weighing_weight || 0,
weighing_weight_display: record.weighing_weight > 0
? `${(record.weighing_weight / 1000).toFixed(2)} kg`
: '0 kg',
},
package: {
package_material_id: record.package_material_id || 0,
package_material_name: record.package_material_name_snapshot || '',
},
print_records: printRecords.map(pr => ({
id: pr.id,
printer_name: pr.printer_name || '',
template_id: pr.template_id || 0,
template_name: '',
platform: pr.platform || '',
printed_at: pr.print_time ? this.app.formatDate(pr.print_time) : null,
})),
print_count: printRecords.length,
printinfo: record.printinfo || null,
ver: record.ver || '',
retry_count: record.retry_count || 0,
create_at: record.create_at ? this.app.formatDate(record.create_at) : null,
delete_at: record.delete_at ? this.app.formatDate(record.delete_at) : null,
};
}
/**
* 运单导出(仓库侧)。
* 复用 list 的筛选逻辑,分批查询,支持进度回调。
*
* @param {Object} options 导出参数。
* @param {Object} [options.where={}] 筛选条件(同 list)。
* @param {Object} [options.sort={}] 排序参数(同 list)。
* @param {string[]} [options.exportFields] 需要导出的字段列表,不传则导出全部字段。
* @param {Function} [options.onProgress] 进度回调,接收 `{ status, progress, currentCount, totalCount, message, result }`。
* @return {Promise<Object>} 导出结果 { list, current_count, total_count, url }。
*/
async export({ where = {}, sort = {}, exportFields, onProgress } = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
// 仓库隔离
const warehouseId = Number(ctx.user && ctx.user.store_id);
if (!warehouseId) {
this.throwError('用户未绑定仓库,无法导出运单');
}
// 排序参数
const allowedSortFields = [ 'create_at', 'weighing_weight', 'id' ];
const sortField = allowedSortFields.includes(sort.field) ? sort.field : 'create_at';
const sortOrder = sort.order === 'asc' ? 'ASC' : 'DESC';
// 构建查询条件(同 list)
const queryWhere = { warehouse_id: warehouseId };
// 主单号查询
if (where.mainWaybillCode && String(where.mainWaybillCode).trim()) {
const mainCode = String(where.mainWaybillCode).trim();
const mainRecord = await ctx.model.OrderExpress.findOne({
where: {
waybill_code: mainCode,
business_key: 1,
warehouse_id: warehouseId,
},
attributes: [ 'order_id' ],
raw: true,
});
if (mainRecord) {
queryWhere.order_id = mainRecord.order_id;
} else {
if (typeof onProgress === 'function') {
await onProgress({ status: 'success', progress: 100, currentCount: 0, totalCount: 0, message: '导出完成', result: { list: [], url: '' } });
}
return { list: [], current_count: 0, total_count: 0, url: '' };
}
}
if (where.waybillCode && String(where.waybillCode).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(where.waybillCode).trim()}%` };
}
if (where.orderId !== undefined && where.orderId !== null && String(where.orderId).trim() !== '') {
queryWhere.order_id = Number(where.orderId);
}
// TODO: 快照字段 delivery_order_code 未落库,暂跳过订单号筛选;快照列就绪后取消注释
if (where.logisticsCode && String(where.logisticsCode).trim()) {
queryWhere.logistics_code = String(where.logisticsCode).trim();
}
if (where.logisticsInterfaceId !== undefined && where.logisticsInterfaceId !== null && String(where.logisticsInterfaceId).trim() !== '') {
queryWhere.logistics_interface_id = Number(where.logisticsInterfaceId);
}
if (where.platformCode && String(where.platformCode).trim()) {
queryWhere.platform_code = String(where.platformCode).trim();
}
if (where.status !== undefined && where.status !== null && String(where.status).trim() !== '') {
queryWhere.status = Number(where.status);
}
if (where.isBack && String(where.isBack).trim()) {
queryWhere.is_back = String(where.isBack).trim();
}
if (where.isIntercept && String(where.isIntercept).trim()) {
queryWhere.is_intercept = String(where.isIntercept).trim();
}
if (where.isGalaxyReceive && String(where.isGalaxyReceive).trim()) {
queryWhere.is_galaxy_receive = String(where.isGalaxyReceive).trim();
}
if (where.waybillType && String(where.waybillType).trim()) {
const type = String(where.waybillType).trim();
if (type === 'main' || type === '1') {
queryWhere.business_key = 1;
} else if (type === 'child' || type === '2') {
queryWhere.business_key = { [Op.gt]: 1 };
}
}
// 货主ID等值
if (where.storeId !== undefined && where.storeId !== null && String(where.storeId).trim() !== '') {
queryWhere.store_id = Number(where.storeId);
}
if (where.packageMaterialId !== undefined && where.packageMaterialId !== null && String(where.packageMaterialId).trim() !== '') {
queryWhere.package_material_id = Number(where.packageMaterialId);
}
if (where.hasWeighingWeight !== undefined && where.hasWeighingWeight !== null && String(where.hasWeighingWeight).trim() !== '') {
const hasWeight = String(where.hasWeighingWeight).trim();
if (hasWeight === 'true') {
queryWhere.weighing_weight = { [Op.gt]: 0 };
} else if (hasWeight === 'false') {
queryWhere.weighing_weight = { [Op.eq]: 0 };
}
}
if (where.keyword && String(where.keyword).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(where.keyword).trim()}%` };
}
if (where.createdAtStart && String(where.createdAtStart).trim()) {
const startDate = this.normalizeDate(String(where.createdAtStart).trim(), false);
if (startDate) {
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate };
}
}
if (where.createdAtEnd && String(where.createdAtEnd).trim()) {
const endDate = this.normalizeDate(String(where.createdAtEnd).trim(), true);
if (endDate) {
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: endDate };
}
}
// 先统计总数
if (typeof onProgress === 'function') {
await onProgress({ status: 'running', progress: 10, currentCount: 0, totalCount: 0, message: '正在统计数据…' });
}
const totalCount = await ctx.model.OrderExpress.count({ where: queryWhere });
if (totalCount === 0) {
if (typeof onProgress === 'function') {
await onProgress({ status: 'success', progress: 100, currentCount: 0, totalCount: 0, message: '导出完成', result: { list: [], url: '' } });
}
return { list: [], current_count: 0, total_count: 0, url: '' };
}
if (typeof onProgress === 'function') {
await onProgress({ status: 'running', progress: 15, currentCount: 0, totalCount, message: `共 ${totalCount} 条,正在导出…` });
}
// 分批查询(避免大数据量内存溢出)
const EXPORT_PAGE_SIZE = 500;
const allRows = [];
const totalPages = Math.ceil(totalCount / EXPORT_PAGE_SIZE);
for (let page = 0; page < totalPages; page++) {
const pageRows = await ctx.model.OrderExpress.findAll({
where: queryWhere,
// TODO: 快照列未落库,暂时只查已有字段;快照就绪后补充
attributes: [
'id', 'waybill_code', 'order_id', 'business_key', 'status',
'warehouse_id', 'store_id',
'logistics_code', 'logistics_name',
'logistics_interface_id', 'logistics_interface_name',
'platform_code',
'is_back', 'is_intercept', 'is_galaxy_receive',
'weighing_weight',
'package_material_id', 'package_material_name_snapshot',
'create_at',
],
order: [[ sortField, sortOrder ]],
limit: EXPORT_PAGE_SIZE,
offset: page * EXPORT_PAGE_SIZE,
raw: true,
});
allRows.push(...pageRows);
// 进度回调(15% ~ 90%)
if (typeof onProgress === 'function') {
const progress = 15 + Math.round(75 * (page + 1) / totalPages);
await onProgress({
status: 'running',
progress,
currentCount: allRows.length,
totalCount,
message: `已导出 ${allRows.length} / ${totalCount} 条`,
});
}
}
// 提取所有唯一的 order_id,SELF JOIN 主单号
const orderIds = [ ...new Set(allRows.map(r => r.order_id).filter(Boolean)) ];
const mainWaybillMap = new Map();
if (orderIds.length > 0) {
const mainRecords = await ctx.model.OrderExpress.findAll({
where: {
order_id: { [Op.in]: orderIds },
business_key: 1,
},
attributes: [ 'order_id', 'waybill_code' ],
raw: true,
});
for (const rec of mainRecords) {
if (!mainWaybillMap.has(rec.order_id)) {
mainWaybillMap.set(rec.order_id, rec.waybill_code);
}
}
}
// 预定义全部导出字段映射
const allFieldMap = {
id: r => r.id,
waybill_code: r => r.waybill_code || '',
main_waybill_code: r => mainWaybillMap.get(r.order_id) || r.waybill_code || '',
waybill_type: r => (Number(r.business_key) === 1 ? '主单号' : '子单号'),
order_id: r => r.order_id,
// TODO: 快照列未落库,暂时填空;快照就绪后替换
order_no: () => '',
warehouse_id: r => r.warehouse_id,
warehouse_name: () => '',
store_id: r => r.store_id || 0,
store_name: () => '',
business_key: r => r.business_key,
status: r => r.status,
status_text: r => (r.status === 1 ? '已分配' : '未分配'),
logistics_code: r => r.logistics_code || '',
logistics_name: r => r.logistics_name || '',
logistics_interface_id: r => r.logistics_interface_id || 0,
logistics_interface_name: r => r.logistics_interface_name || '',
platform_code: r => r.platform_code || '',
is_back: r => r.is_back || 'N',
is_intercept: r => r.is_intercept || 'N',
is_galaxy_receive: r => r.is_galaxy_receive || 'N',
weighing_weight: r => r.weighing_weight || 0,
weighing_weight_display: r => (r.weighing_weight > 0 ? `${(r.weighing_weight / 1000).toFixed(2)} kg` : '0 kg'),
package_material_id: r => r.package_material_id || 0,
package_material_name: r => r.package_material_name_snapshot || '',
create_at: r => (r.create_at ? this.app.formatDate(r.create_at) : null),
};
// 确定导出字段集
const fields = Array.isArray(exportFields) && exportFields.length > 0
? exportFields.filter(f => allFieldMap[f])
: Object.keys(allFieldMap);
const list = allRows.map(row => {
const item = {};
for (const field of fields) {
item[field] = allFieldMap[field](row);
}
return item;
});
if (typeof onProgress === 'function') {
await onProgress({
status: 'running',
progress: 95,
currentCount: allRows.length,
totalCount,
message: '正在生成导出文件…',
});
}
// 生成 Excel 文件并上传
const result = await this.buildWaybillExportFile({
list,
fields,
warehouseId,
totalCount: allRows.length,
});
if (typeof onProgress === 'function') {
await onProgress({
status: 'success',
progress: 100,
currentCount: allRows.length,
totalCount,
message: '导出完成',
result,
});
}
return result;
}
/**
* 生成运单导出 Excel 文件并上传,返回下载链接。
* @param {Object} options 导出选项。
* @param {Array} options.list 导出数据列表。
* @param {string[]} options.fields 导出字段列表。
* @param {number} options.warehouseId 仓库ID。
* @param {number} options.totalCount 总条数。
* @return {Promise<Object>} { current_count, total_count, url }。
*/
async buildWaybillExportFile({ list, fields, warehouseId, totalCount } = {}) {
const { ctx } = this;
// 列名中文映射
const COLUMN_LABELS = {
id: 'ID',
waybill_code: '运单号',
main_waybill_code: '主单号',
waybill_type: '运单类型',
order_id: '订单ID',
order_no: '订单号',
warehouse_id: '仓库ID',
warehouse_name: '仓库名称',
store_id: '货主ID',
store_name: '货主名称',
business_key: '拆单序号',
status: '状态',
status_text: '状态',
logistics_code: '物流编码',
logistics_name: '物流名称',
logistics_interface_id: '物流接口ID',
logistics_interface_name: '物流接口名称',
platform_code: '平台编码',
is_back: '是否退回',
is_intercept: '是否拦截',
is_galaxy_receive: '是否揽收',
weighing_weight: '称重重量(g)',
weighing_weight_display: '称重重量',
package_material_id: '包材ID',
package_material_name: '包材名称',
create_at: '创建时间',
};
// 生成 Excel
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('运单导出');
// 写表头
const headerRow = worksheet.addRow(fields.map(f => COLUMN_LABELS[f] || f));
headerRow.font = { bold: true };
headerRow.alignment = { horizontal: 'center' };
// 写数据
for (const row of list) {
worksheet.addRow(fields.map(f => (row[f] !== undefined && row[f] !== null ? row[f] : '')));
}
// 保存到临时文件
const now = new Date();
const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
const filename = `运单导出_${dateStr}.xlsx`;
const tmpDir = os.tmpdir();
const filePath = path.join(tmpDir, `waybill_export_${Date.now()}_${Math.random().toString(36).slice(2, 8)}.xlsx`);
await workbook.xlsx.writeFile(filePath);
// 上传文件
const uploadService = ctx?.service?.systems?.upload;
let url = '';
let fileKey = '';
if (uploadService && typeof uploadService.uploadFile === 'function') {
try {
const stat = await fsp.stat(filePath);
const safeWarehouseId = String(warehouseId || 'unknown');
const randomToken = Math.random().toString(36).slice(2, 8);
const uploadKey = `exports/waybill/${safeWarehouseId}/${Date.now()}_${randomToken}.xlsx`;
const uploadStream = fs.createReadStream(filePath);
uploadStream.filename = filename;
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
uploadStream.fileSize = stat.size;
const uploadResult = await uploadService.uploadFile(uploadStream, {
key: uploadKey,
category: 'document',
mimetype: 'xls,xlsx,csv',
});
url = uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '';
fileKey = uploadResult.fileName || '';
// 记录上传文件
if (typeof uploadService.uploadSuccessNotify === 'function') {
await uploadService.uploadSuccessNotify({
url: uploadResult.fileName,
fileKey: uploadResult.fileName,
fileName: filename,
fileType: 'document',
mimeType: uploadStream.mimeType,
fileSize: stat.size,
category: 'document',
businessType: 'waybillExport',
businessId: `${warehouseId}`,
uploaderType: ctx?.user?.role || 'system_api',
uploaderDept: ctx?.user?.department || '',
});
}
} catch (uploadError) {
ctx.logger.error('[WaybillService.buildWaybillExportFile] 文件上传失败', {
error: uploadError.message,
filename,
});
}
}
// 清理临时文件
try {
await fsp.unlink(filePath);
} catch (_e) {
// 忽略清理错误
}
return {
current_count: totalCount,
total_count: totalCount,
url,
fileKey,
filename,
};
}
}
module.exports = WaybillService;

View File

@ -438,7 +438,7 @@ class WorkbenchService extends Service {
items_count: itemsCount,
items_total: itemsTotal,
users: usersParam } = params;
if (!deliveryOrderCode) throw new Error('发货单号不能为空');
if (!inputWarehouseId) throw new Error('仓库ID不能为空');
@ -649,6 +649,64 @@ class WorkbenchService extends Service {
ctx.logger.info('[Workbench._packOrder] 写入 %d 个打包人员 operatorText=%s', users.length, operatorText);
}
// 步骤7.5:下发 OSD 叠加到工作台绑定的摄像头(带 Redis 缓存去重)
const cameraIds = Array.isArray(deviceIds) ? deviceIds : [];
if (cameraIds.length > 0) {
let osdText = '';
if (isSandan === 1) {
// 散单:用运单号
const expressRecord = await ctx.model.OrderExpress.findOne({
where: { order_id: orderId, warehouse_id: warehouseId },
attributes: ['waybill_code'],
raw: true,
});
osdText = (expressRecord && expressRecord.waybill_code) || deliveryOrderCode;
} else {
// 团购:波次号+总量
osdText = `波次${actualWaveNo} 共${totalOrders}单`;
}
// 写入 OSD 缓存
try {
const osdCacheKey = `osd_${validWorkbenchId}`;
await this.app.setCacheAsync(osdCacheKey, osdText, 3600);
ctx.logger.info('[Workbench._packOrder] OSD缓存已写入 workbenchId=%d text=%s',
validWorkbenchId, osdText);
} catch (cacheErr) {
ctx.logger.warn('[Workbench._packOrder] OSD缓存写入失败 workbenchId=%d err=%s',
validWorkbenchId, cacheErr.message);
}
const OsdClient = require('../../lib/osd_client');
const osdClient = new OsdClient(ctx);
// 异步下发,不阻塞打包主流程
Promise.all(cameraIds.map(async cameraId => {
try {
const camera = await ctx.model.Camera.findOne({
where: { id: cameraId, warehouse_id: warehouseId },
raw: true,
});
if (!camera || !camera.ip) return;
const result = await osdClient.setOsd({
camera,
warehouseId,
text: osdText,
});
if (!result.success) {
ctx.logger.warn('[Workbench._packOrder] OSD下发失败 cameraId=%d error=%s',
cameraId, result.error || '打印服务返回异常');
}
} catch (err) {
ctx.logger.warn('[Workbench._packOrder] OSD下发异常 cameraId=%d err=%s', cameraId, err.message);
}
})).catch(err => {
ctx.logger.warn('[Workbench._packOrder] OSD批量下发异常 err=%s', err.message);
});
}
// 步骤8:写入操作日志(散单写单个订单,团购批量写波次所有订单)
await this._writePackOperationLog({
warehouseId,
@ -1188,10 +1246,27 @@ class WorkbenchService extends Service {
ctx.logger.warn('[Workbench._queryOrder] 查询订单商品失败: %s', itemsErr.message);
}
// 步骤5:查询货主备注(从合约表 store_warehouse.store_remask)
let storeRemark = '';
const storeId = Number(orderRow.store_id || 0);
if (storeId > 0) {
try {
const swRow = await ctx.model.StoreWarehouse.findOne({
where: { store_id: storeId, warehouse_id: warehouseId },
attributes: ['store_remask'],
raw: true,
});
storeRemark = (swRow && swRow.store_remask) ? String(swRow.store_remask).trim() : '';
} catch (swErr) {
ctx.logger.warn('[Workbench._queryOrder] 查询货主备注失败 storeId=%d: %s', storeId, swErr.message);
}
}
const result = {
barcode: normalizedBarcode,
waybill_code: waybillCode,
isSandan,
store_remark: storeRemark,
express: {
logistics_name: expressRecord.logistics_name,
weighing_weight: expressRecord.weighing_weight,

View File

@ -171,7 +171,7 @@ module.exports = appInfo => {
deletedAt: 'deleted_at', // 软删除字段名
},
pool: {
max: 20,
max: 225,
min: 1,
idle: 10000,
acquire: 30000,

View File

@ -0,0 +1,644 @@
# 售后工单 API 接口设计方案
> **状态**: ⏳ 等待人工审阅
> **设计日期**: 2026-07-29
> **设计人**: wms-db-agent
> **说明**: 本文档仅输出 API 接口设计方案,不直接修改程序代码。审阅通过后再执行实现。
---
## 一、模块概览
| 项目 | 说明 |
|------|------|
| 模块名 | `afterSale` |
| 接口路径 | `POST /system`,body 中 `method` 字段为 `afterSale.{方法名}` |
| 请求方式 | 全部 `POST`,参数放在 `body` 内 |
| 鉴权 | 除 `businessTypes` 外均需登录;写操作需鉴权 |
### 文件规划
```
app/service/systemMethods/afterSale.js ← 入口层(鉴权、参数校验、委托)
app/service/systems/afterSale.js ← 业务层(数据库操作、状态机)
methods/system.json ← API 文档(追加 afterSale group)
```
### 调用链路
```
POST /system { method: "afterSale.list", ... }
→ app/router.js
→ app/service/system.js
→ app/service/systemMethods/afterSale.js ← 鉴权 + 参数校验
→ app/service/systems/afterSale.js ← 业务逻辑 + DB操作
→ app/model/after_sale_work_order.js ← Sequelize Model
→ app/model/after_sale_work_order_step.js
```
---
## 二、接口清单(共 13 个)
| # | method | 描述 | 需登录 | 需鉴权 |
|---|--------|------|--------|--------|
| 1 | `afterSale.businessTypes` | 获取内置业务类型及子类型枚举 | ✗ | ✗ |
| 2 | `afterSale.list` | 工单列表(分页+筛选) | ✓ | ✗ |
| 3 | `afterSale.detail` | 工单详情(含步骤列表) | ✓ | ✗ |
| 4 | `afterSale.create` | 创建工单 | ✓ | ✓ |
| 5 | `afterSale.update` | 更新工单基本信息 | ✓ | ✓ |
| 6 | `afterSale.delete` | 删除工单(软删除) | ✓ | ✓ |
| 7 | `afterSale.assign` | 分配处理人 | ✓ | ✓ |
| 8 | `afterSale.complete` | 完成工单 | ✓ | ✓ |
| 9 | `afterSale.close` | 关闭工单 | ✓ | ✓ |
| 10 | `afterSale.cancel` | 取消工单 | ✓ | ✓ |
| 11 | `afterSale.stepStart` | 开始某个步骤 | ✓ | ✓ |
| 12 | `afterSale.stepComplete` | 完成某个步骤 | ✓ | ✓ |
| 13 | `afterSale.stepSkip` | 跳过某个步骤 | ✓ | ✓ |
---
## 三、接口详细设计
### 3.1 `afterSale.businessTypes` — 获取业务类型枚举
```json
{
"method": "afterSale.businessTypes",
"description": "获取售后工单内置业务类型及子类型枚举,供前端下拉选择使用。数据来源:app/model/after_sale_work_order.js 中的 BUSINESS_TYPES 常量。",
"isNeedAuth": false,
"isNeedLogin": false,
"params": [],
"response": [
{
"name": "data",
"type": "object",
"description": "业务类型枚举,key 为 business_type,value 含 label、table、subtypes",
"example": {
"waybill": {
"label": "运单",
"table": "wms_order_express",
"subtypes": {
"intercept": "拦截",
"urge": "催件",
"damage": "破损",
"lost": "丢件",
"wrong_info": "信息错误"
}
},
"order_delivery": {
"label": "发货订单",
"table": "wms_order_delivery",
"subtypes": {
"mis_shipment": "错发",
"missing_item": "少发",
"wrong_sku": "错品",
"quality_issue": "质量问题",
"delivery_delay": "发货延迟"
}
}
}
}
]
}
```
---
### 3.2 `afterSale.list` — 工单列表
```json
{
"method": "afterSale.list",
"description": "查询售后工单列表,支持分页与多条件筛选。仓库隔离(自动注入 warehouse_id)。",
"isNeedAuth": false,
"isNeedLogin": true,
"params": [
{
"name": "pagination",
"type": "object",
"required": false,
"source": "body",
"description": "分页参数 { page, pageSize },默认 page=1 pageSize=20"
},
{
"name": "where",
"type": "object",
"required": false,
"source": "body",
"description": "筛选条件,所有字段均为可选",
"children": [
{ "name": "workOrderNo", "type": "string", "description": "工单号(模糊搜索)" },
{ "name": "businessType", "type": "string", "description": "业务类型(等值),如 waybill" },
{ "name": "businessSubType","type": "string", "description": "业务子类型(等值),如 intercept" },
{ "name": "businessNo", "type": "string", "description": "关联业务单据号(模糊)" },
{ "name": "status", "type": "number", "description": "工单状态(等值):0/1/2/3/9" },
{ "name": "priorityMin", "type": "number", "description": "优先级下限(>=)" },
{ "name": "priorityMax", "type": "number", "description": "优先级上限(<=)" },
{ "name": "claimStatus", "type": "number", "description": "理赔状态(等值):0/1/2" },
{ "name": "assigneeId", "type": "number", "description": "处理人ID(等值)" },
{ "name": "creatorId", "type": "number", "description": "创建人ID(等值)" },
{ "name": "keyword", "type": "string", "description": "关键词:匹配工单号/标题/业务单据号" },
{ "name": "createdAtStart", "type": "string", "description": "创建时间起始(YYYY-MM-DD)" },
{ "name": "createdAtEnd", "type": "string", "description": "创建时间截止(YYYY-MM-DD)" }
]
},
{
"name": "sort",
"type": "object",
"required": false,
"source": "body",
"description": "排序 { field: 'priority'|'created_at'|'status', order: 'asc'|'desc' },默认 priority desc"
}
],
"response": [
{
"name": "list",
"type": "array",
"description": "工单列表(不含 description/resolution 长文本,减少传输量)",
"children": [
{ "name": "id", "type": "number", "description": "工单ID" },
{ "name": "work_order_no", "type": "string", "description": "工单号" },
{ "name": "warehouse_id", "type": "number", "description": "仓库ID" },
{ "name": "store_id", "type": "number", "description": "货主ID" },
{ "name": "business_type", "type": "string", "description": "业务类型" },
{ "name": "business_sub_type","type": "string", "description": "业务子类型" },
{ "name": "business_id", "type": "number", "description": "关联单据ID" },
{ "name": "business_no", "type": "string", "description": "关联单据号" },
{ "name": "direction", "type": "number", "description": "记账方向:0/1/2" },
{ "name": "status", "type": "number", "description": "工单状态:0/1/2/3/9" },
{ "name": "priority", "type": "number", "description": "优先级:1-100" },
{ "name": "title", "type": "string", "description": "工单标题" },
{ "name": "creator_id", "type": "number", "description": "创建人ID" },
{ "name": "creator_name", "type": "string", "description": "创建人姓名(JOIN account)" },
{ "name": "assignee_id", "type": "number", "description": "当前处理人ID" },
{ "name": "assignee_name", "type": "string", "description": "当前处理人姓名(JOIN account)" },
{ "name": "parent_work_order_id","type":"number","description": "父工单ID" },
{ "name": "current_step", "type": "number", "description": "当前进度步骤序号" },
{ "name": "claim_needed", "type": "number", "description": "是否理赔" },
{ "name": "claim_amount", "type": "number", "description": "理赔金额" },
{ "name": "claim_status", "type": "number", "description": "理赔状态" },
{ "name": "resolved_at", "type": "string", "description": "解决时间" },
{ "name": "created_at", "type": "string", "description": "创建时间" },
{ "name": "updated_at", "type": "string", "description": "更新时间" }
]
},
{ "name": "pagination", "type": "object", "description": "分页信息 { page, pageSize, total, totalPages }" }
]
}
```
---
### 3.3 `afterSale.detail` — 工单详情
```json
{
"method": "afterSale.detail",
"description": "查询单个工单详情,含完整字段 + 步骤列表。仓库隔离。",
"isNeedAuth": false,
"isNeedLogin": true,
"params": [
{
"name": "id",
"type": "number",
"required": true,
"source": "body",
"description": "工单ID(必填)"
}
],
"response": [
{
"name": "data",
"type": "object",
"description": "工单完整信息",
"children": [
{ "name": "id", "type": "number", "description": "工单ID" },
{ "name": "...", "type": "", "description": "同 list 接口所有字段" },
{ "name": "description", "type": "string", "description": "问题描述(详情接口返回)" },
{ "name": "resolution", "type": "string", "description": "处理结果说明(详情接口返回)" },
{ "name": "creator_snapshot", "type": "string", "description": "创建人信息快照" },
{ "name": "steps", "type": "array", "description": "步骤列表",
"children": [
{ "name": "id", "type": "number", "description": "步骤ID" },
{ "name": "step_order", "type": "number", "description": "步骤序号" },
{ "name": "step_name", "type": "string", "description": "步骤名称" },
{ "name": "step_status", "type": "number", "description": "步骤状态:0/1/2/3" },
{ "name": "operator_id", "type": "number", "description": "操作人ID" },
{ "name": "operator_name", "type": "string", "description": "操作人姓名" },
{ "name": "operator_snapshot","type": "string", "description": "操作人快照" },
{ "name": "action", "type": "string", "description": "操作动作" },
{ "name": "remark", "type": "string", "description": "处理备注" },
{ "name": "started_at", "type": "string", "description": "开始时间" },
{ "name": "completed_at", "type": "string", "description": "完成时间" },
{ "name": "created_at", "type": "string", "description": "创建时间" }
]
},
{ "name": "children", "type": "array", "description": "子工单列表(如有)" },
{ "name": "parent", "type": "object", "description": "父工单简要信息(如有)" }
]
}
],
"errors": [
{ "code": "400", "description": "工单ID不能为空" },
{ "code": "404", "description": "工单不存在或无权访问" }
]
}
```
---
### 3.4 `afterSale.create` — 创建工单
```json
{
"method": "afterSale.create",
"description": "创建售后工单。自动生成工单号(AS+时间戳),自动设置 creator_id 和 warehouse_id。创建成功后返回工单详情。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{
"name": "business_type",
"type": "string",
"required": true,
"source": "body",
"description": "业务类型(必填),如 waybill、order_delivery"
},
{
"name": "business_sub_type",
"type": "string",
"required": true,
"source": "body",
"description": "业务子类型(必填),如 intercept、mis_shipment。需与 business_type 匹配(由 BUSINESS_TYPES 校验)"
},
{
"name": "business_id",
"type": "number",
"required": true,
"source": "body",
"description": "关联业务单据主键ID(必填)"
},
{
"name": "business_no",
"type": "string",
"required": false,
"source": "body",
"description": "关联业务单据号(可选,建议传入方便列表展示)"
},
{
"name": "direction",
"type": "number",
"required": false,
"source": "body",
"description": "记账方向:1=入库 2=出库,默认 0(未确定)"
},
{
"name": "priority",
"type": "number",
"required": false,
"source": "body",
"description": "优先级:1~100,默认 50。AI 创建时自动填入"
},
{
"name": "title",
"type": "string",
"required": true,
"source": "body",
"description": "工单标题(必填)"
},
{
"name": "description",
"type": "string",
"required": false,
"source": "body",
"description": "问题描述"
},
{
"name": "claim_needed",
"type": "number",
"required": false,
"source": "body",
"description": "是否需要理赔:0=否 1=是,默认 0"
},
{
"name": "claim_amount",
"type": "number",
"required": false,
"source": "body",
"description": "理赔金额,默认 0.00"
},
{
"name": "parent_work_order_id",
"type": "number",
"required": false,
"source": "body",
"description": "父工单ID(子工单场景),不传则为根工单"
}
],
"response": [
{
"name": "data",
"type": "object",
"description": "创建成功的工单详情(同 detail 接口返回结构)"
}
],
"errors": [
{ "code": "400", "description": "工单标题不能为空" },
{ "code": "400", "description": "业务类型或子类型不合法" },
{ "code": "400", "description": "父工单不存在" }
]
}
```
---
### 3.5 `afterSale.update` — 更新工单基本信息
```json
{
"method": "afterSale.update",
"description": "更新工单基本信息(标题、描述、优先级、记账方向、理赔信息)。不可修改 business_type/business_sub_type/business_id。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" },
{ "name": "title", "type": "string", "required": false, "source": "body", "description": "工单标题" },
{ "name": "description", "type": "string", "required": false, "source": "body", "description": "问题描述" },
{ "name": "priority", "type": "number", "required": false, "source": "body", "description": "优先级" },
{ "name": "direction", "type": "number", "required": false, "source": "body", "description": "记账方向" },
{ "name": "claim_needed", "type": "number", "required": false, "source": "body", "description": "是否需要理赔" },
{ "name": "claim_amount", "type": "number", "required": false, "source": "body", "description": "理赔金额" },
{ "name": "claim_status", "type": "number", "required": false, "source": "body", "description": "理赔状态" }
],
"response": [
{ "name": "data", "type": "object", "description": "更新后的工单详情" }
],
"errors": [
{ "code": "400", "description": "工单ID不能为空" },
{ "code": "404", "description": "工单不存在或无权操作" }
]
}
```
---
### 3.6 `afterSale.delete` — 删除工单
```json
{
"method": "afterSale.delete",
"description": "软删除工单及其所有步骤。仅待处理(0)和已取消(9)状态的工单可删除。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" }
],
"response": [],
"errors": [
{ "code": "400", "description": "工单ID不能为空" },
{ "code": "400", "description": "处理中的工单不可删除" },
{ "code": "404", "description": "工单不存在或无权操作" }
]
}
```
---
### 3.7 `afterSale.assign` — 分配处理人
```json
{
"method": "afterSale.assign",
"description": "将工单分配给指定处理人。仅待处理(0)状态的工单可分配。分配后自动流转至处理中(1)。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" },
{ "name": "assignee_id", "type": "number", "required": true, "source": "body", "description": "处理人ID(必填)" },
{ "name": "remark", "type": "string", "required": false, "source": "body", "description": "分配备注" }
],
"response": [
{ "name": "data", "type": "object", "description": "更新后的工单详情" }
],
"errors": [
{ "code": "400", "description": "工单ID不能为空" },
{ "code": "400", "description": "处理人ID不能为空" },
{ "code": "400", "description": "当前状态不可分配(非待处理状态)" }
]
}
```
---
### 3.8 `afterSale.complete` — 完成工单
```json
{
"method": "afterSale.complete",
"description": "完成工单。仅处理中(1)状态且所有步骤已完成/跳过的工单可完成。完成后自动设置 resolved_at。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" },
{ "name": "resolution", "type": "string", "required": false, "source": "body", "description": "处理结果说明" }
],
"response": [
{ "name": "data", "type": "object", "description": "更新后的工单详情" }
],
"errors": [
{ "code": "400", "description": "工单ID不能为空" },
{ "code": "400", "description": "当前状态不可完成(非处理中状态)" },
{ "code": "400", "description": "仍有步骤未完成,请先完成所有步骤" }
]
}
```
---
### 3.9 `afterSale.close` — 关闭工单
```json
{
"method": "afterSale.close",
"description": "关闭工单。仅已完成(2)状态的工单可关闭。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" },
{ "name": "remark", "type": "string", "required": false, "source": "body", "description": "关闭备注" }
],
"response": [
{ "name": "data", "type": "object", "description": "更新后的工单详情" }
],
"errors": [
{ "code": "400", "description": "工单ID不能为空" },
{ "code": "400", "description": "当前状态不可关闭(非已完成状态)" }
]
}
```
---
### 3.10 `afterSale.cancel` — 取消工单
```json
{
"method": "afterSale.cancel",
"description": "取消工单。仅待处理(0)和处理中(1)状态的工单可取消。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" },
{ "name": "remark", "type": "string", "required": false, "source": "body", "description": "取消原因" }
],
"response": [
{ "name": "data", "type": "object", "description": "更新后的工单详情" }
],
"errors": [
{ "code": "400", "description": "工单ID不能为空" },
{ "code": "400", "description": "当前状态不可取消" }
]
}
```
---
### 3.11 `afterSale.stepStart` — 开始步骤
```json
{
"method": "afterSale.stepStart",
"description": "开始处理某个步骤。将步骤状态设为进行中(1),同时更新主表 current_step。同一时刻只允许一个步骤处于进行中。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "step_id", "type": "number", "required": true, "source": "body", "description": "步骤ID(必填,wms_after_sale_work_order_step.id)" },
{ "name": "remark", "type": "string", "required": false, "source": "body", "description": "备注" }
],
"response": [
{ "name": "data", "type": "object", "description": "更新后的步骤信息" }
],
"errors": [
{ "code": "400", "description": "步骤ID不能为空" },
{ "code": "400", "description": "已有其他步骤正在进行中" },
{ "code": "400", "description": "步骤当前状态不可开始" }
]
}
```
---
### 3.12 `afterSale.stepComplete` — 完成步骤
```json
{
"method": "afterSale.stepComplete",
"description": "完成某个步骤。将步骤状态设为已完成(2),记录操作人和完成时间。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "step_id", "type": "number", "required": true, "source": "body", "description": "步骤ID(必填)" },
{ "name": "action", "type": "string", "required": false, "source": "body", "description": "操作动作描述" },
{ "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注" }
],
"response": [
{ "name": "data", "type": "object", "description": "更新后的步骤信息" }
],
"errors": [
{ "code": "400", "description": "步骤ID不能为空" },
{ "code": "400", "description": "步骤当前状态不可完成(非进行中状态)" }
]
}
```
---
### 3.13 `afterSale.stepSkip` — 跳过步骤
```json
{
"method": "afterSale.stepSkip",
"description": "跳过某个步骤。将步骤状态设为已跳过(3)。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "step_id", "type": "number", "required": true, "source": "body", "description": "步骤ID(必填)" },
{ "name": "remark", "type": "string", "required": false, "source": "body", "description": "跳过原因" }
],
"response": [
{ "name": "data", "type": "object", "description": "更新后的步骤信息" }
],
"errors": [
{ "code": "400", "description": "步骤ID不能为空" },
{ "code": "400", "description": "步骤当前状态不可跳过" }
]
}
```
---
## 四、状态机约束(服务端校验规则)
| 操作 | 允许的当前状态 | 目标状态 |
|------|-------------|---------|
| `create` | — | `status=0`, `current_step=1` |
| `assign` | `status=0` | `status=1` |
| `delete` | `status=0` 或 `status=9` | 软删除 |
| `complete` | `status=1` + 所有步骤已完成/跳过 | `status=2`, `resolved_at=NOW()` |
| `close` | `status=2` | `status=3` |
| `cancel` | `status=0` 或 `status=1` | `status=9` |
| `stepStart` | `step_status=0` + 无其他进行中步骤 | `step_status=1`, `current_step=该step_order` |
| `stepComplete` | `step_status=1` | `step_status=2` |
| `stepSkip` | `step_status=0` | `step_status=3` |
---
## 五、methods/system.json 追加格式
在 `methods.system.json` 的 `methods.groups` 数组末尾追加:
```json
{
"groupName": "售后工单模块",
"module": "afterSale",
"list": [
{ "method": "afterSale.businessTypes", ... },
{ "method": "afterSale.list", ... },
{ "method": "afterSale.detail", ... },
{ "method": "afterSale.create", ... },
{ "method": "afterSale.update", ... },
{ "method": "afterSale.delete", ... },
{ "method": "afterSale.assign", ... },
{ "method": "afterSale.complete", ... },
{ "method": "afterSale.close", ... },
{ "method": "afterSale.cancel", ... },
{ "method": "afterSale.stepStart", ... },
{ "method": "afterSale.stepComplete", ... },
{ "method": "afterSale.stepSkip", ... }
]
}
```
(完整 JSON 定义见第三节各接口)
---
## 六、后续实现计划(审阅通过后执行)
| 步骤 | 文件 | 说明 |
|------|------|------|
| 1 | `app/service/systems/afterSale.js` | 业务层:数据库操作、状态机、工单号生成 |
| 2 | `app/service/systemMethods/afterSale.js` | 入口层:鉴权配置、参数校验、委托调用 |
| 3 | `methods/system.json` | 追加 `afterSale` group 的 13 个 method 文档 |
| 4 | `methods/changes/afterSale-20260729.json` | 接口变更记录 |
---
## 七、待确认事项
- [ ] **1. 模块名**:`afterSale` 是否合适?备选 `asWorkOrder`、`afterSaleWorkOrder`
- [ ] **2. 步骤操作是否需要独立接口**:`stepStart/stepComplete/stepSkip` 三个独立接口 vs 合并为一个 `stepUpdate`(传 status 参数)
- [ ] **3. `businessTypes` 接口免登录**:是否允许未登录用户获取业务类型枚举?
- [ ] **4. 步骤创建时机**:步骤是创建工单时自动初始化一组,还是由前端手动逐条添加?
- [ ] **5. 是否需要批量操作**:批量分配、批量关闭?
- [ ] **6. 是否需要操作日志**:是否复用 `operation_log` 记录关键状态变更?

View File

@ -0,0 +1,440 @@
# 售后工单表设计方案
> **状态**: ✅ 已落库(开发环境)
> **设计日期**: 2026-07-28(v4 定稿:新增 parent_work_order_id 支持主子工单)
> **设计人**: wms-db-agent
> **说明**: 本文档仅输出设计方案,不执行落库。审阅通过后再生成迁移文件。
---
## 一、需求概述
1. **主表**:售后工单单表,支持灵活绑定多种业务单据(运单、订单、入库单、退货单等),通过 `business_type` + `business_sub_type` + `business_id` 三级多态关联
2. **副表**:进度步骤处理表,记录每一步的操作员工、动作、备注(步骤不预设模板,由业务逻辑动态创建)
3. **状态流转**:工单整体状态 + 主表 `current_step` 进度 + 步骤级状态三层次
4. **简单记账**:记录是"进"还是"出"
5. **理赔追踪**:是否需要理赔、理赔金额、理赔结算状态
6. **附件关联**:通过现有 `wms_file_reference` 表关联附件/图片
---
## 二、表结构设计
### 2.1 主表:`wms_after_sale_work_order`(售后工单主表)
| # | 字段名 | 类型 | 必填 | 默认值 | 说明 |
|---|--------|------|------|--------|------|
| 1 | `id` | `BIGINT(20) UNSIGNED` | Y | AUTO | 主键ID |
| 2 | `warehouse_id` | `BIGINT(20) UNSIGNED` | Y | — | 仓库ID |
| 3 | `store_id` | `BIGINT(20) UNSIGNED` | Y | — | 货主ID |
| 4 | `work_order_no` | `VARCHAR(50)` | Y | — | 售后工单号,唯一,格式 `AS` + 时间戳(如 AS202607280001) |
| 5 | `business_type` | `VARCHAR(50)` | Y | — | 关联业务类型,见 §3.1 枚举及 §五 Model 内置定义 |
| 6 | `business_sub_type` | `VARCHAR(50)` | Y | — | 关联业务子类型,如运单下的 `intercept`(拦截)、订单下的 `mis_shipment`(错发),见 §五 |
| 7 | `business_id` | `BIGINT(20) UNSIGNED` | Y | — | 关联业务单据主键ID(多态关联) |
| 8 | `business_no` | `VARCHAR(100)` | N | — | 关联业务单据号(冗余,方便列表展示) |
| 9 | `direction` | `TINYINT UNSIGNED` | Y | 0 | 记账方向:`1`=入库(退货入库/换货入库),`2`=出库(补发/换货出库),`0`=未确定 |
| 10 | `status` | `TINYINT UNSIGNED` | Y | 0 | 工单状态,见 §3.4 状态机 |
| 11 | `priority` | `TINYINT UNSIGNED` | Y | 50 | 优先级:`1`~`100`,数字越大优先级越高,由客服接待或AI自动识别填入 |
| 12 | `title` | `VARCHAR(200)` | Y | — | 工单标题/摘要 |
| 13 | `description` | `TEXT` | N | — | 问题描述 |
| 14 | `creator_id` | `BIGINT(20) UNSIGNED` | Y | — | 创建人ID,关联 `account.id`;`0` 表示 AI 自动接待 |
| 15 | `creator_snapshot` | `TEXT` | N | — | 创建人信息快照(JSON格式);AI创建时记录模型/会话信息 |
| 16 | `assignee_id` | `BIGINT(20) UNSIGNED` | N | — | 当前处理人ID,关联 `account.id` |
| 17 | `parent_work_order_id` | `BIGINT(20) UNSIGNED` | N | — | 父工单ID,自关联 `wms_after_sale_work_order.id`;非空时表示当前工单为子工单 |
| 18 | `current_step` | `TINYINT UNSIGNED` | Y | 1 | **当前进度**(位于主表),值为当前正在处理的 `step_order` 序号 |
| 19 | `claim_needed` | `TINYINT UNSIGNED` | Y | 0 | 是否需要理赔:`0`=不需要,`1`=需要 |
| 20 | `claim_amount` | `DECIMAL(12,2)` | N | 0.00 | 理赔金额(元),精度2位小数 |
| 21 | `claim_status` | `TINYINT UNSIGNED` | Y | 0 | 理赔状态:`0`=未理赔,`1`=已理赔(单笔结清),`2`=月结 |
| 22 | `resolution` | `TEXT` | N | — | 处理结果说明 |
| 23 | `resolved_at` | `DATETIME` | N | — | 解决时间 |
| 24 | `created_at` | `DATETIME` | Y | `CURRENT_TIMESTAMP` | 创建时间 |
| 25 | `updated_at` | `DATETIME` | Y | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 |
| 26 | `deleted_at` | `DATETIME` | N | — | 软删除时间 |
**索引设计**:
| 索引名 | 字段 | 类型 | 说明 |
|--------|------|------|------|
| `PRIMARY` | `id` | 主键 | — |
| `uk_work_order_no` | `work_order_no` | 唯一 | 工单号唯一 |
| `idx_warehouse_id` | `warehouse_id` | 普通 | 按仓库查询 |
| `idx_store_id` | `store_id` | 普通 | 按货主查询 |
| `idx_business_type_subtype_id` | `business_type, business_sub_type, business_id` | 普通 | 按业务类型+子类型+单据ID反查工单 |
| `idx_status` | `status` | 普通 | 按状态筛选 |
| `idx_assignee_id` | `assignee_id` | 普通 | 按处理人查询 |
| `idx_parent_work_order_id` | `parent_work_order_id` | 普通 | 按父工单查所有子工单 |
| `idx_priority` | `priority` | 普通 | 按优先级排序 |
| `idx_claim_status` | `claim_status` | 普通 | 按理赔状态筛选 |
| `idx_created_at` | `created_at` | 普通 | 按时间排序 |
| `idx_deleted_at` | `deleted_at` | 普通 | 软删除查询 |
---
### 2.2 副表:`wms_after_sale_work_order_step`(售后工单进度步骤表)
| # | 字段名 | 类型 | 必填 | 默认值 | 说明 |
|---|--------|------|------|--------|------|
| 1 | `id` | `BIGINT(20) UNSIGNED` | Y | AUTO | 主键ID |
| 2 | `work_order_id` | `BIGINT(20) UNSIGNED` | Y | — | 工单ID,关联 `wms_after_sale_work_order.id` |
| 3 | `step_order` | `TINYINT UNSIGNED` | Y | 1 | 步骤序号(从1开始递增) |
| 4 | `step_name` | `VARCHAR(100)` | Y | — | 步骤名称 |
| 5 | `step_status` | `TINYINT UNSIGNED` | Y | 0 | 步骤状态:`0`=待开始,`1`=进行中,`2`=已完成,`3`=已跳过 |
| 6 | `operator_id` | `BIGINT(20) UNSIGNED` | N | — | 操作员工ID,关联 `account.id` |
| 7 | `operator_snapshot` | `TEXT` | N | — | 操作人信息快照(JSON格式) |
| 8 | `action` | `VARCHAR(100)` | N | — | 操作动作描述(如"核实问题属实,安排退货入库") |
| 9 | `remark` | `TEXT` | N | — | 处理备注 |
| 10 | `started_at` | `DATETIME` | N | — | 步骤开始时间 |
| 11 | `completed_at` | `DATETIME` | N | — | 步骤完成时间 |
| 12 | `created_at` | `DATETIME` | Y | `CURRENT_TIMESTAMP` | 创建时间 |
| 13 | `updated_at` | `DATETIME` | Y | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 |
| 14 | `deleted_at` | `DATETIME` | N | — | 软删除时间 |
**索引设计**:
| 索引名 | 字段 | 类型 | 说明 |
|--------|------|------|------|
| `PRIMARY` | `id` | 主键 | — |
| `idx_work_order_id` | `work_order_id` | 普通 | 按工单查所有步骤 |
| `idx_operator_id` | `operator_id` | 普通 | 按操作人反查 |
| `idx_deleted_at` | `deleted_at` | 普通 | 软删除查询 |
| `uk_work_order_step` | `work_order_id, step_order, deleted_at` | 唯一 | 同一工单下步骤序号唯一(含软删除) |
---
## 三、枚举定义
### 3.1 `business_type` 与 `business_sub_type`(业务类型及子类型)
业务类型和子类型由 Model 文件 `app/model/after_sale_work_order.js` 中的 `BUSINESS_TYPES` 常量统一定义。数据库层面使用 `VARCHAR(50)` 存储,方便扩展。
#### 内置业务类型总览
| business_type | 业务名称 | 关联表 | 子类型 (business_sub_type) |
|---------------|---------|--------|---------------------------|
| `waybill` | 运单 | `wms_order_express` | `intercept`(拦截)、`urge`(催件)、`damage`(破损)、`lost`(丢件)、`wrong_info`(信息错误) |
| `order_delivery` | 发货订单 | `wms_order_delivery` | `mis_shipment`(错发)、`missing_item`(少发)、`wrong_sku`(错品)、`quality_issue`(质量问题)、`delivery_delay`(发货延迟) |
| `entry_order` | 入库单 | `wms_entry_order` | `shortage`(少货)、`damage`(破损)、`wrong_sku`(错品)、`quality_issue`(质量问题) |
| `order_stockout` | 出库单/退货出库单 | `wms_order_stockout` | `return_issue`(退货异常)、`wrong_outbound`(错发)、`shortage`(少发) |
| `receiving` | 收货单 | `wms_receiving` | `shortage`(少货)、`damage`(破损)、`quality_issue`(质量问题) |
| `other` | 其他 | — | `general`(通用) |
> **扩展方式**:在 Model 的 `BUSINESS_TYPES` 常量中增删条目即可,无需 ALTER TABLE。外部代码通过 `require` Model 文件读取。
### 3.2 `priority`(优先级)
```
1 ~ 100 的整数,数字越大优先级越高。
由客服接待手动填入,或由 AI 根据问题描述自动识别并填入。
默认值 50(中等优先级)。
```
### 3.3 `direction`(记账方向)
```
0 — 未确定
1 — 入库(IN):退货入库 / 换货入库 / 赔付补货入库
2 — 出库(OUT):补发出库 / 换货出库 / 退款退货出库
```
> 与 `stock_transaction.transaction_type`(`INBOUND`/`OUTBOUND`)语义对齐。
### 3.4 `status`(工单状态)
```
0 — 待处理 (工单刚创建,尚未分配)
1 — 处理中 (已分配处理人,正在推进)
2 — 已完成 (问题已解决,全部步骤完成)
3 — 已关闭 (问题关闭,不再跟进)
9 — 已取消 (工单作废)
```
### 3.5 `claim_status`(理赔状态)
```
0 — 未理赔 (不需要理赔,或尚未发起理赔)
1 — 已理赔 (单笔已结清,理赔款项已到账)
2 — 月结 (纳入月度结算,按月统一对账打款)
```
### 3.6 `step_status`(步骤状态)
```
0 — 待开始 (步骤尚未激活)
1 — 进行中 (当前正在处理的步骤)
2 — 已完成 (步骤已处理完毕)
3 — 已跳过 (该步骤被跳过,不适用)
```
### 3.7 `creator_id` 特殊值
```
0 — AI 自动接待(非员工账号创建)
> 0 — 对应 account.id,人工客服/员工创建
```
> 当 `creator_id = 0` 时,`creator_snapshot` 可记录 AI 模型标识及会话 ID 等元信息。
---
## 四、状态流转设计
### 4.1 工单级别状态机
```
┌──────────────────────────────────┐
│ │
┌───┴──────┐ ┌───┴──────┐
创建工单 ───→ │ 待处理(0) │ ──── 分配处理人 ───→ │ 处理中(1) │
└───┬──────┘ └───┬──────┘
│ │
│ 取消 │ 全部步骤完成
↓ ↓
┌───┴──────┐ ┌───┴──────┐
│ 已取消(9) │ │ 已完成(2) │
└──────────┘ └───┬──────┘
│
│ 关闭
↓
┌───┴──────┐
│ 已关闭(3) │
└──────────┘
```
**流转规则**:
| 当前状态 | 允许流转到 | 触发条件 |
|----------|-----------|----------|
| `0-待处理` | `1-处理中` | 分配处理人 |
| `0-待处理` | `9-已取消` | 主动取消 |
| `1-处理中` | `2-已完成` | 所有步骤均标记为已完成 |
| `1-处理中` | `9-已取消` | 主动取消 |
| `2-已完成` | `3-已关闭` | 确认关闭 |
| `3-已关闭` | — | 终态,不可流转 |
### 4.2 步骤级别状态机
```
┌──────────────────────────────────┐
│ │
┌───┴──────┐ ┌───┴──────┐
步骤创建 ───→ │ 待开始(0) │ ──── 开始处理 ───→ │ 进行中(1) │
└───┬──────┘ └───┬──────┘
│ │
│ 跳过 │ 完成
↓ ↓
┌───┴──────┐ ┌───┴──────┐
│ 已跳过(3) │ │ 已完成(2) │
└──────────┘ └──────────┘
```
**约束**:
- 同一工单下,同一时刻最多只有 1 个步骤处于 `进行中(1)`
- 步骤按 `step_order` 顺序流转,但允许跳过中间步骤
- 工单进度由主表 `current_step` 字段追踪,指向当前正在处理的 `step_order`
- 所有步骤标记为 `已完成(2)` 或 `已跳过(3)` 后,`current_step` 置为最终步骤号,工单状态可流转至 `已完成(2)`
---
## 五、Model 内置业务类型定义
> **步骤不预设模板**:`wms_after_sale_work_order_step` 表的步骤由业务逻辑在运行时动态创建,不在数据库或 Model 中硬编码步骤模板。
### 5.1 `BUSINESS_TYPES` 常量(定义在 `app/model/after_sale_work_order.js`)
```javascript
/**
* 售后工单业务类型定义
* 外部可通过 require('./app/model/after_sale_work_order').BUSINESS_TYPES 访问
* 增删业务类型或子类型只需修改此常量,无需 ALTER TABLE
*/
const BUSINESS_TYPES = {
waybill: {
label: '运单',
table: 'wms_order_express', // 关联的数据库表名
subtypes: {
intercept: '拦截',
urge: '催件',
damage: '破损',
lost: '丢件',
wrong_info: '信息错误',
},
},
order_delivery: {
label: '发货订单',
table: 'wms_order_delivery',
subtypes: {
mis_shipment: '错发',
missing_item: '少发',
wrong_sku: '错品',
quality_issue: '质量问题',
delivery_delay: '发货延迟',
},
},
entry_order: {
label: '入库单',
table: 'wms_entry_order',
subtypes: {
shortage: '少货',
damage: '破损',
wrong_sku: '错品',
quality_issue: '质量问题',
},
},
order_stockout: {
label: '出库单/退货出库单',
table: 'wms_order_stockout',
subtypes: {
return_issue: '退货异常',
wrong_outbound: '错发',
shortage: '少发',
},
},
receiving: {
label: '收货单',
table: 'wms_receiving',
subtypes: {
shortage: '少货',
damage: '破损',
quality_issue: '质量问题',
},
},
other: {
label: '其他',
table: null,
subtypes: {
general: '通用',
},
},
};
// 辅助函数:根据 business_type 获取关联表名
function getBusinessTable(businessType) {
return BUSINESS_TYPES[businessType]?.table || null;
}
// 辅助函数:校验 business_type + business_sub_type 组合是否合法
function isValidSubType(businessType, businessSubType) {
const def = BUSINESS_TYPES[businessType];
return def && Object.prototype.hasOwnProperty.call(def.subtypes, businessSubType);
}
module.exports = { BUSINESS_TYPES, getBusinessTable, isValidSubType };
```
### 5.2 使用示例
```javascript
// 外部读取
const { BUSINESS_TYPES, getBusinessTable, isValidSubType } = require('./app/model/after_sale_work_order');
// 获取所有业务类型列表
Object.keys(BUSINESS_TYPES); // ['waybill', 'order_delivery', 'entry_order', ...]
// 获取运单下的子类型
BUSINESS_TYPES.waybill.subtypes; // { intercept: '拦截', urge: '催件', ... }
// 获取关联表
const table = getBusinessTable('waybill'); // 'wms_order_express'
// 校验合法性
isValidSubType('waybill', 'intercept'); // true
isValidSubType('waybill', 'mis_shipment'); // false
```
---
## 六、与现有系统的关联
### 6.1 与业务单据的多态关联(三级定位)
```
wms_after_sale_work_order
.business_type = 'waybill'
.business_sub_type = 'intercept' ← 子类型(Model 常量定义)
.business_id = 12345 ← wms_order_express.id
.business_no = 'YD202607280001' ← 冗余单号
实际关联链路:
business_type → BUSINESS_TYPES[type].table → 确定关联表
business_id → 关联表主键
business_sub_type → 细分工单类别(如拦截/催件/破损)
示例:
├── 'waybill' / 'intercept' → wms_order_express.id
├── 'waybill' / 'urge' → wms_order_express.id
├── 'waybill' / 'damage' → wms_order_express.id
├── 'order_delivery' / 'mis_shipment' → wms_order_delivery.id
├── 'order_delivery' / 'missing_item' → wms_order_delivery.id
├── 'entry_order' / 'shortage' → wms_entry_order.id
├── 'order_stockout' / 'return_issue' → wms_order_stockout.id
├── 'receiving' / 'damage' → wms_receiving.id
└── 'other' / 'general' → 自定义
```
### 6.2 与库存交易的对账
```
售后工单.direction = 1 (入库)
→ stock_transaction.transaction_type = 'INBOUND'
→ stock_transaction.order_type = 'AFTER_SALE' (需同步在 stock_transaction 中新增此类型)
售后工单.direction = 2 (出库)
→ stock_transaction.transaction_type = 'OUTBOUND'
→ stock_transaction.order_type = 'AFTER_SALE'
```
### 6.4 与附件的关联
售后工单不新增附件字段,复用现有 `wms_file_reference` 表做多态附件关联:
```
wms_file_reference
.reference_type = 'after_sale_work_order' ← 固定标识
.reference_id = 工单 id ← wms_after_sale_work_order.id
.file_id = 文件 id ← wms_file.id
示例:一张工单可关联多张图片/多个附件(如破损照片、快递面单照片等)。
```
> `file_reference` 表已支持多态关联(`reference_type` + `reference_id`),无需新建表或字段。
### 6.5 与员工的关联
```
wms_after_sale_work_order.creator_id → account.id(创建人)
wms_after_sale_work_order.assignee_id → account.id(当前处理人)
wms_after_sale_work_order_step.operator_id → account.id(步骤操作人)
```
---
## 七、待确认事项(审阅清单)
请审阅时重点关注以下设计决策:
- [x] **1. `business_type` 枚举值**:`order_delivery` / `entry_order` / `order_stockout` / `waybill` / `receiving` / `other` — ✅ 已确认,暂不增加 `return_order` 独立类型(退货场景通过 `order_stockout` 覆盖)
- [x] **2. `direction` 记账方向**:`1`=入库 / `2`=出库 / `0`=未确定 — ✅ 已确认,细粒度区分由关联的实际出入库单承载
- [x] **3. 工单状态值**:`0-待处理/1-处理中/2-已完成/3-已关闭/9-已取消` — ✅ 已确认,当前中间态足够,无需增加"驳回/退回"
- [x] **4. 预设步骤模板**:不再预设步骤模板,步骤由业务逻辑动态创建 ✅
- [x] **5. `business_id` 多态关联**:采用 `business_type` + `business_sub_type` + `business_id` 三级多态关联,子类型由 Model 常量定义 ✅
- [x] **6. 理赔信息**:已新增 `claim_needed` / `claim_amount` / `claim_status` 三个字段 ✅
- [x] **7. 进度追踪**:进度由主表 `current_step` 字段承载(不再仅依赖副表步骤状态) ✅
- [x] **8. 优先级**:改为 `TINYINT UNSIGNED` 取值范围 `1-100`,由客服或 AI 自动识别填入,默认值 `50` ✅
- [x] **9. AI 创建支持**:`creator_id = 0` 表示 AI 自动接待,`creator_snapshot` 记录模型/会话信息 ✅
- [x] **10. 附件/图片**:复用现有 `wms_file_reference` 表做多态关联,不新增字段 ✅
- [x] **11. 预计完成时间**:暂不增加,后续通过 `created_at` + `priority` 做超时告警替代;SLA 配置表留待后续迭代 ✅
- [x] **12. 关联工单**:已确认新增 `parent_work_order_id` 字段,支持主子工单拆分 ✅
- [x] **13. 表名**:`wms_after_sale_work_order` 和 `wms_after_sale_work_order_step` — ✅ 已确认
- [x] **14. 权限**:API 接口设计阶段再补录 `wms_permission` 记录,不阻塞表落库 ✅
---
## 八、后续落库计划(审阅通过后执行)
1. 创建迁移文件 `database/migrations/20260728XXXXXX-create-wms-after-sale-work-order.js`
2. 创建迁移文件 `database/migrations/20260728XXXXXX-create-wms-after-sale-work-order-step.js`
3. 创建 Model 文件 `app/model/after_sale_work_order.js`
4. 创建 Model 文件 `app/model/after_sale_work_order_step.js`
5. 在 `methods/system.json` 中新增接口路由
6. 如需,在 `stock_transaction.order_type` 中新增 `AFTER_SALE` 枚举值(独立迁移)
7. 如需,新增 `wms_permission` 权限记录

View File

@ -0,0 +1,636 @@
# 运单号模块设计方案(仓库侧)
> **状态**: 🔧 开发中(索引已就绪,快照字段待 dev 实现写入逻辑后执行)
> **设计日期**: 2026-07-29
> **设计人**: wms-db-agent
> **说明**: 本文档仅输出设计方案,不执行代码实现。审阅通过后再进入开发。
> **命名空间**: `waybill.warehouse.*`(仓库侧操作);后续预留 `waybill.store.*`(货主侧操作),本期不实现。
---
## 一、需求概述
当前系统缺少独立的运单号查询与管理界面。运单数据(`wms_order_express`)始终依附于订单上下文——运单信息仅通过订单详情接口(`xxx.detail`)的 `expresses[]` 字段返回,或通过 `index.toOrder` 做运单号→订单反查。实际业务中需要:
1. **运单号列表(仓库侧)**:按仓库维度,独立查询所有运单号,支持多条件筛选、分页,支持主单号/子单号关联展示与查询
2. **运单详情(仓库侧)**:查看单个运单的完整信息,包含关联订单、打印记录、打包状态、称重信息
3. **运单导出(仓库侧)**:支持按筛选条件导出运单列表
> **主单号/子单号规则**(沿用已有业务约定):同一 `order_id` 下,`business_key = 1` 的运单为**主单号**,`business_key > 1` 的运单为**子单号**(即拆单产生的子运单)。该规则已在 `order_export.js` 导出逻辑中使用。
>
> **命名空间规划**:`waybill.warehouse.*` 本期实现(仓库侧操作);后续按需扩展 `waybill.store.*`(货主侧操作,按 `store_id` 维度查询)。两套接口共享底层 `systems/waybill.js` 业务逻辑,仅入口鉴权与数据隔离维度不同。
---
## 二、数据模型分析
### 2.1 核心表:`wms_order_express`(运单表,已有)
当前表结构(关键字段):
| 字段 | 类型 | 说明 |
|------|------|------|
| `id` | `BIGINT(20) UNSIGNED` PK | 主键 |
| `waybill_code` | `VARCHAR(50)` | **运单号** |
| `order_id` | `BIGINT(20)` | 订单ID |
| `warehouse_id` | `BIGINT(20) UNSIGNED` | 仓库ID |
| `store_id` | `BIGINT(20) UNSIGNED` | 🆕 货主ID |
| `business_key` | `INTEGER(3)` | 拆单序号(1=主单号,>1=子单号) |
| `status` | `TINYINT(1)` DEFAULT 0 | 状态(1=已分配,0=未分配) |
| `logistics_interface_id` | `BIGINT(20) UNSIGNED` | 物流接口ID |
| `logistics_code` | `VARCHAR(50)` | 物流公司编码 |
| `logistics_name` | `VARCHAR(50)` | 物流公司名称 |
| `logistics_interface_id` | `BIGINT(20) UNSIGNED` | 物流接口ID |
| `logistics_interface_name` | `VARCHAR(50)` | 物流接口名称 |
| `platform_code` | `VARCHAR(50)` | 平台编码 |
| `is_galaxy_receive` | `ENUM('Y','N')` | 是否揽收 |
| `is_back` | `ENUM('Y','N')` | 是否退回 |
| `is_intercept` | `ENUM('Y','N')` | 是否拦截 |
| `weighing_weight` | `INT(11)` DEFAULT 0 | 称重重量(g) |
| `package_material_id` | `BIGINT(20) UNSIGNED` | 包材ID |
| `package_material_name_snapshot` | `VARCHAR(128)` | 包材名称快照 |
| `printinfo` | `TEXT('long')` | 打印信息 |
| `ver` | `VARCHAR(50)` | 打印版本号 |
| `retry_count` | `TINYINT(3)` | 重试次数 |
| `create_at` | `DATE` | 创建时间 |
| `delete_at` | `DATE` | 删除时间 |
**现有索引**:
| 索引名 | 字段 | 类型 |
|--------|------|------|
| `PRIMARY` | `id` | 主键 |
| `uk_order_id_business_key` | `order_id, business_key` | 唯一 |
| `idx_waybill_code` | `waybill_code` | 普通 |
| `idx_create_at` | `create_at` | 普通 |
| `idx_wms_order_express_package_material_id` | `package_material_id` | 普通 |
### 2.2 关联表
| 表名 | 关联字段 | 用途 |
|------|---------|------|
| `wms_order_delivery`(current/history/dispatch) | `order_id` | 订单信息(订单号、货主、波次等) |
| `wms_express` | `logistics_code` ↔ `code` | 物流公司名称(统一展示名) |
| `express_print_record` | `express_no` ↔ `waybill_code` | 打印记录(打印时间、打印机、模板) |
| `pack_task` | `waybill_code` | 打包任务(打包状态、打包人、打包时间) |
| `package_material` | `package_material_id` ↔ `id` | 包材详情 |
### 2.3 索引评估
当前 `wms_order_express` 表的索引不足以支撑运单列表场景的高频查询:
| 缺失索引 | 原因 |
|---------|------|
| `idx_warehouse_id_status` | 运单列表按仓库+状态是最常见查询 |
| `idx_logistics_code` | 按物流公司筛选运单 |
| `idx_logistics_interface_id` | 按快递接口ID筛选运单 |
| `idx_warehouse_id_create_at` | 仓库+时间范围排序分页 |
| `idx_order_id_business_key` | 已有 `uk_order_id_business_key` 唯一索引,可同时覆盖主单号 SELF JOIN 查询 |
> **索引迁移**:以下索引已通过迁移文件 `20260729140000-add-waybill-list-indexes.js` 正式创建,见 §五 文件变更清单。
### 2.4 主单号/子单号关联关系
**规则**(沿用系统已有约定):
- 同一 `order_id` 下,`business_key = 1` → **主单号**(main waybill)
- 同一 `order_id` 下,`business_key > 1` → **子单号**(child waybill)
- 该规则已在 `app/service/systems/order_export.js` 第 444 行使用:`business_key === 1 ? '主单号' : '子单号'`
**查询方式**:
- **正向查(子→主)**:在 `wms_order_express` 上做 SELF JOIN,`t1.order_id = t2.order_id AND t2.business_key = 1` 获取主单号
- **反向查(主→子)**:通过 `order_id` + `business_key > 1` 查子单号;或通过主单号 `waybill_code` 先定位 `order_id`,再查该订单下所有运单
**注意**:
- 大部分运单 `business_key = 1`(未拆单),此时主单号 = 运单号本身
- 仅拆单场景下存在 `business_key > 1` 的子单号
### 2.5 快照字段评估(待开发实现)
> **状态**:字段和迁移已准备就绪,但**创建运单号时写入快照值的逻辑尚未实现**(属于 dev 任务范围)。当前快照列为空,列表仍需 JOIN 订单表。
**原则**:运单列表应尽量避免 JOIN `wms_order_delivery`(current/history/dispatch 多表)和 `store` 表,通过快照字段冗余订单关键信息到 `wms_order_express`。
**现有快照字段**:
| 字段 | 快照内容 | 覆盖场景 |
|------|---------|---------|
| `package_material_name_snapshot` | 包材名称 | ✅ 避 JOIN `package_material` |
**待新增快照字段**(需配合 dev 改造创建运单号逻辑):
| 快照列 | 类型 | 替代的 JOIN | 写入时机 |
|--------|------|-----------|---------|
| `delivery_order_code` | `VARCHAR(50)` | `order_delivery.delivery_order_code` | 运单号分配成功时(express.js) |
| `store_id_snapshot` | `BIGINT(20) UNSIGNED` | `order_delivery.store_id` | 同上 |
| `store_name_snapshot` | `VARCHAR(128)` | `store.name`(货主表) | 同上 |
| `warehouse_name_snapshot` | `VARCHAR(128)` | `store.name`(仓库表) | 同上 |
> **迁移文件**:`20260729130000-add-waybill-order-snapshots.js` 已创建但**已回滚**,待 dev 实现写入逻辑后再执行。
---
## 三、接口设计
### 3.1 模块概览
| 项目 | 说明 |
|------|------|
| 模块名 | `waybill.warehouse` |
| 接口路径 | `POST /system`,body 中 `method` 字段为 `waybill.warehouse.{方法名}` |
| 请求方式 | 全部 `POST`,参数放在 `body` 内 |
| 鉴权 | 全部接口需登录,暂不做细粒度鉴权 |
| 数据隔离 | 按 `warehouse_id` 隔离(仓库侧视角,见 §3.1.1 仓库隔离策略) |
| 后续扩展 | 预留 `waybill.store.*`(货主侧,按 `store_id` 隔离),本期不实现 |
### 3.1.1 仓库隔离策略(已核实)
**核实结论**:仓库隔离策略与系统现有模式一致,无需调整。
**请求上下文来源**(系统统一约定):
| 项目 | 值 | 说明 |
|------|-----|------|
| 仓库ID来源 | `ctx.user.store_id` | 全系统统一:`ctx.user.store_id` 即为当前操作用户所属仓库的 `warehouse_id` |
| 后备方案 | 无(必须登录) | 未登录用户无法访问,不存在 `store_id` 为空的情况 |
| 注入方式 | WHERE 条件自动追加 | 在 `systems/waybill.js` 中 `const warehouseId = Number(ctx.user.store_id)`,追加 `warehouse_id = warehouseId` 到所有查询的 WHERE 子句 |
| 注入时机 | 业务层(systems) | 不在入口层(systemMethods)注入,保持业务层职责单一 |
**参考依据**(系统内一致使用 `ctx.user.store_id` 作为 warehouse_id):
| 文件 | 行号/位置 | 用法 |
|------|----------|------|
| `systems/waybill.js`(现有 toOrder) | 第 29 行 | `ctx.user && ctx.user.store_id ? ctx.user.store_id : null` |
| `systemMethods/index.js` | 第 1593 行 | `ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : null` |
| `systemMethods/print.js` | 第 725 行 | `ctx.user.store_id` |
| `systemMethods/stock/transaction.js` | 第 32 行 | `Number(this.ctx.user && this.ctx.user.store_id)` |
| `systemMethods/storage/management.js` | JSDoc 注释 | "仓库 ID 从用户上下文(ctx.user.store_id / ctx.user.warehouse_id)自动获取" |
> **注**:部分文件也支持 `ctx.user.warehouse_id` 作为备选来源(如 `storage/management.js`),但 `ctx.user.store_id` 是全系统主要来源,且 `wms_order_express` 表中的 `warehouse_id` 字段语义上对应 `store_id`。本期统一使用 `ctx.user.store_id`。
### 3.2 文件规划
```
app/service/systemMethods/waybill/warehouse.js ← 入口层(鉴权、参数校验、委托)
app/service/systems/waybill.js ← 业务层(扩展:新增 list/detail/export 方法)
methods/system.json ← API 文档(新增 waybill.warehouse group)
```
> **注意**:
> - `app/service/systems/waybill.js` 已有 `toOrder()` 方法(运单反查),新方法将添加到同一文件中。
> - 目录 `systemMethods/waybill/` 预留 `store.js`(货主侧入口),本期仅创建 `warehouse.js`。
### 3.3 调用链路
```
POST /system { method: "waybill.warehouse.list", ... }
→ app/router.js
→ app/service/system.js
→ app/service/systemMethods/waybill/warehouse.js ← 鉴权 + 参数校验
→ app/service/systems/waybill.js ← 业务逻辑 + DB操作
→ ctx.model.OrderExpress ← Sequelize Model
→ ctx.model.OrderDeliveryFactory ← 订单信息补充
→ ctx.model.Express ← 物流公司名称
→ ctx.model.ExpressPrintRecord ← 打印记录
```
---
### 3.4 接口清单
| # | method | 描述 | 需登录 | 需鉴权 |
|---|--------|------|--------|--------|
| 1 | `waybill.warehouse.list` | 运单列表-仓库侧(分页+筛选) | ✓ | ✗ |
| 2 | `waybill.warehouse.detail` | 运单详情-仓库侧(含订单/打印/打包/称重信息) | ✓ | ✗ |
| 3 | `waybill.warehouse.export` | 运单导出-仓库侧(按筛选条件) | ✓ | ✗ |
> **预留接口(本期不实现)**:
>
> | # | method | 描述 |
> |---|--------|------|
> | 4 | `waybill.store.list` | 运单列表-货主侧(按 store_id 隔离) |
> | 5 | `waybill.store.detail` | 运单详情-货主侧 |
> | 6 | `waybill.store.export` | 运单导出-货主侧 |
---
### 3.5 `waybill.warehouse.list` — 运单列表(仓库侧)
**功能说明**:查询运单号列表,支持分页与多条件筛选。仓库隔离(自动注入 `warehouse_id`)。
#### 请求参数
```json
{
"method": "waybill.warehouse.list",
"pagination": {
"page": 1,
"pageSize": 20
},
"where": {
"waybillCode": "",
"mainWaybillCode": "",
"waybillType": "",
"orderId": null,
"orderNo": "",
"storeId": null,
"logisticsCode": "",
"logisticsInterfaceId": null,
"platformCode": "",
"status": null,
"isBack": null,
"isIntercept": null,
"isGalaxyReceive": null,
"packageMaterialId": null,
"hasWeighingWeight": null,
"keyword": "",
"createdAtStart": "",
"createdAtEnd": ""
},
"sort": {
"field": "create_at",
"order": "desc"
}
}
```
#### 参数说明
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `pagination` | `object` | ✗ | 分页参数 `{ page, pageSize }`,默认 page=1, pageSize=20 |
| `where` | `object` | ✗ | 筛选条件,所有字段均为可选 |
| `where.waybillCode` | `string` | ✗ | 运单号(模糊搜索) |
| `where.mainWaybillCode` | `string` | ✗ | **主单号**(精确匹配)。先通过主单号定位 `order_id`,再返回该订单下所有运单(主+子)。与 `waybillCode` 互斥,同时传入时 `mainWaybillCode` 优先 |
| `where.waybillType` | `string` | ✗ | 🆕 **运单类型**:`"main"`/`"1"`=主单号(`business_key=1`),`"child"`/`"2"`=子单号(`business_key>1`) |
| `where.orderId` | `number` | ✗ | 订单ID(等值) |
| `where.orderNo` | `string` | ✗ | ⛔ **暂不可用**:订单号(待快照字段 `delivery_order_code` 落库后启用 LIKE 模糊搜索) |
| `where.storeId` | `number` | ✗ | 货主ID(等值,直读 `store_id` 列) |
| `where.logisticsCode` | `string` | ✗ | 物流公司编码(等值) |
| `where.logisticsInterfaceId` | `number` | ✗ | **物流接口ID**(等值),对应 `wms_order_express.logistics_interface_id`,用于按快递接口筛选运单列表 |
| `where.platformCode` | `string` | ✗ | 平台编码(等值),如 PDD/DY/KS/JD/CAINIAO/SPH/XHS |
| `where.status` | `number` | ✗ | 运单状态:`0`=未分配,`1`=已分配 |
| `where.isBack` | `string` | ✗ | 是否退回:`Y`/`N` |
| `where.isIntercept` | `string` | ✗ | 是否拦截:`Y`/`N` |
| `where.isGalaxyReceive` | `string` | ✗ | 是否揽收:`Y`/`N` |
| `where.packageMaterialId` | `number` | ✗ | 包材ID(等值) |
| `where.hasWeighingWeight` | `boolean` | ✗ | 是否已称重:`true`=weighing_weight>0,`false`=weighing_weight=0 |
| `where.keyword` | `string` | ✗ | 关键词:匹配运单号(`waybill_code`)、主单号(`main_waybill_code`)、订单号(需 JOIN) |
| `where.createdAtStart` | `string` | ✗ | 创建时间起始(YYYY-MM-DD) |
| `where.createdAtEnd` | `string` | ✗ | 创建时间截止(YYYY-MM-DD) |
| `sort` | `object` | ✗ | 排序 `{ field, order }`,默认 `create_at desc` |
| `sort.field` | `string` | ✗ | 排序字段:`create_at` / `weighing_weight` / `id` |
| `sort.order` | `string` | ✗ | 排序方向:`asc` / `desc`,默认 `desc` |
#### 响应格式
```json
{
"list": [
{
"id": 123456,
"waybill_code": "SF1234567890",
"main_waybill_code": "SF1234567890",
"waybill_type": "主单号",
"order_id": 78901,
"order_no": "PO202607290001",
"warehouse_id": 1,
"warehouse_name": "默认仓库",
"store_id": 10,
"store_name": "测试货主",
"business_key": 1,
"status": 1,
"status_text": "已分配",
"logistics_interface_id": 3,
"logistics_code": "SF",
"logistics_name": "顺丰速运",
"logistics_interface_name": "顺丰标准",
"platform_code": "PDD",
"platform_name": "拼多多",
"is_back": "N",
"is_intercept": "N",
"is_galaxy_receive": "N",
"weighing_weight": 1250,
"weighing_weight_display": "1.25 kg",
"package_material_id": 5,
"package_material_name": "3号纸箱",
"print_count": 2,
"last_print_at": "2026-07-29 10:30:00",
"create_at": "2026-07-29 08:00:00"
}
],
"pagination": {
"page": 1,
"pageSize": 20,
"total": 156,
"totalPages": 8
}
}
```
#### 响应字段说明
| 字段 | 类型 | 来源 | 说明 |
|------|------|------|------|
| `id` | `number` | `wms_order_express.id` | 运单记录ID |
| `waybill_code` | `string` | `wms_order_express.waybill_code` | 运单号(当前运单的运单号) |
| `main_waybill_code` | `string` | SELF JOIN 同 order 下 `business_key=1` | **主单号**。当 `business_key=1` 时等于 `waybill_code` 本身;当 `business_key>1` 时通过 SELF JOIN 查找同 `order_id` 下 `business_key=1` 的运单号 |
| `waybill_type` | `string` | 计算字段 | 运单类型:`business_key=1` → `"主单号"`,`business_key>1` → `"子单号"` |
| `order_id` | `number` | `wms_order_express.order_id` | 订单ID |
| `order_no` | `string` | JOIN 订单表 | 订单号(`delivery_order_code`)。待快照字段 + 写入逻辑实现后可改为直读 |
| `warehouse_id` | `number` | `wms_order_express.warehouse_id` | 仓库ID |
| `warehouse_name` | `string` | JOIN `store` 表 | 仓库名称。待快照字段 + 写入逻辑实现后可改为直读 |
| `store_id` | `number` | JOIN 订单表 | 货主ID。待快照字段 + 写入逻辑实现后可改为直读 |
| `store_name` | `string` | JOIN `store` 表 | 货主名称。待快照字段 + 写入逻辑实现后可改为直读 |
| `business_key` | `number` | `wms_order_express.business_key` | 拆单序号 |
| `status` | `number` | `wms_order_express.status` | 状态:0/1 |
| `status_text` | `string` | 前端映射 | 状态文本 |
| `logistics_code` | `string` | `wms_order_express.logistics_code` | 物流公司编码 |
| `logistics_name` | `string` | `wms_order_express.logistics_name` | 物流公司名称 |
| `logistics_interface_id` | `number` | `wms_order_express.logistics_interface_id` | 物流接口ID |
| `logistics_interface_name` | `string` | `wms_order_express.logistics_interface_name` | 物流接口名称 |
| `platform_code` | `string` | `wms_order_express.platform_code` | 平台编码 |
| `platform_name` | `string` | 前端映射 | 平台名称 |
| `is_back` | `string` | `wms_order_express.is_back` | 是否退回 |
| `is_intercept` | `string` | `wms_order_express.is_intercept` | 是否拦截 |
| `is_galaxy_receive` | `string` | `wms_order_express.is_galaxy_receive` | 是否揽收 |
| `weighing_weight` | `number` | `wms_order_express.weighing_weight` | 称重重量(g) |
| `weighing_weight_display` | `string` | 格式化 | 称重重量可读展示 |
| `package_material_id` | `number` | `wms_order_express.package_material_id` | 包材ID |
| `package_material_name` | `string` | `wms_order_express.package_material_name_snapshot` | 包材名称 |
| `print_count` | `number` | COUNT `express_print_record` | 打印次数 |
| `last_print_at` | `string` | MAX `express_print_record.created_at` | 最近打印时间 |
| `create_at` | `string` | `wms_order_express.create_at` | 运单创建时间 |
#### 查询逻辑要点
1. **仓库隔离**:自动注入 `warehouse_id = ctx.user.store_id`(系统统一约定,`ctx.user.store_id` 即为当前用户所属仓库ID)。所有查询 WHERE 条件自动追加 `warehouse_id`,不可由前端入参覆盖
2. **主单号关联查询**:每条运单记录通过 SELF JOIN(`t1.order_id = t2.order_id AND t2.business_key = 1`)获取主单号 `main_waybill_code`。当 `business_key = 1` 时,主单号就是自身 `waybill_code`;当 `business_key > 1` 时,需要 JOIN 获取主单号
3. **按主单号入参查询**:当 `where.mainWaybillCode` 传入时,先通过主单号 `waybill_code` 定位 `order_id`(`WHERE waybill_code = ? AND business_key = 1`),再 `WHERE order_id = ?` 返回该订单下所有运单(主+子)
4. **按物流接口ID查询**:直接 `WHERE logistics_interface_id = ?`,等值匹配
5. **订单号模糊搜索**:当 `where.orderNo` 或 `where.keyword` 匹配到非纯数字运单号时,需要 JOIN 订单表(current/history/dispatch)进行 `delivery_order_code LIKE` 匹配
6. **打印次数**:通过子查询或 LEFT JOIN + GROUP BY `express_print_record.express_no = waybill_code` 聚合
7. **性能注意**:打印次数聚合查询在数据量大时可能成为瓶颈,建议仅在 detail 接口返回
> **性能优化策略**(建议):
> - **方案 A(推荐)**:列表仅查 `wms_order_express` 原生字段,不 JOIN 订单/打印/打包表。`print_count` 通过批量异步查询补充,或仅在 detail 接口返回。
> - **方案 B**:列表即 JOIN,但需确保索引覆盖良好。
>
> **快照字段优化(待实现)**:新增快照列 + 创建运单号时写入快照值后,可彻底去掉订单表和 store 表的 JOIN。迁移文件 `20260729130000-add-waybill-order-snapshots.js` 已就绪,待 dev 实现写入逻辑后执行。
---
### 3.6 `waybill.warehouse.detail` — 运单详情(仓库侧)
**功能说明**:查看单个运单的完整信息,包含关联订单、打印记录、打包信息。
#### 请求参数
```json
{
"method": "waybill.warehouse.detail",
"id": 123456
}
```
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `id` | `number` | ✓ | 运单记录ID(`wms_order_express.id`) |
| `waybillCode` | `string` | ✗ | 运单号(与 id 二选一,waybillCode 优先) |
#### 响应格式
```json
{
"id": 123456,
"waybill_code": "SF1234567890",
"main_waybill_code": "SF1234567890",
"waybill_type": "主单号",
"business_key": 1,
"sibling_waybills": [
{ "waybill_code": "SF1234567890", "business_key": 1, "waybill_type": "主单号" },
{ "waybill_code": "SF1234567891", "business_key": 2, "waybill_type": "子单号" }
],
"order": {
"order_id": 78901,
"order_no": "PO202607290001",
"warehouse_id": 1,
"warehouse_name": "默认仓库",
"store_id": 10,
"store_name": "测试货主",
"wave_id": 500,
"wave_no": "W202607290001",
"order_type": "delivery"
},
"logistics": {
"logistics_code": "SF",
"logistics_name": "顺丰速运",
"logistics_interface_id": 3,
"logistics_interface_name": "顺丰标准",
"platform_code": "PDD"
},
"status_info": {
"status": 1,
"status_text": "已分配",
"is_back": "N",
"is_intercept": "N",
"is_galaxy_receive": "N"
},
"weight": {
"weighing_weight": 1250,
"weighing_weight_display": "1.25 kg"
},
"package": {
"package_material_id": 5,
"package_material_name": "3号纸箱"
},
"print_records": [
{
"id": 1001,
"printer_name": "打印机-01",
"template_id": 2,
"template_name": "顺丰标准面单",
"platform": "PDD",
"printed_at": "2026-07-29 10:30:00"
}
],
"print_count": 2,
"printinfo": "{...}",
"ver": "v2.1",
"retry_count": 0,
"create_at": "2026-07-29 08:00:00",
"delete_at": null
}
```
#### 查询逻辑要点
1. 查询 `wms_order_express` 主记录
2. 通过 `order_id` 查询同订单下所有运单组成 `sibling_waybills`(含各运单的 `waybill_code`、`business_key`、`waybill_type`)
3. 通过 `order_id` → `OrderDeliveryFactory` 多表遍历查找订单信息
4. LEFT JOIN `wms_express` 获取物流公司统一名称
5. LEFT JOIN `pack_task` ON `waybill_code` 获取打包信息
6. LEFT JOIN `express_print_record` ON `express_no = waybill_code` 获取打印记录列表
7. 仓库隔离校验
---
### 3.7 `waybill.warehouse.export` — 运单导出(仓库侧)
**功能说明**:按筛选条件导出运单列表为 Excel。复用 `waybill.warehouse.list` 的筛选逻辑,去掉分页,全量导出。
#### 请求参数
同 `waybill.warehouse.list`,不含 `pagination` 参数,可选增加 `exportFields` 指定导出字段。
```json
{
"method": "waybill.warehouse.export",
"where": { "...": "同 waybill.warehouse.list" },
"sort": { "...": "同 waybill.warehouse.list" },
"exportFields": ["waybill_code", "order_no", "logistics_name", "weighing_weight", "create_at"]
}
```
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `where` | `object` | ✗ | 同 `waybill.warehouse.list` 的筛选条件 |
| `sort` | `object` | ✗ | 同 `waybill.warehouse.list` 的排序 |
| `exportFields` | `string[]` | ✗ | 需要导出的字段列表,不传则导出全部字段 |
---
## 四、`methods/system.json` 变更
在 `methods.groups[]` 中新增 `waybill.warehouse` group:
```json
{
"name": "waybill.warehouse",
"description": "运单号管理(仓库侧)",
"methods": [
{
"method": "waybill.warehouse.list",
"description": "运单列表(分页+筛选)。仓库隔离。",
"isNeedAuth": false,
"isNeedLogin": true,
"params": [ "... 参数定义 ..." ],
"response": [ "... 返回值定义 ..." ]
},
{
"method": "waybill.warehouse.detail",
"description": "运单详情(含订单/打印/打包信息)。仓库隔离。",
"isNeedAuth": false,
"isNeedLogin": true,
"params": [ "... 参数定义 ..." ],
"response": [ "... 返回值定义 ..." ]
},
{
"method": "waybill.warehouse.export",
"description": "运单导出。仓库隔离。",
"isNeedAuth": false,
"isNeedLogin": true,
"params": [ "... 参数定义 ..." ],
"response": [ "... 返回值定义 ..." ]
}
]
}
```
> **预留 group(本期不实现)**:`waybill.store` — 运单号管理(货主侧),按 `store_id` 隔离。
>
> 完整的 `methods/system.json` method 定义(含 params/response 的 children 详情)在代码实现阶段由 `wms-doc-agent` 补齐。
---
## 五、文件变更清单
| 操作 | 文件路径 | 说明 |
|------|---------|------|
| **新增** | `app/service/systemMethods/waybill/warehouse.js` | 入口层(仓库侧):继承 `MainService`,`systemInit` 声明免鉴权方法,参数校验,委托 `systems/waybill.js` |
| **预留** | `app/service/systemMethods/waybill/store.js` | 入口层(货主侧):本期不创建,后续按需新增 |
| **修改** | `app/service/systems/waybill.js` | 业务层:在现有 `toOrder()` 方法基础上新增 `list()`、`detail()`、`export()` 方法 |
| **修改** | `methods/system.json` | 新增 `waybill.warehouse` group,注册 3 个 method 定义 |
| **新增** | `database/migrations/20260729140000-add-waybill-list-indexes.js` | 迁移文件:新增 4 个索引(✅ 已执行) |
| **新增** | `database/migrations/20260730000000-add-store-id-to-wms-order-express.js` | 迁移文件:新增 `store_id` 货主ID列(✅ 已执行) |
---
## 六、安全约束
| 约束 | 说明 |
|------|------|
| 仓库隔离 | 所有查询自动注入 `warehouse_id = ctx.user.store_id`(系统统一约定),仅返回当前用户所属仓库数据,不可由入参覆盖 |
| 只读 | 本模块一期仅提供只读查询,不涉及运单创建/修改/删除 |
| 鉴权 | 全部接口仅需登录,暂不做细粒度权限校验(与订单列表保持一致) |
---
## 七、与现有功能的边界划分
| 现有功能 | 所属 method | 与新模块关系 |
|---------|------------|-------------|
| 运单号反查订单 | `index.toOrder` | **保留**,独立于新模块。用于 PDA 扫运单号快速定位订单 |
| 订单详情中的运单信息 | `order.detail → expresses[]` | **保留**,不变。新模块提供运单维度的独立视图 |
| 运单包材绑定 | `order.bindExpressPackageMaterial*` | **保留**,不变。仍按订单维度操作 |
| 运单称重更新 | `order.updateExpressWeighingWeight` | **保留**,不变。仍按订单维度操作 |
| 快递号分配 | `order.pendingOrder.allocateExpressCode` | **保留**,不变。仍按订单维度操作 |
| 订单导出(运单模式) | `order.export (export_mode=waybill)` | **保留**,不变。与新模块 `waybill.warehouse.export` 并存 |
> **核心原则**:新模块不修改任何现有接口,仅新增运单维度的独立查询能力。现有订单维度的运单操作全部保持不动。
---
## 八、后续扩展方向(不在本期范围)
| 扩展 | 说明 |
|------|------|
| 运单拦截/解拦截 | 批量操作运单状态 |
| 运单退回标记 | 标记运单退回并记录原因 |
| 运单打印管理 | 批量补打、重新推送电子面单 |
| 运单异常列表 | 独立展示分配失败/打印失败的运单 |
| 运单物流轨迹 | 对接物流轨迹查询接口 |
---
## 九、审阅检查点
- [ ] 接口设计是否满足业务需求(运单号独立列表 + 详情)
- [x] ~~仓库隔离策略是否正确~~ → 已核实:全系统统一使用 `ctx.user.store_id` 作为 warehouse_id,与现有模式一致
- [ ] 列表字段是否完整(是否需要增减字段)
- [ ] 快照字段写入逻辑:需在创建运单号(express.js)时同步写入快照列值(dev 任务)
- [ ] 是否需要新增数据库索引(已明确需要,`20260729140000` 已执行)
- [ ] 与现有 `index.toOrder`、`order.*` 接口的边界是否清晰
### 当前筛选条件(共 18 项,16 可用 + 2 待快照)
| # | 参数 | 类型 | 匹配 | 状态 |
|---|------|------|------|------|
| — | `warehouse_id` | — | = | ✅ 自动注入 |
| 1 | `waybillCode` | string | LIKE | ✅ |
| 2 | `mainWaybillCode` | string | 精确→order_id | ✅ |
| 3 | `waybillType` | string | `main/1`→bk=1, `child/2`→bk>1 | ✅ 🆕 |
| 4 | `orderId` | number | = | ✅ |
| 5 | `orderNo` | string | LIKE | ⛔ 待快照 |
| 6 | `storeId` | number | = | ✅ 直读 `store_id` |
| 7 | `logisticsCode` | string | = | ✅ |
| 8 | `logisticsInterfaceId` | number | = | ✅ |
| 9 | `platformCode` | string | = | ✅ |
| 10 | `status` | number | = | ✅ |
| 11 | `isBack` | string | = | ✅ |
| 12 | `isIntercept` | string | = | ✅ |
| 13 | `isGalaxyReceive` | string | = | ✅ |
| 14 | `packageMaterialId` | number | = | ✅ |
| 15 | `hasWeighingWeight` | boolean | true→>0, false→=0 | ✅ |
| 16 | `keyword` | string | LIKE waybill_code | ✅ |
| 17 | `createdAtStart` | string YYYY-MM-DD | >= | ✅ |
| 18 | `createdAtEnd` | string YYYY-MM-DD | <= | ✅ |
### 排序
| field | order | 默认 |
|-------|-------|------|
| `create_at` | asc/desc | desc |
| `weighing_weight` | asc/desc | — |
| `id` | asc/desc | — |

View File

@ -0,0 +1,28 @@
'use strict';
module.exports = {
/**
* 移除打印电脑表的 remote_play_url 字段(未被使用)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async up(queryInterface, Sequelize) {
await queryInterface.removeColumn('wms_print_computer', 'remote_play_url');
},
/**
* 回滚:恢复 remote_play_url 字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async down(queryInterface, Sequelize) {
await queryInterface.addColumn('wms_print_computer', 'remote_play_url', {
type: Sequelize.STRING(500),
allowNull: true,
defaultValue: null,
comment: '远程播放地址',
});
},
};

View File

@ -0,0 +1,43 @@
'use strict';
module.exports = {
/**
* 移除打印电脑表的录制配置字段(recording_size_value / recording_size_unit / recording_directory),
* 这些字段不再由 WMS 侧管理。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async up(queryInterface, Sequelize) {
await queryInterface.removeColumn('wms_print_computer', 'recording_directory');
await queryInterface.removeColumn('wms_print_computer', 'recording_size_unit');
await queryInterface.removeColumn('wms_print_computer', 'recording_size_value');
},
/**
* 回滚:恢复录制配置字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async down(queryInterface, Sequelize) {
await queryInterface.addColumn('wms_print_computer', 'recording_size_value', {
type: Sequelize.INTEGER.UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '录制大小数值',
});
await queryInterface.addColumn('wms_print_computer', 'recording_size_unit', {
type: Sequelize.STRING(10),
allowNull: true,
defaultValue: null,
comment: '录制存储单位:KB/MB/GB/TB',
});
await queryInterface.addColumn('wms_print_computer', 'recording_directory', {
type: Sequelize.STRING(500),
allowNull: true,
defaultValue: null,
comment: '录制目录路径',
});
},
};

View File

@ -0,0 +1,28 @@
'use strict';
module.exports = {
/**
* 恢复 wms_print_computer 的 recording_directory 字段(录制目录路径)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('wms_print_computer', 'recording_directory', {
type: Sequelize.STRING(500),
allowNull: true,
defaultValue: null,
comment: '录制目录路径',
});
},
/**
* 回滚:移除 recording_directory 字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async down(queryInterface, Sequelize) {
await queryInterface.removeColumn('wms_print_computer', 'recording_directory');
},
};

View File

@ -0,0 +1,215 @@
'use strict';
const TABLE_NAME = 'wms_after_sale_work_order';
module.exports = {
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME);
if (exists) return;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
warehouse_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID',
},
store_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '货主ID',
},
work_order_no: {
type: Sequelize.STRING(50),
allowNull: false,
comment: '售后工单号,唯一',
},
business_type: {
type: Sequelize.STRING(50),
allowNull: false,
comment: '关联业务类型',
},
business_sub_type: {
type: Sequelize.STRING(50),
allowNull: false,
comment: '关联业务子类型',
},
business_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '关联业务单据主键ID(多态关联)',
},
business_no: {
type: Sequelize.STRING(100),
allowNull: true,
comment: '关联业务单据号(冗余)',
},
direction: {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '记账方向:0=未确定 1=入库 2=出库',
},
status: {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '工单状态:0=待处理 1=处理中 2=已完成 3=已关闭 9=已取消',
},
priority: {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 50,
comment: '优先级:1~100,数字越大优先级越高',
},
title: {
type: Sequelize.STRING(200),
allowNull: false,
comment: '工单标题/摘要',
},
description: {
type: Sequelize.TEXT,
allowNull: true,
comment: '问题描述',
},
creator_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '创建人ID,关联 account.id;0 表示 AI 自动接待',
},
creator_snapshot: {
type: Sequelize.TEXT,
allowNull: true,
comment: '创建人信息快照(JSON格式)',
},
assignee_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '当前处理人ID,关联 account.id',
},
parent_work_order_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '父工单ID,自关联本表;非空时表示子工单',
},
current_step: {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 1,
comment: '当前进度,值为当前正在处理的 step_order 序号',
},
claim_needed: {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '是否需要理赔:0=不需要 1=需要',
},
claim_amount: {
type: Sequelize.DECIMAL(12, 2),
allowNull: true,
defaultValue: 0.00,
comment: '理赔金额(元)',
},
claim_status: {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '理赔状态:0=未理赔 1=已理赔(单笔结清) 2=月结',
},
resolution: {
type: Sequelize.TEXT,
allowNull: true,
comment: '处理结果说明',
},
resolved_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '解决时间',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
deleted_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '软删除时间',
},
});
// 工单号唯一
await queryInterface.addIndex(TABLE_NAME, ['work_order_no'], {
unique: true,
name: 'uk_work_order_no',
});
// 仓库隔离查询
await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], {
name: 'idx_warehouse_id',
});
// 货主隔离查询
await queryInterface.addIndex(TABLE_NAME, ['store_id'], {
name: 'idx_store_id',
});
// 按业务类型+子类型+单据ID反查工单
await queryInterface.addIndex(TABLE_NAME, ['business_type', 'business_sub_type', 'business_id'], {
name: 'idx_business_type_subtype_id',
});
// 按状态筛选
await queryInterface.addIndex(TABLE_NAME, ['status'], {
name: 'idx_status',
});
// 按处理人查询
await queryInterface.addIndex(TABLE_NAME, ['assignee_id'], {
name: 'idx_assignee_id',
});
// 按父工单查子工单
await queryInterface.addIndex(TABLE_NAME, ['parent_work_order_id'], {
name: 'idx_parent_work_order_id',
});
// 按优先级排序
await queryInterface.addIndex(TABLE_NAME, ['priority'], {
name: 'idx_priority',
});
// 按理赔状态筛选
await queryInterface.addIndex(TABLE_NAME, ['claim_status'], {
name: 'idx_claim_status',
});
// 按时间排序
await queryInterface.addIndex(TABLE_NAME, ['created_at'], {
name: 'idx_created_at',
});
// 软删除查询优化
await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], {
name: 'idx_deleted_at',
});
},
down: async queryInterface => {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -0,0 +1,35 @@
'use strict';
module.exports = {
/**
* 恢复 wms_print_computer 的 recording_size_value 和 recording_size_unit 字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('wms_print_computer', 'recording_size_value', {
type: Sequelize.INTEGER.UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '录制大小数值',
});
await queryInterface.addColumn('wms_print_computer', 'recording_size_unit', {
type: Sequelize.STRING(10),
allowNull: true,
defaultValue: null,
comment: '录制存储单位:KB/MB/GB/TB',
});
},
/**
* 回滚:移除 recording_size_value 和 recording_size_unit 字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async down(queryInterface, Sequelize) {
await queryInterface.removeColumn('wms_print_computer', 'recording_size_unit');
await queryInterface.removeColumn('wms_print_computer', 'recording_size_value');
},
};

View File

@ -0,0 +1,115 @@
'use strict';
const TABLE_NAME = 'wms_after_sale_work_order_step';
module.exports = {
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME);
if (exists) return;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
work_order_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '工单ID,关联 wms_after_sale_work_order.id',
},
step_order: {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 1,
comment: '步骤序号(从1开始递增)',
},
step_name: {
type: Sequelize.STRING(100),
allowNull: false,
comment: '步骤名称',
},
step_status: {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '步骤状态:0=待开始 1=进行中 2=已完成 3=已跳过',
},
operator_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '操作员工ID,关联 account.id',
},
operator_snapshot: {
type: Sequelize.TEXT,
allowNull: true,
comment: '操作人信息快照(JSON格式)',
},
action: {
type: Sequelize.STRING(100),
allowNull: true,
comment: '操作动作描述',
},
remark: {
type: Sequelize.TEXT,
allowNull: true,
comment: '处理备注',
},
started_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '步骤开始时间',
},
completed_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '步骤完成时间',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
deleted_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '软删除时间',
},
});
// 按工单查所有步骤
await queryInterface.addIndex(TABLE_NAME, ['work_order_id'], {
name: 'idx_work_order_id',
});
// 按操作人反查
await queryInterface.addIndex(TABLE_NAME, ['operator_id'], {
name: 'idx_operator_id',
});
// 软删除查询优化
await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], {
name: 'idx_deleted_at',
});
// 同一工单下步骤序号唯一(含软删除)
await queryInterface.addIndex(TABLE_NAME, ['work_order_id', 'step_order', 'deleted_at'], {
unique: true,
name: 'uk_work_order_step',
});
},
down: async queryInterface => {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -0,0 +1,84 @@
'use strict';
const TABLE_NAME = 'wms_order_express';
/**
* 获取指定表的索引名集合。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @return {Promise<Set<string>>} 索引名集合。
*/
const getIndexNameSet = async (queryInterface, tableName) => {
const indexes = await queryInterface.showIndex(tableName);
return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean));
};
module.exports = {
/**
* 执行迁移:为运单表新增运单列表高频查询索引(幂等)。
*
* 新增索引:
* - idx_warehouse_id_status:仓库+状态筛选(最常见查询组合)
* - idx_logistics_code:物流公司筛选
* - idx_logistics_interface_id:快递接口ID筛选
* - idx_warehouse_id_create_at:仓库+时间范围排序分页
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface, Sequelize) {
const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME);
if (!indexNameSet.has('idx_warehouse_id_status')) {
await queryInterface.addIndex(TABLE_NAME, {
name: 'idx_warehouse_id_status',
fields: ['warehouse_id', 'status'],
});
}
if (!indexNameSet.has('idx_logistics_code')) {
await queryInterface.addIndex(TABLE_NAME, {
name: 'idx_logistics_code',
fields: ['logistics_code'],
});
}
if (!indexNameSet.has('idx_logistics_interface_id')) {
await queryInterface.addIndex(TABLE_NAME, {
name: 'idx_logistics_interface_id',
fields: ['logistics_interface_id'],
});
}
if (!indexNameSet.has('idx_warehouse_id_create_at')) {
await queryInterface.addIndex(TABLE_NAME, {
name: 'idx_warehouse_id_create_at',
fields: ['warehouse_id', 'create_at'],
});
}
},
/**
* 回滚迁移:移除运单列表查询索引。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface, Sequelize) {
const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME);
if (indexNameSet.has('idx_warehouse_id_status')) {
await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_id_status');
}
if (indexNameSet.has('idx_logistics_code')) {
await queryInterface.removeIndex(TABLE_NAME, 'idx_logistics_code');
}
if (indexNameSet.has('idx_logistics_interface_id')) {
await queryInterface.removeIndex(TABLE_NAME, 'idx_logistics_interface_id');
}
if (indexNameSet.has('idx_warehouse_id_create_at')) {
await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_id_create_at');
}
},
};

View File

@ -0,0 +1,43 @@
'use strict';
const TABLE_NAME = 'wms_camera';
/**
* 新增摄像头认证字段:username(用户名)、password(密码)。
* 用于保存摄像头登录认证信息。
*/
module.exports = {
up: async (queryInterface, Sequelize) => {
const columns = [
{
name: 'username',
def: { type: Sequelize.STRING(100), allowNull: true, comment: '摄像头登录用户名', after: 'stream_type' },
},
{
name: 'password',
def: { type: Sequelize.STRING(100), allowNull: true, comment: '摄像头登录密码', after: 'username' },
},
];
for (const col of columns) {
const tableInfo = await queryInterface.describeTable(TABLE_NAME);
if (!tableInfo[col.name]) {
await queryInterface.addColumn(TABLE_NAME, col.name, col.def);
console.log(`[Migration] wms_camera.${col.name} 已添加`);
} else {
console.log(`[Migration] wms_camera.${col.name} 已存在,跳过`);
}
}
},
down: async queryInterface => {
const columns = ['password', 'username'];
for (const col of columns) {
const tableInfo = await queryInterface.describeTable(TABLE_NAME);
if (tableInfo[col]) {
await queryInterface.removeColumn(TABLE_NAME, col);
console.log(`[Migration] wms_camera.${col} 已回滚删除`);
}
}
},
};

View File

@ -0,0 +1,49 @@
'use strict';
const TABLE_NAME = 'wms_order_express';
const COLUMN_NAME = 'store_id';
/**
* 获取指定表的列名集合。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @return {Promise<Set<string>>} 列名集合。
*/
const getColumnNameSet = async (queryInterface, tableName) => {
const columns = await queryInterface.describeTable(tableName);
return new Set(Object.keys(columns));
};
module.exports = {
/**
* 执行迁移:为运单表新增货主ID字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface, Sequelize) {
const existingColumns = await getColumnNameSet(queryInterface, TABLE_NAME);
if (!existingColumns.has(COLUMN_NAME)) {
await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '货主ID',
});
}
},
/**
* 回滚迁移:移除运单表的货主ID字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface, Sequelize) {
const existingColumns = await getColumnNameSet(queryInterface, TABLE_NAME);
if (existingColumns.has(COLUMN_NAME)) {
await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME);
}
},
};

View File

@ -0,0 +1,83 @@
'use strict';
/**
* 回填 wms_order_express 表的 logistics_code 和 logistics_name。
*
* 背景:取号成功后写入 wms_order_express 时引用了不存在的字段
* listByWarehousePlatformCode.logistics_code / logistics_name,
* 导致 6w+ 条记录该两字段为空。
*
* 本迁移通过 logistics_interface_id 关联 wms_express_interface.sys_express_code,
* 再通过 wms_express.name 获取快递名称,完成数据回填。
*/
module.exports = {
async up(queryInterface) {
const [ results ] = await queryInterface.sequelize.query(`
SELECT COUNT(*) AS cnt
FROM wms_order_express oe
JOIN wms_express_interface ei ON oe.logistics_interface_id = ei.id
WHERE (oe.logistics_code IS NULL OR oe.logistics_code = '')
AND ei.sys_express_code IS NOT NULL
AND ei.sys_express_code != ''
`);
const affectedCount = (results && results[0] && results[0].cnt) || 0;
console.log(`[backfill-order-express-logistics] 预计回填 ${affectedCount} 条记录`);
if (affectedCount === 0) {
console.log('[backfill-order-express-logistics] 无需回填,跳过');
return;
}
await queryInterface.sequelize.query(`
UPDATE wms_order_express oe
JOIN wms_express_interface ei ON oe.logistics_interface_id = ei.id
LEFT JOIN wms_express e ON e.code = ei.sys_express_code
SET
oe.logistics_code = ei.sys_express_code,
oe.logistics_name = COALESCE(e.name, ei.sys_express_code)
WHERE (oe.logistics_code IS NULL OR oe.logistics_code = '')
AND ei.sys_express_code IS NOT NULL
AND ei.sys_express_code != ''
`);
console.log(`[backfill-order-express-logistics] 成功回填 ${affectedCount} 条记录`);
},
async down(queryInterface) {
// 回滚:仅清空通过本迁移回填的记录(条件:logistics_code 等于对应 sys_express_code)
const [ results ] = await queryInterface.sequelize.query(`
SELECT COUNT(*) AS cnt
FROM wms_order_express oe
JOIN wms_express_interface ei ON oe.logistics_interface_id = ei.id
WHERE oe.logistics_code = ei.sys_express_code
AND oe.logistics_code IS NOT NULL
AND oe.logistics_code != ''
AND ei.sys_express_code IS NOT NULL
AND ei.sys_express_code != ''
`);
const rollbackCount = (results && results[0] && results[0].cnt) || 0;
console.log(`[backfill-order-express-logistics] 预计回滚 ${rollbackCount} 条记录`);
if (rollbackCount === 0) {
console.log('[backfill-order-express-logistics] 无需回滚,跳过');
return;
}
await queryInterface.sequelize.query(`
UPDATE wms_order_express oe
JOIN wms_express_interface ei ON oe.logistics_interface_id = ei.id
SET
oe.logistics_code = '',
oe.logistics_name = ''
WHERE oe.logistics_code = ei.sys_express_code
AND oe.logistics_code IS NOT NULL
AND oe.logistics_code != ''
AND ei.sys_express_code IS NOT NULL
AND ei.sys_express_code != ''
`);
console.log(`[backfill-order-express-logistics] 成功回滚 ${rollbackCount} 条记录`);
},
};

View File

@ -0,0 +1,30 @@
'use strict';
/**
* 为 wms_order_express 表新增 delivery_order_code 和 source_order_codes 字段。
*
* 用途:运单记录需要关联对应的发货单号和原始订单号,便于运单追溯和导出。
* 字段格式参考 wms_order_delivery 表的同名字段。
*/
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('wms_order_express', 'delivery_order_code', {
type: Sequelize.STRING(50),
allowNull: true,
comment: '发货单号',
after: 'warehouse_id',
});
await queryInterface.addColumn('wms_order_express', 'source_order_codes', {
type: Sequelize.TEXT,
allowNull: true,
comment: '来源订单号集合',
after: 'delivery_order_code',
});
},
async down(queryInterface) {
await queryInterface.removeColumn('wms_order_express', 'delivery_order_code');
await queryInterface.removeColumn('wms_order_express', 'source_order_codes');
},
};

View File

@ -0,0 +1,72 @@
'use strict';
const TABLE_NAME = 'wms_order_express';
/**
* 回填 wms_order_express.store_id。
* 从对应的仓库分表(current → history → dispatch)中获取 store_id。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
async function backfill(queryInterface) {
// 获取所有不同的 warehouse_id
const [warehouses] = await queryInterface.sequelize.query(
`SELECT DISTINCT warehouse_id FROM ${TABLE_NAME} WHERE store_id IS NULL AND warehouse_id IS NOT NULL`
);
if (!warehouses || warehouses.length === 0) {
return;
}
for (const row of warehouses) {
const warehouseId = row.warehouse_id;
const tableTypes = [
`wms_order_delivery_${warehouseId}`, // current(配送表 / 待处理表)
`wms_order_delivery_${warehouseId}_history`, // history
`wms_order_delivery_${warehouseId}_dispatch`, // dispatch
];
for (const deliveryTable of tableTypes) {
try {
const [result] = await queryInterface.sequelize.query(`
UPDATE ${TABLE_NAME} e
INNER JOIN ${deliveryTable} d ON e.order_id = d.id AND e.warehouse_id = d.warehouse_id
SET e.store_id = d.store_id
WHERE e.store_id IS NULL AND d.store_id IS NOT NULL
`);
console.log(` warehouse=${warehouseId} table=${deliveryTable} rows=${result.info || result}`);
} catch (err) {
// 表可能不存在,跳过
if (err && err.parent && err.parent.code === 'ER_NO_SUCH_TABLE') {
continue;
}
console.warn(` warehouse=${warehouseId} table=${deliveryTable} error=${err.message}`);
}
}
}
}
module.exports = {
/**
* 执行迁移:回填 store_id。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface, Sequelize) {
await backfill(queryInterface);
},
/**
* 回滚迁移:将 store_id 置为 NULL。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface, Sequelize) {
await queryInterface.sequelize.query(
`UPDATE ${TABLE_NAME} SET store_id = NULL`
);
},
};

View File

@ -0,0 +1,60 @@
'use strict';
const TABLE_NAME = 'wms_order_express';
/**
* 回填 wms_order_express 的 delivery_order_code 和 source_order_codes。
* 从对应的仓库分表(current → history → dispatch)中获取。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
async function backfill(queryInterface) {
const [warehouses] = await queryInterface.sequelize.query(
`SELECT DISTINCT warehouse_id FROM ${TABLE_NAME} WHERE delivery_order_code IS NULL AND warehouse_id IS NOT NULL`
);
if (!warehouses || warehouses.length === 0) {
return;
}
for (const row of warehouses) {
const warehouseId = row.warehouse_id;
const tableTypes = [
`wms_order_delivery_${warehouseId}`,
`wms_order_delivery_${warehouseId}_history`,
`wms_order_delivery_${warehouseId}_dispatch`,
];
for (const deliveryTable of tableTypes) {
try {
const [result] = await queryInterface.sequelize.query(`
UPDATE ${TABLE_NAME} e
INNER JOIN ${deliveryTable} d ON e.order_id = d.id AND e.warehouse_id = d.warehouse_id
SET e.delivery_order_code = COALESCE(e.delivery_order_code, d.delivery_order_code),
e.source_order_codes = COALESCE(e.source_order_codes, d.source_order_codes)
WHERE (e.delivery_order_code IS NULL OR e.source_order_codes IS NULL)
AND (d.delivery_order_code IS NOT NULL OR d.source_order_codes IS NOT NULL)
`);
console.log(` warehouse=${warehouseId} table=${deliveryTable} rows=${result.info || result}`);
} catch (err) {
if (err && err.parent && err.parent.code === 'ER_NO_SUCH_TABLE') {
continue;
}
console.warn(` warehouse=${warehouseId} table=${deliveryTable} error=${err.message}`);
}
}
}
}
module.exports = {
async up(queryInterface, Sequelize) {
await backfill(queryInterface);
},
async down(queryInterface, Sequelize) {
await queryInterface.sequelize.query(
`UPDATE ${TABLE_NAME} SET delivery_order_code = NULL, source_order_codes = NULL`
);
},
};

View File

@ -0,0 +1,80 @@
'use strict';
/**
* 为 apiApp 仓库 API 应用管理模块创建权限并授权给客服组-主管及以上角色。
*
* 固定 ID(开发库 & 生产库 wms_permission 当前 max_id 均为 463):
* 464 — 父级菜单 "API应用管理"
* 465 — apiApp.list
* 466 — apiApp.detail
* 467 — apiApp.create
* 468 — apiApp.update
* 469 — apiApp.delete
* 470 — apiApp.regenerateSecret
*
* 授权角色(permissions 不为 "*" 的 主管/经理 级角色):
* 8 — 经理
* 26 — 仓库组-主管
* 28 — 客服组-主管
* 29 — 生产组-主管
*/
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
// ── 1. 插入父级权限 (type=web_pages, sort=1, status=1) ──
await queryInterface.sequelize.query(`
INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at)
VALUES (464, 'apiApp', NULL, 'API应用管理', NULL, 'API应用管理', NULL, 0, 0, NULL, 'web_pages', 1, 1, NOW(), NOW())
`);
// ── 2. 插入 6 个接口权限 ──
const methods = [
[ 465, 'apiApp.list' ],
[ 466, 'apiApp.detail' ],
[ 467, 'apiApp.create' ],
[ 468, 'apiApp.update' ],
[ 469, 'apiApp.delete' ],
[ 470, 'apiApp.regenerateSecret' ],
];
for (const [ id, method ] of methods) {
await queryInterface.sequelize.query(`
INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at)
VALUES (${id}, '${method}', NULL, '${method}', NULL, 'API:${method}', NULL, 0, 0, 464, 'api', 0, 1, NOW(), NOW())
`);
}
// ── 3. 给 客服组-主管及以上角色 追加新权限 ID ──
// 只更新 permissions 为显式列表(非 "*")的角色
const newIdSuffix = ', 465, 466, 467, 468, 469, 470';
await queryInterface.sequelize.query(`
UPDATE wms_role
SET permissions = CONCAT(LEFT(permissions, LENGTH(permissions) - 1), '${newIdSuffix}]')
WHERE id IN (8, 26, 28, 29)
AND permissions != '*'
AND permissions IS NOT NULL
AND LENGTH(permissions) > 2
`);
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
// ── 1. 从角色权限中移除新增的 ID ──
await queryInterface.sequelize.query(`
UPDATE wms_role
SET permissions = REPLACE(permissions, ', 465, 466, 467, 468, 469, 470', '')
WHERE id IN (8, 26, 28, 29)
`);
// ── 2. 删除 6 个接口权限 ──
await queryInterface.sequelize.query(
'DELETE FROM wms_permission WHERE id IN (465, 466, 467, 468, 469, 470)'
);
// ── 3. 删除父级权限 ──
await queryInterface.sequelize.query(
'DELETE FROM wms_permission WHERE id = 464'
);
},
};

View File

@ -1,4 +1,147 @@
[
{
"version": "2026.08.01-system-01",
"date": "2026-08-01",
"type": "added",
"summary": "新增 apiApp 仓库 API 应用管理模块,支持当前仓库维度的 API 应用 CRUD、AppKey/Secret 自动生成与重新生成、IP 白名单、回调地址、限流等配置",
"methods": [
"apiApp.list",
"apiApp.detail",
"apiApp.create",
"apiApp.update",
"apiApp.delete",
"apiApp.regenerateSecret"
],
"notes": [
"apiApp.list:分页查询当前仓库 API 应用列表,支持按 app_name(模糊)、is_enabled 筛选,Secret 自动脱敏(前8位+****)。",
"apiApp.detail:按 ID 查询单个应用详情,需同时匹配 warehouse_id(自动注入 ctx.user.store_id),Secret 脱敏。",
"apiApp.create:创建应用时自动生成 AppKey(AK{yyyyMMddHHmmss}{random8hex})和 AppSecret(64位hex)。默认 interface_type_id 取 WH_CHANNEL。仅创建时返回完整 Secret。",
"apiApp.update:更新可编辑字段(app_name、self_ip_whitelist、callback_url、rate_limit、sign_method、is_enabled),不可变字段为 self_app_key 和 interface_type_id。",
"apiApp.delete:软删除(is_enabled=0),不物理删除。",
"apiApp.regenerateSecret:重新生成 64位hex AppSecret,旧 Secret 立即失效。仅此次返回完整 Secret。",
"仓库隔离:所有操作按 ctx.user.store_id → warehouse_id 自动过滤。",
"Secret 安全策略:list/detail/update 返回脱敏值,仅 create/regenerateSecret 返回完整 Secret。"
],
"module": "apiApp"
},
{
"version": "2026.07.31-system-02",
"date": "2026-07-31",
"type": "added",
"summary": "新增 storage.inventory.export 库存导出与 storage.inventory.exportTaskProgress 导出进度查询,入参复用 list 的 where/sort/group_by_batch 语义,支持两种导出模式(聚合汇总 / 逐条明细),库位信息一并导出",
"methods": [
"storage.inventory.export",
"storage.inventory.exportTaskProgress"
],
"notes": [
"storage.inventory.export:异步提交导出任务,返回 task_id 与受理信息,后端异步生成 Excel 并上传。入参 where/sort/group_by_batch 与 storage.inventory.list 完全一致,无需额外学习成本。",
"group_by_batch=false(默认):按 stock_id + space_id(库位)聚合导出库存汇总,含商品编码/名称/规格/单位/货主/库位编码/名称/总库存/锁定/可用/批次数/最近入库时间。",
"group_by_batch=true:按 storage_id 逐条导出库存明细,含库存记录ID/商品信息/库位信息/批次号/库存类型/数量/生产日期/过期日期/入库时间/入库单号/供应商批次号。",
"新增 storage.inventory.exportTaskProgress:按 task_id/taskId 查询导出任务进度与状态(submitted/running/success/failed/not_found),status=success 时返回 download_url 供客户端下载。",
"导出文件目录:exports/storage/inventory/{warehouseId}/,缓存 TTL 1800 秒。"
],
"module": "storage.inventory"
},
{
"version": "2026.07.31-system-01",
"date": "2026-07-31",
"type": "added",
"summary": "新增按波次批量快捷复核接口 batchQuickRecheckByWave,支持批量波次 IDs 的前置条件检查(储位、快递、同步、拦截),自动完成拣货并标记复核,支持部分失败",
"methods": [
"order.recheckOrder.batchQuickRecheckByWave"
],
"notes": [
"新增 order.recheckOrder.batchQuickRecheckByWave 方法,复用 batchQuickRecheck 的 _completePickForOrder / _markRecheckForOrder / _tryCompleteWaveInTransaction 等内部事务方法",
"入参 wave_ids 支持数组或逗号分隔字符串,兼容 waveIds(驼峰)、wave_id(单值)",
"按波次维度批量查询订单后逐波次、逐订单执行前置校验与复核,每个订单独立事务,部分失败不影响其他订单",
"响应包含 success/failed 列表及计数,failed 项含 order_id、wave_id、delivery_order_code、reason 说明;波次下无订单时仅返回 wave_id + reason"
],
"module": "order.recheckOrder"
},
{
"version": "2026.07.29-system-01",
"date": "2026-07-29",
"type": "added",
"summary": "补全 waybill.warehouse group API 文档参数定义:完善 list/detail/export 的 params 与 response,新增 exportTaskProgress 异步进度查询接口",
"methods": [
"waybill.warehouse.list",
"waybill.warehouse.detail",
"waybill.warehouse.export",
"waybill.warehouse.exportTaskProgress"
],
"notes": [
"waybill.warehouse.list:params 含 pagination/where/sort 完整字段定义,where 支持 15 个筛选维度(运单号、主单号、订单ID、订单号、物流编码、物流接口ID、平台编码、状态、退回/拦截/星河签收、包材ID、已称重、关键词、创建时间范围),sort 白名单 create_at/weighing_weight/id。response 含 list(28 个字段)+ pagination。",
"waybill.warehouse.detail:修正 id 参数为可选(required: false),与 waybillCode 二选一,waybillCode 优先。response 含 id/waybill_code/main_waybill_code/waybill_type/business_key/sibling_waybills/order/logistics/status_info/weight/package/print_records/print_count 等完整详情。",
"waybill.warehouse.export:response 补充 progress/message/update_time 字段,完整覆盖异步任务返回信息。",
"新增 waybill.warehouse.exportTaskProgress:按 task_id/taskId 查询导出进度,response 含 task_id/status/progress/current_count/total_count/message/result/error/download_url/update_time。",
"所有接口 isNeedAuth: false, isNeedLogin: true,仓库隔离通过 ctx.user.store_id 自动注入。"
],
"module": "waybill.warehouse"
},
{
"version": "2026.07.28-system-01",
"date": "2026-07-28",
"type": "added",
"summary": "新增 order.pendingOrder.batchMarkPrinted:批量设置订单为已打印状态,将 print_status 更新为 'fin'",
"methods": [
"order.pendingOrder.batchMarkPrinted"
],
"notes": [
"同步批量更新接口,传入订单ID数组,直接将符合条件的订单 print_status 设为 'fin'。",
"双表查询:先查 current 表(wms_order_delivery_{warehouseId}),未命中的 ID 再兜底查 dispatch 表(wms_order_delivery_{warehouseId}_dispatch)。",
"dispatch 表查询失败仅记录 warn 日志,不影响 current 表已更新的结果。",
"仅允许 step 在 [1,2,3] 且 status 不为 'cancel' 的订单操作,已打印(print_status='fin')的订单会被静默跳过。",
"仓库上下文强制从 ctx.user.store_id 获取,禁止传入外部仓库ID。",
"入参支持 order_ids / orderIds / ids 三种别名,优先级 order_ids > orderIds > ids。",
"返回 updated_count 表示实际更新条数(current + dispatch 合计),ids 原样回传请求的订单ID列表。",
"写入操作日志 operation_code: ORDER_BATCH_MARK_PRINTED。"
],
"module": "order.pendingOrder"
},
{
"version": "2026.07.27-system-03",
"date": "2026-07-27",
"type": "changed",
"summary": "storage.receiving 导出接口拆分:export 改为按仓库维度,新增 storeExport 按货主维度导出",
"methods": [
"storage.receiving.export",
"storage.receiving.exportTaskProgress",
"storage.receiving.storeExport",
"storage.receiving.storeExportTaskProgress"
],
"notes": [
"export 改为仓库维度:过滤条件从 store_id(平台激活货主)改为 warehouse_id(ctx.user.store_id),与 getReceivingList 保持一致。",
"exportTaskProgress 同步更新为仓库维度进度查询,任务 ID 前缀 receiving_export_。",
"新增 storeExport:货主维度导出,通过平台激活上下文获取 store_id,过滤逻辑与 getStoreReceivingList 一致。",
"新增 storeExportTaskProgress:货主维度进度查询,复用 exportTaskProgress 的缓存逻辑,任务 ID 前缀 receiving_store_export_。",
"导出格式:双 Sheet Excel(Sheet1=收货单列表 21 列,Sheet2=收货单明细 17 列),通过 ExcelJS stream + uploadService 上传 COS。",
"仓库导出上传路径 exports/receiving/{warehouseId}/,货主导出上传路径 exports/receiving/store/{storeId}/。",
"修复 exportReceivingList 中 where 条件二次解析问题:增加 ctx.whereParsed 复用(与 getStoreReceivingList 一致),避免 prepareWhereContext 已解析后再重复 parseWhereConditions 导致边界条件丢失。",
"命名对齐 entry 侧:storeExport / storeExportTaskProgress 方法名、任务 ID 前缀、上传路径均与 storage.entry.storeExport 模式一致。"
],
"module": "storage.receiving"
},
{
"version": "2026.07.27-system-02",
"date": "2026-07-27",
"type": "added",
"summary": "新增 order.pendingOrder.allocateSubOrderNumber:待处理订单分配子单号(异步任务),business_key 从 2 开始递增,跳过已分配运单号;新增 allocateSubOrderNumberProgress 按 task_id/business_key 查询进度",
"methods": [
"order.pendingOrder.allocateSubOrderNumber",
"order.pendingOrder.allocateSubOrderNumberProgress"
],
"notes": [
"新增 allocateSubOrderNumber:入参 order_id + sub_order_count,按 business_key 2..(2+count-1) 全量传入 createWaybillCodePipeline。",
"并发安全:全量传入 pipeline,由其内部事务 + UNIQUE(order_id,business_key,status,warehouse_id) 索引保证并发去重。",
"pipeline 内部 createWaybillCode 事务:status=1 已分配→跳过;status=0 占位中→复用;无记录→INSERT status=0 占位。",
"异步任务模式:请求立即返回 task_id(sub_ 前缀),后台 setImmediate 执行,进度通过 Redis 缓存追踪。",
"新增 allocateSubOrderNumberProgress:支持 task_id 查整体进度,business_key 可选参数过滤单个业务ID的详情。",
"进度状态 submitted→running→success/partial/failed,progress 对应 5/50/80/100。",
"result.details 数组记录每个 business_key 的 status(skipped/allocated/failed/pending)与 waybill_code。",
"buildSubOrderDetails 回查最终状态:status=1+waybill→allocated,status=0→failed,无记录→failed。"
],
"module": "order.pendingOrder"
},
{
"version": "2026.07.27-system-01",
"date": "2026-07-27",
@ -2271,24 +2414,6 @@
],
"type": "updated"
},
{
"version": "2026.05.20-system-02",
"date": "2026-05-20",
"summary": "新增打印失败自动补偿能力:定时扫描并触发 print.retryFailed 批量补打",
"methods": [
"print.retryFailed"
],
"notes": [
"新增定时任务:app/schedule/print_retry_compensation.js,按仓库分组调用 print.retryFailed 进行批量补打。",
"配置项位置:config/config.default.js 的 printRetryCompensation,包含:enable(boolean, 默认 false)、intervalMs(毫秒,默认 60000)、batchSize(批量大小,默认 50)、force(boolean,默认 false)、maxRetryCount(number,默认 5)。",
"行为摘要:任务按 printRetryCompensation.intervalMs 频率查询 send_status=send_failed 或 print_status IN (print_failed, timeout),且 next_retry_at <= now 且 retry_count < maxRetryCount 的记录,按仓库分组并调用 print.retryFailed({ print_ids, warehouse_id, force }) 进行补打。",
"兼容性:print.retryFailed 支持显式传入 warehouse_id(调度任务会传入),当未提供时回退到 ctx.user.store_id;若两者均无则接口返回 400。",
"注意:当前实现中传入的 force 参数不会放宽对状态的判定(代码注释说明为“最小实现”),如需放宽需修改 print.getRetryEligibility 的逻辑。",
"回滚说明:1) 将 printRetryCompensation.enable 设为 false 并重启服务以停止新任务;2) 从部署包中移除或注释 app/schedule/print_retry_compensation.js 并重启服务;3) 如需从 methods/changes/system.json 中移除此变更,请通过生成对应 spec(change.version 设置为本条版本并 type='removed')并运行 npm run doc:api:update -- --spec=<spec> 来更新变更记录;4) 若调度已触发的补打需中止,请在调度或队列系统中停止对应任务或通过运维回退正在执行的补打逻辑。"
],
"module": "print",
"type": "added"
},
{
"version": "2026.05.20-system-01",
"date": "2026-05-20",
@ -4953,5 +5078,46 @@
"仓库侧导出自动限定 warehouse_id=ctx.user.store_id,货主侧需传 store_id",
"导出 Excel 列:序号/创建时间/流水类型/仓库ID/货主ID/商品ID/变动数量/变更前库存/变更后库存/变更前锁定/变更后锁定/批次号/单据类型/单据号/收货单ID/入库单ID/发货单ID/操作人/备注"
]
},
{
"version": "2026.07.29-system-01",
"date": "2026-07-29",
"type": "added",
"summary": "新增 waybill.warehouse 运单模块(仓库侧):list(列表)、detail(详情)、export(导出)3 个接口,支持运单号独立查询与管理",
"methods": [
"waybill.warehouse.list",
"waybill.warehouse.detail",
"waybill.warehouse.export"
],
"notes": [
"新增 waybill.warehouse.list:仓库侧运单列表查询,支持分页与多条件筛选(运单号/主单号/订单ID/订单号/物流公司/物流接口/平台/状态/退回/拦截/星河签收/包材/称重/关键词/时间范围),默认按 create_at desc 排序。",
"新增 waybill.warehouse.detail:仓库侧运单详情查询,含关联订单信息、兄弟运单(sibling_waybills)、物流信息、状态信息、称重信息、打包信息(打包状态/打包人/打包时间)、打印记录列表。",
"新增 waybill.warehouse.export:仓库侧运单导出,复用 list 筛选逻辑,异步任务模式,支持自定义导出字段。",
"仓库隔离策略:所有接口自动注入 warehouse_id = ctx.user.store_id(全系统统一约定),不可由前端入参覆盖。",
"快照字段方案:wms_order_express 表新增 delivery_order_code、store_id_snapshot、store_name_snapshot、warehouse_name_snapshot 四个快照列,列表查询无需 JOIN 订单表或货主表,仅单表查询 + SELF JOIN(主单号)。",
"主单号/子单号规则:同一 order_id 下 business_key=1 为主单号,business_key>1 为子单号,沿用系统已有约定。",
"命名空间规划:waybill.warehouse.* 本期实现(仓库侧),后续预留 waybill.store.*(货主侧)。",
"本模块一期仅提供只读查询,不涉及运单创建/修改/删除,不修改任何现有接口。"
],
"module": "waybill.warehouse"
},
{
"version": "2026.07.30-system-01",
"date": "2026-07-30",
"type": "changed",
"summary": "更新 waybill.warehouse group API 文档:list 新增 waybillType/storeId 筛选、移除 pack_status 响应字段;detail 精简 package 对象;export 响应改为纯异步任务模式(仅含 task_id/status/progress/message/update_time)",
"methods": [
"waybill.warehouse.list",
"waybill.warehouse.detail",
"waybill.warehouse.export",
"waybill.warehouse.exportTaskProgress"
],
"notes": [
"waybill.warehouse.list:新增 where.waybillType 筛选(\"main\"/\"1\"=主单号,\"child\"/\"2\"=子单号),新增 where.storeId 货主ID等值筛选。where.orderNo 标注暂不可用(待快照字段就绪)。response 移除 pack_status 字段(两表无关联,不再返回),list 字段数从 28 减至 27。",
"waybill.warehouse.detail:package 对象移除 pack_status/pack_quantity/pack_at/packer_name 四个字段,仅保留 package_material_id 和 package_material_name。description 同步去掉\"打包状态\"相关描述。",
"waybill.warehouse.export:响应简化为纯异步任务模式,data 仅含 task_id/status/progress/message/update_time,不含 total_count/current_count/result/error/download_url 等执行期字段(这些信息由 exportTaskProgress 接口返回)。export 的 where 参数同步新增 waybillType 和 storeId。",
"waybill.warehouse.exportTaskProgress:无变更,保持不变。"
],
"module": "waybill.warehouse"
}
]

File diff suppressed because it is too large Load Diff

View File

@ -162,17 +162,17 @@ function main() {
const switchOutput = runSsh(config, switchAndStartScript, { stdio: 'pipe' });
console.log(String(switchOutput || '').trim());
// 6.5. 健康检查新实例(curl 循环等待,最多 60 秒)
// 6.5. 健康检查新实例(curl 循环等待,最多 10 秒)
const oldDir = `${config.deployRoot}/${currentVersion}`;
const healthCheckScript = [
'set -euo pipefail',
`TARGET_PORT=${targetPort}`,
'for attempt in $(seq 1 30); do',
' if curl -fsS --connect-timeout 2 --max-time 4 "http://127.0.0.1:$TARGET_PORT/" >/dev/null 2>&1; then',
'for attempt in $(seq 1 5); do',
' if curl -fsS --connect-timeout 2 --max-time 3 "http://127.0.0.1:$TARGET_PORT/" >/dev/null 2>&1; then',
` echo "新实例 (${targetVersion}) 健康检查通过 (端口 $TARGET_PORT)"`,
' break',
' fi',
' if [ "$attempt" -eq 30 ]; then',
' if [ "$attempt" -eq 5 ]; then',
` echo "新实例 (${targetVersion}) 健康检查超时 (端口 $TARGET_PORT)" >&2`,
' exit 1',
' fi',
@ -184,11 +184,56 @@ function main() {
const healthOutput = runSsh(config, healthCheckScript, { stdio: 'pipe' });
console.log(String(healthOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 新实例健康检查失败: ${err.message}`);
console.warn(`[WARN] 新实例 (${targetVersion}) 可能未完全就绪,请人工确认 127.0.0.1:${targetPort} 状态`);
// 健康检查失败 → 不做切换,回滚 current.md 并清理失败的新实例
console.error(`[ERROR] 新实例健康检查失败 (10s 超时): ${err.message}`);
console.error(`[ERROR] 发布中止:不切换 Nginx upstream,不停旧实例`);
// 回滚:将 current.md 恢复为旧版本
const revertCurrentMdScript = [
'set -euo pipefail',
`printf '%s\\n' ${quoteForBash(currentVersion)} > ${quoteForBash(currentMdPath)}`,
`echo "已回滚 current.md -> ${currentVersion}"`,
].join('\n');
try {
const revertOutput = runSsh(config, revertCurrentMdScript, { stdio: 'pipe' });
console.log(String(revertOutput || '').trim());
} catch (revertErr) {
console.error(`[ERROR] 回滚 current.md 失败: ${revertErr.message}`);
}
// 清理:杀死启动失败的新实例进程
const killNewScript = [
'set -euo pipefail',
`NEW_DIR=${quoteForBash(targetDir)}`,
`NEW_VERSION=${quoteForBash(targetVersion)}`,
'NEW_PIDS=$(ps -eo pid=,args= | awk -v root="$NEW_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
'if [ -n "$NEW_PIDS" ]; then',
' echo "正在清理失败的新实例 ($NEW_VERSION): $NEW_PIDS"',
' kill $NEW_PIDS || true',
' sleep 2',
' NEW_PIDS_REMAIN=$(ps -eo pid=,args= | awk -v root="$NEW_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
' if [ -n "$NEW_PIDS_REMAIN" ]; then',
' echo "新实例仍有残留进程,强制停止: $NEW_PIDS_REMAIN"',
' kill -9 $NEW_PIDS_REMAIN || true',
' fi',
' echo "失败的新实例 ($NEW_VERSION) 已清理"',
'else',
' echo "未找到新实例 ($NEW_VERSION) 进程,无需清理"',
'fi',
].join('\n');
try {
const killOutput = runSsh(config, killNewScript, { stdio: 'pipe' });
console.log(String(killOutput || '').trim());
} catch (killErr) {
console.error(`[ERROR] 清理失败新实例进程出错: ${killErr.message}`);
}
console.error(`[ERROR] 发布失败: ${envName} -> ${config.username}@${config.host}:${targetDir}`);
console.error(`[ERROR] 旧实例 (${currentVersion}) 仍在运行,线上服务不受影响`);
process.exit(1);
}
// 6.55. 切换 Nginx upstream 端口并 reload
// 6.55. 切换 Nginx upstream 端口并 reload(仅在健康检查通过后执行)
const nginxUpstreamPath = `${config.deployRoot}/nginx-upstream.conf`;
const switchNginxScript = [
'set -euo pipefail',

View File

@ -1,255 +0,0 @@
'use strict';
const assert = require('node:assert/strict');
const schedule = require('../../../app/schedule/print_retry_compensation');
describe('test/app/schedule/print_retry_compensation.test.js', () => {
it('should scan retryable records and invoke retryFailed grouped by warehouse', async () => {
assert.equal(schedule.schedule.interval, '30s');
assert.equal(schedule.schedule.type, 'worker');
assert.equal(schedule.schedule.immediate, false);
const Op = {
and: Symbol('and'),
or: Symbol('or'),
in: Symbol('in'),
lte: Symbol('lte'),
lt: Symbol('lt'),
};
const retryCalls = [];
const ctx = {
app: {
_printRetryCompensationRunning: false,
_printRetryCompensationLastRunAt: 0,
config: {
printRetryCompensation: {
enable: true,
intervalMs: 0,
batchSize: 50,
force: false,
},
},
Sequelize: {
Op,
col(fieldName) {
return `col:${fieldName}`;
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
model: {
PrintRecord: {
async findAll(options) {
assert.equal(options.limit, 50);
assert.equal(options.raw, true);
return [
{ id: 101, warehouse_id: 1 },
{ id: 102, warehouse_id: 1 },
{ id: 201, warehouse_id: 2 },
];
},
},
},
service: {
systemMethods: {
print: {
async retryFailed(data) {
retryCalls.push(data);
return {
flag: 'success',
success_count: data.print_ids.length,
failed_count: 0,
skipped_count: 0,
};
},
},
},
},
};
await schedule.task(ctx);
assert.equal(retryCalls.length, 2);
const firstCall = retryCalls[0];
const secondCall = retryCalls[1];
assert.deepEqual(firstCall, {
print_ids: [ 101, 102 ],
warehouse_id: 1,
force: false,
});
assert.deepEqual(secondCall, {
print_ids: [ 201 ],
warehouse_id: 2,
force: false,
});
assert.equal(ctx.app._printRetryCompensationRunning, false);
});
it('should skip when disabled or already running', async () => {
let findAllCount = 0;
const ctx = {
app: {
_printRetryCompensationRunning: false,
_printRetryCompensationLastRunAt: 0,
config: {
printRetryCompensation: {
enable: false,
intervalMs: 60000,
batchSize: 10,
},
},
Sequelize: {
Op: {},
col(fieldName) {
return `col:${fieldName}`;
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
model: {
PrintRecord: {
async findAll() {
findAllCount += 1;
return [];
},
},
},
service: {
systemMethods: {
print: {
async retryFailed() {
throw new Error('should not reach');
},
},
},
},
};
await schedule.task(ctx);
assert.equal(findAllCount, 0);
ctx.app.config.printRetryCompensation.enable = true;
ctx.app._printRetryCompensationRunning = true;
await schedule.task(ctx);
assert.equal(findAllCount, 0);
});
it('should include retry_count < max_retry_count in where clause', async () => {
const Op = {
and: Symbol('and'),
or: Symbol('or'),
in: Symbol('in'),
lte: Symbol('lte'),
lt: Symbol('lt'),
};
let whereClause;
const ctx = {
app: {
_printRetryCompensationRunning: false,
_printRetryCompensationLastRunAt: 0,
config: { printRetryCompensation: { enable: true, intervalMs: 0, batchSize: 50 } },
Sequelize: { Op, col: fieldName => `col:${fieldName}` },
},
logger: { info() {}, warn() {}, error() {} },
model: {
PrintRecord: {
async findAll(options) {
whereClause = options.where;
return [];
},
},
},
service: { systemMethods: { print: { async retryFailed() {} } } },
};
await schedule.task(ctx);
const andConditions = whereClause[Op.and];
assert(Array.isArray(andConditions), 'where[Op.and] should be an array');
const retryCountCondition = andConditions.find(condition => condition && condition.retry_count);
assert(retryCountCondition, 'retry_count condition should exist in where[Op.and]');
assert.deepStrictEqual(retryCountCondition.retry_count, { [Op.lt]: 'col:max_retry_count' });
});
it('should include next_retry_at <= now in where clause', async () => {
const Op = {
and: Symbol('and'),
or: Symbol('or'),
in: Symbol('in'),
lte: Symbol('lte'),
lt: Symbol('lt'),
};
let whereClause;
const ctx = {
app: {
_printRetryCompensationRunning: false,
_printRetryCompensationLastRunAt: 0,
config: { printRetryCompensation: { enable: true, intervalMs: 0, batchSize: 50 } },
Sequelize: { Op, col: () => {} },
},
logger: { info() {}, warn() {}, error() {} },
model: {
PrintRecord: {
async findAll(options) {
whereClause = options.where;
return [];
},
},
},
service: { systemMethods: { print: { async retryFailed() {} } } },
};
await schedule.task(ctx);
const andConditions = whereClause[Op.and];
assert(Array.isArray(andConditions), 'where[Op.and] should be an array');
const nextRetryAtCondition = andConditions.find(condition => condition && condition.next_retry_at);
assert(nextRetryAtCondition, 'next_retry_at condition should exist in where[Op.and]');
assert(nextRetryAtCondition.next_retry_at[Op.lte], 'should use lte operator');
assert(nextRetryAtCondition.next_retry_at[Op.lte] instanceof Date, 'should compare with a Date object');
});
it('should skip invalid records and not trigger retryFailed', async () => {
let retryFailedCalled = false;
const ctx = {
app: {
_printRetryCompensationRunning: false,
_printRetryCompensationLastRunAt: 0,
config: { printRetryCompensation: { enable: true, intervalMs: 0, batchSize: 50 } },
Sequelize: { Op: {}, col: () => {} },
},
logger: { info() {}, warn() {}, error() {} },
model: {
PrintRecord: {
async findAll() {
return [
{ id: 0, warehouse_id: 1 },
{ id: 1, warehouse_id: 0 },
{ id: -1, warehouse_id: 1 },
{ id: 1, warehouse_id: -1 },
];
},
},
},
service: {
systemMethods: {
print: {
async retryFailed() {
retryFailedCalled = true;
},
},
},
},
};
await schedule.task(ctx);
assert.equal(retryFailedCalled, false, 'retryFailed should not be called for invalid records');
});
});

View File

@ -1187,203 +1187,6 @@ describe('test/app/service/systemMethods/print.send.test.js', () => {
assert.equal(calls.sendToComputerPayloads.length, 0);
});
it('retryFailed 应补打 failed 记录并创建新记录', async () => {
const sourceRecordId = 12001;
const { ctx, calls, state } = createContext({
initialPrintRecords: [
{
id: sourceRecordId,
warehouse_id: 100000,
computer_id: 'PC-STATION-001',
printer: 'PRN-STO',
type: 'express',
status: 'failed',
send_status: 'send_failed',
print_status: 'unknown',
data: {
printer: 'PRN-STO',
component: '菜鸟',
type: 'express',
data: {
task: {
taskID: 'OLD_TASK_ID',
documents: [],
},
},
},
request_code: 'REQ-RETRY-001',
wave_id: 11,
wave_no: 'WAVE-11',
platform_code: 'cainiao',
platform_name: '菜鸟平台',
sys_logistics_code: 'STO',
sys_logistics_name: '申通',
},
],
sendToComputer: async payload => {
calls.sendToComputerPayloads.push(payload);
return { status: 'success' };
},
});
const service = new PrintService(ctx);
const result = await service.retryFailed({
print_ids: [ sourceRecordId ],
});
assert.equal(result.flag, 'success');
assert.equal(result.success_count, 1);
assert.equal(result.failed_count, 0);
assert.equal(result.skipped_count, 0);
assert.equal(result.retried.length, 1);
assert.equal(result.retried[0].source_print_id, sourceRecordId);
assert.equal(result.retried[0].status, 'sent');
assert.equal(calls.printRecordCreatePayloads.length, 1);
assert.equal(calls.sendToComputerPayloads.length, 1);
assert.equal(calls.printRecordCreatePayloads[0].retry_of_print_id, sourceRecordId);
const newRecordId = result.retried[0].new_print_id;
const newRecord = state.printRecordsById[newRecordId];
assert.ok(newRecord);
assert.equal(newRecord.retry_of_print_id, sourceRecordId);
assert.equal(newRecord.status, 'sent');
assert.equal(newRecord.send_status, 'sent');
assert.equal(newRecord.print_status, 'printed');
assert.notEqual(newRecord.data.data.task.taskID, 'OLD_TASK_ID');
assert.equal(newRecord.data.data.task.taskID, result.retried[0].task_code);
assert.equal(state.printRecordsById[sourceRecordId].status, 'failed');
});
it('retryFailed 应跳过 sent/printed 记录', async () => {
const sourceRecordId = 12002;
const { ctx, calls } = createContext({
initialPrintRecords: [
{
id: sourceRecordId,
warehouse_id: 100000,
computer_id: 'PC-STATION-001',
printer: 'PRN-STO',
type: 'express',
status: 'sent',
send_status: 'sent',
print_status: 'printed',
data: {
printer: 'PRN-STO',
component: '菜鸟',
type: 'express',
data: {
task: {
taskID: 'TASK-SENT-001',
documents: [],
},
},
},
},
],
});
const service = new PrintService(ctx);
const result = await service.retryFailed({
print_ids: [ sourceRecordId ],
});
assert.equal(result.flag, 'success');
assert.equal(result.success_count, 0);
assert.equal(result.failed_count, 0);
assert.equal(result.skipped_count, 1);
assert.equal(result.skipped[0].print_id, sourceRecordId);
assert.match(result.skipped[0].reason, /跳过|不允许补打/);
assert.equal(calls.printRecordCreatePayloads.length, 0);
assert.equal(calls.sendToComputerPayloads.length, 0);
});
it('retryFailed 部分成功时应返回正确统计', async () => {
const sourceSuccessId = 12003;
const sourceFailId = 12004;
const sourceSkipId = 12005;
const { ctx, calls, state } = createContext({
initialPrintRecords: [
{
id: sourceSuccessId,
warehouse_id: 100000,
computer_id: 'PC-STATION-001',
printer: 'PRN-STO',
type: 'express',
status: 'failed',
send_status: 'send_failed',
print_status: 'unknown',
data: {
printer: 'PRN-STO',
component: '菜鸟',
type: 'express',
data: { task: { taskID: 'TASK-OLD-SUCCESS', documents: [] } },
},
},
{
id: sourceFailId,
warehouse_id: 100000,
computer_id: 'PC-STATION-001',
printer: 'PRN-YTO',
type: 'express',
status: 'failed',
send_status: 'send_failed',
print_status: 'unknown',
data: {
printer: 'PRN-YTO',
component: '拼多多',
type: 'express',
data: { task: { taskID: 'TASK-OLD-FAIL', documents: [] } },
},
},
{
id: sourceSkipId,
warehouse_id: 100000,
computer_id: 'PC-STATION-001',
printer: 'PRN-STO',
type: 'express',
status: 'sent',
send_status: 'sent',
print_status: 'unknown',
data: {
printer: 'PRN-STO',
component: '菜鸟',
type: 'express',
data: { task: { taskID: 'TASK-SKIP', documents: [] } },
},
},
],
sendToComputer: async payload => {
calls.sendToComputerPayloads.push(payload);
if (calls.sendToComputerPayloads.length === 2) {
return {
status: 'failure',
error: '发送失败-模拟',
};
}
return { status: 'success' };
},
});
const service = new PrintService(ctx);
const result = await service.retryFailed({
print_ids: [ sourceSuccessId, sourceFailId, sourceSkipId ],
});
assert.equal(result.flag, 'success');
assert.equal(result.success_count, 1);
assert.equal(result.failed_count, 1);
assert.equal(result.skipped_count, 1);
assert.equal(result.retried.length, 2);
assert.equal(calls.printRecordCreatePayloads.length, 2);
assert.equal(calls.sendToComputerPayloads.length, 2);
assert.equal(state.printRecordsById[sourceSuccessId].status, 'failed');
assert.equal(state.printRecordsById[sourceFailId].status, 'failed');
assert.equal(state.printRecordsById[sourceSkipId].status, 'sent');
const failedRetryItem = result.retried.find(item => item.source_print_id === sourceFailId);
assert.ok(failedRetryItem);
assert.equal(failedRetryItem.status, 'failed');
});
it('handlePrintCallback success 回调应更新为 printed', async () => {
const { ctx, state, calls } = createContext();
const service = new PrintService(ctx);