Compare commits

...

7 Commits

40 changed files with 5273 additions and 231 deletions

View File

@ -0,0 +1,26 @@
'use strict';
/**
* 出站回调 method 注册表(代码注册,管理端多选列表经拉取接口透出)。
*
* method 即出站路由键:wms_api_app.callback_functions 勾选后,
* 出站回调按 warehouse_id + method 自动路由到承接该 method 的应用;
* callback_functions 为空/未勾选 = 不承接任何回调。
*
* 新增出站回调能力时在此登记 method,管理端接口自动可见。
*/
const CALLBACK_FUNCTIONS = [
{
method: 'notify.reply',
name: '站内信通知回执',
description: '站内信/系统通知/回执出站推送(warehouseNotify 与 inbox 回执共用)',
},
];
/** method 合法值集合(供管理端 create/update 校验) */
const CALLBACK_METHOD_SET = new Set(CALLBACK_FUNCTIONS.map(item => item.method));
module.exports = {
CALLBACK_FUNCTIONS,
CALLBACK_METHOD_SET,
};

View File

@ -70,6 +70,11 @@ module.exports = app => {
allowNull: true,
comment: 'API回调通知URL',
},
callback_functions: {
type: JSON,
allowNull: true,
comment: '承接的出站回调 method 列表(空/未勾选=不承接任何回调;按 method 自动路由)',
},
qimen_app_key: {
type: STRING(100),
allowNull: true,

View File

@ -408,6 +408,12 @@ module.exports = app => {
defaultValue: 0,
comment: '总重量(g)',
},
packages_weight: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '所有包裹总重量(g)',
},
items_hash: {
type: CHAR(32),
allowNull: false,

View File

@ -1,12 +1,13 @@
'use strict';
/**
* 库存盘点明细表模型。
* 库存盘点明细表模型(仅存盘点商品:stock_id + 商品快照)。
* 库位/数量等盘点作业信息存放在 wms_stock_check_record。
* @param {import('egg').Application} app Egg 应用实例。
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
*/
module.exports = app => {
const { BIGINT, STRING, INTEGER, DATE, TINYINT } = app.Sequelize;
const { BIGINT, STRING, INTEGER } = app.Sequelize;
const StockCheckDetail = app.model.define('wms_stock_check_detail', {
id: {
@ -30,16 +31,6 @@ module.exports = app => {
allowNull: false,
comment: '库存商品ID,关联 wms_stock_warehouse.id',
},
location_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '库位ID,关联 wms_location_space.id;无库位商品为空',
},
location_code: {
type: STRING(50),
allowNull: true,
comment: '库位编码快照(space_code)',
},
item_code: {
type: STRING(50),
allowNull: false,
@ -64,53 +55,16 @@ module.exports = app => {
type: INTEGER(12),
allowNull: false,
defaultValue: 0,
comment: '账面数量(生成盘点任务时的系统库存快照)',
},
check_quantity: {
type: INTEGER(12),
allowNull: true,
comment: '实盘数量;未盘点时为空',
},
diff_quantity: {
type: INTEGER(12),
allowNull: true,
comment: '差异数量 = 实盘数量 - 账面数量;正数盘盈,负数盘亏;未盘点时为空',
},
is_diff: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否有差异:1=有差异,0=无差异',
},
status: {
type: STRING(20),
allowNull: false,
defaultValue: 'unchecked',
comment: '明细状态:unchecked=未盘,checked=已盘,confirmed=已确认',
},
checker_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '盘点人账户ID',
},
checker_name: {
type: STRING(50),
allowNull: true,
comment: '盘点人名称快照',
},
checked_at: {
type: DATE,
allowNull: true,
comment: '盘点时间',
comment: '账面数量快照(生成盘点明细时的系统库存,用于差异对比)',
},
remark: {
type: STRING(500),
allowNull: true,
comment: '备注(如差异原因说明)',
comment: '备注',
},
}, {
tableName: 'wms_stock_check_detail',
comment: '库存盘点明细表',
comment: '库存盘点明细表(盘点商品清单)',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
@ -119,13 +73,11 @@ module.exports = app => {
{ name: 'idx_check_id', fields: [ 'check_id' ] },
{ name: 'idx_warehouse_stock', fields: [ 'warehouse_id', 'stock_id' ] },
{ name: 'idx_stock_id', fields: [ 'stock_id' ] },
{ name: 'idx_location_id', fields: [ 'location_id' ] },
{ name: 'idx_is_diff', fields: [ 'is_diff' ] },
],
});
StockCheckDetail.associate = function() {
const { StockCheck, StockWarehouse } = app.model;
const { StockCheck, StockWarehouse, StockCheckRecord } = app.model;
// 关联盘点主表
StockCheckDetail.belongsTo(StockCheck, {
foreignKey: 'check_id',
@ -136,6 +88,11 @@ module.exports = app => {
foreignKey: 'stock_id',
as: 'stockWarehouse',
});
// 一条明细对应多条盘点作业记录
StockCheckDetail.hasMany(StockCheckRecord, {
foreignKey: 'detail_id',
as: 'records',
});
};
return StockCheckDetail;

View File

@ -0,0 +1,111 @@
'use strict';
/**
* 库存盘点作业记录表模型(存储盘点的库位、数量信息)。
* 一个盘点明细(商品)可在多个库位多次上报,每次上报一条记录。
* @param {import('egg').Application} app Egg 应用实例。
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
*/
module.exports = app => {
const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize;
const StockCheckRecord = app.model.define('wms_stock_check_record', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键',
},
check_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '关联盘点主表 wms_stock_check.id(冗余,便于按任务查记录)',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(冗余,隔离查询)',
},
detail_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '关联盘点明细 wms_stock_check_detail.id',
},
stock_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '库存商品ID(冗余,商品维度查询),关联 wms_stock_warehouse.id',
},
location_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '库位ID,关联 wms_location_space.id;库位编码匹配时回填,未匹配为空',
},
location_code: {
type: STRING(50),
allowNull: false,
defaultValue: '',
comment: '库位编码(盘点上报的库位,空串表示无库位分组)',
},
quantity: {
type: INTEGER(12),
allowNull: false,
defaultValue: 0,
comment: '实盘数量(不小于0的整数)',
},
checker_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '盘点人账户ID',
},
checker_name: {
type: STRING(50),
allowNull: true,
comment: '盘点人名称快照',
},
checked_at: {
type: DATE,
allowNull: true,
comment: '上报时间',
},
remark: {
type: STRING(500),
allowNull: true,
comment: '备注',
},
}, {
tableName: 'wms_stock_check_record',
comment: '库存盘点作业记录表(库位+数量)',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: false,
indexes: [
{ name: 'idx_check_id', fields: [ 'check_id' ] },
{ name: 'idx_detail_id', fields: [ 'detail_id' ] },
{ name: 'idx_stock_id', fields: [ 'stock_id' ] },
{ name: 'idx_warehouse_location', fields: [ 'warehouse_id', 'location_code' ] },
],
});
StockCheckRecord.associate = function() {
const { StockCheck, StockCheckDetail, StockWarehouse } = app.model;
// 关联盘点主表
StockCheckRecord.belongsTo(StockCheck, {
foreignKey: 'check_id',
as: 'check',
});
// 关联盘点明细
StockCheckRecord.belongsTo(StockCheckDetail, {
foreignKey: 'detail_id',
as: 'detail',
});
// 关联库存商品
StockCheckRecord.belongsTo(StockWarehouse, {
foreignKey: 'stock_id',
as: 'stockWarehouse',
});
};
return StockCheckRecord;
};

View File

@ -43,6 +43,20 @@ module.exports = app => {
type: TEXT,
comment: '打包要求',
},
pick_requirements: {
type: TEXT,
comment: '拣货要求',
},
recheck_requirements: {
type: TEXT,
comment: '眼球复核要求',
},
merge_requirements: {
type: CHAR(1),
allowNull: false,
defaultValue: 'Y',
comment: '要求是否合并:Y=合并(拣货/复核要求统一输出打包要求),N=不合并',
},
brand_name: {
type: STRING(100),

View File

@ -260,7 +260,7 @@ ${historyContext}
- searchStock/searchWarehouseStock 返回的 image_url 为图片URL数组(可能多张),has_images 为 true 时给出链接
- searchStock/searchWarehouseStock 返回的 barcodes 为关联条码,回复时可列出帮助核对
- searchStock/searchWarehouseStock 返回的管理标识 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt 分别表示SN管理/效期管理/批次管理
- searchStock/searchWarehouseStock 返回的 box_spec 为箱规(长宽高体积毛净重装箱数),packing_requirements 为打包要求,用户问及时告知
- searchStock/searchWarehouseStock 返回的 box_spec 为箱规(长宽高体积毛净重装箱数),packing_requirements 为打包要求,pick_requirements 为拣货要求、recheck_requirements 为眼球复核要求(merge_requirements=Y 要求合并时均与打包要求一致),用户问及时告知
- searchStock/searchWarehouseStock 返回的 prohibited_type 为违禁品类型,非空时告知用户
- 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择
- 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史

View File

@ -419,7 +419,7 @@ class InboxFunctionsService extends Service {
});
this.register('searchStock', {
description: '搜索仓库商品(货主级)。返回商品ID/编码/名称/品牌/单位/毛重/管理标识/库存/图片/关联条码/箱规/违禁品/打包要求',
description: '搜索仓库商品(货主级)。返回商品ID/编码/名称/品牌/单位/毛重/管理标识/库存/图片/关联条码/箱规/违禁品/打包要求/拣货要求/眼球复核要求/要求合并',
params: {
keyword: { type: 'string', required: true, description: '搜索关键词:商品编码(item_code)、条码(barcode)、商品名称(item_name)' },
},
@ -455,7 +455,7 @@ class InboxFunctionsService extends Service {
}
const items = await ctx.model.StockWarehouse.findAll({
attributes: [ 'id', 'item_code', 'item_name', 'brand_name', 'stock_unit', 'gross_weight', 'quantity', 'locked_quantity', 'is_images', 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt', 'prohibited_id', 'enable_box_spec', 'box_gross_weight', 'box_net_weight', 'box_length', 'box_width', 'box_height', 'quantity_per_box', 'box_volume', 'packing_requirements' ],
attributes: [ 'id', 'item_code', 'item_name', 'brand_name', 'stock_unit', 'gross_weight', 'quantity', 'locked_quantity', 'is_images', 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt', 'prohibited_id', 'enable_box_spec', 'box_gross_weight', 'box_net_weight', 'box_length', 'box_width', 'box_height', 'quantity_per_box', 'box_volume', 'packing_requirements', 'pick_requirements', 'recheck_requirements', 'merge_requirements' ],
where: {
store_id: storeId,
[Op.or]: orConditions,
@ -548,6 +548,13 @@ class InboxFunctionsService extends Service {
net_weight: i.box_net_weight || 0, quantity_per_box: i.quantity_per_box || 0,
} : null,
packing_requirements: i.packing_requirements || '',
pick_requirements: (i.merge_requirements || 'Y') === 'Y'
? (i.packing_requirements || '')
: (i.pick_requirements || ''),
recheck_requirements: (i.merge_requirements || 'Y') === 'Y'
? (i.packing_requirements || '')
: (i.recheck_requirements || ''),
merge_requirements: i.merge_requirements || 'Y',
prohibited_type: prohibitedMap[i.prohibited_id] || '',
})),
},
@ -559,7 +566,7 @@ class InboxFunctionsService extends Service {
});
this.register('searchWarehouseStock', {
description: '搜索仓库商品(仓库级,不限货主)。返回商品ID/货主/编码/名称/条码/品牌/单位/毛重/管理标识/库存/图片/关联条码/箱规/违禁品/打包要求',
description: '搜索仓库商品(仓库级,不限货主)。返回商品ID/货主/编码/名称/条码/品牌/单位/毛重/管理标识/库存/图片/关联条码/箱规/违禁品/打包要求/拣货要求/眼球复核要求/要求合并',
params: {
keyword: { type: 'string', required: true, description: '搜索关键词:商品编码(item_code)、条码(barcode)、商品名称(item_name)' },
},
@ -594,7 +601,7 @@ class InboxFunctionsService extends Service {
}
const items = await ctx.model.StockWarehouse.findAll({
attributes: [ 'id', 'store_id', 'item_code', 'item_name', 'brand_name', 'stock_unit', 'gross_weight', 'quantity', 'locked_quantity', 'is_images', 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt', 'prohibited_id', 'enable_box_spec', 'box_gross_weight', 'box_net_weight', 'box_length', 'box_width', 'box_height', 'quantity_per_box', 'box_volume', 'packing_requirements' ],
attributes: [ 'id', 'store_id', 'item_code', 'item_name', 'brand_name', 'stock_unit', 'gross_weight', 'quantity', 'locked_quantity', 'is_images', 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt', 'prohibited_id', 'enable_box_spec', 'box_gross_weight', 'box_net_weight', 'box_length', 'box_width', 'box_height', 'quantity_per_box', 'box_volume', 'packing_requirements', 'pick_requirements', 'recheck_requirements', 'merge_requirements' ],
where: {
[Op.or]: orConditions,
},
@ -686,6 +693,13 @@ class InboxFunctionsService extends Service {
net_weight: i.box_net_weight || 0, quantity_per_box: i.quantity_per_box || 0,
} : null,
packing_requirements: i.packing_requirements || '',
pick_requirements: (i.merge_requirements || 'Y') === 'Y'
? (i.packing_requirements || '')
: (i.pick_requirements || ''),
recheck_requirements: (i.merge_requirements || 'Y') === 'Y'
? (i.packing_requirements || '')
: (i.recheck_requirements || ''),
merge_requirements: i.merge_requirements || 'Y',
prohibited_type: prohibitedMap[i.prohibited_id] || '',
})),
},
@ -719,7 +733,7 @@ class InboxFunctionsService extends Service {
'id', 'delivery_order_code', 'source_platform_code', 'source_order_codes',
'store_id', 'warehouse_id', 'status', 'step',
'name', 'mobile', 'province', 'city', 'area', 'detail_address',
'items_count', 'items_total', 'items_weight',
'items_count', 'items_total', 'items_weight', 'packages_weight',
'express_code', 'logistics_name', 'logistics_code',
'total_amount', 'freight',
'create_at', 'updated_at', 'delivery_time',
@ -845,6 +859,8 @@ class InboxFunctionsService extends Service {
// 重量信息(必须区分说明)
items_weight: found.items_weight || 0,
items_weight_note: '商品总重量(克),订单中所有商品SKU的合计重量',
packages_weight: found.packages_weight || 0,
packages_weight_note: '所有包裹总重量(克),订单全部运单称重重量之和',
has_waybill: hasWaybill,
has_waybill_note: hasWaybill ? '' : '该订单尚未分配运单号,无实际称重重量',
waybills: linkedExpress.map(e => ({

View File

@ -527,7 +527,8 @@ class InboxProcessorService extends Service {
}
const ackExtId = `sys:ack:${extId}`;
const callbackConfig = await this.getApiAppCallbackConfig(warehouseId);
// 多候选路由:按 method 查询全部承接应用(id 升序),逐个尝试直到成功
const callbackConfigs = await this.listApiAppCallbackConfigs(warehouseId, 'notify.reply');
// 重推(reuse_message_id>0):直接复用原记录,避免按 sys:ack: 前缀另建一条记录——
// 那样会让原记录(如 sys:notice:* 系统通知)状态永远停留在失败/待推送,且每次重推都新建记录
// 声明在 try 之外:异常兜底回写失败状态时仍需定位到该记录
@ -578,9 +579,8 @@ class InboxProcessorService extends Service {
}
}
const callbackUrl = callbackConfig.url;
if (callbackUrl) {
const crypto = require('crypto');
const hasCallbackConfigs = callbackConfigs.length > 0;
if (hasCallbackConfigs) {
const method = 'notify.reply';
const notifyBody = {
code: 200,
@ -600,92 +600,53 @@ class InboxProcessorService extends Service {
},
};
const bodyJson = JSON.stringify(notifyBody);
const timestamp = Math.floor(Date.now() / 1000);
const appKey = callbackConfig.appKey || '';
const appSecret = callbackConfig.appSecret || '';
// MD5 签名:MD5(appSecret + timestamp + bodyJson)
const sign = appSecret
? crypto.createHash('md5').update(appSecret + timestamp + bodyJson).digest('hex')
: '';
const urlWithSign = `${callbackUrl}?app_key=${encodeURIComponent(appKey)}&method=${encodeURIComponent(method)}&timestamp=${timestamp}&sign=${encodeURIComponent(sign)}`;
const curlResult = await ctx.curl(urlWithSign, {
method: 'POST', dataType: 'json', contentType: 'json',
data: notifyBody,
headers: { 'Content-Type': 'application/json' }, timeout: 10000,
});
// HTTP 200 且 body.code=200 → 推送成功
const pushOk = curlResult && curlResult.status === 200
&& (!curlResult.data || curlResult.data.code === undefined || curlResult.data.code === 200);
// 记录出站通知日志到 wms_warehouse_log
try {
const { WarehouseLog } = ctx.model;
await WarehouseLog.create({
log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'),
app_key: appKey || null,
method,
warehouse_id: warehouseId || null,
url: urlWithSign || null,
http_status: curlResult ? curlResult.status : null,
body: JSON.stringify(notifyBody).substring(0, 65535),
result: curlResult ? JSON.stringify(curlResult.data || {}).substring(0, 65535) : '',
use_time: Date.now() - timestamp * 1000,
created_at: new Date(),
});
} catch (logErr) {
ctx.logger.error('[notify-log] 日志写入失败: ' + logErr.message);
}
if (pushOk) {
await InboxMessage.update(
{
push_status: 2,
push_response: { http_status: curlResult.status, body: curlResult.data || null },
pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'),
},
{ where: { id: outboundId } }
);
// 同步更新原入站消息的推送状态
if (parentId) {
// 逐个候选尝试:第一个成功即止;全部失败回写失败状态且不改动接口配置
for (const callbackConfig of callbackConfigs) {
const attempt = await this.pushReplyOnce({ callbackConfig, warehouseId, method, notifyBody });
if (attempt.pushOk) {
await InboxMessage.update(
{
push_status: 2,
push_response: { http_status: attempt.httpStatus, body: attempt.response || null },
pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'),
},
{ where: { id: parentId } }
{ where: { id: outboundId } }
);
// 同步更新原入站消息的推送状态
if (parentId) {
await InboxMessage.update(
{
push_status: 2,
pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'),
},
{ where: { id: parentId } }
);
}
return true;
}
return true;
}
// 推送失败:回写状态和原因
// 全部候选尝试失败:回写状态和原因
await InboxMessage.update(
{
push_status: 3,
push_response: {
http_status: curlResult ? curlResult.status : null,
body: curlResult ? (curlResult.data || null) : null,
error: curlResult ? '回调返回非200或code非200' : '回调无响应',
error: `全部 ${callbackConfigs.length} 个回调应用尝试失败`,
},
},
{ where: { id: outboundId } }
);
return false;
}
// 未配置回调地址:回写状态
// 无应用承接该回调:回写状态
await InboxMessage.update(
{
push_status: 3,
push_response: { error: '未配置回调地址(wms_api_app.callback_url为空)' },
push_response: { error: '无应用承接该回调(callback_functions 未勾选或应用未启用)' },
},
{ where: { id: outboundId } }
);
ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,回写失败状态 ext_id=${extId}`);
ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 无应用承接回调 notify.reply,回写失败状态 ext_id=${extId}`);
return false;
} catch (error) {
ctx.logger.warn(`[inbox processor] 回执写入失败: ${error.message}`);
@ -859,38 +820,162 @@ class InboxProcessorService extends Service {
/**
* 获取仓库 ApiApp 回调配置(URL + 签名凭证)。
* 兼容旧调用:默认取承接 notify.reply 的首个应用。
*
* @param {number} warehouseId 仓库ID。
* @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调地址与签名凭证,未配置/异常时各字段为 null。
*/
async getApiAppCallbackConfig(warehouseId) {
return await this.getApiAppCallbackConfigByMethod(warehouseId, 'notify.reply');
}
/**
* 按 method 获取仓库 ApiApp 回调配置(取候选列表中首个应用)。
*
* @param {number} warehouseId 仓库ID。
* @param {string} method 出站 method。
* @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调地址与签名凭证,未配置/异常时各字段为 null。
*/
async getApiAppCallbackConfigByMethod(warehouseId, method) {
const list = await this.listApiAppCallbackConfigs(warehouseId, method);
const first = list[0] || {};
return {
url: first.url || null,
appKey: first.appKey || null,
appSecret: first.appSecret || null,
};
}
/**
* 查询仓库下承接指定 method 的全部回调候选应用(按 id 升序)。
* callback_functions 为空/未勾选的应用不承接任何回调(不放行)。
*
* @param {number} warehouseId 仓库ID。
* @param {string} method 出站 method。
* @return {Promise<Array<{appId: number, url: string|null, appKey: string|null, appSecret: string|null}>>} 候选列表。
*/
async listApiAppCallbackConfigs(warehouseId, method) {
const { ctx } = this;
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
return { url: null, appKey: null, appSecret: null };
return [];
}
const apiAppModel = ctx.model && ctx.model.ApiApp;
if (!apiAppModel || typeof apiAppModel.findAll !== 'function') {
return [];
}
try {
const apiApp = await ctx.model.ApiApp.findOne({
attributes: [ 'callback_url', 'self_app_key', 'self_app_secret' ],
const rows = await apiAppModel.findAll({
attributes: [ 'id', 'callback_url', 'self_app_key', 'self_app_secret', 'callback_functions' ],
where: {
warehouse_id: warehouseId,
interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID,
is_enabled: 1,
},
order: [[ 'id', 'ASC' ]],
raw: true,
});
return {
url: (apiApp && apiApp.callback_url) || null,
appKey: (apiApp && apiApp.self_app_key) || null,
appSecret: (apiApp && apiApp.self_app_secret) || null,
};
const methodStr = String(method || '').trim();
return rows
.filter(row => {
let list = row.callback_functions;
if (typeof list === 'string') {
try {
list = JSON.parse(list);
} catch (error) {
list = null;
}
}
return Array.isArray(list)
&& list.map(item => String(item || '').trim()).includes(methodStr);
})
.map(row => ({
appId: Number(row.id),
url: row.callback_url || null,
appKey: row.self_app_key || null,
appSecret: row.self_app_secret || null,
}));
} catch (error) {
ctx.logger.warn(`[inbox processor] 查询回调配置失败: ${error.message}`);
return { url: null, appKey: null, appSecret: null };
ctx.logger.warn(`[inbox processor] 查询回调配置列表失败: ${error.message}`);
return [];
}
}
/**
* 单次回执推送尝试(回执专用协议:MD5(appSecret+timestamp+bodyJson) + POST)。
* 每次尝试均写 wms_warehouse_log,失败不改动接口配置。
*
* @param {Object} options 尝试参数。
* @param {Object} options.callbackConfig 候选应用 { appId, url, appKey, appSecret }。
* @param {number} options.warehouseId 仓库ID。
* @param {string} options.method 出站 method。
* @param {Object} options.notifyBody 推送体(已组装)。
* @return {Promise<Object>} { pushOk, httpStatus, response, error }。
*/
async pushReplyOnce({ callbackConfig, warehouseId, method, notifyBody }) {
const { ctx } = this;
const crypto = require('crypto');
const callbackUrl = callbackConfig.url;
const bodyJson = JSON.stringify(notifyBody);
const timestamp = Math.floor(Date.now() / 1000);
const appKey = callbackConfig.appKey || '';
const appSecret = callbackConfig.appSecret || '';
// MD5 签名:MD5(appSecret + timestamp + bodyJson)
const sign = appSecret
? crypto.createHash('md5').update(appSecret + timestamp + bodyJson).digest('hex')
: '';
const urlWithSign = `${callbackUrl}?app_key=${encodeURIComponent(appKey)}&method=${encodeURIComponent(method)}&timestamp=${timestamp}&sign=${encodeURIComponent(sign)}`;
const startTime = Date.now();
let curlResult = null;
let error = null;
try {
curlResult = await ctx.curl(urlWithSign, {
method: 'POST', dataType: 'json', contentType: 'json',
data: notifyBody,
headers: { 'Content-Type': 'application/json' }, timeout: 10000,
});
} catch (curlError) {
error = curlError;
}
// HTTP 200 且 body.code=200 → 推送成功
const pushOk = !!curlResult && curlResult.status === 200
&& (!curlResult.data || curlResult.data.code === undefined || curlResult.data.code === 200);
// 记录出站通知日志到 wms_warehouse_log(每次尝试均记录)
try {
const { WarehouseLog } = ctx.model;
await WarehouseLog.create({
log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'),
app_key: appKey || null,
method,
warehouse_id: warehouseId || null,
url: urlWithSign || null,
http_status: curlResult ? curlResult.status : null,
body: bodyJson.substring(0, 65535),
result: curlResult
? JSON.stringify(curlResult.data || {}).substring(0, 65535)
: 'Error: ' + (error ? error.message : ''),
use_time: Date.now() - startTime,
created_at: new Date(),
});
} catch (logErr) {
ctx.logger.error('[notify-log] 日志写入失败: ' + logErr.message);
}
return {
pushOk,
httpStatus: curlResult ? curlResult.status : null,
response: curlResult ? (curlResult.data || null) : null,
error: error ? error.message : (pushOk ? null : '回调返回非200或code非200'),
};
}
/**
* 获取仓库 ApiApp 回调地址(兼容旧调用)。
* @param {number} warehouseId 仓库ID。

View File

@ -45,7 +45,7 @@ class ApiAppService extends MainService {
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',
'self_ip_whitelist', 'callback_url', 'callback_functions', 'interface_type_id',
'rate_limit', 'sign_method', 'is_enabled', 'created_at', 'updated_at',
],
where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: defaultTypeId },
@ -112,6 +112,17 @@ class ApiAppService extends MainService {
return this.success('重新生成成功', result);
} catch (e) { return this.fail(e.message); }
}
/**
* 拉取出站回调 method 注册表(管理端多选列表)。
* @return {Promise<Object>} { list: [{method,name,description}], total }。
*/
async listCallbackFunctions() {
try {
const result = this.service.systems.apiApp.listCallbackFunctions();
return this.success('获取成功', result);
} catch (e) { return this.fail(e.message); }
}
}
module.exports = ApiAppService;

View File

@ -39,7 +39,7 @@ const ORDER_LIST_BASE_ATTRIBUTES = [
'province', 'city', 'area', 'town', 'detail_address',
'id_type', 'id_number',
'sync_status',
'items', 'items_count', 'items_total', 'items_weight',
'items', 'items_count', 'items_total', 'items_weight', 'packages_weight',
'wave_id',
'wave_no',
'wave_strategy_version',
@ -1991,7 +1991,8 @@ class OrderBaseService extends MainService {
'id', 'item_code', 'item_name', 'sku_property',
'quantity', 'locked_quantity', 'is_batch_mgmt',
'is_shelf_life_mgmt', 'is_images',
'store_id', 'packing_requirements', 'stock_unit',
'store_id', 'packing_requirements', 'pick_requirements',
'recheck_requirements', 'merge_requirements', 'stock_unit',
],
raw: true,
}),
@ -2053,6 +2054,13 @@ class OrderBaseService extends MainService {
is_images: row.is_images || 'N',
store_id: row.store_id != null ? Number(row.store_id) : 0,
packing_requirements: row.packing_requirements || '',
pick_requirements: (row.merge_requirements || 'Y') === 'Y'
? (row.packing_requirements || '')
: (row.pick_requirements || ''),
recheck_requirements: (row.merge_requirements || 'Y') === 'Y'
? (row.packing_requirements || '')
: (row.recheck_requirements || ''),
merge_requirements: row.merge_requirements || 'Y',
stock_unit: row.stock_unit || '',
image_url: fallbackImageUrlMap.get(row.id) || [],
barcodes: fallbackBarcodeMap.get(row.id) || [],
@ -2084,6 +2092,9 @@ class OrderBaseService extends MainService {
is_images: 'N',
store_id: 0,
packing_requirements: '',
pick_requirements: '',
recheck_requirements: '',
merge_requirements: 'Y',
stock_unit: '',
image_url: [],
barcodes: [],
@ -2107,6 +2118,9 @@ class OrderBaseService extends MainService {
is_images: stockDetail.is_images || 'N',
store_id: stockDetail.store_id != null ? Number(stockDetail.store_id) : 0,
packing_requirements: stockDetail.packing_requirements || '',
pick_requirements: stockDetail.pick_requirements || '',
recheck_requirements: stockDetail.recheck_requirements || '',
merge_requirements: stockDetail.merge_requirements || 'Y',
stock_unit: stockDetail.stock_unit || '',
image_url: Array.isArray(stockDetail.image_url) ? [ ...stockDetail.image_url ] : [],
barcodes: Array.isArray(stockDetail.barcodes) ? [ ...stockDetail.barcodes ] : [],

View File

@ -301,7 +301,7 @@ class DeliveryOrderService extends OrderBaseService {
'name', 'mobile', 'province', 'city', 'area', 'detail_address',
'buyer_nick', 'seller_nick', 'shop_nick',
'total_amount', 'item_amount', 'freight',
'items_count', 'items_weight',
'items_count', 'items_weight', 'packages_weight',
'wave_no', 'delivery_time', 'create_at',
],
where: whereClause,
@ -371,6 +371,7 @@ class DeliveryOrderService extends OrderBaseService {
buyer_nick: order.buyer_nick || '', seller_nick: order.seller_nick || '', shop_nick: order.shop_nick || '',
total_amount: order.total_amount || 0, item_amount: order.item_amount || 0, freight: order.freight || 0,
items_count: order.items_count || 0, items_weight: order.items_weight || 0,
packages_weight: order.packages_weight || 0,
wave_no: order.wave_no || '',
delivery_time: order.delivery_time ? app.formatDate(order.delivery_time) : null,
create_at: order.create_at ? app.formatDate(order.create_at) : null,
@ -396,6 +397,7 @@ class DeliveryOrderService extends OrderBaseService {
buyer_nick: order.buyer_nick || '', seller_nick: order.seller_nick || '', shop_nick: order.shop_nick || '',
total_amount: order.total_amount || 0, item_amount: order.item_amount || 0, freight: order.freight || 0,
items_count: order.items_count || 0, items_weight: order.items_weight || 0,
packages_weight: order.packages_weight || 0,
wave_no: order.wave_no || '',
delivery_time: order.delivery_time ? app.formatDate(order.delivery_time) : null,
create_at: order.create_at ? app.formatDate(order.create_at) : null,
@ -453,7 +455,7 @@ class DeliveryOrderService extends OrderBaseService {
'name', 'mobile', 'province', 'city', 'area', 'detail_address',
'buyer_nick', 'seller_nick', 'shop_nick',
'total_amount', 'item_amount', 'freight',
'items_count', 'items_weight',
'items_count', 'items_weight', 'packages_weight',
'wave_no', 'delivery_time', 'create_at',
];

View File

@ -6624,6 +6624,49 @@ class PendingOrderService extends OrderBaseService {
const logisticsInterfaceName = String(requestData.logistics_interface_name || '').trim() || null;
// 1.1 可选参数:快递编码。传入时参考 updateOrderExpress 的行为,同步修改订单的快递信息
const expressCodeRaw = String(requestData.express_code || '').trim();
let expressResolved = null;
if (expressCodeRaw) {
// 使用带缓存的仓库快递列表
const expressList = await this.service.systems.express.getExpressList();
const expressItem = Array.isArray(expressList)
? expressList.find(item => String(item.code || item.value || '').trim() === expressCodeRaw)
: null;
if (!expressItem) {
throw new Error(`快递编码 ${expressCodeRaw} 不存在`);
}
let sysLogisticsCode;
let sysLogisticsName;
let logisticsCode;
let logisticsName;
if (expressItem.is_system_setting) {
// 自定义映射:express_code 字段存储对应的系统快递编码
sysLogisticsCode = String(expressItem.express_code || '').trim();
// 系统快递名称从列表中查找
const sysItem = expressList.find(item => !item.is_system_setting && String(item.code || '').trim() === sysLogisticsCode);
sysLogisticsName = sysItem ? String(sysItem.name || '').trim() : sysLogisticsCode;
logisticsCode = expressItem.code;
logisticsName = String(expressItem.alias || expressItem.name || '').trim();
} else {
// 系统快递:logistics_code/name 与 sys 一致
sysLogisticsCode = expressItem.code;
sysLogisticsName = String(expressItem.name || '').trim();
logisticsCode = expressItem.code;
logisticsName = sysLogisticsName;
}
expressResolved = {
sysLogisticsCode,
sysLogisticsName,
logisticsCode,
logisticsName,
};
}
// 2. 查询订单并校验状态(待处理:step in [1,2,3] 且 outbound_status != 'padding')
const model = await this.getOrderModel('order', warehouseId);
const where = this.buildOrderWhere([ orderId ], warehouseId);
@ -6684,8 +6727,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,
logistics_code: expressResolved
? expressResolved.logisticsCode
: String(order.sys_logistics_code || '').trim() || null,
logistics_name: expressResolved
? expressResolved.logisticsName
: 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,
@ -6695,13 +6742,22 @@ class PendingOrderService extends OrderBaseService {
create_at: new Date(),
});
// 3.2 更新订单表的 print_status 与 post_status 为 'fin',表示外部已打印
// 3.2 更新订单表的 print_status 与 post_status 为 'fin',表示外部已打印;
// 若传入了 express_code,同步修改订单的快递信息(与 updateOrderExpress 口径一致)
const orderUpdateFields = {
print_status: 'fin',
post_status: 'fin',
updated_at: new Date(),
};
if (expressResolved) {
orderUpdateFields.sys_logistics_code = expressResolved.sysLogisticsCode;
orderUpdateFields.sys_logistics_name = expressResolved.sysLogisticsName;
orderUpdateFields.logistics_code = expressResolved.logisticsCode;
orderUpdateFields.logistics_name = expressResolved.logisticsName;
}
await model.update(
{
print_status: 'fin',
post_status: 'fin',
updated_at: new Date(),
},
orderUpdateFields,
{
where: {
id: orderId,
@ -6723,7 +6779,14 @@ class PendingOrderService extends OrderBaseService {
logisticsInterfaceName,
businessKey: nextBusinessKey,
expressRecordId: expressRecord.id,
message: `手工录入运单号:订单 ${orderId},运单号 ${waybillCode}`,
expressCode: expressCodeRaw || null,
sysLogisticsCode: expressResolved ? expressResolved.sysLogisticsCode : String(order.sys_logistics_code || '').trim() || null,
sysLogisticsName: expressResolved ? expressResolved.sysLogisticsName : String(order.sys_logistics_name || '').trim() || null,
logisticsCode: expressResolved ? expressResolved.logisticsCode : String(order.sys_logistics_code || '').trim() || null,
logisticsName: expressResolved ? expressResolved.logisticsName : String(order.sys_logistics_name || '').trim() || null,
message: expressResolved
? `手工录入运单号:订单 ${orderId},运单号 ${waybillCode},快递 ${expressResolved.logisticsCode}(${expressResolved.logisticsName})`
: `手工录入运单号:订单 ${orderId},运单号 ${waybillCode}`,
},
beforeChanges: null,
});
@ -6757,14 +6820,23 @@ class PendingOrderService extends OrderBaseService {
);
}
return this.success('ok', {
const result = {
id: expressRecord.id,
order_id: orderId,
waybill_code: waybillCode,
business_key: nextBusinessKey,
logistics_interface_name: logisticsInterfaceName,
create_at: expressRecord.create_at,
});
};
if (expressResolved) {
result.express_code = expressCodeRaw;
result.sys_logistics_code = expressResolved.sysLogisticsCode;
result.sys_logistics_name = expressResolved.sysLogisticsName;
result.logistics_code = expressResolved.logisticsCode;
result.logistics_name = expressResolved.logisticsName;
}
return this.success('ok', result);
}
/**

View File

@ -859,6 +859,9 @@ class RecheckOrderService extends OrderBaseService {
item_name: String(item.item_name || '').trim(),
sku_property: String(item.sku_property || '').trim(),
packing_requirements: String(item.packing_requirements || '').trim(),
pick_requirements: String(item.pick_requirements || '').trim(),
recheck_requirements: String(item.recheck_requirements || '').trim(),
merge_requirements: String(item.merge_requirements || 'Y').trim(),
barcodes: Array.isArray(item.barcodes) ? [ ...item.barcodes ] : [],
images: Array.isArray(item.images) ? [ ...item.images ] : [],
has_shared_barcode: Boolean(item.has_shared_barcode),
@ -1115,6 +1118,7 @@ class RecheckOrderService extends OrderBaseService {
'store_id',
'intercept_status',
'items_weight',
'packages_weight',
'items_hash',
'items_crc',
],
@ -1239,6 +1243,7 @@ class RecheckOrderService extends OrderBaseService {
: '',
intercept_status: String(row.intercept_status || '').trim(),
items_weight: Number(row.items_weight || 0),
packages_weight: Number(row.packages_weight || 0),
items_hash: String(row.items_hash || '').trim(),
items_crc: Number(row.items_crc || 0),
};
@ -1535,6 +1540,9 @@ class RecheckOrderService extends OrderBaseService {
item_name: String(stockInfo.item_name || item.item_name || '').trim(),
sku_property: String(stockInfo.sku_property || '').trim(),
packing_requirements: String(stockInfo.packing_requirements || '').trim(),
pick_requirements: String(stockInfo.pick_requirements || '').trim(),
recheck_requirements: String(stockInfo.recheck_requirements || '').trim(),
merge_requirements: String(stockInfo.merge_requirements || 'Y').trim(),
barcodes,
images,
has_shared_barcode: hasSharedBarcode,
@ -3589,6 +3597,7 @@ class RecheckOrderService extends OrderBaseService {
o.items_count,
o.items_total,
o.items_weight,
o.packages_weight,
o.weight_type,
o.status,
o.create_at,
@ -3636,6 +3645,7 @@ class RecheckOrderService extends OrderBaseService {
items_count: Number(row?.items_count || 0),
items_total: Number(row?.items_total || 0),
items_weight: row?.items_weight != null ? Number(row.items_weight) : null,
packages_weight: row?.packages_weight != null ? Number(row.packages_weight) : null,
weight_type: this.formatWeightTypeLabel(row?.weight_type),
waybill_code: String(row?.waybill_code || '').trim(),
wave_index: Number(row?.wave_index || 0),

View File

@ -2943,7 +2943,7 @@ class WaveService extends OrderBaseService {
attributes: [
'id', 'store_id', 'logistics_name',
'sys_logistics_code', 'sys_logistics_name',
'items_hash', 'items', 'items_total', 'items_weight',
'items_hash', 'items', 'items_total', 'items_weight', 'packages_weight',
'post_status', 'pick_status', 'outbound_status', 'create_at',
],
raw: true,
@ -3078,6 +3078,7 @@ class WaveService extends OrderBaseService {
group_count: g.orders.length,
items_total,
items_weight: firstOrder.items_weight != null ? Number(firstOrder.items_weight) : null,
packages_weight: firstOrder.packages_weight != null ? Number(firstOrder.packages_weight) : null,
store_id: store_ids.length === 1 ? store_ids[0] : 0,
store_ids,
logistics_code: logisticsCode,
@ -3196,7 +3197,7 @@ class WaveService extends OrderBaseService {
attributes: [
'id', 'store_id', 'logistics_name',
'sys_logistics_code', 'sys_logistics_name',
'items_hash', 'items', 'items_total', 'items_weight',
'items_hash', 'items', 'items_total', 'items_weight', 'packages_weight',
'post_status', 'pick_status', 'outbound_status', 'create_at',
],
raw: true,
@ -3331,6 +3332,7 @@ class WaveService extends OrderBaseService {
group_count: g.orders.length,
items_total,
items_weight: firstOrder.items_weight != null ? Number(firstOrder.items_weight) : null,
packages_weight: firstOrder.packages_weight != null ? Number(firstOrder.packages_weight) : null,
store_id: store_ids.length === 1 ? store_ids[0] : 0,
store_ids,
logistics_code: logisticsCode,
@ -5026,6 +5028,7 @@ class WaveService extends OrderBaseService {
items_count: normalizedOrderRow.items_count ?? null,
items_total: normalizedOrderRow.items_total ?? null,
items_weight: normalizedOrderRow.items_weight != null ? Number(normalizedOrderRow.items_weight) : null,
packages_weight: normalizedOrderRow.packages_weight != null ? Number(normalizedOrderRow.packages_weight) : null,
weight_type: this.formatWeightTypeLabel(normalizedOrderRow.weight_type),
sys_logistics_name: this.resolveWaveStrategyFallbackSysLogisticsName(normalizedOrderRow),
store_name: this.resolveWaveStrategyFallbackStoreName(normalizedOrderRow),

View File

@ -0,0 +1,624 @@
'use strict';
const MainService = require('../../main');
const STOCK_CHECK_EXPORT_TASK_CACHE_KEY_PREFIX = 'stock_check_export_task_';
const STOCK_CHECK_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
/** 单次导出任务允许的最大盘点任务数量 */
const STOCK_CHECK_EXPORT_MAX_TASK_IDS = 50;
/** 全部 14 个 method 名(免权限/免鉴权清单共用) */
const ALL_METHOD_NAMES = 'create,list,addDetail,detailDelete,detail,report,recordList,recordDelete,finish,submit,cancel,audit,export,exportTaskProgress';
/**
* 系统方法层:stock.check(库存盘点模块接口包装层)。
* 主要职责:统一包装系统方法接口,处理权限、日志、where 解析等公共逻辑,
* 将具体业务逻辑下沉到 systems.stockCheck 中。
*/
class StockCheckMethodService extends MainService {
constructor(ctx) {
super(ctx);
// 免登录方法列表:空(全部需要登录)
const _noNeedLogin = '';
// 免权限方法列表:全部 14 个方法免 API 权限校验(与 stock/transaction.js 口径一致)
const _noNeedRight = ALL_METHOD_NAMES;
// 免日志方法列表:查询类与导出类不记录操作日志(recordDelete 为写操作,保留操作日志)
const _noNeedLog = 'list,detail,recordList,export,exportTaskProgress';
// 免鉴权(仓库有效期检查)方法列表:全部方法免鉴权(与 stock/transaction.js 口径一致)
const _noNeedAuth = ALL_METHOD_NAMES;
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 统一调用库存盘点业务服务,并捕获业务错误码。
*
* @param {Function} fn 业务调用函数。
* @param {string} fallbackMessage 兜底错误文案。
* @return {Promise<Object>} 统一 success/fail 包装。
*/
async _call(fn, fallbackMessage) {
try {
const result = await fn();
return this.success('ok', result);
} catch (error) {
const code = Number(error && error.code);
if (Number.isInteger(code) && code >= 400 && code < 600) {
return this.fail(error.message || fallbackMessage, {}, code);
}
this.ctx.logger.error(`[stock.check] ${fallbackMessage}: ${error && error.message ? error.message : error}`);
return this.fail('服务器内部错误', {}, 500);
}
}
/**
* 创建盘点任务(空任务)。
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
*
* @param {Object} data 请求体。
* @param {string} [data.title] 盘点名称/主题。
* @param {string} [data.type] 盘点范围类型:all/store/goods/location。
* @param {string} [data.mode] 盘点方式:open=明盘/blind=盲盘。
* @param {number} [data.store_id] 货主ID(按货主盘点时必填)。
* @param {string} [data.check_date] 盘点日期。
* @param {string} [data.remark] 备注。
* @return {Promise<Object>} 统一 success 包装,返回新建的盘点任务信息。
*/
async create(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const creatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0;
const creatorName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : '';
const { title, type, mode, store_id: storeId, check_date: checkDate, remark } = data || {};
return this._call(
() => this.service.systems.stockCheck.create({
warehouseId,
title,
type,
mode,
storeId,
checkDate,
remark,
creatorId,
creatorName,
}),
'创建盘点任务失败'
);
}
/**
* 拉取盘点任务列表。
* 按当前用户仓库(ctx.user.store_id)限定数据范围。
*
* @param {Object} data 请求体。
* @param {Object} [data.pagination] 分页参数。
* @param {Object} [data.where] 查询条件。
* @param {string|Array<string>} [data.where.status] 状态筛选(单值或数组)。
* @param {number} [data.where.store_id] 货主筛选。
* @param {string} [data.where.keyword] 关键字(单号/标题模糊)。
* @return {Promise<Object>} 统一 success 包装,返回 rows/total。
*/
async list(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { pagination } = data || {};
return this._call(async () => {
const { whereValue = {} } = this.prepareWhereContext(data);
const status = whereValue.status !== undefined ? whereValue.status : data.status;
const storeId = whereValue.store_id !== undefined ? whereValue.store_id : data.store_id;
const keyword = whereValue.keyword !== undefined ? whereValue.keyword : data.keyword;
return this.service.systems.stockCheck.list({
warehouseId,
status,
storeId,
keyword,
pagination,
});
}, '查询盘点任务列表失败');
}
/**
* 添加盘点明细。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {Array<number>} data.stock_ids 商品库存ID列表(wms_stock_warehouse.id)。
* @return {Promise<Object>} 统一 success 包装,返回新增数与跳过数。
*/
async addDetail(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id, stock_ids: stockIds } = data || {};
return this._call(
() => this.service.systems.stockCheck.addDetail({ warehouseId, id, stockIds }),
'添加盘点明细失败'
);
}
/**
* 删除盘点明细(从任务中移除某个商品)。
* 仅主表状态 created/rejected 允许删除;明细存在作业记录时一并防御性删除;
* 删除后重算主表 total_items。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {number} data.detail_id 盘点明细ID(兼容 detailId 驼峰写法)。
* @param {number} [data.detailId] 盘点明细ID(驼峰别名)。
* @return {Promise<Object>} 统一 success 包装,返回 { detail_id, deleted, total_items }。
*/
async detailDelete(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id, detail_id: detailIdRaw, detailId: detailIdAlias } = data || {};
const detailId = detailIdRaw !== undefined && detailIdRaw !== null && detailIdRaw !== ''
? detailIdRaw
: detailIdAlias;
return this._call(
() => this.service.systems.stockCheck.detailDelete({
warehouseId,
id,
detailId,
}),
'删除盘点明细失败'
);
}
/**
* 拉取盘点任务的全部明细行(商品清单)及每条明细的盘点作业记录(库位+数量)。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @return {Promise<Object>} 统一 success 包装,返回 { check, rows, total };rows 每条含商品快照 +
* 已盘聚合(checked_quantity/diff_quantity/is_diff/location_codes/checkers/last_checked_at)、
* records(作业记录列表)与 locations(按库位聚合 [{ location_id, location_code, quantity }])。
*/
async detail(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id } = data || {};
return this._call(
() => this.service.systems.stockCheck.detail({ warehouseId, id }),
'查询盘点明细失败'
);
}
/**
* 盘点作业上报(覆盖式)。
* 同明细 + 同库位编码重复上报时更新已有记录(未传库位归入"无库位"分组,location_code 为 null),不再新增。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {number} data.detail_id 明细ID。
* @param {string} [data.location] 库位编码(可空)。
* @param {number} data.quantity 实盘数量(>=0)。
* @return {Promise<Object>} 统一 success 包装,返回 { record, detail_id, mode: 'created'|'updated', ...summary }。
*/
async report(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const checkerId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0;
const checkerName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : '';
const { id, detail_id: detailId, location, quantity } = data || {};
return this._call(
() => this.service.systems.stockCheck.report({
warehouseId,
id,
detailId,
location,
quantity,
checkerId,
checkerName,
}),
'盘点作业上报失败'
);
}
/**
* 拉取盘点作业记录列表。
* 至少传 id(盘点任务ID)或 detail_id(明细ID)之一;按记录 id 倒序,返回分页结果。
*
* @param {Object} data 请求体。
* @param {number} [data.id] 盘点任务ID(可选)。
* @param {number} [data.detail_id] 明细ID(可选,传了只查该明细)。
* @param {Object} [data.pagination] 分页参数。
* @return {Promise<Object>} 统一 success 包装,返回 { rows, total, page, pageSize };
* rows 每条为记录表全字段 + 商品快照列(item_code/item_name)。
*/
async recordList(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id, detail_id: detailId, pagination } = data || {};
return this._call(
() => this.service.systems.stockCheck.recordList({
warehouseId,
id,
detailId,
pagination,
}),
'查询盘点作业记录失败'
);
}
/**
* 删除盘点作业记录。
* 仅主表状态 approved/checking 允许删除;删除后重算盘点进度汇总,主表状态不回退。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {number} data.record_id 作业记录ID(兼容 recordId 写法)。
* @param {number} [data.recordId] 作业记录ID(驼峰别名)。
* @return {Promise<Object>} 统一 success 包装,返回 { record_id, deleted, ...summary }。
*/
async recordDelete(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id, record_id: recordIdRaw, recordId: recordIdAlias } = data || {};
const recordId = recordIdRaw !== undefined && recordIdRaw !== null && recordIdRaw !== ''
? recordIdRaw
: recordIdAlias;
return this._call(
() => this.service.systems.stockCheck.recordDelete({
warehouseId,
id,
recordId,
}),
'删除盘点作业记录失败'
);
}
/**
* 完成盘点作业(允许部分未盘完成,未盘明细按实盘 0 处理计为盘亏)。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @return {Promise<Object>} 统一 success 包装,返回差异汇总(含 unchecked_items 未盘明细数)。
*/
async finish(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id } = data || {};
return this._call(
() => this.service.systems.stockCheck.finish({ warehouseId, id }),
'完成盘点作业失败'
);
}
/**
* 完成盘点任务(提交审核)。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @return {Promise<Object>} 统一 success 包装,返回最新状态。
*/
async submit(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id } = data || {};
return this._call(
() => this.service.systems.stockCheck.submit({ warehouseId, id }),
'提交盘点任务失败'
);
}
/**
* 取消盘点任务。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @return {Promise<Object>} 统一 success 包装,返回最新状态。
*/
async cancel(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id } = data || {};
return this._call(
() => this.service.systems.stockCheck.cancel({ warehouseId, id }),
'取消盘点任务失败'
);
}
/**
* 审核盘点任务。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {string} data.action 审核动作:approve=通过,reject=驳回。
* @param {string} [data.reason] 驳回原因(写入备注)。
* @return {Promise<Object>} 统一 success 包装,返回最新状态。
*/
async audit(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id, action, reason } = data || {};
return this._call(
() => this.service.systems.stockCheck.audit({ warehouseId, id, action, reason }),
'审核盘点任务失败'
);
}
/**
* 提交盘点任务导出任务。
* 异步执行:查询任务与明细 → ExcelJS 流式写入(Sheet1=盘点单行,Sheet2=明细行)→ COS 上传。
* 进度通过 Redis 缓存追踪,立即返回任务ID。
*
* @param {Object} data 请求体。
* @param {Array<number>} [data.ids] 盘点任务ID数组(兼容 task_ids 写法,上限 50)。
* @param {Array<number>} [data.task_ids] 盘点任务ID数组(兼容别名)。
* @return {Promise<Object>} 统一 success 包装,返回任务ID。
*/
async export(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { ids, task_ids: taskIdsRaw } = data || {};
const idSource = ids !== undefined ? ids : taskIdsRaw;
const idList = Array.isArray(idSource) ? idSource : (idSource !== undefined ? [ idSource ] : []);
const numericIds = [ ...new Set(idList.map(value => Number(value)).filter(value => Number.isInteger(value) && value > 0)) ];
if (numericIds.length === 0) {
return this.fail('请至少选择一个盘点任务', {}, 400);
}
if (numericIds.length > STOCK_CHECK_EXPORT_MAX_TASK_IDS) {
return this.fail(`单次最多导出 ${STOCK_CHECK_EXPORT_MAX_TASK_IDS} 个盘点任务`, {}, 400);
}
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.stockCheck.exportStockChecks({
warehouseId,
ids: numericIds,
onProgress: async progress => {
const safeProgress = this.isPlainObject(progress) ? progress : {};
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: safeProgress.status || 'running',
progress: safeProgress.progress,
current_count: safeProgress.currentCount || 0,
total_count: safeProgress.totalCount || 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,
current_count: 0,
total_count: 0,
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,
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.cdnUrl
|| safeResult.cosUrl
|| safeResult.fileKey
|| ''
);
return this.success('ok', {
task_id: taskId,
...cachedTask,
download_url: downloadUrl,
});
}
// ===========================
// 导出任务辅助方法
// ===========================
/**
* 生成导出任务ID。
*
* @return {string} 导出任务ID。
*/
generateExportTaskId() {
const warehouseId = this.ctx && this.ctx.user && this.ctx.user.store_id
? this.ctx.user.store_id
: 'unknown';
const timestamp = Date.now();
const randomToken = Math.random().toString(36).slice(2, 10);
return `stock_check_export_${warehouseId}_${timestamp}_${randomToken}`;
}
/**
* 归一化导出任务ID(兼容 task_id / taskId)。
*
* @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 `${STOCK_CHECK_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 || ''),
update_time: Date.now(),
};
try {
await this.app.setCacheAsync(
cacheKey,
progressPayload,
STOCK_CHECK_EXPORT_TASK_CACHE_TTL_SECONDS
);
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[stock.check.export] 写入导出任务缓存失败: ${errorMessage}`);
}
}
/**
* 读取导出任务进度缓存。
*
* @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;
}
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(`[stock.check.export] 读取导出任务缓存失败: ${errorMessage}`);
return null;
}
}
}
module.exports = StockCheckMethodService;

View File

@ -81,6 +81,9 @@ class WarehouseService extends MainService {
bucket: 'storeOutStock',
field: 'stock_id',
},
has_requirements: {
bucket: 'requirement',
},
},
});
const result = await service.systems.stockStore.getWarehouseStock(where, pagination, sortParams);
@ -130,6 +133,9 @@ class WarehouseService extends MainService {
bucket: 'storeOutStock',
field: 'stock_id',
},
has_requirements: {
bucket: 'requirement',
},
},
});
// 始终按当前货主维度查(store_id = self)
@ -184,6 +190,9 @@ class WarehouseService extends MainService {
bucket: 'storeOutStock',
field: 'stock_id',
},
has_requirements: {
bucket: 'requirement',
},
},
});
@ -268,6 +277,9 @@ class WarehouseService extends MainService {
bucket: 'storeOutStock',
field: 'stock_id',
},
has_requirements: {
bucket: 'requirement',
},
},
});
@ -513,6 +525,9 @@ class WarehouseService extends MainService {
sku_property,
stock_unit,
packing_requirements,
pick_requirements,
recheck_requirements,
merge_requirements,
length,
width,
height,
@ -556,6 +571,9 @@ class WarehouseService extends MainService {
sku_property,
stock_unit,
packing_requirements,
pick_requirements,
recheck_requirements,
merge_requirements,
length,
width,
height,

View File

@ -618,6 +618,9 @@ class AfterSaleService extends Service {
is_images: stock.is_images || 'N',
store_id: stock.store_id || null,
packing_requirements: stock.packing_requirements || '',
pick_requirements: stock.pick_requirements || '',
recheck_requirements: stock.recheck_requirements || '',
merge_requirements: stock.merge_requirements || 'Y',
stock_unit: stock.stock_unit || '',
image_url: stock.image_url || [],
barcodes: stock.barcodes || [],
@ -682,6 +685,7 @@ class AfterSaleService extends Service {
store_id: order.store_id,
// 重量(g)
items_weight: order.items_weight || 0,
packages_weight: order.packages_weight || 0,
// 波次
wave_id: order.wave_id || 0,
wave_no: order.wave_no || '',

View File

@ -2,6 +2,7 @@
const { randomBytes } = require('node:crypto');
const { Service } = require('egg');
const { CALLBACK_FUNCTIONS, CALLBACK_METHOD_SET } = require('../../lib/callback_functions');
class ApiAppService extends Service {
/**
@ -75,7 +76,7 @@ class ApiAppService extends Service {
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',
'self_ip_whitelist', 'callback_url', 'callback_functions', 'interface_type_id',
'rate_limit', 'sign_method', 'is_enabled', 'created_at', 'updated_at',
],
where,
@ -148,6 +149,7 @@ class ApiAppService extends Service {
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,
callback_functions: this.normalizeCallbackFunctions(data.callback_functions),
rate_limit: Number(data.rate_limit) || 1000,
sign_method: 'md5',
is_enabled: 1,
@ -171,6 +173,7 @@ class ApiAppService extends Service {
self_app_secret: record.self_app_secret,
self_ip_whitelist: record.self_ip_whitelist,
callback_url: record.callback_url,
callback_functions: record.callback_functions,
rate_limit: record.rate_limit,
sign_method: record.sign_method,
is_enabled: record.is_enabled,
@ -179,6 +182,34 @@ class ApiAppService extends Service {
};
}
/**
* 校验并规范化 callback_functions:
* 仅允许代码注册表中的 method,去重去空;
* 非数组入参视为 null(不承接任何回调)。
* @param {*} value 入参值。
* @return {Array<string>|null} 规范化后的 method 数组(可为空数组)。
*/
normalizeCallbackFunctions(value) {
if (!Array.isArray(value)) return null;
const functions = [ ...new Set(value.map(item => String(item || '').trim()).filter(Boolean)) ];
const invalid = functions.filter(method => !CALLBACK_METHOD_SET.has(method));
if (invalid.length > 0) {
throw new Error(`存在未注册的回调方法: ${invalid.join(', ')}`);
}
return functions;
}
/**
* 拉取出站回调 method 注册表(管理端多选列表)。
* @return {Object} { list: [{method,name,description}], total }。
*/
listCallbackFunctions() {
return {
list: CALLBACK_FUNCTIONS.map(item => ({ ...item })),
total: CALLBACK_FUNCTIONS.length,
};
}
/**
* 更新仓库 API 应用。
* @param {number|string} id 应用 ID。
@ -203,11 +234,13 @@ class ApiAppService extends Service {
throw new Error('API应用不存在或不属于当前仓库');
}
const updatableFields = [ 'app_name', 'self_ip_whitelist', 'callback_url', 'rate_limit', 'sign_method', 'is_enabled' ];
const updatableFields = [ 'app_name', 'self_ip_whitelist', 'callback_url', 'callback_functions', 'rate_limit', 'sign_method', 'is_enabled' ];
for (const field of updatableFields) {
if (data[field] !== undefined && data[field] !== null) {
if (field === 'sign_method') {
throw new Error('签名方法当前仅支持 md5,不允许修改');
} else if (field === 'callback_functions') {
record[field] = this.normalizeCallbackFunctions(data[field]);
} else if (field === 'is_enabled') {
record[field] = Number(data[field]);
} else if (field === 'rate_limit') {
@ -242,6 +275,7 @@ class ApiAppService extends Service {
: '',
self_ip_whitelist: record.self_ip_whitelist,
callback_url: record.callback_url,
callback_functions: record.callback_functions,
rate_limit: record.rate_limit,
sign_method: record.sign_method,
is_enabled: record.is_enabled,

View File

@ -437,6 +437,138 @@ class OrderExpressService extends Service {
return Array.isArray(rows) ? rows : [];
}
/**
* 回写订单表的 packages_weight(所有包裹总重量 = 该订单全部有效运单称重之和)。
*
* 称重主流程的补充回写动作,失败仅告警不阻断称重流程。
*
* @param {number} orderId 订单ID。
* @param {number|null} warehouseId 仓库ID,缺失时跳过回写。
* @param {Object|null} [orderDeliveryModel] 已知的订单分表模型;缺省时按 current → dispatch → history 自动定位。
* @return {Promise<number>} 计算出的包裹总重量(g),失败返回 0。
*/
async _syncOrderPackagesWeight(orderId, warehouseId, orderDeliveryModel = null) {
const { ctx } = this;
const normalizedOrderId = Number(orderId || 0);
if (normalizedOrderId <= 0 || !warehouseId) {
return 0;
}
try {
const orderExpressModel = ctx.model && ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.sum !== 'function') {
return 0;
}
const sumResult = await orderExpressModel.sum('weighing_weight', {
where: {
order_id: normalizedOrderId,
delete_at: null,
warehouse_id: warehouseId,
},
});
const packagesWeight = Number.isFinite(Number(sumResult)) && Number(sumResult) > 0
? Math.round(Number(sumResult))
: 0;
let targetModel = orderDeliveryModel;
if (!targetModel || typeof targetModel.update !== 'function') {
const factory = ctx.model && ctx.model.OrderDeliveryFactory;
if (!factory || typeof factory.getCurrentModel !== 'function') {
return packagesWeight;
}
const tableOrders = [
{ label: 'current', getModel: () => factory.getCurrentModel(warehouseId) },
{ label: 'dispatch', getModel: () => factory.getDispatchModel(warehouseId) },
{ label: 'history', getModel: () => factory.getHistoryModel(warehouseId) },
];
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.update !== 'function') continue;
const found = await model.findOne({
where: { id: normalizedOrderId, warehouse_id: warehouseId },
attributes: [ 'id' ],
raw: true,
});
if (found) {
targetModel = model;
break;
}
} catch (_err) { continue; }
}
}
if (targetModel && typeof targetModel.update === 'function') {
await targetModel.update(
{ packages_weight: packagesWeight },
{ where: { id: normalizedOrderId, warehouse_id: warehouseId } }
);
}
return packagesWeight;
} catch (err) {
ctx.logger && ctx.logger.warn && ctx.logger.warn(
`[order_express._syncOrderPackagesWeight] 回写包裹总重量失败 orderId=${normalizedOrderId}: ${err && err.message}`
);
return 0;
}
}
/**
* 批量回写波次内各订单的 packages_weight(所有包裹总重量 = 各订单全部有效运单称重之和)。
*
* 一次聚合查询 + 逐订单 UPDATE,失败仅告警不阻断称重流程。
*
* @param {number[]} orderIds 波次内参与称重的订单ID列表。
* @param {number} warehouseId 仓库ID。
* @param {Object} orderDeliveryModel 订单分表模型(波次订单所在分表)。
* @return {Promise<void>} 无返回值。
*/
async _syncWavePackagesWeight(orderIds, warehouseId, orderDeliveryModel) {
const { ctx } = this;
const normalizedOrderIds = (Array.isArray(orderIds) ? orderIds : [])
.map(id => Number(id || 0))
.filter(id => id > 0);
if (normalizedOrderIds.length === 0 || !warehouseId) {
return;
}
try {
const orderExpressModel = ctx.model && ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') {
return;
}
const { Op } = this.app.Sequelize;
const rows = await orderExpressModel.findAll({
where: {
order_id: { [Op.in]: normalizedOrderIds },
delete_at: null,
warehouse_id: warehouseId,
},
attributes: [ 'order_id', 'weighing_weight' ],
raw: true,
});
const sumMap = new Map();
for (const row of (Array.isArray(rows) ? rows : [])) {
const oid = Number(row && row.order_id || 0);
if (oid <= 0) continue;
sumMap.set(oid, (sumMap.get(oid) || 0) + Number(row.weighing_weight || 0));
}
if (orderDeliveryModel && typeof orderDeliveryModel.update === 'function') {
for (const oid of normalizedOrderIds) {
await orderDeliveryModel.update(
{ packages_weight: Math.round(sumMap.get(oid) || 0) },
{ where: { id: oid, warehouse_id: warehouseId } }
);
}
}
} catch (err) {
ctx.logger && ctx.logger.warn && ctx.logger.warn(
`[order_express._syncWavePackagesWeight] 批量回写包裹总重量失败: ${err && err.message}`
);
}
}
/**
* 更新订单运单称重重量。
*
@ -795,6 +927,9 @@ class OrderExpressService extends Service {
totalCount: orderIds.length,
});
// 回写波次内各订单的 packages_weight(所有包裹总重量 = 各订单全部运单称重之和)
await this._syncWavePackagesWeight(orderIds, warehouseId, orderDeliveryModel);
// 构建拆单汇总信息(按触发订单 ID 汇总)
const summary = await this._buildWaveWeighingSummary(waveId, orderId, warehouseId, weight);
@ -1035,6 +1170,9 @@ class OrderExpressService extends Service {
warehouseId,
});
// 回写订单表 packages_weight:所有包裹总重量 = 该订单全部有效运单称重之和
const packagesWeight = await this._syncOrderPackagesWeight(Number(targetRow.order_id), warehouseId);
// 从订单表读取当前 items_weight(只读,不做 UPDATE)
// 依次查 current / dispatch 两张表
let itemsWeight = 0;
@ -1068,6 +1206,7 @@ class OrderExpressService extends Service {
order_id: Number(targetRow.order_id),
waybill_code: String(targetRow.waybill_code || '').trim(),
weighing_weight: weight,
packages_weight: packagesWeight,
items_weight: itemsWeight,
};
}
@ -1147,6 +1286,9 @@ class OrderExpressService extends Service {
totalCount,
});
// 回写波次内各订单的 packages_weight(所有包裹总重量 = 各订单全部运单称重之和)
await this._syncWavePackagesWeight(orderIds, warehouseId, orderDeliveryModel);
// 构建拆单汇总信息(按触发订单 ID 汇总,未传时取波次下第一个订单)
const scopeOrderId = (Number.isFinite(Number(orderId)) && Number(orderId) > 0)
? Number(orderId)

View File

@ -143,6 +143,7 @@ class OrderReviewService extends OrderBaseService {
'wave_id',
'wave_no',
'items_weight',
'packages_weight',
'items_total',
'items_count',
'lock_status',
@ -478,6 +479,7 @@ class OrderReviewService extends OrderBaseService {
waybill_code: String(expressRow && expressRow.waybill_code || normalizedWaybillCode).trim(),
wave_no: String(orderRow && orderRow.wave_no || '').trim() || null,
total_weight: orderRow && orderRow.items_weight != null ? Number(orderRow.items_weight) : null,
packages_weight: orderRow && orderRow.packages_weight != null ? Number(orderRow.packages_weight) : null,
total_piece_count: totalPieceCount > 0 ? totalPieceCount : fallbackPieceCount,
total_sku_count: totalSkuCount > 0 ? totalSkuCount : fallbackSkuCount,
lock_status: lockStatus,

View File

@ -172,8 +172,9 @@ class ReceivingEntryMatchService extends Service {
});
if (existing) {
if (existing.deleted_at) {
// 已软删除的记录,恢复它
if (existing.deletedAt || existing.deleted_at) {
// 已软删除的记录,恢复它(台账重置为 {},从 0 重新分配)
existing.allocated_quantity = {};
await existing.restore();
ctx.logger.info(
`[ReceivingEntryMatch] 恢复已删除的绑定关系 entryOrderId=${entryOrderId} receivingId=${receivingId}`
@ -352,33 +353,65 @@ class ReceivingEntryMatchService extends Service {
throw new Error(`入库单绑定收货单失败,已回滚: ${error.message}`);
}
} else {
// CREATED:保持原有逻辑,仅逐条写入主表绑定关系
// CREATED:逐条写入主表绑定关系,幂等三态:
// 已存在未删除 → 跳过;已软删除(解绑产生)→ 恢复;不存在 → 新建。
// 注意不能用 findOrCreate:其查询默认排除软删除行,解绑后再绑定同一对
// (entry_order_id, receiving_id) 会撞唯一索引 uk_entry_order_receiving,
// 抛 SequelizeUniqueConstraintError(message 为 "Validation error")。
for (const receiving of validatedReceivings) {
try {
const [ , created ] = await ctx.model.EntryOrderReceiving.findOrCreate({
const existing = await ctx.model.EntryOrderReceiving.findOne({
where: { entry_order_id: entryOrderId, receiving_id: receiving.id },
defaults: {
entry_order_id: entryOrderId,
receiving_id: receiving.id,
// 新链路绑定行台账初始化为空对象(区别于旧数据 NULL)
allocated_quantity: {},
},
paranoid: false,
});
if (created) {
ctx.logger.info(
`[ReceivingEntryMatch] 主表绑定成功 entryOrderId=${entryOrderId} receivingId=${receiving.id}`
);
let created = false;
let restored = false;
if (existing) {
if (existing.deletedAt || existing.deleted_at) {
// 解绑产生的软删除行:台账在解绑时已重置为 {},恢复后从 0 重新分配
existing.allocated_quantity = {};
await existing.restore();
restored = true;
ctx.logger.info(
`[ReceivingEntryMatch] 恢复已解绑的绑定关系 entryOrderId=${entryOrderId} receivingId=${receiving.id}`
);
} else {
ctx.logger.info(
`[ReceivingEntryMatch] 主表绑定已存在,跳过 entryOrderId=${entryOrderId} receivingId=${receiving.id}`
);
}
} else {
ctx.logger.info(
`[ReceivingEntryMatch] 主表绑定已存在,跳过 entryOrderId=${entryOrderId} receivingId=${receiving.id}`
);
try {
await ctx.model.EntryOrderReceiving.create({
entry_order_id: entryOrderId,
receiving_id: receiving.id,
// 新链路绑定行台账初始化为空对象(区别于旧数据 NULL)
allocated_quantity: {},
});
created = true;
ctx.logger.info(
`[ReceivingEntryMatch] 主表绑定成功 entryOrderId=${entryOrderId} receivingId=${receiving.id}`
);
} catch (createError) {
// 并发场景:唯一索引冲突视为绑定已建立(与 findOrCreate 幂等语义一致)
if (createError.name === 'SequelizeUniqueConstraintError') {
ctx.logger.warn(
`[ReceivingEntryMatch] 主表绑定已存在(并发写入) entryOrderId=${entryOrderId} ` +
`receivingId=${receiving.id}`
);
} else {
throw createError;
}
}
}
boundResults.push({
receiving_id: receiving.id,
receiving_number: receiving.receiving_number,
created,
restored,
});
} catch (error) {
ctx.logger.error(
@ -491,6 +524,8 @@ class ReceivingEntryMatchService extends Service {
if (existing) {
const deletedAt = existing.deletedAt || existing.deleted_at || null;
if (deletedAt) {
// 恢复软删除行(台账在解绑时已重置为 {},此处显式兜底,从 0 重新分配)
existing.allocated_quantity = {};
await existing.restore({ transaction });
restored = true;
ctx.logger.info(
@ -2125,17 +2160,42 @@ class ReceivingEntryMatchService extends Service {
operator_name: ctx.currentUser?.employees_name || '',
}, { transaction });
// 6. 确保主级绑定存在(新链路台账初始化为空对象)
await ctx.model.EntryOrderReceiving.findOrCreate({
where: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id },
defaults: {
entry_order_id: entryOrderId,
receiving_id: lockedDetail[0].receiving_id,
allocated_quantity: {},
},
// 6. 确保主级绑定存在(新链路台账初始化为空对象)。
// 三态幂等:findOrCreate 默认排除软删除行,解绑后再分配会撞唯一索引,
// 这里改为 paranoid:false 查询 + 恢复软删除行 + 新建(唯一索引冲突视为并发已建立)。
const receivingId = Number(lockedDetail[0].receiving_id);
const existingBinding = await ctx.model.EntryOrderReceiving.findOne({
where: { entry_order_id: entryOrderId, receiving_id: receivingId },
paranoid: false,
transaction,
});
if (existingBinding) {
if (existingBinding.deletedAt || existingBinding.deleted_at) {
existingBinding.allocated_quantity = {};
await existingBinding.restore({ transaction });
ctx.logger.info(
`[ReceivingEntryMatch] 恢复已解绑的主表绑定(PDA 分配) entryOrderId=${entryOrderId} ` +
`receivingId=${receivingId}`
);
}
} else {
try {
await ctx.model.EntryOrderReceiving.create({
entry_order_id: entryOrderId,
receiving_id: receivingId,
allocated_quantity: {},
}, { transaction });
} catch (createError) {
if (createError.name !== 'SequelizeUniqueConstraintError') {
throw createError;
}
ctx.logger.warn(
`[ReceivingEntryMatch] 主表绑定已存在(并发写入) entryOrderId=${entryOrderId} receivingId=${receivingId}`
);
}
}
// 7. 回写数量台账:本批次对该收货明细的分配量累加到绑定行
const ledgerDeltaMap = new Map();
ledgerDeltaMap.set(Number(receivingDetailId), {

File diff suppressed because it is too large Load Diff

View File

@ -1506,6 +1506,9 @@ class stockStoreService extends Service {
// 其他字段
packing_requirements: sourceData.packing_requirements || '',
pick_requirements: sourceData.pick_requirements || '',
recheck_requirements: sourceData.recheck_requirements || '',
merge_requirements: sourceData.merge_requirements || 'Y',
create_at: now,
update_at: now,
is_valid: 'Y',
@ -1729,6 +1732,9 @@ class stockStoreService extends Service {
bucket: 'storeOutStock',
field: 'stock_id',
},
has_requirements: {
bucket: 'requirement',
},
keyword: {
bucket: 'keyword',
},
@ -1798,6 +1804,39 @@ class stockStoreService extends Service {
[Op.and]: dynamicConditions,
});
}
// 作业要求虚拟筛选:是否有作业要求
// 值:Y=有作业要求(拣货/复核/打包任一非空),N=无作业要求,
// pick/recheck/packing=对应要求不为空(大小写不敏感)
const rawRequirementCondition = rawConditionsByField.has_requirements;
if (rawRequirementCondition) {
const flagValue = rawRequirementCondition.value;
const normalizedFlag = String(flagValue === undefined || flagValue === null ? '' : flagValue).trim().toLowerCase();
const isYes = flagValue === true || flagValue === 1 || normalizedFlag === 'y'
|| normalizedFlag === 'true' || normalizedFlag === '1'
|| normalizedFlag === '是' || normalizedFlag === '有';
const isNo = flagValue === false || flagValue === 0 || normalizedFlag === 'n'
|| normalizedFlag === 'false' || normalizedFlag === '0'
|| normalizedFlag === '否' || normalizedFlag === '无';
const singleFieldNameMap = {
packing: 'packing_requirements',
pick: 'pick_requirements',
recheck: 'recheck_requirements',
};
const singleFieldName = singleFieldNameMap[normalizedFlag] || '';
if (isYes || isNo || singleFieldName) {
const requirementFieldNames = singleFieldName
? [ singleFieldName ]
: [ 'packing_requirements', 'pick_requirements', 'recheck_requirements' ];
const requirementFieldConditions = requirementFieldNames.map(fieldName => (isNo
? { [fieldName]: { [Op.or]: [ null, '' ] } }
: { [fieldName]: { [Op.and]: [{ [Op.ne]: '' }, { [Op.not]: null }] } }));
queryOptions.where[Op.and].push(isNo
? { [Op.and]: requirementFieldConditions }
: { [Op.or]: requirementFieldConditions });
}
}
if (barcodeDynamicConditions.length > 0) {
barcodeQueryOptions.where[Op.and].push({
[Op.and]: barcodeDynamicConditions,
@ -2549,7 +2588,7 @@ class stockStoreService extends Service {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'managementFlags', 'stock_unit', 'need_recheck' ];
const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'pick_requirements', 'recheck_requirements', 'merge_requirements', 'managementFlags', 'stock_unit', 'need_recheck' ];
const { ids, method, value } = ctx.request.body;
@ -2632,6 +2671,18 @@ class stockStoreService extends Service {
update_by: ctx.user.id || ctx.user.username,
};
} else if (method === 'merge_requirements') {
// 要求是否合并:Y=合并,N=不合并
const updateValue = String(value).trim().toUpperCase();
if (![ 'Y', 'N' ].includes(updateValue)) {
return { message: '要求合并必须是 Y(合并)或 N(不合并)', code: 405 };
}
updateData = {
merge_requirements: updateValue,
update_at: new Date(),
update_by: ctx.user.id || ctx.user.username,
};
} else if (method === 'managementFlags') {
// 管理标识是对象格式,需要更新三个独立字段
if (typeof value !== 'object') {
@ -3050,6 +3101,9 @@ class stockStoreService extends Service {
'length',
'net_weight',
'packing_requirements',
'pick_requirements',
'recheck_requirements',
'merge_requirements',
'prohibited_id',
'retail_price',
'sku_property',
@ -3075,6 +3129,15 @@ class stockStoreService extends Service {
raw: true,
});
stock.enable_box_spec = !!stock.enable_box_spec;
// 要求合并开关归一化(默认合并);合并时拣货/复核要求统一用打包要求覆盖输出
stock.packing_requirements = stock.packing_requirements || '';
stock.merge_requirements = stock.merge_requirements || 'Y';
stock.pick_requirements = stock.merge_requirements === 'Y'
? stock.packing_requirements
: (stock.pick_requirements || '');
stock.recheck_requirements = stock.merge_requirements === 'Y'
? stock.packing_requirements
: (stock.recheck_requirements || '');
return stock;
}
/**
@ -3088,7 +3151,7 @@ class stockStoreService extends Service {
const warehouseId = ctx.user.store_id;
const {
item_code, item_name, goods_code, sku_property, stock_unit,
packing_requirements, length, width, height, volume,
packing_requirements, pick_requirements, recheck_requirements, merge_requirements, length, width, height, volume,
volume_cm3, volumeCm3,
gross_weight, net_weight, tag_price, retail_price,
is_sn_mgmt, is_shelf_life_mgmt, is_batch_mgmt,
@ -3160,6 +3223,9 @@ class stockStoreService extends Service {
sku_property,
stock_unit,
packing_requirements,
pick_requirements,
recheck_requirements,
merge_requirements,
length,
width,
height,
@ -3256,7 +3322,7 @@ class stockStoreService extends Service {
const warehouseId = ctx.user.store_id;
const {
item_code, store_id, item_name, goods_code, sku_property, stock_unit,
packing_requirements, length, width, height, volume,
packing_requirements, pick_requirements, recheck_requirements, merge_requirements, length, width, height, volume,
gross_weight, net_weight, tag_price, retail_price,
is_sn_mgmt, is_shelf_life_mgmt, is_batch_mgmt,
prohibited_id, brand_name, managementFlags,
@ -3284,6 +3350,9 @@ class stockStoreService extends Service {
sku_property,
stock_unit,
packing_requirements,
pick_requirements,
recheck_requirements,
merge_requirements: merge_requirements || 'Y',
length,
width,
height,
@ -3363,6 +3432,11 @@ class stockStoreService extends Service {
throw new Error('need_recheck 必须是 Y(需要复核)或 N(不需要复核)');
}
// 要求是否合并:仅允许 Y(合并)/ N(不合并)
if (data.merge_requirements !== undefined && data.merge_requirements !== null && ![ 'Y', 'N' ].includes(String(data.merge_requirements).trim())) {
throw new Error('merge_requirements 必须是 Y(合并)或 N(不合并)');
}
// 数值类型验证
const numericFields = [ 'length', 'width', 'height', 'volume', 'gross_weight', 'net_weight' ];
for (const field of numericFields) {

View File

@ -35,7 +35,7 @@ class StockWarehouseService extends Service {
* @param {Object} [options={}] 选项
* @param {number} [options.warehouseId] 仓库ID(优先使用 options.warehouseId,否则兜底 ctx.user.store_id)
* @param {number} [options.cacheTTL=300] 缓存过期时间(秒)
* @return {Promise<Array<{id: number, item_code: string, item_name: string, sku_property: string, quantity: number, locked_quantity: number, is_batch_mgmt: string, is_shelf_life_mgmt: string, is_images: string, need_recheck: string, store_id: number, packing_requirements: string, stock_unit: string, image_url: string[], barcodes: Array<{id: number, barcode: string}>}>>} 商品详情列表
* @return {Promise<Array<{id: number, item_code: string, item_name: string, sku_property: string, quantity: number, locked_quantity: number, is_batch_mgmt: string, is_shelf_life_mgmt: string, is_images: string, need_recheck: string, store_id: number, packing_requirements: string, pick_requirements: string, recheck_requirements: string, merge_requirements: string, stock_unit: string, image_url: string[], barcodes: Array<{id: number, barcode: string}>}>>} 商品详情列表
*/
async getStockDetails(stockIds, options = {}) {
const { ctx, app } = this;
@ -90,7 +90,8 @@ class StockWarehouseService extends Service {
'id', 'item_code', 'item_name', 'sku_property',
'quantity', 'locked_quantity', 'is_batch_mgmt',
'is_shelf_life_mgmt', 'is_images', 'need_recheck',
'store_id', 'packing_requirements', 'stock_unit',
'store_id', 'packing_requirements', 'pick_requirements',
'recheck_requirements', 'merge_requirements', 'stock_unit',
],
raw: true,
}),
@ -157,6 +158,13 @@ class StockWarehouseService extends Service {
need_recheck: row.need_recheck || 'Y',
store_id: row.store_id != null ? Number(row.store_id) : 0,
packing_requirements: row.packing_requirements || '',
pick_requirements: (row.merge_requirements || 'Y') === 'Y'
? (row.packing_requirements || '')
: (row.pick_requirements || ''),
recheck_requirements: (row.merge_requirements || 'Y') === 'Y'
? (row.packing_requirements || '')
: (row.recheck_requirements || ''),
merge_requirements: row.merge_requirements || 'Y',
stock_unit: row.stock_unit || '',
image_url: imageUrlMap.get(row.id) || [],
barcodes: barcodeMap.get(row.id) || [],
@ -208,6 +216,20 @@ class StockWarehouseService extends Service {
if (cached && cached.need_recheck == null) {
cached.need_recheck = 'Y';
}
// 兼容旧缓存:无要求合并开关时按默认合并处理;无拣货/复核要求时按合并规则回退为打包要求
if (cached && cached.merge_requirements == null) {
cached.merge_requirements = 'Y';
}
if (cached && cached.pick_requirements == null) {
cached.pick_requirements = (cached.merge_requirements || 'Y') === 'Y'
? (cached.packing_requirements || '')
: '';
}
if (cached && cached.recheck_requirements == null) {
cached.recheck_requirements = (cached.merge_requirements || 'Y') === 'Y'
? (cached.packing_requirements || '')
: '';
}
result.push(cached);
}
} else if (dbResults.has(stockId)) {

View File

@ -31,7 +31,7 @@ class StockWarehouseService extends Service {
* @param {Object} [options={}] 选项
* @param {number} [options.warehouseId] 仓库ID(优先使用 options.warehouseId,否则兜底 ctx.user.store_id)
* @param {number} [options.cacheTTL=300] 缓存过期时间(秒)
* @return {Promise<Array<{id: number, item_code: string, item_name: string, sku_property: string, quantity: number, locked_quantity: number, is_batch_mgmt: string, is_shelf_life_mgmt: string, image_url: string, is_images: string, need_recheck: string, store_id: number, packing_requirements: string, stock_unit: string, barcodes: Array<{id: number, barcode: string, sku_property: string}>}>>} 商品详情列表
* @return {Promise<Array<{id: number, item_code: string, item_name: string, sku_property: string, quantity: number, locked_quantity: number, is_batch_mgmt: string, is_shelf_life_mgmt: string, image_url: string, is_images: string, need_recheck: string, store_id: number, packing_requirements: string, pick_requirements: string, recheck_requirements: string, merge_requirements: string, stock_unit: string, barcodes: Array<{id: number, barcode: string, sku_property: string}>}>>} 商品详情列表
*/
async getStockDetails(stockIds, options = {}) {
const { ctx, app } = this;
@ -78,7 +78,8 @@ class StockWarehouseService extends Service {
'quantity', 'locked_quantity', 'is_batch_mgmt',
'is_shelf_life_mgmt', 'image_url', 'is_images',
'need_recheck',
'store_id', 'packing_requirements', 'stock_unit',
'store_id', 'packing_requirements', 'pick_requirements',
'recheck_requirements', 'merge_requirements', 'stock_unit',
],
raw: true,
});
@ -120,6 +121,13 @@ class StockWarehouseService extends Service {
need_recheck: row.need_recheck || 'Y',
store_id: row.store_id != null ? Number(row.store_id) : 0,
packing_requirements: row.packing_requirements || '',
pick_requirements: (row.merge_requirements || 'Y') === 'Y'
? (row.packing_requirements || '')
: (row.pick_requirements || ''),
recheck_requirements: (row.merge_requirements || 'Y') === 'Y'
? (row.packing_requirements || '')
: (row.recheck_requirements || ''),
merge_requirements: row.merge_requirements || 'Y',
stock_unit: row.stock_unit || '',
barcodes: barcodeMap.get(row.id) || [],
};
@ -159,6 +167,20 @@ class StockWarehouseService extends Service {
if (cached.need_recheck == null) {
cached.need_recheck = 'Y';
}
// 兼容旧缓存:无要求合并开关时按默认合并处理;无拣货/复核要求时按合并规则回退为打包要求
if (cached.merge_requirements == null) {
cached.merge_requirements = 'Y';
}
if (cached.pick_requirements == null) {
cached.pick_requirements = (cached.merge_requirements || 'Y') === 'Y'
? (cached.packing_requirements || '')
: '';
}
if (cached.recheck_requirements == null) {
cached.recheck_requirements = (cached.merge_requirements || 'Y') === 'Y'
? (cached.packing_requirements || '')
: '';
}
result.push(cached);
}
} else if (dbResults.has(stockId)) {

View File

@ -32,34 +32,91 @@ class WarehouseNotifyService extends Service {
/**
* 获取仓库 ApiApp 回调配置(URL + 签名凭证)。
* 兼容旧调用:默认取承接 notify.reply 的首个应用。
* @param {number} warehouseId 仓库 ID。
* @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调配置。
*/
async getCallbackConfig(warehouseId) {
return await this.getCallbackConfigByMethod(warehouseId, 'notify.reply');
}
/**
* 按 method 获取仓库 ApiApp 回调配置(取候选列表中首个应用)。
* @param {number} warehouseId 仓库 ID。
* @param {string} method 出站 method(如 notify.reply)。
* @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调配置。
*/
async getCallbackConfigByMethod(warehouseId, method) {
const list = await this.listCallbackConfigs(warehouseId, method);
const first = list[0] || {};
return {
url: first.url || null,
appKey: first.appKey || null,
appSecret: first.appSecret || null,
};
}
/**
* 判断应用的 callback_functions 是否承接指定 method(兼容 JSON 字符串形式)。
* @param {*} callbackFunctions 应用承接的 method 列表(数组或 JSON 字符串)。
* @param {string} method 目标 method。
* @return {boolean} 是否承接。
*/
containsCallbackMethod(callbackFunctions, method) {
let list = callbackFunctions;
if (typeof list === 'string') {
try {
list = JSON.parse(list);
} catch (error) {
list = null;
}
}
if (!Array.isArray(list)) return false;
const methodStr = String(method || '').trim();
return list.map(item => String(item || '').trim()).includes(methodStr);
}
/**
* 查询仓库下承接指定 method 的全部回调候选应用(按 id 升序)。
* callback_functions 为空/未勾选的应用不承接任何回调(不放行)。
* @param {number} warehouseId 仓库 ID。
* @param {string} method 出站 method。
* @return {Promise<Array<{appId: number, url: string|null, appKey: string|null, appSecret: string|null}>>} 候选列表。
*/
async listCallbackConfigs(warehouseId, method) {
const { ctx } = this;
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
return { url: null, appKey: null, appSecret: null };
return [];
}
const apiAppModel = ctx.model && ctx.model.ApiApp;
if (!apiAppModel || typeof apiAppModel.findAll !== 'function') {
return [];
}
try {
const apiApp = await ctx.model.ApiApp.findOne({
attributes: [ 'callback_url', 'self_app_key', 'self_app_secret' ],
const rows = await apiAppModel.findAll({
attributes: [ 'id', 'callback_url', 'self_app_key', 'self_app_secret', 'callback_functions' ],
where: {
warehouse_id: warehouseId,
interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID,
is_enabled: 1,
},
order: [[ 'id', 'ASC' ]],
raw: true,
});
return {
url: (apiApp && apiApp.callback_url) || null,
appKey: (apiApp && apiApp.self_app_key) || null,
appSecret: (apiApp && apiApp.self_app_secret) || null,
};
return rows
.filter(row => this.containsCallbackMethod(row.callback_functions, method))
.map(row => ({
appId: Number(row.id),
url: row.callback_url || null,
appKey: row.self_app_key || null,
appSecret: row.self_app_secret || null,
}));
} catch (error) {
ctx.logger.warn(`[warehouseNotify] 查询回调配置失败: ${error.message}`);
return { url: null, appKey: null, appSecret: null };
ctx.logger.warn(`[warehouseNotify] 查询回调配置列表失败: ${error.message}`);
return [];
}
}
@ -125,29 +182,16 @@ class WarehouseNotifyService extends Service {
}
/**
* 向仓库 ApiApp 回调地址推送消息(MD5 签名 + POST)。
* @param {Object} options 推送参数。
* 单次回调推送尝试(复用 MD5 签名 + POST 协议,成功/失败均写日志)。
* @param {Object} options 尝试参数。
* @param {Object} options.config 候选应用 { appId, url, appKey, appSecret }。
* @param {number} options.warehouseId 仓库 ID。
* @param {string} [options.method='notify.reply'] 出站 method。
* @param {Object} [options.data={}] 消息数据(包裹在 body.data 中)。
* @return {Promise<Object>} 推送结果。
* @param {string} options.method 出站 method。
* @param {Object} options.body 请求体。
* @return {Promise<Object>} 单次结果 { success, appId, httpStatus, response, error }。
*/
async push({ warehouseId, method = 'notify.reply', data = {} } = {}) {
async pushOnce({ config, warehouseId, method, body }) {
const { ctx } = this;
const config = await this.getCallbackConfig(warehouseId);
if (!config.url) {
ctx.logger.info(`[warehouseNotify] 仓库 ${warehouseId} 未配置回调地址,跳过推送 method=${method}`);
return {
success: false,
skipped: true,
reason: '未配置回调地址(wms_api_app.callback_url 为空)',
warehouseId,
method,
};
}
const body = { code: 200, data };
const bodyJson = JSON.stringify(body);
const timestamp = Math.floor(Date.now() / 1000);
const sign = this.buildSignature({
@ -193,9 +237,7 @@ class WarehouseNotifyService extends Service {
return {
success: pushOk,
skipped: false,
warehouseId,
method,
appId: config.appId,
httpStatus: curlResult ? curlResult.status : null,
response: curlResult ? (curlResult.data || null) : null,
error: pushOk ? null : '回调返回非200或code非200',
@ -214,9 +256,7 @@ class WarehouseNotifyService extends Service {
return {
success: false,
skipped: false,
warehouseId,
method,
appId: config.appId,
httpStatus: null,
response: null,
error: error.message,
@ -224,6 +264,63 @@ class WarehouseNotifyService extends Service {
}
}
/**
* 向仓库 ApiApp 回调地址推送消息(MD5 签名 + POST)。
* 路由规则:查承接该 method 的全部候选应用(按 id 升序)逐个尝试,
* 第一个成功即返回;全部失败返回失败且不改动任何接口配置。
* @param {Object} options 推送参数。
* @param {number} options.warehouseId 仓库 ID。
* @param {string} [options.method='notify.reply'] 出站 method。
* @param {Object} [options.data={}] 消息数据(包裹在 body.data 中)。
* @return {Promise<Object>} 推送结果(含 attempts 明细)。
*/
async push({ warehouseId, method = 'notify.reply', data = {} } = {}) {
const { ctx } = this;
const methodStr = String(method || '').trim() || 'notify.reply';
const candidates = await this.listCallbackConfigs(warehouseId, methodStr);
if (candidates.length === 0) {
ctx.logger.info(`[warehouseNotify] 仓库 ${warehouseId} 无应用承接回调 method=${methodStr},跳过推送`);
return {
success: false,
skipped: true,
reason: '无应用承接该回调 method(callback_functions 未勾选或应用未启用)',
warehouseId,
method: methodStr,
attempts: [],
};
}
const body = { code: 200, data };
const attempts = [];
for (const config of candidates) {
const attempt = await this.pushOnce({ config, warehouseId, method: methodStr, body });
attempts.push(attempt);
if (attempt.success) {
return {
success: true,
skipped: false,
warehouseId,
method: methodStr,
appId: config.appId,
httpStatus: attempt.httpStatus,
response: attempt.response,
attempts,
};
}
}
ctx.logger.warn(`[warehouseNotify] 仓库 ${warehouseId} method=${methodStr} 全部 ${candidates.length} 个候选应用尝试失败`);
return {
success: false,
skipped: false,
warehouseId,
method: methodStr,
attempts,
error: `全部 ${candidates.length} 个回调应用尝试失败`,
};
}
/**
* 向指定群(可选)与成员(可选)推送系统级业务通知(复用 notify.reply,type=system)。
* 对方接口只处理 content 内容,推送体仅保留协议必需字段:

View File

@ -1646,6 +1646,11 @@ class WorkbenchService extends Service {
ctx.logger.info('[Workbench._sendWeight] 散单称重 barcode=%s orderId=%d weightG=%s',
normalizedBarcode, orderId, normalizedWeight);
// 回写订单表 packages_weight:所有包裹总重量 = 该订单全部有效运单称重之和
const packagesWeight = await ctx.service.systems.orderExpress._syncOrderPackagesWeight(
orderId, warehouseId, orderDeliveryModel
);
// 写入操作日志
await this._writeWeighOpLog({
orderId,
@ -1660,6 +1665,7 @@ class WorkbenchService extends Service {
waybill_code: normalizedBarcode,
order_id: orderId,
weighing_weight: normalizedWeight,
packages_weight: packagesWeight,
items_weight: Number(orderRow.items_weight || 0),
mode: 'single',
};
@ -1682,6 +1688,11 @@ class WorkbenchService extends Service {
ctx.logger.info('[Workbench._sendWeight] 非团购波次称重 barcode=%s orderId=%d weightG=%s waveType=%s',
normalizedBarcode, orderId, normalizedWeight, waveRow ? waveRow.wave_type : 'N/A');
// 回写订单表 packages_weight:所有包裹总重量 = 该订单全部有效运单称重之和
const packagesWeight = await ctx.service.systems.orderExpress._syncOrderPackagesWeight(
orderId, warehouseId, orderDeliveryModel
);
// 写入操作日志
await this._writeWeighOpLog({
orderId,
@ -1696,6 +1707,7 @@ class WorkbenchService extends Service {
waybill_code: normalizedBarcode,
order_id: orderId,
weighing_weight: normalizedWeight,
packages_weight: packagesWeight,
items_weight: Number(orderRow.items_weight || 0),
mode: 'single',
};
@ -1737,6 +1749,9 @@ class WorkbenchService extends Service {
}
);
// 回写波次内各订单的 packages_weight(所有包裹总重量 = 各订单全部运单称重之和)
await ctx.service.systems.orderExpress._syncWavePackagesWeight(orderIds, warehouseId, orderDeliveryModel);
ctx.logger.info('[Workbench._sendWeight] 团购波次批量称重 barcode=%s waveId=%d waveNo=%s orderCount=%d weightG=%s',
normalizedBarcode, waveId, waveRow.wave_no, totalCount, normalizedWeight);
@ -1984,6 +1999,9 @@ class WorkbenchService extends Service {
barcodes: stock.barcodes || [],
image_url: stock.image_url || [],
packing_requirements: String(stock.packing_requirements || '').trim(),
pick_requirements: String(stock.pick_requirements || '').trim(),
recheck_requirements: String(stock.recheck_requirements || '').trim(),
merge_requirements: String(stock.merge_requirements || 'Y').trim(),
need_recheck: String(stock.need_recheck || 'Y').trim(),
is_wave_summary: true,
};
@ -2103,6 +2121,9 @@ class WorkbenchService extends Service {
barcodes: stock.barcodes || [],
image_url: stock.image_url || '',
packing_requirements: String(stock.packing_requirements || '').trim(),
pick_requirements: String(stock.pick_requirements || '').trim(),
recheck_requirements: String(stock.recheck_requirements || '').trim(),
merge_requirements: String(stock.merge_requirements || 'Y').trim(),
need_recheck: String(stock.need_recheck || 'Y').trim(),
};
});
@ -2453,6 +2474,7 @@ class WorkbenchService extends Service {
items_count: orderRow.items_count,
items_total: orderRow.items_total,
items_weight: orderRow.items_weight,
packages_weight: orderRow.packages_weight,
source_platform_code: orderRow.source_platform_code,
logistics_name: orderRow.logistics_name,
picker_id: pickerId,

View File

@ -0,0 +1,55 @@
'use strict';
/**
* wms_api_app 新增 callback_functions 字段(出站回调 method 路由)。
*
* 语义:应用承接的出站回调 method 列表(JSON 数组)。
* 为空/未勾选 = 不承接任何回调;出站回调按 warehouse_id + method 自动路由到
* 勾选了该 method 的应用,多个应用按 id 升序逐个尝试,全部失败不改配置。
*
* A 方案存量回填:仓库接口类型(OPEN_API_WAREHOUSE)下启用的应用
* 默认承接 notify.reply,升级后站内信推送不受影响。
*/
module.exports = {
async up(queryInterface, Sequelize) {
const { sequelize } = queryInterface;
// 幂等:列已存在则跳过
const [ columns ] = await sequelize.query(
"SHOW COLUMNS FROM `wms_api_app` LIKE 'callback_functions'"
);
if (columns.length === 0) {
await queryInterface.addColumn('wms_api_app', 'callback_functions', {
type: Sequelize.JSON,
allowNull: true,
comment: '承接的出站回调 method 列表(空/未勾选=不承接任何回调;按 method 自动路由)',
});
}
// 存量回填:按 interface_code 查仓库接口类型 ID(避免硬编码数字漂移)
const [ interfaceRows ] = await sequelize.query(
"SELECT id FROM wms_interface_type WHERE interface_code = 'OPEN_API_WAREHOUSE' LIMIT 1"
);
const interfaceTypeId = interfaceRows && interfaceRows.length
? Number(interfaceRows[0].id)
: 3;
await sequelize.query(
'UPDATE wms_api_app SET callback_functions = JSON_ARRAY(\'notify.reply\') ' +
'WHERE interface_type_id = :interfaceTypeId AND is_enabled = 1 ' +
'AND (callback_functions IS NULL OR JSON_LENGTH(callback_functions) = 0)',
{ replacements: { interfaceTypeId } }
);
},
async down(queryInterface) {
const { sequelize } = queryInterface;
const [ columns ] = await sequelize.query(
"SHOW COLUMNS FROM `wms_api_app` LIKE 'callback_functions'"
);
if (columns.length > 0) {
await queryInterface.removeColumn('wms_api_app', 'callback_functions');
}
},
};

View File

@ -0,0 +1,43 @@
'use strict';
const CHECK_TABLE_NAME = 'wms_stock_check';
const DETAIL_TABLE_NAME = 'wms_stock_check_detail';
/**
* 库存盘点状态机对齐迁移。
* 主表 wms_stock_check.status 的 defaultValue 由 'pending' 改为 'created',
* 注释更新为新状态机枚举;detail_status 与明细表 status 的注释同步更新(字段类型不变)。
*/
module.exports = {
up: async queryInterface => {
// 主表 status:默认值 pending → created,注释更新为新状态机枚举
await queryInterface.sequelize.query(
`ALTER TABLE \`${CHECK_TABLE_NAME}\` MODIFY COLUMN \`status\` VARCHAR(20) NOT NULL DEFAULT 'created' COMMENT '盘点状态机:created=已创建(空任务),submitted=待审核,rejected=已驳回,approved=审核完成(待盘点作业),checking=盘点作业中,completed=已完成,cancelled=已取消'`
);
// 主表 detail_status:注释同步更新(类型与默认值不变)
await queryInterface.sequelize.query(
`ALTER TABLE \`${CHECK_TABLE_NAME}\` MODIFY COLUMN \`detail_status\` VARCHAR(30) NOT NULL DEFAULT 'none_checked' COMMENT '明细盘点进度(按已盘明细占比自动重算):none_checked=未盘,partial_checked=部分已盘,all_checked=全部已盘'`
);
// 明细表 status:注释同步更新(类型与默认值不变)
await queryInterface.sequelize.query(
`ALTER TABLE \`${DETAIL_TABLE_NAME}\` MODIFY COLUMN \`status\` VARCHAR(20) NOT NULL DEFAULT 'unchecked' COMMENT '明细状态:unchecked=未盘,checked=已盘'`
);
},
down: async queryInterface => {
// 回退:恢复旧默认值与旧注释
await queryInterface.sequelize.query(
`ALTER TABLE \`${CHECK_TABLE_NAME}\` MODIFY COLUMN \`status\` VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT '盘点状态:pending=待盘点,in_progress=盘点中,checked=已盘待确认,confirmed=已确认,completed=已完成,cancelled=已取消'`
);
await queryInterface.sequelize.query(
`ALTER TABLE \`${CHECK_TABLE_NAME}\` MODIFY COLUMN \`detail_status\` VARCHAR(30) NOT NULL DEFAULT 'none_checked' COMMENT '明细盘点进度:none_checked=未盘,partial_checked=部分已盘,all_checked=全部已盘'`
);
await queryInterface.sequelize.query(
`ALTER TABLE \`${DETAIL_TABLE_NAME}\` MODIFY COLUMN \`status\` VARCHAR(20) NOT NULL DEFAULT 'unchecked' COMMENT '明细状态:unchecked=未盘,checked=已盘,confirmed=已确认'`
);
},
};

View File

@ -0,0 +1,40 @@
'use strict';
/**
* apiApp.listCallbackFunctions(出站回调 method 注册表拉取)API 权限记录迁移。
*
* 权限明细(固定 ID 636,当前迁移内最大已用 ID=635):
* 636 — apiApp.listCallbackFunctions API:出站回调方法注册表
*
* 角色授权:与同组 apiApp 权限(465-470)口径一致——该组权限仅对
* permissions='*' 的通配角色(超管/经理/仓库管理员)开放,
* 无任何非通配角色持有,因此本迁移仅插入权限记录,不做角色注入。
*
* 幂等:INSERT IGNORE 创建权限记录。
*/
const TABLE = 'wms_permission';
const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at';
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
const apis = [
[ 636, 'apiApp.listCallbackFunctions', 'API:出站回调方法注册表' ],
];
for (const [ id, path, metaTitle ] of apis) {
await queryInterface.sequelize.query(
`INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
{ replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] }
);
}
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.sequelize.query(
`DELETE FROM \`${TABLE}\` WHERE id = 636 AND path = 'apiApp.listCallbackFunctions'`
);
},
};

View File

@ -0,0 +1,184 @@
'use strict';
/**
* 拆分盘点明细表:明细表只保留盘点商品(stock_id + 商品快照),
* 盘点作业产生的库位/数量信息下沉到新建的 wms_stock_check_record(盘点作业记录表)。
*
* 变更内容:
* 1. wms_stock_check_detail 移除作业字段:
* location_id / location_code(库位信息)
* check_quantity / diff_quantity / is_diff(实盘数量与差异)
* status / checker_id / checker_name / checked_at(盘点状态与盘点人)
* 2. 新建 wms_stock_check_record(盘点作业记录,一个明细可在多个库位多次上报):
* check_id(关联主表,冗余)、warehouse_id(冗余隔离)、detail_id(关联明细)、
* stock_id(冗余,商品维度查询)、location_id(space_code 匹配时回填)、
* location_code(库位编码)、quantity(实盘数量)、checker_id / checker_name、
* checked_at(上报时间)、remark、created_at / updated_at。
*
* 索引(wms_stock_check_record):
* idx_check_id(按任务查记录)
* idx_detail_id(按明细查记录)
* idx_stock_id(按商品反查)
* idx_warehouse_location(仓库+库位)
*/
const DETAIL_TABLE_NAME = 'wms_stock_check_detail';
const RECORD_TABLE_NAME = 'wms_stock_check_record';
/** 明细表需要移除的作业字段 */
const DROP_COLUMNS = [
'location_id',
'location_code',
'check_quantity',
'diff_quantity',
'is_diff',
'status',
'checker_id',
'checker_name',
'checked_at',
];
module.exports = {
up: async (queryInterface, Sequelize) => {
const { BIGINT, STRING, INTEGER, DATE } = Sequelize;
// 1) 明细表移除作业字段
for (const columnName of DROP_COLUMNS) {
await queryInterface.removeColumn(DETAIL_TABLE_NAME, columnName);
}
// 2) 新建盘点作业记录表
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === RECORD_TABLE_NAME);
if (!exists) {
await queryInterface.createTable(RECORD_TABLE_NAME, {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
check_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '关联盘点主表 wms_stock_check.id(冗余,便于按任务查记录)',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(冗余,隔离查询)',
},
detail_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '关联盘点明细 wms_stock_check_detail.id',
},
stock_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '库存商品ID(冗余,商品维度查询),关联 wms_stock_warehouse.id',
},
location_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '库位ID,关联 wms_location_space.id;库位编码匹配时回填,未匹配为空',
},
location_code: {
type: STRING(50),
allowNull: true,
comment: '库位编码(盘点上报的库位)',
},
quantity: {
type: INTEGER(12),
allowNull: false,
defaultValue: 0,
comment: '实盘数量(不小于0的整数)',
},
checker_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '盘点人账户ID',
},
checker_name: {
type: STRING(50),
allowNull: true,
comment: '盘点人名称快照',
},
checked_at: {
type: DATE,
allowNull: true,
comment: '上报时间',
},
remark: {
type: STRING(500),
allowNull: true,
comment: '备注',
},
created_at: { type: DATE, allowNull: false },
updated_at: { type: DATE, allowNull: false },
});
await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'check_id' ], { name: 'idx_check_id' });
await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'detail_id' ], { name: 'idx_detail_id' });
await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'stock_id' ], { name: 'idx_stock_id' });
await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'warehouse_id', 'location_code' ], { name: 'idx_warehouse_location' });
}
},
down: async (queryInterface, Sequelize) => {
const { BIGINT, STRING, INTEGER, DATE, TINYINT } = Sequelize;
// 删除记录表
await queryInterface.dropTable(RECORD_TABLE_NAME);
// 恢复明细表作业字段
await queryInterface.addColumn(DETAIL_TABLE_NAME, 'location_id', {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '库位ID,关联 wms_location_space.id;无库位商品为空',
});
await queryInterface.addColumn(DETAIL_TABLE_NAME, 'location_code', {
type: STRING(50),
allowNull: true,
comment: '库位编码快照(space_code)',
});
await queryInterface.addColumn(DETAIL_TABLE_NAME, 'check_quantity', {
type: INTEGER(12),
allowNull: true,
comment: '实盘数量;未盘点时为空',
});
await queryInterface.addColumn(DETAIL_TABLE_NAME, 'diff_quantity', {
type: INTEGER(12),
allowNull: true,
comment: '差异数量 = 实盘数量 - 账面数量;正数盘盈,负数盘亏;未盘点时为空',
});
await queryInterface.addColumn(DETAIL_TABLE_NAME, 'is_diff', {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否有差异:1=有差异,0=无差异',
});
await queryInterface.addColumn(DETAIL_TABLE_NAME, 'status', {
type: STRING(20),
allowNull: false,
defaultValue: 'unchecked',
comment: '明细状态:unchecked=未盘,checked=已盘,confirmed=已确认',
});
await queryInterface.addColumn(DETAIL_TABLE_NAME, 'checker_id', {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '盘点人账户ID',
});
await queryInterface.addColumn(DETAIL_TABLE_NAME, 'checker_name', {
type: STRING(50),
allowNull: true,
comment: '盘点人名称快照',
});
await queryInterface.addColumn(DETAIL_TABLE_NAME, 'checked_at', {
type: DATE,
allowNull: true,
comment: '盘点时间',
});
},
};

View File

@ -0,0 +1,58 @@
'use strict';
/**
* 盘点作业记录表覆盖式语义加固:
* 1. location_code 归一:NULL → ''(空串表示"无库位"分组,使唯一索引可约束空库位场景)。
* 2. 合并历史重复记录:同一 (detail_id, location_code) 组保留 id 最大(最新)的一条,其余删除。
* 3. location_code 改为 NOT NULL DEFAULT ''。
* 4. 新增唯一索引 uk_detail_location(detail_id, location_code),从数据库层面保证
* report 覆盖式上报(同明细+同库位更新而非新增)在并发下不产生重复记录。
*/
const TABLE_NAME = 'wms_stock_check_record';
module.exports = {
up: async (queryInterface, Sequelize) => {
const { STRING } = Sequelize;
// 1) NULL → ''
await queryInterface.sequelize.query(
`UPDATE ${TABLE_NAME} SET location_code = '' WHERE location_code IS NULL`
);
// 2) 合并重复:每组保留 id 最大的记录
await queryInterface.sequelize.query(`
DELETE r1 FROM ${TABLE_NAME} r1
JOIN ${TABLE_NAME} r2
ON r1.detail_id = r2.detail_id
AND r1.location_code = r2.location_code
AND r1.id < r2.id
`);
// 3) 列定义调整
await queryInterface.changeColumn(TABLE_NAME, 'location_code', {
type: STRING(50),
allowNull: false,
defaultValue: '',
comment: '库位编码(盘点上报的库位,空串表示无库位分组)',
});
// 4) 唯一索引(覆盖式语义的数据库层保证)
await queryInterface.addIndex(TABLE_NAME, [ 'detail_id', 'location_code' ], {
unique: true,
name: 'uk_detail_location',
});
},
down: async (queryInterface, Sequelize) => {
const { STRING } = Sequelize;
await queryInterface.removeIndex(TABLE_NAME, 'uk_detail_location');
await queryInterface.changeColumn(TABLE_NAME, 'location_code', {
type: STRING(50),
allowNull: true,
defaultValue: null,
comment: '库位编码(盘点上报的库位)',
});
},
};

View File

@ -0,0 +1,24 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('wms_stock_warehouse', 'pick_recheck_requirements', {
type: Sequelize.TEXT,
allowNull: true,
comment: '拣货眼球复核要求',
after: 'packing_requirements',
});
await queryInterface.addColumn('wms_stock_warehouse', 'three_in_one_switch', {
type: Sequelize.CHAR(1),
allowNull: false,
defaultValue: 'Y',
comment: '三合一开关:Y=开启,N=关闭',
after: 'pick_recheck_requirements',
});
},
async down(queryInterface) {
await queryInterface.removeColumn('wms_stock_warehouse', 'three_in_one_switch');
await queryInterface.removeColumn('wms_stock_warehouse', 'pick_recheck_requirements');
},
};

View File

@ -0,0 +1,30 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('wms_stock_warehouse', 'pick_requirements', {
type: Sequelize.TEXT,
allowNull: true,
comment: '拣货要求',
after: 'packing_requirements',
});
await queryInterface.addColumn('wms_stock_warehouse', 'recheck_requirements', {
type: Sequelize.TEXT,
allowNull: true,
comment: '眼球复核要求',
after: 'pick_requirements',
});
await queryInterface.removeColumn('wms_stock_warehouse', 'pick_recheck_requirements');
},
async down(queryInterface, Sequelize) {
await queryInterface.addColumn('wms_stock_warehouse', 'pick_recheck_requirements', {
type: Sequelize.TEXT,
allowNull: true,
comment: '拣货眼球复核要求',
after: 'packing_requirements',
});
await queryInterface.removeColumn('wms_stock_warehouse', 'recheck_requirements');
await queryInterface.removeColumn('wms_stock_warehouse', 'pick_requirements');
},
};

View File

@ -0,0 +1,40 @@
'use strict';
const TABLE_NAME = 'wms_stock_warehouse';
const OLD_COLUMN = 'three_in_one_switch';
const NEW_COLUMN = 'merge_requirements';
/**
* 将 three_in_one_switch 重命名为 merge_requirements(要求是否合并)。
* 语义:Y=合并(拣货/复核要求统一输出打包要求),N=不合并,默认 Y。
*/
module.exports = {
up: async (queryInterface, Sequelize) => {
const columns = await queryInterface.describeTable(TABLE_NAME);
if (!Object.prototype.hasOwnProperty.call(columns, OLD_COLUMN)) {
// 旧列不存在,视为已执行(幂等)
return;
}
await queryInterface.renameColumn(TABLE_NAME, OLD_COLUMN, NEW_COLUMN);
await queryInterface.changeColumn(TABLE_NAME, NEW_COLUMN, {
type: Sequelize.CHAR(1),
allowNull: false,
defaultValue: 'Y',
comment: '要求是否合并:Y=合并(拣货/复核要求统一输出打包要求),N=不合并',
});
},
down: async (queryInterface, Sequelize) => {
const columns = await queryInterface.describeTable(TABLE_NAME);
if (!Object.prototype.hasOwnProperty.call(columns, NEW_COLUMN)) {
return;
}
await queryInterface.renameColumn(TABLE_NAME, NEW_COLUMN, OLD_COLUMN);
await queryInterface.changeColumn(TABLE_NAME, OLD_COLUMN, {
type: Sequelize.CHAR(1),
allowNull: false,
defaultValue: 'Y',
comment: '三合一开关:Y=开启,N=关闭',
});
},
};

View File

@ -0,0 +1,17 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('wms_order_delivery', 'packages_weight', {
type: Sequelize.INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '所有包裹总重量(g)',
after: 'items_weight',
});
},
async down(queryInterface) {
await queryInterface.removeColumn('wms_order_delivery', 'packages_weight');
},
};

View File

@ -1,4 +1,157 @@
[
{
"version": "2026.09.30-manual-waybill-express-code",
"date": "2026-09-30",
"type": "updated",
"summary": "order.pendingOrder.manualWaybill 新增可选参数 express_code:传入时同步修改订单的快递编码,行为参考 updateOrderExpress",
"methods": [
"order.pendingOrder.manualWaybill"
],
"notes": [
"代码依据:app/service/systemMethods/order/pendingOrder.js#manualWaybill 新增可选入参 express_code(string,选填,trim 后为空视为未传);传入时参考 updateOrderExpress 的解析口径——从当前仓库快递列表(带缓存 getExpressList)中查找对应项,不存在则抛『快递编码 <express_code> 不存在』;自定义映射(is_system_setting=true)时订单 sys_logistics_code/name 写系统快递编码和名称、logistics_code/name 写自定义编码和名称,系统快递(is_system_setting=false)时四个字段均写系统快递的 code/name;不传时保持原行为(运单记录沿用订单当前 sys_logistics_code/name)。",
"写入范围:传入 express_code 时,订单表同步更新 sys_logistics_code/sys_logistics_name/logistics_code/logistics_name 四字段(与 print_status/post_status='fin' 同一次 update),运单记录(wms_order_express)的 logistics_code/logistics_name 写入解析后的新值;不传时运单记录沿用订单原系统快递字段。",
"操作日志:extras 新增 expressCode/sysLogisticsCode/sysLogisticsName/logisticsCode/logisticsName 字段,message 在传入 express_code 时补充快递信息。",
"响应:传入 express_code 时额外返回 express_code、sys_logistics_code、sys_logistics_name、logistics_code、logistics_name;不传时响应结构与原版本一致(向后兼容)。",
"文档变更范围:methods/system.json 的 order.pendingOrder.manualWaybill 更新 description、params 新增 express_code、response 新增 5 个可选字段、errors 新增 404 快递编码不存在;根版本 0.3.204 → 0.3.205、updatedAt 更新为 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。"
]
},
{
"version": "2026.09.29-stock-check-no-global-sequence",
"date": "2026-09-29",
"type": "updated",
"summary": "盘点单号改为全局递增:generateCheckNo 移除按仓库隔离(uk_check_no 全局唯一索引下按仓从 1 起会跨仓撞号),create 撞唯一键自动重取重试最多 5 次,口径与收货单 receiving_number 一致",
"methods": [
"stock.check.create"
],
"notes": [
"代码依据:app/service/systems/stock_check.js#generateCheckNo 移除 warehouse_id 隔离条件,改为查询全局最大 PD+YYYYMMDD 前缀单号取末尾 6 位序号 +1;新增 isCheckNoDuplicateError()(parent.code==='ER_DUP_ENTRY' 且 sqlMessage 命中 uk_check_no/check_no,参照收货单 isReceivingNumberDuplicateError 口径);create() 撞唯一键自动重取单号重试最多 5 次(与收货单 create 重试口径一致),超过重试次数或非单号冲突错误原样抛出。",
"原因说明:uk_check_no 为全局唯一索引(不区分仓库),原按仓库隔离序号各自从 1 起会跨仓撞号;改为全局递增后并发创建仍有极小概率撞号,由唯一键重试兜底。",
"收货单参照口径:与收货单 receiving_number 一致——按全局最大序号 +1 生成 + 撞唯一键自动重取重试。",
"并发重试说明:每次重试都重新调用 generateCheckNo() 取最新全局最大序号;仅 ER_DUP_ENTRY 且命中 uk_check_no 才重试,其它错误直接抛出。",
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.create 的 description 与 notes;根版本 0.3.203 → 0.3.204、updatedAt 保持 2026-09-29;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。"
]
},
{
"version": "2026.09.29-stock-check-detail-delete",
"date": "2026-09-29",
"type": "added",
"summary": "新增 stock.check.detailDelete:删除盘点明细(从任务移除商品),仅 created/rejected 状态允许,删除时防御性清理作业记录并重算 total_items",
"methods": [
"stock.check.detailDelete"
],
"notes": [
"代码依据:app/service/systemMethods/stock/check.js(ALL_METHOD_NAMES 扩为 14 个含 detailDelete;detailDelete 从登录上下文注入 warehouseId,入参 id + detail_id(兼容 detailId 驼峰,detail_id 优先),走统一 _call 捕获业务错误码;为写操作,不在免日志清单 list/detail/recordList/export/exportTaskProgress 中)、app/service/systems/stock_check.js(detailDelete:id/detail_id 非法抛 400『盘点任务ID不能为空/盘点明细ID不能为空』,任务不存在/明细不存在分别抛 400;仅 ADD_DETAIL_ALLOWED_STATUSES(created/rejected)允许删除,否则 400『当前状态(xxx)不允许删除明细』;删除明细后防御性清理 wms_stock_check_record 并重算主表 total_items;返回 { detail_id, deleted:true, total_items })。",
"状态限制口径:仅主表 created/rejected 允许删除明细(与 addDetail 口径一致,共用 ADD_DETAIL_ALLOWED_STATUSES);其它状态返回 400。",
"防御清理说明:正常流程 created/rejected 状态不应存在作业记录,但为兜底,删除明细时按 { detail_id, check_id, warehouse_id } 一并删除 wms_stock_check_record 中的关联记录,避免残留孤儿记录;删除后重算主表 total_items。",
"权限口径:随 ALL_METHOD_NAMES 免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(免鉴权清单)、必须登录(isNeedLogin=true,免登录清单为空);detailDelete 为写操作,记录操作日志。",
"文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.detailDelete(放在 addDetail 之后,与代码 ALL_METHOD_NAMES 顺序一致);根版本 0.3.202 → 0.3.203、updatedAt 保持 2026-09-29;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次先按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON,随后同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。"
]
},
{
"version": "2026.09.29-stock-check-record-unique-index",
"date": "2026-09-29",
"type": "updated",
"summary": "盘点作业记录表加固:location_code 空串归一 + 历史重复合并 + 唯一索引 uk_detail_location(detail_id, location_code),从数据库层保证 report 覆盖式上报并发安全;接口返回口径不变(空库位 location_code 仍为 null)",
"methods": [
"stock.check.report",
"stock.check.recordList"
],
"notes": [
"代码依据:app/service/systems/stock_check.js(report 未传库位归一存空串 '';查重条件统一 { detail_id, location_code };依赖数据库层唯一索引 uk_detail_location 保证并发安全;recordList 返回 location_code 空串归一为 null;detail 的 locations/location_codes 输出口径不变,空库位组 location_code=null)、app/model/stock_check_record.js(location_code allowNull=false defaultValue='')。",
"迁移:database/migrations/20260929130000-unique-stock-check-record-detail-location.js——location_code 归一 NULL→''、合并历史重复记录(同 detail_id+location_code 保留 id 最大一条)、列改 NOT NULL DEFAULT ''、新增唯一索引 uk_detail_location(detail_id, location_code);本地与生产均已执行。",
"口径变化:report 未传库位不再存 NULL 而是存空串 ''(\"无库位\"分组),覆盖式查重条件不变({ detail_id, location_code },含空串分组),并发下由唯一索引兜底不产生重复记录。",
"接口兼容性:对外返回口径不变——recordList 将空串归一为 null、detail 的 locations/location_codes 空库位组 location_code 仍为 null,客户端无需调整。",
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.report 的 description/notes 与 location 入参描述、stock.check.recordList 的 rows response 描述与 notes(空串归一 null 口径);根版本 0.3.201 → 0.3.202、updatedAt 保持 2026-09-29;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。",
"维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库,后续由维护者决定是否同步入库。"
]
},
{
"version": "2026.09.29-stock-check-work-adjust",
"date": "2026-09-29",
"type": "updated",
"summary": "盘点作业接口 5 项调整:report 改为覆盖式(同明细+同库位重复上报更新已有记录)、新增 recordDelete(删作业记录重算汇总)与 recordList(分页查作业记录)、detail rows 增加按库位聚合 locations、finish 放宽未盘校验(未盘按实盘 0 计盘亏并返回 unchecked_items)",
"methods": [
"stock.check.report",
"stock.check.detail",
"stock.check.finish",
"stock.check.recordDelete",
"stock.check.recordList"
],
"notes": [
"代码依据:app/service/systemMethods/stock/check.js(ALL_METHOD_NAMES 扩为 13 个含 recordList/recordDelete;免权限/免鉴权清单共用全部方法,免日志清单为 list/detail/recordList/export/exportTaskProgress;recordDelete 入参兼容 record_id/recordId 写法)、app/service/systems/stock_check.js(report 覆盖式上报:同 detail_id + 同 location_code(含同为空库位 location_code 为 NULL)更新已有记录 quantity/checker_id/checker_name/checked_at 并保留/回填 location_id,否则新增,返回 mode=created|updated;recordList 按 id DESC 分页返回记录全字段 + item_code/item_name;recordDelete 仅 approved/checking 状态、删除后重算汇总且主表状态不回退;detail rows 增加 locations 按库位聚合;finish 未盘明细按实盘 0 计盘亏并返回 unchecked_items)。",
"行为口径变化明细:①stock.check.report 从每次新增一条记录改为覆盖式——同 detail_id + 同 location_code(含同为空库位)重复上报更新已有记录(quantity/checker/checked_at),首次上报才新增,返回 mode=created|updated;②新增 stock.check.recordDelete:入参 id + record_id(兼容 recordId),仅 approved/checking 状态允许,删除后重算 total_items/checked_items/diff_items/detail_status(明细记录删光后回到未盘),主表状态不回退,返回 { record_id, deleted:true, ...summary };③新增 stock.check.recordList:入参 id(可选)+ detail_id(可选)+ pagination 至少传其一,返回 { rows, total, page, pageSize },rows=记录全字段 + item_code/item_name,按 id DESC;④stock.check.detail rows 每条新增 locations 数组(按库位聚合 [{ location_id, location_code, quantity }],空库位归 location_code=null 组),records 与既有聚合字段不变;⑤stock.check.finish 不再拦截未盘明细,未盘按实盘 0 处理(diff=-账面快照,计盘亏与 diff_items),返回新增 unchecked_items 字段。",
"无 schema 变更:本次仅业务行为调整,wms_stock_check / wms_stock_check_detail / wms_stock_check_record 表结构未变,无需数据库迁移。",
"权限口径:recordList/recordDelete 与同分组其它方法一致——免 API 权限(isNeedAuth=false)、免仓库有效期鉴权、必须登录(isNeedLogin=true);recordList 为查询类免操作日志,recordDelete 为写操作记录操作日志。",
"文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.recordList、stock.check.recordDelete 两条 method,更新 stock.check.report/detail/finish 三条 description 与 response(report 增加 mode 字段、detail rows 增加 locations 聚合、finish 增加 unchecked_items 并移除未盘拦截错误);根版本 0.3.200 → 0.3.201、updatedAt 保持 2026-09-29;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。",
"维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库,后续由维护者决定是否同步入库。"
]
},
{
"version": "2026.09.29-storage-entry-bindReceiving-soft-deleted-restore",
"date": "2026-09-29",
"type": "fixed",
"summary": "storage.entry.bindReceiving 修复解绑后重新绑定失败:CREATED 分支改用三态幂等(已存在跳过/软删除恢复/新建),不再因软删除残留行撞唯一索引报 BINDING_WRITE_FAILED(Validation error)",
"methods": [
"storage.entry.bindReceiving"
],
"notes": [
"根因:findOrCreate 查询默认排除软删除行(paranoid),解绑(unbindReceiving 软删除主表绑定行)后再次绑定同一 (entry_order_id, receiving_id) 时,create 撞唯一索引 uk_entry_order_receiving 抛 SequelizeUniqueConstraintError(message 为 \"Validation error\"),被捕获计入 skipped 并返回 BINDING_WRITE_FAILED。生产现场:绑定行 id=793(入库单 1280 RK202609290005 ↔ 收货单 4686 R20725003)于 2026-09-28 19:02 解绑软删除,2026-09-29 重新绑定即失败。",
"修复:app/service/systems/receiving_entry_match.js 的 bindEntryOrderReceiving CREATED 分支改为 paranoid:false 查询三态处理——未删除已存在跳过(created=false)、已软删除则 allocated_quantity 重置为 {} 并 restore(restored=true)、不存在新建(create 唯一索引冲突视为并发已建立,created=false);bound 项统一返回 created/restored 两字段。",
"同类加固:_commitBinding(PDA 上架确保主表绑定)的 findOrCreate 同步改为三态;_bindEntryOrderReceiving(自动匹配)与 _bindOneReceivingAndSyncStorage(COMPLETED)恢复软删除行时显式 allocated_quantity={} 兜底、软删除判断兼容 deletedAt/deleted_at 两种属性名。",
"文档变更范围:methods/system.json storage.entry.bindReceiving 的 bound.created/restored 描述更新、restored required 改为 true;根版本 0.3.199 → 0.3.200、updatedAt 保持 2026-09-29;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。",
"维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次直接写 JSON,未连接数据库、未写库,后续由维护者决定是否同步入库。"
]
},
{
"version": "2026.09.29-stock-check-detail-split",
"date": "2026-09-29",
"type": "updated",
"summary": "盘点明细表拆分:wms_stock_check_detail 仅保留盘点商品(stock_id+快照),库位/数量信息下沉到新建 wms_stock_check_record(盘点作业记录表);report 改为写入记录(同明细可多库位多次上报),已盘口径=存在记录,差异=记录数量合计-账面快照;detail 返回 records 与聚合字段;导出明细行含库位合并/盘点人合并。",
"methods": [
"stock.check.report",
"stock.check.detail",
"stock.check.finish",
"stock.check.export",
"stock.check.exportTaskProgress"
],
"notes": [
"代码依据:app/model/stock_check_detail.js(明细表仅存盘点商品:stock_id+商品快照,移除 location_id/location_code/check_quantity/diff_quantity/is_diff/status/checker_id/checker_name/checked_at)、app/model/stock_check_record.js(新建盘点作业记录表:check_id/warehouse_id/detail_id/stock_id/location_id/location_code/quantity/checker_id/checker_name/checked_at/remark,一个明细可在多库位多次上报)、app/service/systems/stock_check.js(report 写入记录不再更新明细;detail 返回 records 与聚合字段;finish 未盘=无记录明细、差异按记录聚合;export Sheet2 商品级聚合+库位/盘点人合并)、app/service/systemMethods/stock/check.js(report 从登录上下文注入 checkerId/checkerName)。",
"迁移:database/migrations/20260929120000-split-stock-check-detail-create-record.js(明细表移除 9 个作业字段 + 新建 wms_stock_check_record 及 4 个索引 idx_check_id/idx_detail_id/idx_stock_id/idx_warehouse_location),本地与生产均已执行。",
"口径变化明细:report 每次上报新增一条作业记录(同明细可在多库位多次上报),明细已盘数量=记录 quantity 合计;已盘口径=存在记录(DISTINCT detail_id);差异=记录数量合计-账面快照 system_quantity;detail.rows 返回 checked_quantity/diff_quantity/is_diff/status/location_codes[]/checkers[]/last_checked_at + records[];finish 未盘明细=无记录明细;export Sheet2 明细行(商品级聚合)列为 盘点单号/商品编码/商品名称/规格/账面数量/已盘数量/差异数量/是否有差异/库位编码(顿号合并)/盘点人(合并)/最近盘点时间。",
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.report/detail/finish/export 共 4 条 method 的 description 与 response;根版本 0.3.198 → 0.3.199、updatedAt 保持 2026-09-29;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。",
"维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库,后续由维护者决定是否同步入库。"
]
},
{
"version": "2026.09.29-stock-check-apis",
"date": "2026-09-29",
"type": "added",
"summary": "新增库存盘点模块 11 个 method(创建空任务/列表/添加明细/拉取明细/盘点作业上报/完成盘点/提交审核/取消/审核/导出/导出进度),完整状态机 created→submitted→approved/rejected→checking→completed/cancelled",
"methods": [
"stock.check.create",
"stock.check.list",
"stock.check.addDetail",
"stock.check.detail",
"stock.check.report",
"stock.check.finish",
"stock.check.submit",
"stock.check.cancel",
"stock.check.audit",
"stock.check.export",
"stock.check.exportTaskProgress"
],
"notes": [
"代码依据:app/service/systemMethods/stock/check.js(11 个 method 包装层,统一 _call 包装 400/500)与 app/service/systems/stock_check.js(状态机、单号生成 PD+YYYYMMDD+6位序号、汇总重算、Excel 导出 + COS 上传)。",
"表结构:wms_stock_check(盘点主表,仓库隔离 warehouse_id、盘点单号 check_no 唯一、状态 status、明细进度 detail_status、汇总 total_items/checked_items/diff_items)与 wms_stock_check_detail(盘点明细表,商品/库位快照、账面数量 system_quantity、实盘数量 check_quantity、差异数量 diff_quantity=实盘-账面)。",
"迁移:database/migrations/20260929100000-create-wms-stock-check.js、20260929101000-create-wms-stock-check-detail.js、20260929110000-align-stock-check-status-machine.js(主表 status 默认值 pending → created、注释对齐新状态机),本地与生产均已执行。",
"权限口径:11 个 method 全部免权限/免鉴权(仓库有效期检查)/需登录;list/detail/export/exportTaskProgress 免操作日志;不产生 wms_permission 权限记录,无需执行 permission:sync:system-api。",
"导出任务口径:Redis 进度缓存 key stock_check_export_task_{taskId}、TTL 1800 秒;每任务一个 Sheet(Sheet 名=盘点单号 check_no);单次最多 50 个盘点任务。",
"文档变更范围:methods/system.json 新增分组 module=stock.check(库存盘点模块)共 11 条 method;根版本 0.3.196 → 0.3.197、updatedAt 2026-09-28 → 2026-09-29;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。",
"维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库,后续由维护者决定是否同步入库。"
]
},
{
"version": "2026.09.28-weigh-pack-padding-message",
"date": "2026-09-28",

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,73 @@
'use strict';
/**
* 幂等补齐订单分表的 packages_weight 列(所有包裹总重量)。
*
* 背景:该列由订单模型(app/model/order_delivery.js)定义,分表工厂
* (order_delivery_factory.js)在首次访问某张分表时自动同步;history /
* outsourced 等长期不被访问的表可能滞后,可用本脚本提前补齐。
*
* 用法:
* 开发:node script/fix-order-packages-weight-column.cjs
* 生产:PowerShell 中 $env:NODE_ENV='production'; node script/fix-order-packages-weight-column.cjs
*
* 安全:只 ADD 缺失列(INT(11) NOT NULL DEFAULT 0,与模型定义一致),
* 不触碰 id / AUTO_INCREMENT,不修改已有列,可重复执行。
*/
(async () => {
try {
const configs = require('../database/config.js');
const env = process.env.NODE_ENV || 'development';
const cfg = configs[env];
if (!cfg) {
console.error('NO_CONFIG_FOR_ENV');
process.exit(2);
}
const mysql = require('mysql2/promise');
const conn = await mysql.createConnection({
host: cfg.host,
port: cfg.port || 3306,
user: cfg.username,
password: cfg.password,
database: cfg.database,
});
const [ tables ] = await conn.query(
`SELECT TABLE_NAME FROM information_schema.TABLES
WHERE TABLE_SCHEMA = ? AND TABLE_NAME LIKE 'wms_order_delivery\\_%'
ORDER BY TABLE_NAME`,
[ cfg.database ]
);
console.log(`环境: ${env}, 库: ${cfg.host}:${cfg.port}/${cfg.database}`);
console.log(`订单分表数量: ${tables.length}\n`);
const columnSql = "ADD COLUMN packages_weight INT(11) NOT NULL DEFAULT 0 COMMENT '所有包裹总重量(g)'";
let added = 0;
let ok = 0;
for (const row of tables) {
const tableName = row.TABLE_NAME || row.table_name;
const [ columns ] = await conn.query(
`SELECT COLUMN_NAME FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = 'packages_weight'`,
[ cfg.database, tableName ]
);
if (columns.length === 0) {
await conn.query(`ALTER TABLE \`${tableName}\` ${columnSql}`);
console.log(`[ADD] ${tableName} 已补齐列`);
added += 1;
} else {
ok += 1;
}
}
console.log(`\n完成: 已存在 ${ok} 张, 新增 ${added} 张`);
await conn.end();
process.exit(0);
} catch (err) {
console.error('ERROR', err.message);
process.exit(3);
}
})();