feat(backend): 出入库记录与库存锁定链路、出库单快递/收件人与推送队列

- 出入库记录(库存流水):新增 stock_records 表/模型/只读接口(列表 + 业务动作选项)与「出入库记录」菜单;
  库存变动统一收敛到 app/utils/stockRecord.js#applyStockChange,与流水写入同事务(含变动前后总/锁定/可用数量)
- 发货单:审核(1→2) 按明细锁定库存、发货确认(3→4) 扣减、推送失败退回/驳回/取消/作废释放(新增 stock_locked 列);
  恢复(9→1) 时曾推送过的单据换号(WMS 取消后原单号仍被占用,沿用旧号重推会被判「订单已存在」)
- 出库单:新增快递(express_code/express_name)、收件人(receiver_*) 与多运单号(express_codes) 字段;
  推送报文补齐 logisticsCode/receiverInfo;新增出库单推送服务与定时任务
- 快递:多运单号回填、仓库快递映射(warehouse_express_mappings) 与快递字典补录等迁移
- 契约:补充出入库记录、出库单快递/收件人等定义(swagger.json 为本地生成、不入库)
This commit is contained in:
liufumingren 2026-09-14 00:59:23 +08:00
parent d54d7a1ea6
commit 39c19a4de7
34 changed files with 3517 additions and 79 deletions

View File

@ -1015,8 +1015,24 @@ module.exports = {
status: { type: 'integer', description: '状态:1待出库 2已审核 3已推送 4完成 5已作废 9已取消' },
customer: { type: 'string', description: '客户/收货方' },
operator: { type: 'string', description: '操作人' },
waybill_codes: { type: 'array', itemType: 'string', description: '运单号集合(WMS 出库确认回传,多包裹时为多个;列名对齐 wms_order_stockout;系统托管)' },
total_amount: { type: 'number', description: '单据总金额' },
remark: { type: 'string', description: '备注' },
express_code: { type: 'string', description: '快递公司编码(推送 deliveryOrder.logisticsCode,如 SF/STO)' },
express_name: { type: 'string', description: '快递公司名称(按快递公司字典解析的快照)' },
receiver_name: { type: 'string', description: '收件人姓名(receiverInfo.name)' },
receiver_company: { type: 'string', description: '收件人公司名称(receiverInfo.company)' },
receiver_tel: { type: 'string', description: '收件人固定电话(receiverInfo.tel)' },
receiver_mobile: { type: 'string', description: '收件人移动电话(receiverInfo.mobile)' },
receiver_email: { type: 'string', description: '收件人邮箱(receiverInfo.email)' },
receiver_country_code: { type: 'string', description: '收件人国家二字码(receiverInfo.countryCode)' },
receiver_province: { type: 'string', description: '收件人省份(receiverInfo.province)' },
receiver_city: { type: 'string', description: '收件人城市(receiverInfo.city)' },
receiver_area: { type: 'string', description: '收件人区县(receiverInfo.area)' },
receiver_town: { type: 'string', description: '收件人街道/镇(receiverInfo.town)' },
receiver_detail_address: { type: 'string', description: '收件人详细地址(receiverInfo.detailAddress)' },
receiver_zip_code: { type: 'string', description: '收件人邮编(receiverInfo.zipCode)' },
receiver_id: { type: 'string', description: '收件人证件号(receiverInfo.id)' },
void_at: { type: 'string', description: '作废时间(状态 5=已作废)' },
void_by: { type: 'integer', description: '作废人ID(关联 users)' },
void_reason: { type: 'string', description: '作废原因' },
@ -1033,6 +1049,21 @@ module.exports = {
operator: { type: 'string', description: '操作人' },
total_amount: { type: 'number', description: '单据总金额' },
remark: { type: 'string', description: '备注' },
express_code: { type: 'string', description: '快递公司编码(推送为 deliveryOrder.logisticsCode,如 SF/STO)' },
express_name: { type: 'string', description: '快递公司名称(传编码时前端自动带出,便于列表展示)' },
receiver_name: { type: 'string', description: '收件人姓名' },
receiver_company: { type: 'string', description: '收件人公司名称' },
receiver_tel: { type: 'string', description: '收件人固定电话' },
receiver_mobile: { type: 'string', description: '收件人移动电话' },
receiver_email: { type: 'string', description: '收件人邮箱' },
receiver_country_code: { type: 'string', description: '收件人国家二字码' },
receiver_province: { type: 'string', description: '收件人省份' },
receiver_city: { type: 'string', description: '收件人城市' },
receiver_area: { type: 'string', description: '收件人区县' },
receiver_town: { type: 'string', description: '收件人街道/镇' },
receiver_detail_address: { type: 'string', description: '收件人详细地址' },
receiver_zip_code: { type: 'string', description: '收件人邮编' },
receiver_id: { type: 'string', description: '收件人证件号(receiverInfo.id)' },
items: { type: 'array', itemType: 'createStockItemRequest', description: '明细,可随单一次性写入' },
},
updateOutboundOrderRequest: {
@ -1042,6 +1073,21 @@ module.exports = {
operator: { type: 'string', description: '操作人' },
total_amount: { type: 'number', description: '单据总金额' },
remark: { type: 'string', description: '备注' },
express_code: { type: 'string', description: '快递公司编码(推送为 deliveryOrder.logisticsCode,如 SF/STO)' },
express_name: { type: 'string', description: '快递公司名称' },
receiver_name: { type: 'string', description: '收件人姓名' },
receiver_company: { type: 'string', description: '收件人公司名称' },
receiver_tel: { type: 'string', description: '收件人固定电话' },
receiver_mobile: { type: 'string', description: '收件人移动电话' },
receiver_email: { type: 'string', description: '收件人邮箱' },
receiver_country_code: { type: 'string', description: '收件人国家二字码' },
receiver_province: { type: 'string', description: '收件人省份' },
receiver_city: { type: 'string', description: '收件人城市' },
receiver_area: { type: 'string', description: '收件人区县' },
receiver_town: { type: 'string', description: '收件人街道/镇' },
receiver_detail_address: { type: 'string', description: '收件人详细地址' },
receiver_zip_code: { type: 'string', description: '收件人邮编' },
receiver_id: { type: 'string', description: '收件人证件号(receiverInfo.id)' },
},
voidOutboundOrderRequest: {
void_reason: { type: 'string', description: '作废原因(选填)' },
@ -1080,7 +1126,8 @@ module.exports = {
got_amount: { type: 'number', description: '已收金额' },
logistics_code: { type: 'string', description: '物流公司编码(快递公司字典 express_companies.code,如 SF/YTO)' },
logistics_name: { type: 'string', description: '物流公司名称(随编码自动带出)' },
express_code: { type: 'string', description: '运单号(面单号,系统托管:取号/回写链路写入,手工不填)' },
express_code: { type: 'string', description: '运单号(面单号,系统托管:取号/回写链路写入,手工不填;多包裹时为首个运单号)' },
express_codes: { type: 'array', itemType: 'string', description: '运单号集合(WMS 发货确认回传,多包裹时为多个;系统托管)' },
logistics_area_code: { type: 'string', description: '快递区域编码(大头笔,系统托管)' },
operator_name: { type: 'string', description: 'ERP 审核人(奇门 operatorName)' },
oaid_order_source_code: { type: 'string', description: 'OAID 订单来源编码(手工单不填写)' },
@ -1100,6 +1147,9 @@ module.exports = {
zip_code: { type: 'string', description: '邮编(receiverInfo.zipCode)' },
oaid: { type: 'string', description: 'OAID(receiverInfo.oaid,手工单不填写)' },
status: { type: 'integer', description: '状态:1待处理 2已审核 3已推送 4已完成 5已作废 9已取消' },
stock_locked: { type: 'integer', description: '库存锁定标记:1=审核时已按明细锁定库存(推送失败/驳回/取消/作废时释放,发货确认时扣减),0=未锁定;系统托管,不接受传入' },
shop_sync_status: { type: 'integer', description: '回传平台店铺状态:0未同步 1同步中 2同步成功 3同步失败;系统托管,不接受传入(实际回传链路待实现)' },
shop_sync_retry_count: { type: 'integer', description: '回传平台店铺的重试次数;系统托管,不接受传入' },
item_total: { type: 'number', description: '商品总数(明细计划数量合计,系统托管)' },
item_kind: { type: 'integer', description: '商品种类数(不重复商品数,系统托管)' },
audit_by: { type: 'integer', description: '审核人ID(关联 users,待处理→已审核时写入)' },
@ -1358,6 +1408,36 @@ module.exports = {
remark: { type: 'string', description: '备注' },
},
// ---------- 仓库快递映射 warehouse_express_mappings ----------
warehouseExpressMappingItem: {
id: { type: 'integer', description: '主键' },
principal_id: { type: 'integer', description: '所属主体ID' },
warehouse_id: { type: 'integer', description: '仓库ID(映射按仓库维度)' },
express_code: { type: 'string', description: '默认快递编码(OMS/标准编码,如 SF/ZT,关联快递公司字典)' },
express_name: { type: 'string', description: '快递名称(由 express_code 关联快递公司字典派生)' },
custom_code: { type: 'string', description: '自定义编码(外部传入的快递编码,如 SF.KY/KYSF)' },
status: { type: 'integer', description: '状态:1启用 0禁用(仅启用参与回传解析)' },
remark: { type: 'string', description: '备注' },
created_at: { type: 'string', description: '创建时间' },
updated_at: { type: 'string', description: '更新时间' },
},
warehouseExpressMappingPage: buildPage('warehouseExpressMappingItem', '仓库快递映射列表'),
warehouseExpressMappingListResponse: buildListResponse('warehouseExpressMappingPage'),
createWarehouseExpressMappingRequest: {
warehouse_id: { type: 'integer', required: true, description: '仓库ID(必填,需属于当前主体)' },
express_code: { type: 'string', required: true, description: '默认快递编码(必填,需存在于快递公司字典,如 SF)' },
custom_code: { type: 'string', required: true, description: '自定义编码(必填,统一转大写,同仓库内唯一,如 SF.KY)' },
status: { type: 'integer', description: '状态:1启用 0禁用,默认 1' },
remark: { type: 'string', description: '备注' },
},
updateWarehouseExpressMappingRequest: {
warehouse_id: { type: 'integer', description: '仓库ID' },
express_code: { type: 'string', description: '默认快递编码(需存在于快递公司字典)' },
custom_code: { type: 'string', description: '自定义编码(统一转大写,同仓库内唯一)' },
status: { type: 'integer', description: '状态:1启用 0禁用' },
remark: { type: 'string', description: '备注' },
},
// ---------- 出入库明细 stock_items ----------
stockItemItem: {
id: { type: 'integer', description: '主键' },
@ -1461,4 +1541,42 @@ module.exports = {
message: { type: 'string', description: '提示信息' },
data: { type: 'array', itemType: 'fileItem', description: '命中的文件列表,可直接复用其 url' },
},
// ---------- 出入库记录(库存流水)stock_records ----------
stockRecord: {
id: { type: 'integer', description: '主键' },
principal_id: { type: 'integer', description: '所属主体ID' },
warehouse_id: { type: 'integer', description: '仓库ID' },
product_id: { type: 'integer', description: '系统商品ID' },
item_code: { type: 'string', description: '商品编码(快照)' },
item_name: { type: 'string', description: '商品名称(快照)' },
item_type: { type: 'string', description: '库存类型:ZC 正品 / CC 残次品' },
biz_type: { type: 'string', description: '业务动作:outbound_lock 出库推送锁定 / outbound_unlock 出库解锁 / outbound_deduct 出库确认扣减 / outbound_restore 出库驳回回补 / inbound_increase 入库确认增加 / order_lock 订单审核锁定 / order_unlock 订单解锁 / order_deduct 订单发货确认扣减' },
biz_type_label: { type: 'string', description: '业务动作中文名' },
direction: { type: 'integer', description: '业务方向:1入库方向 2出库方向' },
direction_label: { type: 'string', description: '业务方向中文名' },
bill_type: { type: 'integer', description: '单据类型:1入库单 2出库单 3发货单(订单)' },
bill_id: { type: 'integer', description: '单据头ID' },
bill_no: { type: 'string', description: '单据号(入库单 RK_ / 出库单 CK_ / 发货单 FH_)' },
quantity: { type: 'number', description: '本次变动数量(恒为正数,方向见 direction / biz_type)' },
quantity_before: { type: 'number', description: '变动前总数量' },
quantity_after: { type: 'number', description: '变动后总数量' },
lock_quantity: { type: 'number', description: '本次锁定变动量(正=加锁 负=解锁)' },
lock_before: { type: 'number', description: '变动前锁定数量' },
lock_after: { type: 'number', description: '变动后锁定数量' },
available_before: { type: 'number', description: '变动前可用数量' },
available_after: { type: 'number', description: '变动后可用数量' },
remark: { type: 'string', description: '备注(触发原因)' },
created_by: { type: 'integer', description: '操作人ID(系统自动写入为空)' },
created_at: { type: 'string', description: '记录时间' },
},
/** 业务动作选项(筛选下拉) */
stockRecordBizType: {
value: { type: 'string', description: '业务动作编码' },
label: { type: 'string', description: '业务动作中文名' },
direction: { type: 'integer', description: '业务方向:1入库方向 2出库方向' },
bill_type: { type: 'integer', description: '单据类型:1入库单 2出库单 3发货单(订单)' },
},
stockRecordPage: buildPage('stockRecord', '出入库记录(库存流水)列表'),
stockRecordListResponse: buildListResponse('stockRecordPage'),
};

View File

@ -4,6 +4,9 @@ const { Controller } = require('egg');
const { parsePagination, buildPageResult } = require('../lib/pagination');
const { validateItems, buildItemRow } = require('../lib/orderDeliveryItems');
const recalcOrderDelivery = require('../utils/recalcOrderDelivery');
const nextRejectedBillNo = require('../utils/rejectBillNo');
const { lockDeliveryStock, releaseDeliveryStock } = require('../utils/deliveryStock');
const { isValidShopSyncStatus, SHOP_SYNC_STATUS_LIST } = require('../lib/shopSyncStatus');
const QimenWmsClient = require('../lib/wms/qimenClient');
const {
DELIVERY_ORDER_TYPE_LIST,
@ -63,8 +66,9 @@ function validateReceiver(data) {
const MANAGED_FIELDS = [
'delivery_order_code',
'need_oms_waybill',
'express_code', 'logistics_area_code',
'status', 'pushed_at', 'wms_push_result', 'created_by',
'express_code', 'logistics_area_code', 'express_codes',
'shop_sync_status', 'shop_sync_retry_count',
'status', 'pushed_at', 'wms_push_result', 'created_by', 'stock_locked',
'item_total', 'item_kind', 'item_amount',
'audit_by', 'audit_time',
'void_at', 'void_by', 'void_reason',
@ -112,6 +116,7 @@ class OrderDeliveryController extends Controller {
* @request query string order_type 订单类型(ORDER 组枚举):JYCK 一般交易出库单 / HHCK 换货出库 / BFCK 补发出库
* @request query integer shop_id 店铺ID
* @request query integer warehouse_id 仓库ID
* @request query integer shop_sync_status 回传平台店铺状态:0未同步 1同步中 2同步成功 3同步失败
* @response 200 orderDeliveryListResponse success
*/
async index() {
@ -124,6 +129,7 @@ class OrderDeliveryController extends Controller {
order_type: orderType,
shop_id: shopId,
warehouse_id: warehouseId,
shop_sync_status: shopSyncStatus,
} = ctx.query;
const principalId = ctx.state.principalId;
@ -133,6 +139,17 @@ class OrderDeliveryController extends Controller {
if (orderType) where.order_type = String(orderType).trim().toUpperCase();
if (shopId) where.shop_id = Number(shopId);
if (warehouseId) where.warehouse_id = Number(warehouseId);
if (shopSyncStatus !== undefined && shopSyncStatus !== '') {
if (!isValidShopSyncStatus(shopSyncStatus)) {
ctx.status = 400;
ctx.body = {
code: 400,
message: `shop_sync_status 取值非法(支持 ${SHOP_SYNC_STATUS_LIST.map(i => `${i.value}${i.label}`).join(' / ')})`,
};
return;
}
where.shop_sync_status = Number(shopSyncStatus);
}
const { count, rows } = await ctx.model.OrderDelivery.findAndCountAll({
where,
@ -738,6 +755,8 @@ class OrderDeliveryController extends Controller {
/**
* @summary 审核发货单
* @description 状态流转:待处理(1) → 已审核(2);需先录入明细且已选择店铺(手工单必须选店铺);写入审核人与审核时间。
* **审核即锁定库存**:按明细 plan_qty 锁定(占用可用,可用不足则审核失败 400),锁定与状态流转同事务,
* 并写一条出入库记录(biz_type=order_lock);推送失败退回/驳回/取消/作废时释放,WMS 发货确认时扣减。
* **审核只入队不推送**:由定时任务(app/schedule/orderDeliveryPush.js)异步递交 WMS,避免集中审核打满对方服务;
* 也可用「批量推送」或单条「推送」接口立即推送
* @router post /api/order-deliveries/{id}/audit
@ -772,20 +791,52 @@ class OrderDeliveryController extends Controller {
return;
}
// 清空上一轮推送记录(重试次数从 0 开始),状态置「已审核(2)」等待定时任务推送
await order.update({
status: 2,
audit_by: ctx.userId,
audit_time: new Date(),
pushed_at: null,
wms_push_result: null,
});
ctx.body = { code: 0, message: '审核成功,已进入推送队列,稍后自动推送仓库', data: { id: order.id, status: 2 } };
// 审核即锁定库存(按明细 plan_qty 占用可用,可用不足则审核失败),并写 order_lock 流水;
// 库存锁定与状态流转同事务,避免『已审核但未锁定』的不一致
const transaction = await ctx.model.transaction();
let lockResult;
try {
lockResult = await lockDeliveryStock(ctx, order, { createdBy: ctx.userId, transaction });
// 清空上一轮推送记录(重试次数从 0 开始),状态置「已审核(2)」等待定时任务推送
await order.update({
status: 2,
audit_by: ctx.userId,
audit_time: new Date(),
pushed_at: null,
wms_push_result: null,
}, { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
if (err.code === 'INSUFFICIENT_STOCK') {
const product = await ctx.model.Product.findByPk(err.productId, { attributes: [ 'item_code', 'item_name' ] });
const label = product ? `${product.item_name}(${product.item_code})` : `商品#${err.productId}`;
ctx.status = 400;
ctx.body = { code: 400, message: `库存不足,无法审核:${label} 可用 ${err.available},需 ${err.require}` };
return;
}
ctx.logger.error(`[order-delivery] 审核锁定库存失败 id=${order.id}`, err);
ctx.status = 500;
ctx.body = { code: 500, message: `审核失败:${err.message}` };
return;
}
ctx.body = {
code: 0,
message: '审核成功,已进入推送队列,稍后自动推送仓库',
data: {
id: order.id,
status: 2,
stock_locked: lockResult.affected,
stock_skipped_lines: lockResult.skippedLines,
},
};
}
/**
* @summary 批量审核发货单
* @description 按「选中单据(ids)」或「筛选条件」批量审核(1→2,只入队不推送);
* @description 按「选中单据(ids)」或「筛选条件」批量审核(1→2,只入队不推送);每单在独立事务内
* 先锁定库存再置状态(库存不足等失败仅跳过该单,不影响其他单据,失败明细见 data.failures);
* 传 dry_run=true 只返回影响范围(命中/可审核/跳过数量与样例)
* @router post /api/order-deliveries/audit-batch
* @apikey
@ -840,11 +891,41 @@ class OrderDeliveryController extends Controller {
return;
}
const [ affected ] = await ctx.model.OrderDelivery.update(
{ status: 2, audit_by: ctx.userId, audit_time: new Date(), pushed_at: null, wms_push_result: null },
{ where: auditableWhere }
);
// 逐单审核:每单在独立事务内「锁定库存 + 状态置 2」,单号级别失败(如库存不足)不影响其他单据
const rows = await ctx.model.OrderDelivery.findAll({
where: auditableWhere,
attributes: [ 'id', 'delivery_order_code', 'principal_id', 'warehouse_id', 'stock_locked' ],
order: [[ 'id', 'ASC' ]],
});
const failures = [];
let affected = 0;
for (const order of rows) {
const transaction = await ctx.model.transaction();
try {
await lockDeliveryStock(ctx, order, { createdBy: ctx.userId, transaction });
await order.update({
status: 2,
audit_by: ctx.userId,
audit_time: new Date(),
pushed_at: null,
wms_push_result: null,
}, { transaction });
await transaction.commit();
affected += 1;
} catch (err) {
await transaction.rollback();
failures.push({
id: Number(order.id),
delivery_order_code: order.delivery_order_code,
message: err.message,
});
ctx.logger.warn(`[order-delivery] 批量审核跳过 ${order.delivery_order_code}:${err.message}`);
}
}
result.affected = affected;
result.failed = failures.length;
if (failures.length) result.failures = failures.slice(0, 10);
ctx.body = { code: 0, message: 'success', data: result };
}
@ -964,7 +1045,10 @@ class OrderDeliveryController extends Controller {
/**
* @summary 驳回发货单
* @description 审核的反向操作:已审核(2) → 待处理(1);
* 单号(delivery_order_code)来自外部/人工且是唯一去重键,驳回不换号(与出入库单驳回换号不同)
* 驳回会变更单号(基础单号后追加/递增 `_N`,首次 `_1`、再次 `_2`,与出入库单一致),
* 保证「一次推送对应一个全新的外部单号」(WMS 侧 deliveryOrderCode 为唯一键,沿用旧号重推会报单据已存在);
* 驳回同时释放审核时锁定的库存(写 order_unlock 流水);释放失败则不流转状态;
* 推送失败过且外部可能已建单的,会先冲正取消(未建成时该调用失败,忽略即可)
* @router post /api/order-deliveries/{id}/reject
* @apikey
* @request path integer *id 发货单主键ID
@ -995,15 +1079,36 @@ class OrderDeliveryController extends Controller {
}
}
await order.update({ status: 1, audit_by: null, audit_time: null, pushed_at: null, wms_push_result: null });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
// 驳回前释放审核时锁定的库存(并记 order_unlock 流水);释放失败则不流转状态,避免锁定泄漏
try {
await releaseDeliveryStock(ctx, order, { createdBy: ctx.userId, remark: '订单驳回释放锁定库存' });
} catch (err) {
ctx.logger.error(`[order-delivery] 驳回释放库存失败 id=${order.id}`, err);
ctx.status = 500;
ctx.body = { code: 500, message: `驳回失败(释放锁定库存异常):${err.message}` };
return;
}
// 驳回换号:FH_1 → FH_1_1 → FH_1_2,避免重新审核后用旧单号推送被 WMS 判重
const newCode = nextRejectedBillNo(order.delivery_order_code, order.id, DELIVERY_BILL_PREFIX);
await order.update({
status: 1,
delivery_order_code: newCode,
audit_by: null,
audit_time: null,
pushed_at: null,
wms_push_result: null,
});
ctx.body = { code: 0, message: 'success', data: { id: order.id, delivery_order_code: order.delivery_order_code } };
}
/**
* @summary 取消发货单
* @description 状态流转:待处理(1)/已审核(2)/已推送(3) → 已取消(9);
* 已完成(4)与已作废(5)不可取消;已推送(3)的单据会先调用 WMS order.cancel(ORDER 组)取消外部发货单,
* 取消失败(如仓库已开始配货)时不流转状态并返回失败原因
* 取消失败(如仓库已开始配货)时不流转状态并返回失败原因;**取消成功后释放审核时锁定的库存**
* (写 order_unlock 流水,释放与状态流转同事务)。
* 注:WMS 主动取消(回调 deliveryorder.cancel)不在 OMS 处理范围内(未注册该回调),只处理 OMS 侧取消成功后的释放
* @router post /api/order-deliveries/{id}/cancel
* @apikey
* @request path integer *id 发货单主键ID
@ -1048,21 +1153,50 @@ class OrderDeliveryController extends Controller {
const pushedResult = order.wms_push_result && typeof order.wms_push_result === 'object'
? order.wms_push_result
: {};
await order.update({
status: 9,
wms_push_result: { ...pushedResult, cancelResult: resp, cancelledAt: new Date().toISOString() },
});
// 外部取消成功后才释放本地锁定:释放与状态流转同事务,避免「外部已取消、本地仍锁定」
const transaction = await ctx.model.transaction();
try {
await releaseDeliveryStock(ctx, order, { createdBy: ctx.userId, remark: '订单取消释放锁定库存', transaction });
await order.update({
status: 9,
wms_push_result: { ...pushedResult, cancelResult: resp, cancelledAt: new Date().toISOString() },
}, { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
ctx.logger.error(`[order-delivery] 取消释放库存失败 id=${order.id}`, err);
ctx.status = 500;
ctx.body = { code: 500, message: `取消失败(释放锁定库存异常):${err.message}` };
return;
}
ctx.body = { code: 0, message: 'success', data: { id: order.id, wms_response: resp } };
return;
}
await order.update({ status: 9 });
// 未推送(1/2):OMS 侧取消即释放锁定(无外部单据)
const transaction = await ctx.model.transaction();
try {
await releaseDeliveryStock(ctx, order, { createdBy: ctx.userId, remark: '订单取消释放锁定库存', transaction });
await order.update({ status: 9 }, { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
ctx.logger.error(`[order-delivery] 取消释放库存失败 id=${order.id}`, err);
ctx.status = 500;
ctx.body = { code: 500, message: `取消失败(释放锁定库存异常):${err.message}` };
return;
}
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/**
* @summary 恢复发货单
* @description 状态流转:已取消(9) → 待处理(1)
* @description 状态流转:已取消(9) → 待处理(1);
* **曾推送过的单据恢复时换号**(基础单号后追加/递增 `_N`,如 FH_3 → FH_3_1 → FH_3_2),
* 原因:WMS 侧 deliveryOrderCode 为唯一键,且外部单据取消后原单号仍被占用,
* 沿用旧号重推会被判「订单已存在」(WMS 按成功返回,OMS 却可能指向已取消的外部单);
* 同时清空 audit_by/audit_time/pushed_at/wms_push_result(重回待处理,重试计数归零)。
* 从未推送过的单据(取消时还没推过)保持原单号,避免无意义换号
* @router post /api/order-deliveries/{id}/restore
* @apikey
* @request path integer *id 发货单主键ID
@ -1082,13 +1216,35 @@ class OrderDeliveryController extends Controller {
return;
}
await order.update({ status: 1 });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
// 是否推送过:pushed_at 在每次真实推送尝试前写入(乐观锁),推送结果也存 wms_push_result
const pushedBefore = order.pushed_at != null || order.wms_push_result != null;
if (!pushedBefore) {
await order.update({ status: 1 });
ctx.body = { code: 0, message: 'success', data: { id: order.id, bill_no_changed: false } };
return;
}
// 推送过:换号(保证「一次推送对应一个全新的外部单号」)并清空审核/推送痕迹
const newCode = nextRejectedBillNo(order.delivery_order_code, order.id, DELIVERY_BILL_PREFIX);
await order.update({
status: 1,
delivery_order_code: newCode,
audit_by: null,
audit_time: null,
pushed_at: null,
wms_push_result: null,
});
ctx.body = {
code: 0,
message: 'success',
data: { id: order.id, delivery_order_code: order.delivery_order_code, bill_no_changed: true },
};
}
/**
* @summary 作废发货单
* @description 仅「已审核(2)」可作废;状态置为已作废(5),记录作废人/时间/原因,不可恢复也禁止删除
* @description 仅「已审核(2)」可作废;状态置为已作废(5),记录作废人/时间/原因,不可恢复也禁止删除;
* 作废时释放审核锁定的库存(写 order_unlock 流水)
* @router post /api/order-deliveries/{id}/void
* @apikey
* @request path integer *id 发货单主键ID
@ -1111,6 +1267,15 @@ class OrderDeliveryController extends Controller {
const body = ctx.request.body || {};
const reason = body.void_reason ? String(body.void_reason).trim() : '';
// 作废前释放审核时锁定的库存(并记 order_unlock 流水);释放失败则不流转状态
try {
await releaseDeliveryStock(ctx, order, { createdBy: ctx.userId, remark: '订单作废释放锁定库存' });
} catch (err) {
ctx.logger.error(`[order-delivery] 作废释放库存失败 id=${order.id}`, err);
ctx.status = 500;
ctx.body = { code: 500, message: `作废失败(释放锁定库存异常):${err.message}` };
return;
}
await order.update({
status: 5,
void_at: new Date(),
@ -1161,7 +1326,11 @@ class OrderDeliveryController extends Controller {
// 店铺筛选:from_shop_id 为通用写法(shop_id 仅作兼容,设置店铺接口里 shop_id 是「目标店铺」不能当条件)
const fromShopId = body.from_shop_id ? Number(body.from_shop_id) : (body.shop_id ? Number(body.shop_id) : null);
const fromWarehouseId = body.from_warehouse_id ? Number(body.from_warehouse_id) : null;
if (!code && status === null && !orderType && !fromShopId && !fromWarehouseId) {
// 回传平台店铺状态筛选(与列表 index 同口径,保证「当前筛选条件」不被忽略)
const shopSyncStatus = body.shop_sync_status === undefined || body.shop_sync_status === null || body.shop_sync_status === ''
? null
: Number(body.shop_sync_status);
if (!code && status === null && !orderType && !fromShopId && !fromWarehouseId && shopSyncStatus === null) {
return { ok: false, message: '请指定操作范围:勾选单据(ids)或至少传一个筛选条件' };
}
if (code) where.delivery_order_code = { [Op.like]: `%${code}%` };
@ -1169,6 +1338,7 @@ class OrderDeliveryController extends Controller {
if (orderType) where.order_type = orderType;
if (fromShopId) where.shop_id = fromShopId;
if (fromWarehouseId) where.warehouse_id = fromWarehouseId;
if (shopSyncStatus !== null) where.shop_sync_status = shopSyncStatus;
}
const dryRun = body.dry_run === true || body.dry_run === 'true' || body.dry_run === 1;

View File

@ -2,7 +2,7 @@
const { Controller } = require('egg');
const recalcStock = require('../utils/recalcStock');
const stock = require('../utils/stock');
const { applyStockChange } = require('../utils/stockRecord');
const nextRejectedBillNo = require('../utils/rejectBillNo');
const { parsePagination, buildPageResult } = require('../lib/pagination');
const QimenWmsClient = require('../lib/wms/qimenClient');
@ -19,7 +19,8 @@ const OUTBOUND_BILL_PREFIX = 'CK';
*/
const MANAGED_FIELDS = [
'bill_no', 'status', 'pushed_at', 'wms_push_result',
'void_at', 'void_by', 'void_reason', 'stock_deducted', 'item_total', 'item_kind',
'void_at', 'void_by', 'void_reason', 'stock_deducted', 'stock_locked', 'item_total', 'item_kind',
'waybill_codes',
];
/**
@ -277,7 +278,18 @@ class OutboundOrderController extends Controller {
}
}
/** 审核:已创建(1) -> 已审核(2),需先录入明细 */
/**
* @summary 审核出库单
* @description 状态流转:待出库(1) → 已审核(2);需先录入明细。
* **审核只入队不推送**:由定时任务(app/schedule/outboundOrderPush.js)异步递交 WMS stockout.create,
* 避免集中审核时把对方服务打满;也可用「推送」按钮立即推送(状态仍需为已审核)。
* 审核同时清空上一轮推送记录(重试次数归零)。推送失败的处理见 app/service/outboundOrderPush.js:
* 对方明确失败(含库存锁定失败)立即退回「待出库(1)」并释放锁定库存;无响应/超时最多尝试 3 次后同样退回。
* @router post /api/outbound-orders/{id}/audit
* @apikey
* @request path integer *id 出库单主键ID
* @response 200 baseResponse success
*/
async audit() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
@ -297,8 +309,49 @@ class OutboundOrderController extends Controller {
ctx.body = { code: 400, message: '单据无明细,无法审核' };
return;
}
await order.update({ status: 2 });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
// 清空上一轮推送记录(重试次数从 0 开始),进入推送队列等待定时任务自动推送
await order.update({ status: 2, pushed_at: null, wms_push_result: null });
ctx.body = {
code: 0,
message: '审核成功,已进入推送队列,稍后自动推送仓库',
data: { id: order.id, status: 2 },
};
}
/**
* 推送:已审核(2) -> 已推送(3),立即递交 WMS(stockout.create)一次
*
* 详细口径(锁定库存、失败冲正与重试)见 app/service/outboundOrderPush.js;
* 定时任务会自动推送「已审核」单据,此接口用于需要立即推送的场景
* @router post /api/outbound-orders/{id}/push
* @apikey
* @request path integer *id 出库单主键ID
* @response 200 baseResponse success
*/
async push() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id, { attributes: [ 'id', 'status' ] });
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
if (order.status !== 2) {
ctx.status = 400;
ctx.body = { code: 400, message: '只有「已审核」状态的单据可以推送' };
return;
}
const pushResult = await ctx.service.outboundOrderPush.pushOne(order.id, { source: 'manual' });
if (!pushResult.ok) {
ctx.status = pushResult.skipped ? 400 : 502;
ctx.body = { code: ctx.status, message: pushResult.message };
return;
}
ctx.body = {
code: 0,
message: 'success',
data: { id: order.id, status: 3, attempts: pushResult.attempts, wms_response: pushResult.response },
};
}
/**
* 推送:已审核(2) -> 已推送(3),锁定库存(占用可用,防超卖)并递交 WMS(stockout.create)
@ -375,7 +428,22 @@ class OutboundOrderController extends Controller {
const qty = Number(it.quantity) || 0;
try {
// 行级库存类型:CC=残次 -> 锁定残次库存,其余(ZP等)归为正品 ZC
await stock.lock(ctx, order.principal_id, pid, qty, reserveTx, it.inventory_type === 'CC' ? 'CC' : 'ZC');
// 锁定同时写一条「出入库记录」(outbound_lock),记录锁定前后的锁定/可用数量
await applyStockChange(ctx, {
bizType: 'outbound_lock',
principalId: order.principal_id,
warehouseId: order.warehouse_id,
productId: pid,
itemCode: it.code || (pmap.get(pid) && pmap.get(pid).item_code),
itemName: it.name || (pmap.get(pid) && pmap.get(pid).item_name),
itemType: it.inventory_type === 'CC' ? 'CC' : 'ZC',
quantity: qty,
billId: order.id,
billNo: order.bill_no,
createdBy: ctx.userId,
remark: '出库单推送仓库锁定库存',
transaction: reserveTx,
});
} catch (err) {
if (err.code === 'INSUFFICIENT_STOCK') {
const p = pmap.get(pid);
@ -450,13 +518,27 @@ class OutboundOrderController extends Controller {
ctx.body = { code: 502, message: err.message };
}
}
/** 推送失败时释放已锁定库存 */
/** 推送失败时释放已锁定库存(并记一条出库解锁流水) */
async _releaseStock(order, items) {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
for (const it of items) {
await stock.unlock(ctx, order.principal_id, Number(it.product_id), Number(it.quantity) || 0, transaction, it.inventory_type === 'CC' ? 'CC' : 'ZC');
await applyStockChange(ctx, {
bizType: 'outbound_unlock',
principalId: order.principal_id,
warehouseId: order.warehouse_id,
productId: Number(it.product_id),
itemCode: it.code,
itemName: it.name,
itemType: it.inventory_type === 'CC' ? 'CC' : 'ZC',
quantity: Number(it.quantity) || 0,
billId: order.id,
billNo: order.bill_no,
createdBy: ctx.userId,
remark: '推送失败释放锁定库存',
transaction,
});
}
await transaction.commit();
} catch (err) {
@ -505,13 +587,27 @@ class OutboundOrderController extends Controller {
if (order.status === 3) {
const items = await ctx.model.StockItem.findAll({
where: { bill_type: 2, bill_id: order.id, product_id: { [ctx.app.Sequelize.Op.ne]: null } },
attributes: [ 'product_id', 'quantity', 'inventory_type' ],
attributes: [ 'product_id', 'code', 'name', 'quantity', 'inventory_type' ],
order: [[ 'product_id', 'ASC' ]],
});
const transaction = await ctx.model.transaction();
try {
for (const it of items) {
await stock.unlock(ctx, order.principal_id, Number(it.product_id), Number(it.quantity) || 0, transaction, it.inventory_type === 'CC' ? 'CC' : 'ZC');
await applyStockChange(ctx, {
bizType: 'outbound_unlock',
principalId: order.principal_id,
warehouseId: order.warehouse_id,
productId: Number(it.product_id),
itemCode: it.code,
itemName: it.name,
itemType: it.inventory_type === 'CC' ? 'CC' : 'ZC',
quantity: Number(it.quantity) || 0,
billId: order.id,
billNo: order.bill_no,
createdBy: ctx.userId,
remark: '出库单取消释放锁定库存',
transaction,
});
}
await order.update({ status: 9 }, { transaction });
await transaction.commit();
@ -640,7 +736,7 @@ class OutboundOrderController extends Controller {
const items = await ctx.model.StockItem.findAll({
where: { bill_type: 2, bill_id: order.id, product_id: { [ctx.app.Sequelize.Op.ne]: null } },
attributes: [ 'product_id', 'quantity', 'inventory_type' ],
attributes: [ 'product_id', 'code', 'name', 'quantity', 'inventory_type' ],
order: [[ 'product_id', 'ASC' ]],
});
const transaction = await ctx.model.transaction();
@ -651,11 +747,39 @@ class OutboundOrderController extends Controller {
// 行级库存类型:CC=残次 -> 残次库存,其余(ZP等)归为正品 ZC
const itemType = it.inventory_type === 'CC' ? 'CC' : 'ZC';
if (order.stock_deducted) {
// 发货通知已按明细扣减总数量(锁定已同步释放):回补总数量
await stock.increase(ctx, order.principal_id, pid, qty, transaction, itemType);
// 发货通知已按明细扣减总数量(锁定已同步释放):回补总数量(并记一条出库驳回回补流水)
await applyStockChange(ctx, {
bizType: 'outbound_restore',
principalId: order.principal_id,
warehouseId: order.warehouse_id,
productId: pid,
itemCode: it.code,
itemName: it.name,
itemType,
quantity: qty,
billId: order.id,
billNo: order.bill_no,
createdBy: ctx.userId,
remark: '出库单驳回回补总数量',
transaction,
});
} else {
// 仅推送锁定、尚未扣减:释放锁定
await stock.unlock(ctx, order.principal_id, pid, qty, transaction, itemType);
// 仅推送锁定、尚未扣减:释放锁定(并记一条出库解锁流水)
await applyStockChange(ctx, {
bizType: 'outbound_unlock',
principalId: order.principal_id,
warehouseId: order.warehouse_id,
productId: pid,
itemCode: it.code,
itemName: it.name,
itemType,
quantity: qty,
billId: order.id,
billNo: order.bill_no,
createdBy: ctx.userId,
remark: '出库单驳回释放锁定',
transaction,
});
}
}
const newBillNo = nextRejectedBillNo(order.bill_no, order.id, OUTBOUND_BILL_PREFIX);

View File

@ -0,0 +1,130 @@
'use strict';
const { Controller } = require('egg');
const { parsePagination, buildPageResult } = require('../lib/pagination');
const { BIZ_TYPES, BIZ_TYPE_LIST, DIRECTION_LABELS } = require('../utils/stockRecord');
/**
* 把查询入参转成 Date:日期(YYYY-MM-DD)按当天 00:00:00 / 23:59:59 处理,含时间的按原值
* @param {String} value 入参时间字符串
* @param {Boolean} isEnd 是否为区间结束(true 时补到当天最后一刻)
* @return {Date|null} Date 或 null
*/
function toDate(value, isEnd) {
const raw = String(value == null ? '' : value).trim();
if (!raw) return null;
const normalized = raw.includes('T') ? raw : raw.replace(' ', 'T');
const dateOnly = /^\d{4}-\d{2}-\d{2}$/.test(raw);
const text = dateOnly ? `${raw}T${isEnd ? '23:59:59' : '00:00:00'}` : normalized;
const date = new Date(text);
return Number.isNaN(date.getTime()) ? null : date;
}
/**
* @controller StockRecordController 出入库记录(库存流水)
*
* 记录每一次库存变动:出库单推送锁定、出库解锁、出库确认扣减、出库驳回回补、入库确认增加,
* 以及发货单(订单)审核锁定、订单解锁、订单发货确认扣减,
* 写入入口统一在 app/utils/stockRecord.js(与库存变动同事务),本控制器只提供只读查询。
* 数据按主体隔离(principal_id 由 principalCheck 中间件校验后写入 ctx.state.principalId)。
*/
class StockRecordController extends Controller {
/**
* @summary 出入库记录列表
* @description 分页查询当前主体下的库存流水,支持按商品、仓库、业务动作、出入方向、单据类型、
* 单据号与时间区间过滤;keyword 同时匹配单据号/商品编码/商品名称。
* 前端可先用商品选择器按「商品编码/商品名称」关键词锁定 product_id,再按商品精确查询。
* @router get /api/stock-records
* @apikey
* @request query integer page 页码,默认 1
* @request query integer pageSize 每页条数,默认 20
* @request query integer product_id 商品ID(商品选择器锁定后传入,精确匹配)
* @request query integer warehouse_id 仓库ID
* @request query string biz_type 业务动作:outbound_lock 出库推送锁定 / outbound_unlock 出库解锁 / outbound_deduct 出库确认扣减 / outbound_restore 出库驳回回补 / inbound_increase 入库确认增加 / order_lock 订单审核锁定 / order_unlock 订单解锁 / order_deduct 订单发货确认扣减
* @request query integer direction 业务方向:1入库方向 2出库方向
* @request query integer bill_type 单据类型:1入库单 2出库单 3发货单(订单)
* @request query string item_type 库存类型:ZC 正品 / CC 残次品
* @request query string bill_no 单据号,支持模糊匹配
* @request query string keyword 关键词,匹配单据号/商品编码/商品名称
* @request query string start_time 记录时间起(YYYY-MM-DD 或 YYYY-MM-DD HH:mm:ss)
* @request query string end_time 记录时间止(日期只写到天时按当天 23:59:59)
* @response 200 stockRecordListResponse success
*/
async index() {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
const {
product_id: productId,
warehouse_id: warehouseId,
biz_type: bizType,
direction,
bill_type: billType,
item_type: itemType,
bill_no: billNo,
keyword,
start_time: startTime,
end_time: endTime,
} = ctx.query;
const where = { principal_id: ctx.state.principalId };
if (productId) where.product_id = Number(productId);
if (warehouseId) where.warehouse_id = Number(warehouseId);
if (bizType) where.biz_type = String(bizType).trim();
if (direction !== undefined && direction !== '') where.direction = Number(direction);
if (billType !== undefined && billType !== '') where.bill_type = Number(billType);
if (itemType) where.item_type = String(itemType).trim().toUpperCase();
if (billNo) where.bill_no = { [Op.like]: `%${billNo}%` };
// 关键词:未锁定商品时用模糊匹配(单据号 / 商品编码 / 商品名称);已锁定商品时用 product_id 精确过滤
if (keyword) {
where[Op.or] = [
{ bill_no: { [Op.like]: `%${keyword}%` } },
{ item_code: { [Op.like]: `%${keyword}%` } },
{ item_name: { [Op.like]: `%${keyword}%` } },
];
}
const startDate = toDate(startTime, false);
const endDate = toDate(endTime, true);
if (startDate || endDate) {
where.created_at = {};
if (startDate) where.created_at[Op.gte] = startDate;
if (endDate) where.created_at[Op.lte] = endDate;
// 只有一个边界时补全另一个,避免 Sequelize 生成空条件
if (!startDate) where.created_at[Op.gte] = new Date(0);
if (!endDate) where.created_at[Op.lte] = new Date();
}
const { count, rows } = await ctx.model.StockRecord.findAndCountAll({
where,
offset,
limit,
order: [[ 'id', 'DESC' ]],
});
// 附上中文标签,前端直接展示(避免前后端枚举文案漂移)
const list = rows.map(row => {
const item = row.get ? row.get({ plain: true }) : row;
const meta = BIZ_TYPES[item.biz_type] || {};
item.biz_type_label = meta.label || item.biz_type;
item.direction_label = DIRECTION_LABELS[item.direction] || '';
return item;
});
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) };
}
/**
* @summary 出入库记录业务动作选项
* @description 返回业务动作枚举(值与中文名、方向、单据类型),供前端筛选下拉使用,避免前后端枚举漂移
* @router get /api/stock-records/biz-types
* @apikey
* @response 200 baseResponse success
*/
async bizTypes() {
const { ctx } = this;
ctx.body = { code: 0, message: 'success', data: BIZ_TYPE_LIST };
}
}
module.exports = StockRecordController;

View File

@ -0,0 +1,252 @@
'use strict';
const { Controller } = require('egg');
const { parsePagination, buildPageResult } = require('../lib/pagination');
/**
* 编码归一化:去空白 + 转大写(字典 code 与外部传入编码比对均按大写口径)
* @param {*} value 原值
* @return {string} 归一化后的编码
*/
function normalizeCode(value) {
return value === undefined || value === null ? '' : String(value).trim().toUpperCase();
}
/**
* @controller WarehouseExpressMappingController 仓库快递映射
* 配置「外部传入的快递编码(自定义编码)→ OMS 默认快递编码」的映射,按仓库维度维护;
* 供 WMS 出库确认 / 发货确认回传时解析快递编码使用(映射优先 → 字典兜底 → 都没有报错)。
*
* 表格展示:快递名称(express_companies 派生)、默认快递编码(express_code)、自定义编码(custom_code)。
*/
class WarehouseExpressMappingController extends Controller {
/**
* @summary 仓库快递映射列表
* @description 分页查询映射,支持按仓库、默认/自定义编码与状态过滤;附快递名称(字典派生)
* @router get /api/warehouse-express-mappings
* @apikey
* @request query integer page 页码,默认 1
* @request query integer pageSize 每页条数,默认 20
* @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
* @request query integer warehouse_id 仓库ID
* @request query string express_code 默认快递编码(模糊匹配)
* @request query string custom_code 自定义编码(模糊匹配)
* @request query integer status 状态:1启用 0禁用
* @response 200 warehouseExpressMappingListResponse success
*/
async index() {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
const { warehouse_id: warehouseId, express_code: expressCode, custom_code: customCode, status } = ctx.query;
const where = { principal_id: ctx.state.principalId };
if (warehouseId) where.warehouse_id = Number(warehouseId);
if (expressCode) where.express_code = { [Op.like]: `%${normalizeCode(expressCode)}%` };
if (customCode) where.custom_code = { [Op.like]: `%${normalizeCode(customCode)}%` };
if (status !== undefined && status !== '') where.status = Number(status);
const { count, rows } = await ctx.model.WarehouseExpressMapping.findAndCountAll({
where,
offset,
limit,
order: [[ 'warehouse_id', 'ASC' ], [ 'id', 'DESC' ]],
include: [
{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] },
{ model: ctx.model.ExpressCompany, as: 'expressCompany', attributes: [ 'id', 'code', 'name' ] },
],
});
const list = rows.map(row => {
const plain = row.get({ plain: true });
// 快递名称:优先取字典关联结果(字典被删除时回退为空),保证表格「快递名称」列始终可用
plain.express_name = (plain.expressCompany && plain.expressCompany.name) || '';
delete plain.expressCompany;
return plain;
});
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) };
}
/**
* @summary 仓库快递映射详情
* @router get /api/warehouse-express-mappings/{id}
* @apikey
* @request path integer *id 映射主键ID
* @response 200 warehouseExpressMappingItem success
*/
async show() {
const { ctx } = this;
const row = await ctx.model.WarehouseExpressMapping.findOne({
where: { id: ctx.params.id, principal_id: ctx.state.principalId },
include: [
{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] },
{ model: ctx.model.ExpressCompany, as: 'expressCompany', attributes: [ 'id', 'code', 'name' ] },
],
});
if (!row) {
ctx.status = 404;
ctx.body = { code: 404, message: '仓库快递映射不存在' };
return;
}
const plain = row.get({ plain: true });
plain.express_name = (plain.expressCompany && plain.expressCompany.name) || '';
delete plain.expressCompany;
ctx.body = { code: 0, message: 'success', data: plain };
}
/**
* @summary 新增仓库快递映射
* @description 校验仓库属于当前主体、默认快递编码存在于快递公司字典、同仓库内自定义编码不重复
* @router post /api/warehouse-express-mappings
* @apikey
* @request body createWarehouseExpressMappingRequest *body
* @response 200 baseResponse success
*/
async create() {
const { ctx } = this;
const body = { ...ctx.request.body };
const principalId = ctx.state.principalId;
const checked = await this._validate(ctx, {
principalId,
warehouseId: body.warehouse_id,
expressCode: body.express_code,
customCode: body.custom_code,
});
if (!checked.ok) {
ctx.status = 400;
ctx.body = { code: 400, message: checked.message };
return;
}
const item = await ctx.model.WarehouseExpressMapping.create({
principal_id: principalId,
warehouse_id: checked.warehouseId,
express_code: checked.expressCode,
custom_code: checked.customCode,
status: body.status === undefined || body.status === '' ? 1 : Number(body.status) === 1 ? 1 : 0,
remark: body.remark || null,
});
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
}
/**
* @summary 更新仓库快递映射
* @description 仅更新传入字段;同样校验仓库归属、字典存在性与编码唯一性(排除自身)
* @router put /api/warehouse-express-mappings/{id}
* @apikey
* @request path integer *id 映射主键ID
* @request body updateWarehouseExpressMappingRequest body
* @response 200 baseResponse success
*/
async update() {
const { ctx } = this;
const item = await ctx.model.WarehouseExpressMapping.findOne({
where: { id: ctx.params.id, principal_id: ctx.state.principalId },
});
if (!item) {
ctx.status = 404;
ctx.body = { code: 404, message: '仓库快递映射不存在' };
return;
}
const body = { ...ctx.request.body };
delete body.principal_id;
const warehouseId = body.warehouse_id === undefined ? item.warehouse_id : body.warehouse_id;
const expressCode = body.express_code === undefined ? item.express_code : body.express_code;
const customCode = body.custom_code === undefined ? item.custom_code : body.custom_code;
const checked = await this._validate(ctx, {
principalId: item.principal_id,
warehouseId,
expressCode,
customCode,
excludeId: item.id,
});
if (!checked.ok) {
ctx.status = 400;
ctx.body = { code: 400, message: checked.message };
return;
}
const patch = {
warehouse_id: checked.warehouseId,
express_code: checked.expressCode,
custom_code: checked.customCode,
};
if (body.status !== undefined && body.status !== '') patch.status = Number(body.status) === 1 ? 1 : 0;
if (body.remark !== undefined) patch.remark = body.remark || null;
await item.update(patch);
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
}
/**
* @summary 删除仓库快递映射
* @router delete /api/warehouse-express-mappings/{id}
* @apikey
* @request path integer *id 映射主键ID
* @response 200 baseResponse success
*/
async destroy() {
const { ctx } = this;
const item = await ctx.model.WarehouseExpressMapping.findOne({
where: { id: ctx.params.id, principal_id: ctx.state.principalId },
});
if (!item) {
ctx.status = 404;
ctx.body = { code: 404, message: '仓库快递映射不存在' };
return;
}
await item.destroy();
ctx.body = { code: 0, message: 'success' };
}
/**
* 校验映射入参(仓库归属主体 + 默认快递编码在字典中 + 自定义编码同仓库唯一)
* @param {Object} ctx egg context
* @param {Object} params 校验参数
* @param {Number} params.principalId 主体ID
* @param {*} params.warehouseId 仓库ID
* @param {*} params.expressCode 默认快递编码
* @param {*} params.customCode 自定义编码
* @param {Number} [params.excludeId] 更新时排除的自身ID
* @return {Promise<{ok: Boolean, message?: String, warehouseId?: Number, expressCode?: String, customCode?: String}>}
*/
async _validate(ctx, { principalId, warehouseId, expressCode, customCode, excludeId }) {
const id = Number(warehouseId);
if (!id) return { ok: false, message: 'warehouse_id(仓库)为必填项' };
const warehouse = await ctx.model.Warehouse.findOne({ where: { id, principal_id: principalId }, attributes: [ 'id' ] });
if (!warehouse) return { ok: false, message: '仓库不存在或不属于当前主体' };
const code = normalizeCode(expressCode);
if (!code) return { ok: false, message: 'express_code(默认快递编码)为必填项' };
const company = await ctx.model.ExpressCompany.findOne({ where: { code }, attributes: [ 'id', 'code', 'name' ] });
if (!company) {
return { ok: false, message: `默认快递编码 ${code} 不在快递公司字典中,请先在「快递公司」中维护` };
}
const custom = normalizeCode(customCode);
if (!custom) return { ok: false, message: 'custom_code(自定义编码)为必填项' };
if (custom === code) {
return { ok: false, message: '自定义编码不能与默认快递编码相同(相同即无需映射)' };
}
const Op = this.app.Sequelize.Op;
const duplicate = await ctx.model.WarehouseExpressMapping.findOne({
where: {
warehouse_id: id,
custom_code: custom,
...(excludeId ? { id: { [Op.ne]: excludeId } } : {}),
},
attributes: [ 'id' ],
});
if (duplicate) {
return { ok: false, message: `该仓库下自定义编码 ${custom} 已存在映射(同仓库内唯一),请直接编辑原记录` };
}
return { ok: true, warehouseId: id, expressCode: code, customCode: custom };
}
}
module.exports = WarehouseExpressMappingController;

View File

@ -3,7 +3,7 @@
const { Controller } = require('egg');
const { qimenSign, timingSafeEqual } = require('../lib/wms/sign');
const orderCallback = require('../lib/orderCallback');
const stock = require('../utils/stock');
const { applyStockChange } = require('../utils/stockRecord');
/** 时间戳时效阈值:±10 分钟(600 秒),与 WMS 文档一致 */
const TIME_TOLERANCE_SEC = 600;
@ -121,11 +121,24 @@ class WmsNotifyController extends Controller {
if (order && !order.stock_deducted) {
const items = await ctx.model.StockItem.findAll({
where: { bill_type: 2, bill_id: order.id, product_id: { [ctx.app.Sequelize.Op.ne]: null } },
attributes: [ 'product_id', 'quantity' ],
attributes: [ 'product_id', 'code', 'name', 'quantity' ],
order: [[ 'product_id', 'ASC' ]],
});
for (const it of items) {
await stock.deduct(ctx, principalId, Number(it.product_id), Number(it.quantity) || 0, transaction);
// 扣减库存 + 写一条出库确认记录(含变动后锁定数量与可用数量)
await applyStockChange(ctx, {
bizType: 'outbound_deduct',
principalId,
warehouseId: api.warehouse_id,
productId: Number(it.product_id),
itemCode: it.code,
itemName: it.name,
quantity: Number(it.quantity) || 0,
billId: order.id,
billNo: order.bill_no,
remark: 'WMS 发货通知扣减库存(notify.delivery)',
transaction,
});
}
await order.update({ stock_deducted: 1 }, { transaction });
deducted = true;
@ -144,7 +157,18 @@ class WmsNotifyController extends Controller {
if (!itemCode || qty <= 0) continue;
const product = await ctx.model.Product.findOne({ where: { item_code: itemCode, principal_id: principalId } });
if (!product) continue;
await stock.deduct(ctx, principalId, product.id, qty, transaction);
await applyStockChange(ctx, {
bizType: 'outbound_deduct',
principalId,
warehouseId: api.warehouse_id,
productId: product.id,
itemCode,
itemName: product.item_name,
quantity: qty,
billNo: code,
remark: 'WMS 发货通知扣减库存(按明细兜底)',
transaction,
});
}
}
await transaction.commit();

View File

@ -18,8 +18,11 @@ const orderCallback = require('./orderCallback');
* data 为成功时的业务数据,外层由控制器统一包装为 { flag, code, message, data, timestamp }。
*
* 单据处理统一走 app/lib/orderCallback.js:按 app_key 定位到的「主体 + 仓库」校验后
* 用单据号(inbound_orders.bill_no / outbound_orders.bill_no)定位 OMS 单据;
* 新增方法时在 METHODS 中按 `模块.动作` 注册即可。
* 用单据号(inbound_orders.bill_no / outbound_orders.bill_no / order_deliveries.delivery_order_code)
* 定位 OMS 单据;新增方法时在 METHODS 中按 `模块.动作` 注册即可。
*
* ⚠️ 单号表不可混用(以 D:/wms/methods/openapi_callback.json 为准):
* entryorder.confirm → 入库单;stockout.confirm → 出库单(CK_ 组);deliveryorder.confirm → 发货单(FH_ 组)
*/
const METHODS = {
/**
@ -96,29 +99,36 @@ const METHODS = {
}),
/**
* 发货单确认(method = deliveryorder.confirm):WMS 已发货出库
* 写回明细「已出数量」,扣减系统库存并置「已完成(4)」(幂等,明细以仓库侧为准)
* 发货单确认(method = deliveryorder.confirm):WMS 已完成发货(ORDER 组 JYCK/HHCK/BFCK)
* 报文:`{ request: { deliveryOrder: { deliveryOrderCode }, packages: { package: [...] }, orderLines: [...] } }`
* (对齐 D:/wms/methods/openapi_callback.json#deliveryorder.confirm)
* 处理:按 deliveryOrderCode / outBizCode 定位发货单(order_deliveries)→ 回写
* `packages.package[].expressCode` 运单号与物流公司 → 状态「已推送(3)」→「已完成(4)」;幂等
* @param {Object} ctx egg context
* @param {Object} payload 调用上下文
* @param {Object} payload.api 按 app_key 定位到的接口配置
* @param {Object} payload.warehouse 接口配置关联的仓库
* @param {Object} payload.body 回调报文(含 deliveryOrderCode / orderCode 与 orderLines)
* @param {Object} payload.body 回调报文(含 deliveryOrder / packages / orderLines)
* @return {Promise<Object>} { ok, message, data }
*/
'deliveryorder.confirm': (ctx, { api, warehouse, body }) => orderCallback.confirmOutbound(ctx, {
'deliveryorder.confirm': (ctx, { api, warehouse, body }) => orderCallback.confirmDelivery(ctx, {
principalId: api.principal_id,
warehouseId: warehouse.id,
data: body,
}),
/**
* 出库单确认(method = stockout.confirm):WMS 出库完成(非订单出库单)
* 处理同 deliveryorder.confirm,单号取 stockoutOrderCode / orderCode
* 出库单确认(method = stockout.confirm):WMS 出库完成(非订单出库单,CK 组 / wms_order_stockout)
* 写回明细「已出数量」,扣减系统库存并置「已完成(4)」(幂等,明细以仓库侧为准)
* 报文:`{ request: { deliveryOrder: { deliveryOrderCode, outBizCode }, packages, orderLines } }`
* (对齐 D:/wms/methods/openapi_callback.json#stockout.confirm,deliveryOrderCode = 出库单号 stockout_order_code)
* 出库单无运单号/物流公司列 → 报文里的包裹/运单信息留存在 `outbound_orders.wms_push_result.confirm`(幂等)
* 注:发货单(ORDER 组)的完成回调是 deliveryorder.confirm,走 confirmDelivery,不能用本方法
* @param {Object} ctx egg context
* @param {Object} payload 调用上下文
* @param {Object} payload.api 按 app_key 定位到的接口配置
* @param {Object} payload.warehouse 接口配置关联的仓库
* @param {Object} payload.body 回调报文(含 stockoutOrderCode / orderCode 与 orderLines)
* @param {Object} payload.body 回调报文(含 deliveryOrder.deliveryOrderCode / outBizCode 与 orderLines)
* @return {Promise<Object>} { ok, message, data }
*/
'stockout.confirm': (ctx, { api, warehouse, body }) => orderCallback.confirmOutbound(ctx, {

View File

@ -1,7 +1,8 @@
'use strict';
const stock = require('../utils/stock');
const completeInbound = require('../utils/completeInbound');
const { applyStockChange } = require('../utils/stockRecord');
const { deductDeliveryStock } = require('../utils/deliveryStock');
/**
* 外部回调(对外通用回调接口 /openapi)驱动 OMS 单据的共用处理逻辑。
@ -11,7 +12,10 @@ const completeInbound = require('../utils/completeInbound');
* 因此「写回实际数量」「按单号定位单据」只保留这一份实现。
*
* 单据定位规则:app_key 已在控制器侧定位到「主体 + 仓库」,此处按
* bill_no(WMS entryOrderCode / deliveryOrderCode / stockoutOrderCode)+ principal_id 查单,
* 入库单 / 出库单:bill_no(WMS entryOrderCode / stockoutOrderCode)+ principal_id 查单;
* 其中 stockout.confirm 的出库单号在 request.deliveryOrder.deliveryOrderCode(同 outBizCode),
* 入库单号在 request.entryOrder.entryOrderCode;
* 发货单:delivery_order_code(WMS deliveryOrderCode / outBizCode)+ principal_id 查单,
* 并校验单据的 warehouse_id 与 app_key 定位到的仓库一致,避免跨仓库误处理。
*
* 报文结构兼容(见 unwrapPayload):openapi 出站回调整体包一层 request(request.entryOrder.entryOrderCode),
@ -26,17 +30,46 @@ const INBOUND_CODE_PATHS = [
'order.orderCode',
];
/** 出库单单号候选字段(支持嵌套路径) */
/**
* 出库单单号候选字段(支持嵌套路径)
* 对应 WMS 出站回调 `stockout.confirm`(见 D:/wms/methods/openapi_callback.json:报文体为
* `{ request: { deliveryOrder: { deliveryOrderCode, outBizCode }, packages, orderLines } }`,
* 其中 deliveryOrder.deliveryOrderCode = wms_order_stockout.stockout_order_code,outBizCode 同值);
* 部分外部系统会按奇门 flat 结构直接下发顶层 stockoutOrderCode / orderCode,故一并兼容。
* 注:候选路径允许与 deliveryorder.confirm 同名(deliveryOrder.deliveryOrderCode),
* 两者不会混用 —— 方法名已决定查哪张单号表(stockout.confirm→outbound_orders,
* deliveryorder.confirm→order_deliveries),本常量只被 confirmOutbound / cancelOrder 使用。
*/
const OUTBOUND_CODE_PATHS = [
'deliveryOrderCode',
'deliveryOrder.deliveryOrderCode',
'stockoutOrderCode',
'stockoutOrder.stockoutOrderCode',
'stockout.stockoutOrderCode',
'deliveryOrder.deliveryOrderCode',
'deliveryOrder.stockoutOrderCode',
'deliveryOrder.outBizCode',
'orderCode',
'order.orderCode',
];
/**
* 发货单单号候选字段(支持嵌套路径)
* 对应 WMS 出站回调 `deliveryorder.confirm`(见 D:/wms/methods/openapi_callback.json:
* request.deliveryOrder.deliveryOrderCode = wms_order.delivery_order_code,outBizCode 同值)
*/
const DELIVERY_CODE_PATHS = [
'deliveryOrderCode',
'deliveryOrder.deliveryOrderCode',
'outBizCode',
'deliveryOrder.outBizCode',
'orderCode',
'order.orderCode',
];
/** 发货单已完成状态(order_deliveries.status) */
const DELIVERY_STATUS_DONE = 4;
/** 发货单已推送状态(可被发货确认推进为已完成) */
const DELIVERY_STATUS_PUSHED = 3;
/** 入库单匹配信息候选字段 */
const MATCH_INFO_PATHS = {
match_type: [ 'matchType', 'match_type' ],
@ -102,6 +135,227 @@ function extractLines(data) {
return [];
}
/**
* 从回调报文中提取包裹数组(deliveryorder.confirm 的 packages.package)
* 兼容 `{ packages: { package: [ ... ] } }`(WMS 实际结构)、`{ packages: [ ... ] }`、
* `{ packages: { package: { ... } } }`(单包裹对象)与顶层 `package`。
* @param {Object} data 回推报文(已归一化)
* @return {Array<Object>} 包裹数组(无则空数组)
*/
function extractPackages(data) {
const source = data || {};
const raw = source.packages
|| (source.deliveryOrder && source.deliveryOrder.packages)
|| source.package
|| [];
const list = raw && !Array.isArray(raw) && raw.package !== undefined ? raw.package : raw;
if (Array.isArray(list)) return list.filter(v => v && typeof v === 'object' && !Array.isArray(v));
return list && typeof list === 'object' && !Array.isArray(list) ? [ list ] : [];
}
/**
* 在包裹数组中按候选字段取第一个非空字符串
* @param {Array<Object>} packages 包裹数组
* @param {Array<String>} keys 候选字段名
* @return {String} 值(无则空串)
*/
function pickFromPackages(packages, keys) {
for (const pkg of packages || []) {
const value = pickFromObject(pkg, keys);
if (value) return value;
}
return '';
}
/**
* 汇总包裹数组里的全部运单号(一单可拆多个包裹 → 多个运单号,去重去空)
* 与 pickFromPackages(只取第一个)区分:本函数用于多值列(出库单 outbound_orders.waybill_codes /
* 发货单 order_deliveries.express_codes)。
* @param {Array<Object>} packages 包裹数组
* @return {Array<String>} 运单号数组(无则空数组)
*/
function collectExpressCodes(packages) {
const codes = [];
for (const pkg of packages || []) {
const code = truncate(pickFromObject(pkg, [ 'expressCode', 'express_code' ]), 50);
if (code && !codes.includes(code)) codes.push(code);
}
return codes;
}
/**
* 解析回传包裹里的快递编码(**仓库映射优先 → 字典兜底 → 都没有报错**)
*
* 顺序(口径对齐 WMS `stockout_order.js#resolveStockoutExpress` 的「先 wms_express_setting 映射、
* 再系统快递列表匹配」):
* ① 命中「仓库快递映射」(warehouse_express_mappings:warehouse_id + custom_code,status=1)
* → 取映射到的**默认快递编码**(express_code)与其字典名称;
* ② 未命中映射 → 外部编码本身若在快递公司字典(express_companies)里,直接**兜底**用原编码;
* ③ 两者都没有 → 报错,提示去 OMS 外部仓库配置映射。
*
* 口径:只解析**非空**编码(未传 packages / 编码为空时不拦截,该字段在 WMS 规范里选填);
* 比对统一 trim + 大写。
* @param {Object} ctx egg context
* @param {Number} warehouseId app_key 定位到的仓库ID(映射按仓库维度)
* @param {Array<Object>} packages 包裹数组
* @return {Promise<{ok: Boolean, items: Array<Object>, first: Object|null, message?: String}>}
* items: [{ raw, code, name, source }],source = mapping(映射命中)/ dictionary(字典兜底);
* first: 第一个解析结果,供覆盖本地快递列(多包裹时取第一个非空)
*/
async function resolvePackageExpress(ctx, warehouseId, packages) {
const raws = [];
for (const pkg of packages || []) {
const raw = truncate(pickFromObject(pkg, [ 'logisticsCode', 'logistics_code' ]), 50).toUpperCase();
if (raw && !raws.includes(raw)) raws.push(raw);
}
if (!raws.length) return { ok: true, items: [], first: null };
const Op = ctx.app.Sequelize.Op;
// ① 仓库映射(一次查全部,避免逐包查询)
const mappings = await ctx.model.WarehouseExpressMapping.findAll({
where: { warehouse_id: warehouseId, custom_code: { [Op.in]: raws }, status: 1 },
attributes: [ 'custom_code', 'express_code' ],
});
const mappedByRaw = new Map(
mappings.map(m => [ String(m.custom_code).trim().toUpperCase(), String(m.express_code).trim().toUpperCase() ])
);
// ② 快递公司字典:把「映射结果」与「未命中映射的原编码」一起查名称
const codes = [ ...new Set(raws.map(raw => mappedByRaw.get(raw) || raw)) ];
const companies = await ctx.model.ExpressCompany.findAll({
where: { code: { [Op.in]: codes } },
attributes: [ 'code', 'name' ],
});
const nameByCode = new Map(companies.map(c => [ String(c.code).trim().toUpperCase(), c.name || '' ]));
const items = [];
const missing = [];
for (const raw of raws) {
const mapped = mappedByRaw.get(raw);
if (mapped) {
items.push({ raw, code: mapped, name: nameByCode.get(mapped) || '', source: 'mapping' });
} else if (nameByCode.has(raw)) {
items.push({ raw, code: raw, name: nameByCode.get(raw) || '', source: 'dictionary' });
} else {
missing.push(raw);
}
}
if (missing.length) {
return {
ok: false,
items,
first: null,
message: `外部传入的快递编码(${missing.join('、')})没有关联映射,请到 OMS 外部仓库完成映射配置`,
};
}
return { ok: true, items, first: items[0] || null };
}
/**
* 从对象中按候选字段取第一个非空字符串
* @param {Object} obj 源对象
* @param {Array<String>} keys 候选字段名
* @return {String} 值(无则空串)
*/
function pickFromObject(obj, keys) {
const source = obj || {};
for (const key of keys) {
const value = source[key];
if (value !== undefined && value !== null && String(value).trim() !== '') return String(value).trim();
}
return '';
}
/**
* 转数字,非法值返回 null
* @param {*} value 原值
* @return {Number|null} 数字或 null
*/
function toNumberOrNull(value) {
if (value === undefined || value === null || String(value).trim() === '') return null;
const num = Number(value);
return Number.isFinite(num) ? num : null;
}
/**
* 按列长截断字符串(避免超长报错,如运单号列 50)
* @param {String} value 原值
* @param {Number} max 最大长度
* @return {String} 截断后的值
*/
function truncate(value, max) {
const str = value == null ? '' : String(value).trim();
return str.length > max ? str.slice(0, max) : str;
}
/**
* 把 JSON 列值归一化为数组(兼容驱动/历史数据返回字符串的情况)
* @param {*} value JSON 列值
* @return {Array} 数组(非数组/解析失败返回空数组)
*/
function toJsonArray(value) {
if (Array.isArray(value)) return value;
if (typeof value === 'string' && value.trim()) {
try {
const parsed = JSON.parse(value);
return Array.isArray(parsed) ? parsed : [];
} catch (err) {
return [];
}
}
return [];
}
/**
* 把 JSON 列值归一化为普通对象(兼容驱动/历史数据返回字符串的情况)
* @param {*} value JSON 列值
* @return {Object} 普通对象(非对象/解析失败返回空对象)
*/
function toPlainObject(value) {
if (value && typeof value === 'object' && !Array.isArray(value)) return value;
if (typeof value === 'string' && value.trim()) {
try {
const parsed = JSON.parse(value);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
} catch (err) {
return {};
}
}
return {};
}
/**
* 稳定序列化(对象 key 递归升序),用于 JSON 结构比较。
* ⚠️ MySQL 的 JSON 列会重排对象 key(落库后读回的顺序与写入时的字面量顺序不同),
* 因此直接 JSON.stringify 比较会误判为「有变化」,必须按 key 排序后再比。
* @param {*} value 任意 JSON 值
* @return {String} 稳定字符串
*/
function stableStringify(value) {
if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
if (value && typeof value === 'object') {
return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`;
}
return JSON.stringify(value === undefined ? null : value);
}
/**
* 比较两份确认摘要是否一致(忽略 confirmed_at 时间戳),用于幂等判断:
* WMS 重推同一报文时不反复刷新留存时间戳,也不产生无意义的写库。
* @param {Object} a 已留存的摘要
* @param {Object} b 本次组装出的摘要
* @return {Boolean} 除 confirmed_at 外内容一致返回 true
*/
function isSameConfirmSummary(a, b) {
if (!a || !b) return false;
const strip = summary => {
const copy = { ...summary };
delete copy.confirmed_at;
return stableStringify(copy);
};
return strip(a) === strip(b);
}
/**
* 把外部回推的实际数量写回单据明细的「已入/已出」数量(按 itemCode 匹配明细行)
* @param {Object} ctx egg context
@ -220,8 +474,24 @@ async function matchInbound(ctx, { principalId, warehouseId, data }) {
}
/**
* 出库单确认(deliveryorder.confirm / stockout.confirm):WMS 已发货出库
* 出库单确认(stockout.confirm):WMS 出库完成(非订单出库单,CK 组 / wms_order_stockout)
* 写回明细「已出数量」,扣减系统库存(总数量与锁定各减明细数量,幂等),并置「已完成(4)」
* 注:发货单(ORDER 组 JYCK/HHCK/BFCK,wms_order_delivery)的完成回调是 deliveryorder.confirm,
* 由 confirmDelivery 处理,两者不能混用单号表。
*
* 报文对齐 WMS 出站回调规范(D:/wms/methods/openapi_callback.json#stockout.confirm):
* request.deliveryOrder.deliveryOrderCode / outBizCode → 定位 OMS 出库单 outbound_orders.bill_no
* request.packages.package[].expressCode → 运单号(全部写入 outbound_orders.waybill_codes)
* request.packages.package[].logisticsCode / logisticsName → **覆盖**出库单的 express_code / express_name
* request.orderLines[].{planQty, actualQty} → 写回明细 actual_out_qty
* request.deliveryOrder.status 固定 DELIVERED、confirmType 固定 0(最终确认)
* 报文摘要(包裹/明细/时间)另存 `outbound_orders.wms_push_result.confirm` 供排查;
* 幂等:除时间戳外摘要无变化、运单号与快递公司列均已同步时不重复写库。
*
* ⚠️ **快递公司以回传为准(覆盖)**:WMS 可能「转快递」(推送 ZT 自提、实际发 YTO 圆通),
* 回传的 `packages[].logisticsCode/logisticsName` 才是实际承运,故按回传值**覆盖**
* `outbound_orders.express_code/express_name`(回传为空时不覆盖,避免清空已有值);
* 因而不要求回传编码等于推送编码,也不做两边字典一致性约束。
* @param {Object} ctx egg context
* @param {Object} options 处理参数
* @param {Number} options.principalId 主体ID
@ -232,22 +502,41 @@ async function matchInbound(ctx, { principalId, warehouseId, data }) {
async function confirmOutbound(ctx, { principalId, warehouseId, data }) {
const payload = unwrapPayload(data);
const code = pickFirst(payload, OUTBOUND_CODE_PATHS);
if (!code) return { ok: false, message: '缺少出库单号(deliveryOrderCode / stockoutOrderCode / orderCode)' };
if (!code) {
return {
ok: false,
message: '缺少出库单号(deliveryOrder.deliveryOrderCode / stockoutOrderCode / orderCode)',
};
}
const found = await findBill(ctx, { model: 'OutboundOrder', code, principalId, warehouseId });
if (found.error) return { ok: false, message: found.error };
const order = found.order;
const actualUpdated = await applyActualQty(ctx, order.id, 2, 'actual_out_qty', extractLines(payload));
const lines = extractLines(payload);
const packages = extractPackages(payload);
// 幂等:已完成且已扣减库存的单据不再重复处理
// 快递编码解析(仓库映射优先 → 字典兜底 → 都没有报错)——必须在任何写库动作之前完成
const expressResult = await resolvePackageExpress(ctx, warehouseId, packages);
if (!expressResult.ok) return { ok: false, message: expressResult.message };
const actualUpdated = await applyActualQty(ctx, order.id, 2, 'actual_out_qty', lines);
// 幂等:已完成且已扣减库存的单据不再重复处理(仅补写缺失的确认摘要,便于留存运单号)
if (order.status === 4 && order.stock_deducted) {
const summaryResult = await applyOutboundConfirmSummary(ctx, order, payload, packages, lines, { express: expressResult.first });
const done = {
bill_id: order.id,
bill_no: order.bill_no,
status: order.status,
already_completed: true,
actual_qty_updated: actualUpdated,
waybill_code: summaryResult.summary.waybill_code,
waybill_codes: summaryResult.summary.waybill_codes,
logistics_code: summaryResult.summary.logistics_code,
logistics_name: summaryResult.summary.logistics_name,
express_updated: summaryResult.expressUpdated,
summary_updated: summaryResult.changed,
};
ctx.logger.info('[order-callback] 出库单已完成,跳过', done);
return { ok: true, message: 'ok', data: done };
@ -258,20 +547,37 @@ async function confirmOutbound(ctx, { principalId, warehouseId, data }) {
const items = await ctx.model.StockItem.findAll({
where: { bill_type: 2, bill_id: order.id, product_id: { [ctx.app.Sequelize.Op.ne]: null } },
attributes: [ 'product_id', 'quantity', 'inventory_type' ],
attributes: [ 'product_id', 'code', 'name', 'quantity', 'inventory_type' ],
order: [[ 'product_id', 'ASC' ]],
});
if (!items.length) return { ok: false, message: `单据 ${order.bill_no} 无明细,无法完成出库` };
const transaction = await ctx.model.transaction();
let summaryResult;
try {
if (!order.stock_deducted) {
for (const it of items) {
const p = it.get ? it.get({ plain: true }) : it;
const itemType = p.inventory_type === 'CC' ? 'CC' : 'ZC';
await stock.deduct(ctx, principalId, Number(p.product_id), Number(p.quantity) || 0, transaction, itemType);
// 扣减库存 + 写一条出库确认记录(含变动后锁定数量与可用数量)
await applyStockChange(ctx, {
bizType: 'outbound_deduct',
principalId,
warehouseId: order.warehouse_id,
productId: Number(p.product_id),
itemCode: p.code,
itemName: p.name,
itemType,
quantity: Number(p.quantity) || 0,
billId: order.id,
billNo: order.bill_no,
remark: '出库确认扣减库存(WMS 回推)',
transaction,
});
}
}
// 确认摘要(含运单号/物流公司)与状态、库存同事务写入
summaryResult = await applyOutboundConfirmSummary(ctx, order, payload, packages, lines, { transaction, express: expressResult.first });
await order.update({ status: 4, stock_deducted: 1 }, { transaction });
await transaction.commit();
} catch (err) {
@ -286,11 +592,332 @@ async function confirmOutbound(ctx, { principalId, warehouseId, data }) {
stock_deducted: 1,
already_completed: false,
actual_qty_updated: actualUpdated,
waybill_code: summaryResult.summary.waybill_code,
waybill_codes: summaryResult.summary.waybill_codes,
logistics_code: summaryResult.summary.logistics_code,
logistics_name: summaryResult.summary.logistics_name,
express_updated: summaryResult.expressUpdated,
summary_updated: summaryResult.changed,
};
ctx.logger.info('[order-callback] 出库确认完成', result);
return { ok: true, message: 'ok', data: result };
}
/**
* 回写发货单的运单号与物流公司(幂等:值未变化时不写库)
* 数据来源 request.packages.package[](每个运单号一条),取第一个非空的 expressCode /
* logisticsCode / logisticsName;无包裹信息时不改动原值。
* 多包裹:全部运单号另存 express_codes(JSON 数组),express_code 仍是首个运单号(兼容既有口径)。
*
* ⚠️ **物流公司以回传为准(覆盖)**:WMS 可能「转快递」,回传的 logisticsCode/logisticsName
* 才是实际承运,故与本地值不同时直接覆盖(不回写推送值、不做两边字典一致性约束)。
* @param {Object} ctx egg context
* @param {Object} order 发货单 model 实例(order_deliveries)
* ⚠️ 物流公司以解析结果为准:先按仓库快递映射(warehouse_express_mappings)把外部自定义编码
* 解析成 OMS 默认快递编码,未命中映射则用字典兼容(extern 编码本身在 express_companies 里),
* 两者都没有由调用方报错;因此物流公司列写的是**解析后**的编码/名称。
* @param {Array<Object>} packages 包裹数组
* @param {Object} [options] 可选参数
* @param {Object} [options.express] 解析后的快递({ raw, code, name, source }),优先于包裹里的原值
* @return {Promise<{changed: Array<String>, express_code: String, express_codes: Array<String>,
* logistics_code: String, logistics_name: String}>} changed 为本次实际写入的列名
*/
async function applyDeliveryPackageInfo(ctx, order, packages, { express } = {}) {
const list = packages || [];
const expressCode = truncate(pickFromPackages(list, [ 'expressCode', 'express_code' ]), 50);
// 物流公司:优用解析结果(映射/字典),无解析结果时回退到包裹原值
const logisticsCode = truncate((express && express.code) || pickFromPackages(list, [ 'logisticsCode', 'logistics_code' ]), 50);
const logisticsName = truncate((express && express.name) || pickFromPackages(list, [ 'logisticsName', 'logistics_name' ]), 200);
// 多包裹:全部运单号留存到 express_codes(列 express_code 保留首个,兼容既有单值口径)
const expressCodes = collectExpressCodes(list);
const patch = {};
if (expressCode && String(order.express_code || '').trim() !== expressCode) patch.express_code = expressCode;
if (logisticsCode && String(order.logistics_code || '').trim() !== logisticsCode) patch.logistics_code = logisticsCode;
if (logisticsName && String(order.logistics_name || '').trim() !== logisticsName) patch.logistics_name = logisticsName;
if (expressCodes.length && stableStringify(toJsonArray(order.express_codes)) !== stableStringify(expressCodes)) {
patch.express_codes = expressCodes;
}
const changed = Object.keys(patch);
if (changed.length) {
await order.update(patch);
ctx.logger.info(`[order-callback] 发货单 ${order.delivery_order_code} 回写运单/物流信息:${changed.join(', ')}`);
}
const storedCodes = toJsonArray(order.express_codes);
return {
changed,
express_code: order.express_code || '',
express_codes: storedCodes.length ? storedCodes : expressCodes,
logistics_code: order.logistics_code || '',
logistics_name: order.logistics_name || '',
};
}
/**
* 组装发货确认报文摘要(写入 wms_push_result.confirm,便于排查运单号/确认时间/发货明细)
* 字段口径对齐 D:/wms/methods/openapi_callback.json#deliveryorder.confirm
* @param {Object} payload 归一化后的回调报文
* @param {Array<Object>} packages 包裹数组
* @param {Array<Object>} lines 发货明细行数组
* @return {Object} 摘要对象
*/
function buildDeliveryConfirmSummary(payload, packages, lines) {
const d = (payload && payload.deliveryOrder) || {};
const list = packages || [];
const orderLines = lines || [];
return {
out_biz_code: pickFirst(payload, [ 'outBizCode', 'deliveryOrder.outBizCode' ]),
wms_delivery_order_id: toNumberOrNull(d.deliveryOrderId),
warehouse_code: pickFromObject(d, [ 'warehouseCode' ]),
order_type: pickFromObject(d, [ 'orderType' ]),
status: pickFromObject(d, [ 'status' ]),
confirm_type: toNumberOrNull(d.confirmType),
order_confirm_time: pickFromObject(d, [ 'orderConfirmTime' ]),
operate_time: pickFromObject(d, [ 'operateTime' ]),
storage_fee: pickFromObject(d, [ 'storageFee' ]),
total_order_lines: toNumberOrNull(d.totalOrderLines) == null ? orderLines.length : toNumberOrNull(d.totalOrderLines),
packages: list.map(pkg => ({
package_code: pickFromObject(pkg, [ 'packageCode', 'package_code' ]),
express_code: pickFromObject(pkg, [ 'expressCode', 'express_code' ]),
logistics_code: pickFromObject(pkg, [ 'logisticsCode', 'logistics_code' ]),
logistics_name: pickFromObject(pkg, [ 'logisticsName', 'logistics_name' ]),
invoice_no: pickFromObject(pkg, [ 'invoiceNo', 'invoice_no' ]),
})),
lines: orderLines.map(line => ({
order_line_no: pickFromObject(line, [ 'orderLineNo', 'order_line_no' ]),
item_code: pickFromObject(line, [ 'itemCode', 'item_code' ]),
plan_qty: toNumberOrNull(line.planQty),
actual_qty: toNumberOrNull(line.actualQty),
})),
confirmed_at: new Date().toISOString(),
};
}
// -------- 出库确认报文摘要(stockout.confirm:包裹/运单信息留存) --------
/**
* 组装出库确认报文摘要(写入 outbound_orders.wms_push_result.confirm,便于排查运单号/物流公司/出库明细)
* 字段口径对齐 D:/wms/methods/openapi_callback.json#stockout.confirm(与发货单摘要同风格)
* @param {Object} payload 归一化后的回调报文
* @param {Array<Object>} packages 包裹数组
* @param {Array<Object>} lines 出库明细行数组
* @return {Object} 摘要对象
*/
function buildOutboundConfirmSummary(payload, packages, lines) {
const d = (payload && payload.deliveryOrder) || {};
const list = packages || [];
const orderLines = lines || [];
const totalLines = toNumberOrNull(d.totalOrderLines);
return {
out_biz_code: pickFirst(payload, [ 'outBizCode', 'deliveryOrder.outBizCode' ]),
wms_delivery_order_id: toNumberOrNull(d.deliveryOrderId),
warehouse_code: pickFromObject(d, [ 'warehouseCode' ]),
order_type: pickFromObject(d, [ 'orderType' ]),
status: pickFromObject(d, [ 'status' ]),
confirm_type: toNumberOrNull(d.confirmType),
order_confirm_time: pickFromObject(d, [ 'orderConfirmTime' ]),
operate_time: pickFromObject(d, [ 'operateTime' ]),
total_order_lines: totalLines == null ? orderLines.length : totalLines,
// 运单号/物流公司提到摘要根节点,便于直接读取(包内 express_code 依旧对应该单体
// package.expressCode;根节点用 waybill_* 区分「运单号」,与快递公司列 express_code 区分开)
waybill_code: pickFromPackages(list, [ 'expressCode', 'express_code' ]),
waybill_codes: collectExpressCodes(list),
logistics_code: pickFromPackages(list, [ 'logisticsCode', 'logistics_code' ]),
logistics_name: pickFromPackages(list, [ 'logisticsName', 'logistics_name' ]),
packages: list.map(pkg => ({
package_code: pickFromObject(pkg, [ 'packageCode', 'package_code' ]),
express_code: pickFromObject(pkg, [ 'expressCode', 'express_code' ]),
logistics_code: pickFromObject(pkg, [ 'logisticsCode', 'logistics_code' ]),
logistics_name: pickFromObject(pkg, [ 'logisticsName', 'logistics_name' ]),
})),
lines: orderLines.map(line => ({
order_line_no: pickFromObject(line, [ 'orderLineNo', 'order_line_no' ]),
item_code: pickFromObject(line, [ 'itemCode', 'item_code' ]),
item_name: pickFromObject(line, [ 'itemName', 'item_name' ]),
inventory_type: pickFromObject(line, [ 'inventoryType', 'inventory_type' ]),
plan_qty: toNumberOrNull(line.planQty),
actual_qty: toNumberOrNull(line.actualQty),
})),
confirmed_at: new Date().toISOString(),
};
}
/**
* 按需把出库确认摘要合并进 outbound_orders.wms_push_result.confirm(保留原有推送结果字段),
* 并用回传的快递公司**覆盖**出库单的 express_code / express_name。
*
* ⚠️ 覆盖口径:WMS 可能「转快递」(如推送 ZT 自提、实际发 YTO 圆通),回传的
* `packages.package[].logisticsCode/logisticsName` 才是**实际承运**,故本地快照以回传值覆盖,
* 不再要求与推送值一致(推送值可在 api_outbound_logs 的请求报文里回溯)。
* 回传为空时不覆盖(避免把已有值清空)。
*
* 出库单的运单号集合另存 outbound_orders.waybill_codes(JSON 数组,列名对齐 wms_order_stockout);
* 幂等:除 confirmed_at 外与已留存摘要一致、且 waybill_codes / 快递公司列均已同步时跳过写库
* (WMS 重推不刷新时间戳)。
* @param {Object} ctx egg context
* @param {Object} order 出库单 model 实例(outbound_orders)
* @param {Object} payload 归一化后的回调报文
* @param {Array<Object>} packages 包裹数组
* @param {Array<Object>} lines 出库明细行数组
* @param {Object} [options] 可选参数
* @param {Object} [options.transaction] 事务;传入时摘要与状态/库存同事务写入
* @param {Object} [options.express] 解析后的快递({ raw, code, name, source }),用于覆盖 express_code/express_name
* @return {Promise<{summary: Object, changed: Boolean, expressUpdated: Array<String>}>} 摘要 + 是否写库 + 覆盖的快递列
*/
async function applyOutboundConfirmSummary(ctx, order, payload, packages, lines, { transaction, express } = {}) {
const summary = buildOutboundConfirmSummary(payload, packages, lines);
const codes = collectExpressCodes(packages);
const current = toPlainObject(order.wms_push_result);
// 摘要变化 / 运单号集合列未同步(含历史单列还是 NULL)/ 快递公司需按回传覆盖,任一成立都要写库
const summaryChanged = !isSameConfirmSummary(current.confirm, summary);
const codesChanged = codes.length > 0
&& stableStringify(toJsonArray(order.waybill_codes)) !== stableStringify(codes);
const expressPatch = buildExpressOverride(order, express);
const expressUpdated = Object.keys(expressPatch);
if (!summaryChanged && !codesChanged && !expressUpdated.length) {
ctx.logger.info(`[order-callback] 出库单 ${order.bill_no} 确认摘要无变化,跳过写库`);
return { summary, changed: false, expressUpdated };
}
const patch = { wms_push_result: { ...current, confirm: summary }, ...expressPatch };
// 空包裹不改动原值(避免无包裹信息的重推把已有运单号清掉)
if (codes.length) patch.waybill_codes = codes;
await order.update(patch, { transaction });
ctx.logger.info(
`[order-callback] 出库单 ${order.bill_no} 留存确认摘要(运单号 ${summary.waybill_codes.join('、') || '-'} / 物流 ${summary.logistics_name || '-'})`
+ (expressUpdated.length ? `;按回传覆盖 ${expressUpdated.join(', ')}` : '')
);
return { summary, changed: true, expressUpdated };
}
/**
* 用**解析后**的快递(仓库映射优先 → 字典兜底)覆盖出库单的 express_code / express_name
* (有值且与现值不同才写)
* @param {Object} order 出库单 model 实例(outbound_orders)
* @param {Object} express 解析结果({ raw, code, name, source })
* @return {Object} 需要写入的列(空对象表示无需覆盖)
*/
function buildExpressOverride(order, express) {
const code = truncate((express && express.code) || '', 50);
const name = truncate((express && express.name) || '', 200);
const patch = {};
if (code && String(order.express_code || '').trim() !== code) patch.express_code = code;
if (name && String(order.express_name || '').trim() !== name) patch.express_name = name;
return patch;
}
/**
* 发货单确认(deliveryorder.confirm):WMS 已完成发货(ORDER 组 JYCK/HHCK/BFCK → wms_order_delivery)
*
* 报文对齐 WMS 出站回调规范(D:/wms/methods/openapi_callback.json#deliveryorder.confirm):
* request.deliveryOrder.deliveryOrderCode / outBizCode → 定位 OMS 发货单 order_deliveries.delivery_order_code
* request.packages.package[].{expressCode, logisticsCode, logisticsName, packageCode, invoiceNo} → 运单号/物流公司回写
* request.orderLines[].{planQty, actualQty} → 报文摘要登记(发货单明细无「已发数量」列,故不落明细)
* request.deliveryOrder.status 固定 DELIVERED、confirmType 固定 0(最终确认)
*
* 处理内容:① 回写运单号 express_code 与物流公司(缺失或变化时)② 状态「已推送(3)」→「已完成(4)」
* ③ 若审核时已锁定库存(order_deliveries.stock_locked=1)则扣减库存(总数量与锁定同减)
* 并写 order_deduct 流水;历史单据(stock_locked=0)不扣减,避免凭空减少总数量
* 幂等:已完成(4) 的单据再次收到(可能多次)相同报文时只做缺失字段补写并直接回成功
* (不重复改状态、不重复扣减库存、不重复写推送结果);状态非 3/4 时返回失败,交由调用方告警/重试。
* @param {Object} ctx egg context
* @param {Object} options 处理参数
* @param {Number} options.principalId 主体ID
* @param {Number} options.warehouseId app_key 定位到的仓库ID
* @param {Object} options.data 回调报文
* @return {Promise<{ok: Boolean, message: String, data?: Object}>} 处理结果
*/
async function confirmDelivery(ctx, { principalId, warehouseId, data }) {
const payload = unwrapPayload(data);
const code = pickFirst(payload, DELIVERY_CODE_PATHS);
if (!code) return { ok: false, message: '缺少发货单号(deliveryOrderCode / outBizCode)' };
const order = await ctx.model.OrderDelivery.findOne({
where: { delivery_order_code: code, principal_id: principalId },
});
if (!order) return { ok: false, message: `未找到发货单:${code}` };
// 历史单据可能没有 warehouse_id,仅在双方都有值时校验仓库归属
if (order.warehouse_id && warehouseId && Number(order.warehouse_id) !== Number(warehouseId)) {
return { ok: false, message: `单据 ${code} 不属于当前 app_key 对应的仓库` };
}
const packages = extractPackages(payload);
const lines = extractLines(payload);
// 快递编码解析(仓库映射优先 → 字典兜底 → 都没有报错)——必须在写回运单/物流信息之前完成
const expressResult = await resolvePackageExpress(ctx, warehouseId, packages);
if (!expressResult.ok) return { ok: false, message: expressResult.message };
// 运单号/物流公司回写:幂等(值未变化则不写库),已完成单据也允许补写缺失值
const pkgInfo = await applyDeliveryPackageInfo(ctx, order, packages, { express: expressResult.first });
// 幂等:已完成(4) 直接回成功,不再流转状态、不重复扣减库存(外部重复推送同一报文时返回相同结果)
if (Number(order.status) === DELIVERY_STATUS_DONE) {
const done = {
delivery_order_id: order.id,
delivery_order_code: order.delivery_order_code,
status: DELIVERY_STATUS_DONE,
already_completed: true,
express_code: pkgInfo.express_code,
express_codes: pkgInfo.express_codes,
logistics_code: pkgInfo.logistics_code,
logistics_name: pkgInfo.logistics_name,
package_updated: pkgInfo.changed,
stock_locked: Number(order.stock_locked) === 1,
};
ctx.logger.info('[order-callback] 发货单已完成,跳过(幂等回执)', done);
return { ok: true, message: 'ok', data: done };
}
if (Number(order.status) !== DELIVERY_STATUS_PUSHED) {
return {
ok: false,
message: `单据 ${code} 当前状态(${order.status})不允许发货确认,需为「已推送(3)」`,
};
}
// 扣减库存(仅审核时锁定过的单据)+ 状态流转 + 推送结果,同事务写入
const transaction = await ctx.model.transaction();
let stockResult;
try {
stockResult = await deductDeliveryStock(ctx, order, {
remark: '订单发货确认扣减库存(WMS 回推 deliveryorder.confirm)',
transaction,
});
await order.update({
status: DELIVERY_STATUS_DONE,
// 保留原推送信息,追加本次发货确认报文摘要
wms_push_result: {
...(order.wms_push_result && typeof order.wms_push_result === 'object' ? order.wms_push_result : {}),
confirm: buildDeliveryConfirmSummary(payload, packages, lines),
},
}, { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
const result = {
delivery_order_id: order.id,
delivery_order_code: order.delivery_order_code,
status: DELIVERY_STATUS_DONE,
already_completed: false,
express_code: pkgInfo.express_code,
express_codes: pkgInfo.express_codes,
logistics_code: pkgInfo.logistics_code,
logistics_name: pkgInfo.logistics_name,
package_updated: pkgInfo.changed,
stock_deducted: stockResult.affected,
stock_skipped: stockResult.skipped,
stock_skipped_lines: stockResult.skippedLines,
line_count: lines.length,
};
ctx.logger.info('[order-callback] 发货确认完成', result);
return { ok: true, message: 'ok', data: result };
}
/**
* 订单取消通知(order.cancel):外部已取消该单据
* 未完成(≠4)的单据置为「已取消(9)」;出库单若已推送(3)则同时释放锁定库存
@ -327,7 +954,7 @@ async function cancelOrder(ctx, { principalId, warehouseId, data }) {
if (billType === 2 && order.status === 3 && !order.stock_deducted) {
const items = await ctx.model.StockItem.findAll({
where: { bill_type: 2, bill_id: order.id, product_id: { [ctx.app.Sequelize.Op.ne]: null } },
attributes: [ 'product_id', 'quantity', 'inventory_type' ],
attributes: [ 'product_id', 'code', 'name', 'quantity', 'inventory_type' ],
order: [[ 'product_id', 'ASC' ]],
});
const transaction = await ctx.model.transaction();
@ -335,7 +962,20 @@ async function cancelOrder(ctx, { principalId, warehouseId, data }) {
for (const it of items) {
const p = it.get ? it.get({ plain: true }) : it;
const itemType = p.inventory_type === 'CC' ? 'CC' : 'ZC';
await stock.unlock(ctx, principalId, Number(p.product_id), Number(p.quantity) || 0, transaction, itemType);
await applyStockChange(ctx, {
bizType: 'outbound_unlock',
principalId,
warehouseId: order.warehouse_id,
productId: Number(p.product_id),
itemCode: p.code,
itemName: p.name,
itemType,
quantity: Number(p.quantity) || 0,
billId: order.id,
billNo: order.bill_no,
remark: '取消释放锁定库存(order.cancel)',
transaction,
});
}
await order.update({ status: 9 }, { transaction });
await transaction.commit();
@ -362,9 +1002,12 @@ async function cancelOrder(ctx, { principalId, warehouseId, data }) {
module.exports = {
pickFirst,
extractLines,
extractPackages,
applyActualQty,
resolvePackageExpress,
confirmInbound,
matchInbound,
confirmOutbound,
confirmDelivery,
cancelOrder,
};

View File

@ -0,0 +1,58 @@
'use strict';
/**
* 回传平台店铺(shops 表:淘宝/抖音等)的同步状态口径(唯一来源)
*
* 用途:发货单(order_deliveries)完成后,把发货结果(运单号/发货状态等)回传平台店铺。
* 本阶段只落字段与状态机基线(迁移 20260915001500),实际回传链路(OMS → 平台)尚未实现,
* 枚举供后续 service / schedule 与前端复用,避免各处再写一份数字。
* 落库字段:order_deliveries.shop_sync_status / shop_sync_retry_count(均为系统托管,接口不可传)
* 注:入库单(inbound_orders)与出库单(outbound_orders)**不使用**该口径 ——
* 入库单的库存由 OMS 侧自行管理、不涉及平台店铺回传。
*/
const SHOP_SYNC_STATUS = {
PENDING: 0,
SYNCING: 1,
SUCCESS: 2,
FAILED: 3,
};
/** 状态 → 中文标签 */
const SHOP_SYNC_STATUS_LABELS = {
[SHOP_SYNC_STATUS.PENDING]: '未同步',
[SHOP_SYNC_STATUS.SYNCING]: '同步中',
[SHOP_SYNC_STATUS.SUCCESS]: '同步成功',
[SHOP_SYNC_STATUS.FAILED]: '同步失败',
};
/** 枚举列表(下拉/提示用,按状态值升序) */
const SHOP_SYNC_STATUS_LIST = Object.keys(SHOP_SYNC_STATUS_LABELS)
.map(value => Number(value))
.sort((a, b) => a - b)
.map(value => ({ value, label: SHOP_SYNC_STATUS_LABELS[value] }));
/**
* 判断是否为合法的同步状态值
* @param {*} value 原值
* @return {Boolean} 合法返回 true
*/
function isValidShopSyncStatus(value) {
return Object.prototype.hasOwnProperty.call(SHOP_SYNC_STATUS_LABELS, Number(value));
}
/**
* 归一化同步状态值(非法值回退「未同步(0)」)
* @param {*} value 原值
* @return {Number} 合法状态值
*/
function normalizeShopSyncStatus(value) {
return isValidShopSyncStatus(value) ? Number(value) : SHOP_SYNC_STATUS.PENDING;
}
module.exports = {
SHOP_SYNC_STATUS,
SHOP_SYNC_STATUS_LABELS,
SHOP_SYNC_STATUS_LIST,
isValidShopSyncStatus,
normalizeShopSyncStatus,
};

View File

@ -422,6 +422,9 @@ class QimenWmsClient {
* 构建 stockout.create(非订单出库单)请求体(对齐 WMS 出库单规范)
* 字段来源:单据头 + 明细(含商品快照);货主编码取接口配置 owner_code,仓库编码取 warehouse.code;
* 明细行 itemId 为 WMS 必填项,取 warehouse_products.wms_item_id(由调用方查好后传入)
* 快递公司与收件人:`deliveryOrder.logisticsCode` ← outbound_orders.express_code;
* `deliveryOrder.receiverInfo`(13 字段:name/company/zipCode/tel/mobile/email/countryCode/
* province/city/area/town/detailAddress/id)← outbound_orders.receiver_*,全空则整块不下发
* @param {Object} order OMS 出库单(model 实例或 plain,已 include warehouse)
* @param {Array} items 出库明细(stock_items,已 include product)
* @param {Object} [opts] { warehouse, wmsItemIdByProduct }
@ -459,6 +462,29 @@ class QimenWmsClient {
remark: o.remark || '',
};
// 快递公司:deliveryOrder.logisticsCode(货主开启 enable_external_express_code 时按快递设置匹配,
// 匹配不到用出库单兜底快递编码,默认 ZT 自提);无值时不带,保持与历史报文一致
if (o.express_code) deliveryOrder.logisticsCode = o.express_code;
// 收件人:deliveryOrder.receiverInfo(13 个标准字段,WMS 侧落 wms_order_stockout.receiver_* 列,
// 供转订单与确认回传使用);任一字段有值才下发,全空则整块不传
const receiverInfo = {
name: o.receiver_name || '',
company: o.receiver_company || '',
zipCode: o.receiver_zip_code || '',
tel: o.receiver_tel || '',
mobile: o.receiver_mobile || '',
email: o.receiver_email || '',
countryCode: o.receiver_country_code || '',
province: o.receiver_province || '',
city: o.receiver_city || '',
area: o.receiver_area || '',
town: o.receiver_town || '',
detailAddress: o.receiver_detail_address || '',
id: o.receiver_id || '',
};
if (Object.values(receiverInfo).some(v => v)) deliveryOrder.receiverInfo = receiverInfo;
return {
deliveryOrder,
orderLines: { orderLine: orderLineList },

View File

@ -68,7 +68,8 @@ module.exports = app => {
// ---------- 快递 ----------
logistics_code: { type: STRING(50), comment: '物流公司编码(WMS 标准编码,如 SF/YTO)' },
logistics_name: { type: STRING(200), comment: '物流公司名称' },
express_code: { type: STRING(50), comment: '运单号(面单号)' },
express_code: { type: STRING(50), comment: '运单号(面单号,取首个包裹)' },
express_codes: { type: JSON, comment: '运单号集合(WMS 发货确认 packages.package[].expressCode,多包裹时为数组)' },
logistics_area_code: { type: STRING(50), comment: '快递区域编码(大头笔信息)' },
// ---------- 操作人 / 其他 ----------
@ -103,6 +104,12 @@ module.exports = app => {
item_total: { type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '商品总数(明细计划数量合计)' },
item_kind: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '商品种类数(不重复商品数)' },
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1待处理 2已审核 3已推送 4已完成 5已作废 9已取消' },
stock_locked: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '库存锁定标记:1=审核时已按明细锁定库存(推送失败/驳回/取消/作废时释放,发货确认时扣减),0=未锁定',
},
audit_by: { type: BIGINT.UNSIGNED, comment: '审核人ID(关联 users,待处理→已审核时写入)' },
audit_time: { type: DATE, comment: '审核时间' },
void_at: { type: DATE, comment: '作废时间(状态 5=已作废)' },
@ -112,6 +119,20 @@ module.exports = app => {
pushed_at: { type: DATE, comment: 'WMS 推送时间' },
wms_push_result: { type: JSON, comment: 'WMS 推送结果(外部单号/返回码/消息/原始报文)' },
// ---------- 回传平台店铺(shops 表:淘宝/抖音等;与推送 WMS 无关) ----------
shop_sync_status: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '回传平台店铺状态:0未同步 1同步中 2同步成功 3同步失败(口径见 app/lib/shopSyncStatus.js,链路待实现)',
},
shop_sync_retry_count: {
type: INTEGER.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '回传平台店铺的重试次数(每次失败后 +1)',
},
created_at: { type: DATE, comment: '创建时间(对应 WMS create_at,取服务器时间)' },
updated_at: { type: DATE, comment: '更新时间' },
}, {

View File

@ -6,7 +6,7 @@
* @return {object} outboundOrder model
*/
module.exports = app => {
const { BIGINT, STRING, TINYINT, DECIMAL, INTEGER, DATE } = app.Sequelize;
const { BIGINT, STRING, TINYINT, DECIMAL, INTEGER, DATE, JSON } = app.Sequelize;
const OutboundOrder = app.model.define('outbound_order', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
@ -28,7 +28,29 @@ module.exports = app => {
item_kind: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '商品种类数(不重复商品数)' },
total_amount: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '单据总金额' },
remark: { type: STRING(255), comment: '备注' },
// ---------- 快递公司(推送 stockout.create 的 deliveryOrder.logisticsCode) ----------
express_code: { type: STRING(50), comment: '快递公司编码:推送为 deliveryOrder.logisticsCode,出库确认回传后按 WMS 实际承运覆盖(可能转快递)' },
express_name: { type: STRING(200), comment: '快递公司名称:推送时按字典解析,出库确认回传后按 WMS 实际承运覆盖' },
// ---------- 收件人(奇门 receiverInfo 扁平落库,列名对齐 WMS wms_order_stockout) ----------
receiver_name: { type: STRING(50), comment: '收件人姓名(receiverInfo.name)' },
receiver_company: { type: STRING(200), comment: '收件人公司名称(receiverInfo.company)' },
receiver_tel: { type: STRING(50), comment: '收件人固定电话(receiverInfo.tel)' },
receiver_mobile: { type: STRING(50), comment: '收件人移动电话(receiverInfo.mobile)' },
receiver_email: { type: STRING(100), comment: '收件人邮箱(receiverInfo.email)' },
receiver_country_code: { type: STRING(50), comment: '收件人国家二字码(receiverInfo.countryCode)' },
receiver_province: { type: STRING(50), comment: '收件人省份(receiverInfo.province)' },
receiver_city: { type: STRING(50), comment: '收件人城市(receiverInfo.city)' },
receiver_area: { type: STRING(50), comment: '收件人区县(receiverInfo.area)' },
receiver_town: { type: STRING(50), comment: '收件人街道/镇(receiverInfo.town)' },
receiver_detail_address: { type: STRING(200), comment: '收件人详细地址(receiverInfo.detailAddress)' },
receiver_zip_code: { type: STRING(50), comment: '收件人邮编(receiverInfo.zipCode)' },
receiver_id: { type: STRING(50), comment: '收件人证件号(receiverInfo.id)' },
stock_deducted: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '发货通知(notify.delivery)是否已扣减库存:1是 0否(幂等)' },
stock_locked: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '推送锁定库存标记:1=已锁定(重试不重复锁定,确认扣减/释放后置 0),0=未锁定' },
waybill_codes: { type: JSON, allowNull: true, comment: '运单号集合(WMS 出库确认 packages.package[].expressCode,多包裹时为数组;列名对齐 wms_order_stockout)' },
pushed_at: { type: DATE, allowNull: true, comment: 'WMS 推送时间' },
wms_push_result: { type: JSON, allowNull: true, comment: 'WMS 推送结果(外部单号/返回码/消息/原始报文)' },
void_at: { type: DATE, allowNull: true, comment: '作废时间(状态 5=已作废)' },

View File

@ -0,0 +1,56 @@
'use strict';
/**
* 出入库记录(库存流水)模型,对应 stock_records 表
*
* 每次库存变动(出库推送锁定 / 出库解锁 / 出库确认扣减 / 入库确认增加)写一行,
* 记录变动数量与变动前后的总数量、锁定数量、可用数量,用于对账与排查。
* 业务动作常量与写入入口统一在 app/utils/stockRecord.js(BIZ_TYPES / applyStockChange)。
*
* - item_type:ZC=正品 / CC=残次品(product_stocks 维度)
* - direction:1入库 2出库;bill_type:1入库单 2出库单
* @param {Egg.Application} app egg application
* @return {object} stockRecord model
*/
module.exports = app => {
const { BIGINT, STRING, TINYINT, DECIMAL, DATE } = app.Sequelize;
const StockRecord = app.model.define('stock_record', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
warehouse_id: { type: BIGINT.UNSIGNED, comment: '仓库ID(关联 warehouses)' },
product_id: { type: BIGINT.UNSIGNED, comment: '系统商品ID(关联 products)' },
item_code: { type: STRING(100), comment: '商品编码(快照)' },
item_name: { type: STRING(255), comment: '商品名称(快照)' },
item_type: { type: STRING(4), allowNull: false, defaultValue: 'ZC', comment: '库存类型:ZC=正品 CC=残次品' },
biz_type: { type: STRING(30), allowNull: false, comment: '业务动作:outbound_lock / outbound_unlock / outbound_deduct / inbound_increase' },
direction: { type: TINYINT, allowNull: false, comment: '出入方向:1入库 2出库' },
bill_type: { type: TINYINT, allowNull: false, comment: '单据类型:1入库单 2出库单' },
bill_id: { type: BIGINT.UNSIGNED, comment: '单据头ID(inbound_orders.id / outbound_orders.id)' },
bill_no: { type: STRING(50), comment: '单据号(RK_{id} / CK_{id})' },
quantity: { type: DECIMAL(15, 3), allowNull: false, defaultValue: 0, comment: '本次变动数量(恒为正数)' },
quantity_before: { type: DECIMAL(15, 3), allowNull: false, defaultValue: 0, comment: '变动前总数量' },
quantity_after: { type: DECIMAL(15, 3), allowNull: false, defaultValue: 0, comment: '变动后总数量' },
lock_quantity: { type: DECIMAL(15, 3), allowNull: false, defaultValue: 0, comment: '本次锁定变动量(正=加锁 负=解锁)' },
lock_before: { type: DECIMAL(15, 3), allowNull: false, defaultValue: 0, comment: '变动前锁定数量' },
lock_after: { type: DECIMAL(15, 3), allowNull: false, defaultValue: 0, comment: '变动后锁定数量' },
available_before: { type: DECIMAL(15, 3), allowNull: false, defaultValue: 0, comment: '变动前可用数量' },
available_after: { type: DECIMAL(15, 3), allowNull: false, defaultValue: 0, comment: '变动后可用数量' },
remark: { type: STRING(255), comment: '备注' },
created_by: { type: BIGINT.UNSIGNED, comment: '操作人ID(系统自动写入为空)' },
created_at: { type: DATE, comment: '记录时间(业务发生时间)' },
updated_at: { type: DATE, comment: '更新时间' },
}, {
tableName: 'stock_records',
comment: '出入库记录(库存流水)表',
});
StockRecord.associate = () => {
app.model.StockRecord.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
app.model.StockRecord.belongsTo(app.model.Product, { foreignKey: 'product_id', as: 'product' });
app.model.StockRecord.belongsTo(app.model.Warehouse, { foreignKey: 'warehouse_id', as: 'warehouse' });
app.model.StockRecord.belongsTo(app.model.User, { foreignKey: 'created_by', as: 'creator' });
};
return StockRecord;
};

View File

@ -0,0 +1,48 @@
'use strict';
/**
* 仓库快递映射模型,对应 warehouse_express_mappings 表
*
* 用途:外部(WMS)回传的快递编码可能是仓库维度的「自定义编码」(对齐 WMS `wms_express_setting`:
* `code`=业务自定义编码如 SF.KY/KYSF,`express_code`=系统标准编码),本表把
* `custom_code`(自定义编码)映射到 `express_code`(OMS/标准编码,关联 express_companies.code)。
*
* 出库确认(stockout.confirm)/ 发货确认(deliveryorder.confirm)回传时按以下顺序解析:
* ① 命中本表映射(warehouse_id + custom_code,且 status=1)→ 用映射到的默认快递编码;
* ② 未命中 → 外部编码本身若在快递公司字典里,直接兜底;
* ③ 都没有 → 报错「外部传入的快递编码(xxx)没有关联映射,请到 OMS 外部仓库完成映射配置」。
*
* @param {Egg.Application} app egg application
* @return {object} warehouseExpressMapping model
*/
module.exports = app => {
const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize;
const WarehouseExpressMapping = app.model.define('warehouse_express_mapping', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID(冗余仓库主体,便于隔离)' },
warehouse_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '仓库ID(关联 warehouses,映射按仓库维度)' },
express_code: { type: STRING(50), allowNull: false, comment: '默认快递编码(OMS/标准编码,关联 express_companies.code)' },
custom_code: { type: STRING(50), allowNull: false, comment: '自定义编码(外部传入的快递编码,如 SF.KY/KYSF)' },
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用(仅启用参与回传解析)' },
remark: { type: STRING(255), comment: '备注' },
created_at: { type: DATE, comment: '创建时间' },
updated_at: { type: DATE, comment: '更新时间' },
}, {
tableName: 'warehouse_express_mappings',
comment: '仓库快递映射表(外部快递编码 → OMS 默认快递编码)',
});
WarehouseExpressMapping.associate = () => {
app.model.WarehouseExpressMapping.belongsTo(app.model.Warehouse, { foreignKey: 'warehouse_id', as: 'warehouse' });
app.model.WarehouseExpressMapping.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
// 默认快递编码 → 快递公司字典(express_companies.code 全局唯一),用于表格展示「快递名称」
app.model.WarehouseExpressMapping.belongsTo(app.model.ExpressCompany, {
foreignKey: 'express_code',
targetKey: 'code',
as: 'expressCompany',
});
};
return WarehouseExpressMapping;
};

View File

@ -103,10 +103,16 @@ module.exports = app => {
router.resources('inboundOrders', '/api/inbound-orders', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder);
router.resources('outboundOrders', '/api/outbound-orders', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder);
router.resources('stockItems', '/api/stock-items', jwtAuth, principalCheck({ model: 'StockItem' }), controller.stockItem);
// 出入库记录(库存流水):只读列表 + 业务动作选项(下拉),按主体隔离;记录由业务事务写入,不提供增删改接口
router.get('/api/stock-records/biz-types', jwtAuth, principalCheck(), controller.stockRecord.bizTypes);
router.get('/api/stock-records', jwtAuth, principalCheck(), controller.stockRecord.index);
// 快递公司字典(通用字典,不区分主体):下拉需在 resources 之前注册,避免 /select 被当作 :id
router.get('/api/express-companies/select', jwtAuth, controller.expressCompany.select);
router.resources('expressCompanies', '/api/express-companies', jwtAuth, controller.expressCompany);
// 仓库快递映射(外部传入的自定义快递编码 → OMS 默认快递编码,按仓库维度;供回传解析与「外部仓库」页配置)
router.resources('warehouseExpressMappings', '/api/warehouse-express-mappings', jwtAuth, principalCheck({ model: 'WarehouseExpressMapping' }), controller.warehouseExpressMapping);
// 收件人信息智能识别(通用能力,仅需登录):需在 resources 之前注册,避免被 /:id 误匹配
router.post('/api/order-deliveries/parse-receiver', jwtAuth, controller.orderDelivery.parseReceiver);

View File

@ -0,0 +1,35 @@
'use strict';
/**
* 出库单推送队列:每 30 秒扫描「已审核(2)」的单据并递交 WMS(stockout.create)
*
* 说明(与发货单 app/schedule/orderDeliveryPush.js 同口径):
* - 审核只入队(1→2),由本定时任务异步推送,避免集中审核时把对方服务打满
* - 单条失败处理见 app/service/outboundOrderPush.js:对方明确失败 / 库存锁定失败立即退回「待出库(1)」
* (并释放锁定库存、冲正外部单据);无响应/超时最多尝试 3 次(每次间隔 >= 20s),
* 仍未成功同样退回「待出库(1)」并释放锁定库存
* - 并发安全:服务层用 pushed_at 做乐观锁抢占,多 worker 下同一单只推一次
*/
module.exports = {
schedule: {
interval: '30s',
type: 'worker',
immediate: false,
disable: false,
},
/**
* 扫描并推送待推送出库单
* @param {Egg.Context} ctx egg context(定时任务上下文)
* @return {Promise<Object>} 本轮统计
*/
async task(ctx) {
const stat = await ctx.service.outboundOrderPush.processPending();
if (stat.scanned > 0) {
ctx.logger.info(
`[outbound-push] 本轮扫描 ${stat.scanned} 条:成功 ${stat.pushed},失败 ${stat.failed},待重试 ${stat.retry},跳过 ${stat.skipped}`
);
}
return stat;
},
};

View File

@ -2,6 +2,7 @@
const Service = require('egg').Service;
const QimenWmsClient = require('../lib/wms/qimenClient');
const { releaseDeliveryStock } = require('../utils/deliveryStock');
/** 单条单据最多推送尝试次数(无响应/超时才算一次可重试的失败;对方明确响应失败不重试) */
const PUSH_MAX_ATTEMPTS = 3;
@ -94,6 +95,25 @@ class OrderDeliveryPushService extends Service {
}
}
/**
* 释放发货单已锁定的库存(best-effort)
* 失败只记日志不抛出:既不阻塞「退回待审核」状态流转,`stock_locked` 也保持 1,
* 便于后续驳回/取消/作废时再次尝试释放,不会出现“锁定了但无人认领”的丢失
* @param {Object} order 发货单实例(需含 id / principal_id / warehouse_id / delivery_order_code / stock_locked)
* @param {String} remark 备注(写入出入库记录)
* @return {Promise<void>}
*/
async releaseStock(order, remark) {
try {
const result = await releaseDeliveryStock(this.ctx, order, { remark });
if (!result.skipped) {
this.ctx.logger.info(`[delivery-push] ${order.delivery_order_code} 已释放锁定库存(${result.affected} 行):${remark}`);
}
} catch (err) {
this.ctx.logger.error(`[delivery-push] ${order.delivery_order_code} 释放锁定库存失败:${err.message}`);
}
}
/**
* 取上次推送记录(wms_push_result JSON)
* @param {Object} order 发货单
@ -229,8 +249,9 @@ class OrderDeliveryPushService extends Service {
ctx.logger.warn(`[delivery-push] ${order.delivery_order_code} 第 ${attempts}/${PUSH_MAX_ATTEMPTS} 次推送异常(将重试):${err.message}`);
return { ok: false, retry: true, message: err.message, attempts };
}
// 达到上限:冲正外部单据后退回「待审核(1)」
// 达到上限:冲正外部单据后退回「待审核(1)」,并释放审核时锁定的库存
const cancelResult = await this.cancelRemote(client, order);
await this.releaseStock(order, '推送超时退回待审核,释放锁定库存');
await order.update({
status: 1,
audit_by: null,
@ -259,9 +280,10 @@ class OrderDeliveryPushService extends Service {
return { ok: true, message: '已推送仓库', response: resp, attempts };
}
// 对方明确响应失败:不重试,冲正后退回「待审核(1)」
// 对方明确响应失败:不重试,冲正后退回「待审核(1)」,并释放审核时锁定的库存
const cancelResult = await this.cancelRemote(client, order);
const message = resp && (resp.message || resp.code);
await this.releaseStock(order, '推送失败退回待审核,释放锁定库存');
await order.update({
status: 1,
audit_by: null,

View File

@ -0,0 +1,515 @@
'use strict';
const Service = require('egg').Service;
const QimenWmsClient = require('../lib/wms/qimenClient');
const { applyStockChange } = require('../utils/stockRecord');
/** 单条单据最多推送尝试次数(无响应/超时才算一次可重试的失败;对方明确响应失败不重试) */
const PUSH_MAX_ATTEMPTS = 3;
/** 同一单据两次尝试的最小间隔(毫秒):避免失败单在定时任务里被连续猛推 */
const PUSH_THROTTLE_MS = 20000;
/** 定时任务每次最多处理的单据数 */
const PUSH_PENDING_LIMIT = 10;
/** 手动批量推送每次最多处理的单据数(其余交给定时任务,避免一次请求打爆对方服务) */
const PUSH_BATCH_LIMIT = 50;
/** 手动批量推送时两条之间的间隔(毫秒),用于限流 */
const PUSH_BATCH_GAP_MS = 150;
/**
* 出库单推送服务(审核入队 → 定时任务/手动推送)
*
* 状态机约定(outbound_orders.status):
* - 审核(1→2):仅入队,不推送(清空上一轮推送记录,重试计数归零)
* - 推送成功(2→3):锁定库存(占用可用,防超卖)、写 operate_time/pushed_at/wms_push_result
* - 对方服务明确响应失败 / 库存锁定失败:判定失败,释放锁定库存 + best-effort 冲正外部单据,退回「待出库(1)」
* - 无响应/超时/网络异常:保留「已审核(2)」等下次重试(此时库存保持锁定,不重复锁定),最多 3 次;
* 达到 3 次仍失败同样退回「待出库(1)」并释放锁定
*
* 并发防重:用 pushed_at 做乐观锁(CAS)抢占单据,多 worker 下同一单只会被一个进程推送一次
* 库存标记:outbound_orders.stock_locked(1=当前占用着锁定库存),释放/扣减后置 0
*/
class OutboundOrderPushService extends Service {
/**
* 查该仓库启用的类奇门接口配置
* @param {Object} order 出库单(需含 principal_id / warehouse_id)
* @return {Promise<Object|null>} warehouse_apis 记录
*/
async findWarehouseApi(order) {
return this.ctx.model.WarehouseApi.findOne({
where: {
warehouse_id: order.warehouse_id,
principal_id: order.principal_id,
type: 'qimen',
status: 1,
},
order: [[ 'id', 'ASC' ]],
});
}
/**
* 取上次推送记录(wms_push_result JSON)
* @param {Object} order 出库单
* @return {Object} 上次记录(无则空对象)
*/
_prevResult(order) {
const raw = order.wms_push_result;
return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
}
/**
* 加载单据(含仓库/创建人,推送报文需要)
* @param {number|string} id 出库单ID
* @return {Promise<Object|null>} 出库单实例
*/
async loadOrder(id) {
return this.ctx.model.OutboundOrder.findByPk(id, {
include: [
{ model: this.ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] },
{ model: this.ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] },
],
});
}
/**
* 取参与推送的明细(仅已关联商品的明细:无商品的行既不锁定库存也无法下发 itemId)
* @param {number|string} orderId 出库单ID
* @return {Promise<Array>} stock_items 明细
*/
async loadItems(orderId) {
const Op = this.app.Sequelize.Op;
return this.ctx.model.StockItem.findAll({
where: { bill_type: 2, bill_id: orderId, product_id: { [Op.ne]: null } },
attributes: [ 'id', 'product_id', 'code', 'name', 'quantity', 'inventory_type' ],
order: [[ 'id', 'ASC' ]],
});
}
/**
* 取明细对应商品档案(写库存流水需要编码/名称快照)
* @param {Array} items 明细
* @return {Promise<Map>} productId -> product
*/
async loadProductMap(items) {
const Op = this.app.Sequelize.Op;
const ids = [ ...new Set(items.map(i => Number(i.product_id)).filter(Boolean)) ];
if (!ids.length) return new Map();
const rows = await this.ctx.model.Product.findAll({
where: { id: { [Op.in]: ids } },
attributes: [ 'id', 'item_code', 'item_name' ],
});
return new Map(rows.map(p => [ Number(p.id), p ]));
}
/**
* 按商品回查该仓库的 WMS 内部商品ID(warehouse_products.wms_item_id,stockout.create 的 itemId 必填)
* @param {Object} order 出库单
* @param {Array} items 明细
* @return {Promise<Object>} productId -> wms_item_id
*/
async resolveWmsItemIds(order, items) {
const Op = this.app.Sequelize.Op;
const productIds = [ ...new Set(items.map(i => Number(i.product_id)).filter(Boolean)) ];
if (!productIds.length) return {};
const links = await this.ctx.model.WarehouseProduct.findAll({
where: {
principal_id: order.principal_id,
warehouse_id: order.warehouse_id,
product_id: { [Op.in]: productIds },
},
attributes: [ 'product_id', 'wms_item_id' ],
});
const byProduct = {};
for (const l of links) {
if (l.wms_item_id != null) byProduct[Number(l.product_id)] = Number(l.wms_item_id);
}
return byProduct;
}
/**
* 冲正外部出库单(best-effort,失败只记录不抛出)
* @param {Object} client QimenWmsClient
* @param {Object} order 出库单
* @return {Promise<Object>} 冲正返回或异常信息
*/
async cancelRemote(client, order) {
try {
return await client.cancelOrder(order);
} catch (err) {
return { code: 'EXCEPTION', message: err.message };
}
}
/**
* 锁定库存(推送前占用可用,防超卖)并记 outbound_lock 流水,与 stock_locked 标记同事务
*
* 已锁定(stock_locked=1)时直接跳过:推送无响应重试时库存保持锁定,不能重复占用
* @param {Object} order 出库单实例
* @param {Array} items 明细
* @param {Map} pmap productId -> product(流水快照)
* @param {Object} [options] { remark }
* @return {Promise<{skipped: boolean, affected: number}>}
* @throws {Error} 库存不足时抛 INSUFFICIENT_STOCK(message 已带商品名/可用/需求)
*/
async lockStock(order, items, pmap, options = {}) {
const { ctx } = this;
if (Number(order.stock_locked) === 1) return { skipped: true, affected: 0 };
const transaction = await ctx.model.transaction();
let affected = 0;
try {
for (const it of items) {
const pid = Number(it.product_id);
try {
// 行级库存类型:CC=残次 -> 锁定残次库存,其余(ZP等)归为正品 ZC
await applyStockChange(ctx, {
bizType: 'outbound_lock',
principalId: order.principal_id,
warehouseId: order.warehouse_id,
productId: pid,
itemCode: it.code || (pmap.get(pid) && pmap.get(pid).item_code),
itemName: it.name || (pmap.get(pid) && pmap.get(pid).item_name),
itemType: it.inventory_type === 'CC' ? 'CC' : 'ZC',
quantity: Number(it.quantity) || 0,
billId: order.id,
billNo: order.bill_no,
createdBy: ctx.userId,
remark: options.remark || '出库单推送仓库锁定库存',
transaction,
});
} catch (err) {
if (err.code === 'INSUFFICIENT_STOCK') {
const p = pmap.get(pid);
err.message = `库存不足:${p ? `${p.item_name}(${p.item_code})` : '商品#' + pid},可用 ${err.available},需 ${err.require}`;
}
throw err;
}
affected += 1;
}
await order.update({ stock_locked: 1 }, { transaction });
await transaction.commit();
order.stock_locked = 1;
return { skipped: false, affected };
} catch (err) {
await transaction.rollback();
throw err;
}
}
/**
* 解锁库存(记 outbound_unlock 流水,并把 stock_locked 置 0)
*
* 失败时抛错:调用方(取消/作废/驳回)据此阻断状态流转,避免「锁定了但单据已终结」
* @param {Object} order 出库单实例
* @param {Array} [items] 明细(缺省按单据现查)
* @param {String} remark 备注(写入出入库记录)
* @return {Promise<{skipped: boolean, affected: number}>}
*/
async unlockStock(order, items, remark) {
const { ctx } = this;
const rows = items && items.length ? items : await this.loadItems(order.id);
if (!rows.length) return { skipped: true, affected: 0 };
const transaction = await ctx.model.transaction();
let affected = 0;
try {
for (const it of rows) {
await applyStockChange(ctx, {
bizType: 'outbound_unlock',
principalId: order.principal_id,
warehouseId: order.warehouse_id,
productId: Number(it.product_id),
itemCode: it.code,
itemName: it.name,
itemType: it.inventory_type === 'CC' ? 'CC' : 'ZC',
quantity: Number(it.quantity) || 0,
billId: order.id,
billNo: order.bill_no,
createdBy: ctx.userId,
remark: remark || '出库单释放锁定库存',
transaction,
});
affected += 1;
}
await order.update({ stock_locked: 0 }, { transaction });
await transaction.commit();
order.stock_locked = 0;
return { skipped: false, affected };
} catch (err) {
await transaction.rollback();
throw err;
}
}
/**
* 释放锁定库存(best-effort,仅记录日志不抛出)
* 用于推送失败退回场景:退货状态流转优先,stock_locked 保持 1 便于后续驳回/取消/作废再释放
* @param {Object} order 出库单实例
* @param {Array} items 明细
* @param {String} remark 备注
* @return {Promise<void>}
*/
async releaseStock(order, items, remark) {
const { ctx } = this;
try {
const result = await this.unlockStock(order, items, remark);
if (!result.skipped) {
ctx.logger.info(`[outbound-push] ${order.bill_no} 已释放锁定库存(${result.affected} 行):${remark}`);
}
} catch (err) {
ctx.logger.error(`[outbound-push] ${order.bill_no} 释放锁定库存失败:${err.message}`);
}
}
/**
* 推送单条出库单(一次尝试)
*
* 返回 ok=false 时:
* - retry=true :无响应/超时,单据保留「已审核(2)」(库存维持锁定),等下次定时任务重试
* - retry=false:对方明确失败 / 库存锁定失败 / 已达重试上限,单据已退回「待出库(1)」
* @param {number|string} id 出库单ID
* @param {Object} [options] { source: 'schedule' | 'manual' | 'batch' }
* @return {Promise<{ok: boolean, skipped?: boolean, retry?: boolean, message: string, response?: Object, attempts?: number}>}
*/
async pushOne(id, options = {}) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const source = options.source || 'manual';
const order = await this.loadOrder(id);
if (!order) return { ok: false, message: '出库单不存在' };
if (Number(order.status) !== 2) {
return { ok: false, skipped: true, message: `当前状态不可推送(status=${order.status})` };
}
if (!(Number(order.warehouse_id) > 0)) {
return { ok: false, skipped: true, message: '单据未指定仓库,无法推送:请驳回后补全仓库' };
}
const api = await this.findWarehouseApi(order);
if (!api) {
return {
ok: false,
skipped: true,
message: `仓库「${order.warehouse ? `${order.warehouse.name}(${order.warehouse.code})` : `#${order.warehouse_id}`}」未配置启用中的类奇门接口`,
};
}
// 乐观锁抢占:多 worker / 并发请求下同一单只推一次(同时把本次尝试时间写入 pushed_at)
const now = new Date();
const throttleBefore = new Date(now.getTime() - PUSH_THROTTLE_MS);
const [ claimed ] = await ctx.model.OutboundOrder.update(
{ pushed_at: now },
{
where: {
id: order.id,
status: 2,
[Op.or]: [
{ pushed_at: null },
{ pushed_at: { [Op.lt]: throttleBefore } },
],
},
}
);
if (!claimed) {
return { ok: false, skipped: true, message: '该单据正在推送或处于重试间隔内,已跳过' };
}
const prev = this._prevResult(order);
const attempts = Number(prev.attempts || 0) + 1;
const base = {
deliveryOrderCode: order.bill_no,
warehouseApiId: api.id,
apiType: api.type,
attempts,
maxAttempts: PUSH_MAX_ATTEMPTS,
source,
attemptedAt: now.toISOString(),
};
const items = await this.loadItems(order.id);
if (!items.length) {
// 审核要求有明细,正常不会走到这里;真出现则退回「待出库」,让用户补明细后重新审核
await order.update({
status: 1,
pushed_at: null,
wms_push_result: { ...base, success: false, failureKind: 'empty_items', retryable: false, message: '单据无明细,无法推送' },
});
ctx.logger.warn(`[outbound-push] ${order.bill_no} 无明细,已退回待出库`);
return { ok: false, retry: false, message: '单据无明细,无法推送', attempts };
}
const pmap = await this.loadProductMap(items);
const client = new QimenWmsClient(api, this.app);
// 先锁定库存(占用可用,防止超卖)——不向 WMS 提交前先占用,避免外部建单而本地无占用
try {
await this.lockStock(order, items, pmap);
} catch (err) {
const insufficient = err.code === 'INSUFFICIENT_STOCK';
const message = insufficient ? err.message : `库存锁定失败:${err.message}`;
await order.update({
status: 1,
pushed_at: null,
wms_push_result: {
...base,
success: false,
failureKind: insufficient ? 'insufficient_stock' : 'lock_failed',
retryable: false,
message,
},
});
ctx.logger.warn(`[outbound-push] ${order.bill_no} 推送前锁定库存失败,已退回待出库:${message}`);
return { ok: false, retry: false, message, attempts };
}
let resp;
try {
resp = await client.createStockout(order, items, {
warehouse: order.warehouse,
wmsItemIdByProduct: await this.resolveWmsItemIds(order, items),
});
} catch (err) {
// 超时 / 网络异常 / 非法响应:可重试(库存保持锁定,重试不会重复占用)
const canRetry = attempts < PUSH_MAX_ATTEMPTS;
if (canRetry) {
await order.update({
wms_push_result: { ...base, success: false, failureKind: 'timeout', retryable: true, error: err.message },
});
ctx.logger.warn(`[outbound-push] ${order.bill_no} 第 ${attempts}/${PUSH_MAX_ATTEMPTS} 次推送异常(将重试):${err.message}`);
return { ok: false, retry: true, message: err.message, attempts };
}
// 达到上限:冲正外部单据后退回「待出库」,并释放锁定库存
const cancelResult = await this.cancelRemote(client, order);
await this.releaseStock(order, items, '推送超时退回待出库,释放锁定库存');
await order.update({
status: 1,
pushed_at: null,
wms_push_result: {
...base,
success: false,
failureKind: 'timeout',
retryable: false,
error: err.message,
cancelResult,
},
});
ctx.logger.error(`[outbound-push] ${order.bill_no} 连续 ${attempts} 次推送异常,已退回待出库:${err.message}`);
return { ok: false, retry: false, message: `连续 ${attempts} 次无响应/超时,已退回待出库:${err.message}`, attempts };
}
if (client.isSuccess(resp)) {
await order.update({
status: 3,
operate_time: now,
pushed_at: now,
wms_push_result: { ...base, success: true, response: resp },
});
ctx.logger.info(`[outbound-push] ${order.bill_no} 推送成功(第 ${attempts} 次)`);
return { ok: true, message: '已推送仓库', response: resp, attempts };
}
// 对方明确响应失败:不重试,冲正后退回「待出库」,并释放锁定库存
const cancelResult = await this.cancelRemote(client, order);
const message = resp && (resp.message || resp.code);
await this.releaseStock(order, items, '推送失败退回待出库,释放锁定库存');
await order.update({
status: 1,
pushed_at: null,
wms_push_result: {
...base,
success: false,
failureKind: 'business',
retryable: false,
code: resp && resp.code,
message,
response: resp,
cancelResult,
},
});
ctx.logger.warn(`[outbound-push] ${order.bill_no} 推送失败(对方明确拒绝),已退回待出库:${message}`);
return { ok: false, retry: false, message: `WMS 返回失败:${message}`, response: resp, attempts };
}
/**
* 扫描「已审核(2)」的单据并推送(定时任务入口)
* @param {Object} [options] { limit }
* @return {Promise<{scanned: number, pushed: number, failed: number, retry: number, skipped: number}>}
*/
async processPending(options = {}) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const limit = Number(options.limit) > 0 ? Number(options.limit) : PUSH_PENDING_LIMIT;
const throttleBefore = new Date(Date.now() - PUSH_THROTTLE_MS);
const orders = await ctx.model.OutboundOrder.findAll({
where: {
status: 2,
warehouse_id: { [Op.ne]: null },
[Op.or]: [
{ pushed_at: null },
{ pushed_at: { [Op.lt]: throttleBefore } },
],
},
attributes: [ 'id' ],
// pushed_at 为 NULL(从未尝试)优先,其次按尝试时间升序
order: [[ 'pushed_at', 'ASC' ], [ 'id', 'ASC' ]],
limit,
});
const stat = { scanned: orders.length, pushed: 0, failed: 0, retry: 0, skipped: 0 };
for (const row of orders) {
const res = await this.pushOne(row.id, { source: 'schedule' });
if (res.ok) stat.pushed++;
else if (res.skipped) stat.skipped++;
else if (res.retry) stat.retry++;
else stat.failed++;
}
return stat;
}
/**
* 批量推送指定ID列表(限流顺序执行)
* @param {number[]} ids 出库单ID列表
* @param {Object} [options] { limit, gap }
* @return {Promise<Object>} 统计与明细
*/
async pushMany(ids, options = {}) {
const limit = Number(options.limit) > 0 ? Number(options.limit) : PUSH_BATCH_LIMIT;
const gap = options.gap === undefined ? PUSH_BATCH_GAP_MS : Number(options.gap);
const targets = ids.slice(0, limit);
const result = {
requested: ids.length,
processed: targets.length,
pendingRest: Math.max(ids.length - targets.length, 0),
pushed: 0,
failed: 0,
retry: 0,
skipped: 0,
details: [],
};
for (let i = 0; i < targets.length; i++) {
const id = targets[i];
const res = await this.pushOne(id, { source: 'batch' });
if (res.ok) result.pushed++;
else if (res.skipped) result.skipped++;
else if (res.retry) result.retry++;
else result.failed++;
result.details.push({
id: Number(id),
ok: res.ok,
skipped: !!res.skipped,
retry: !!res.retry,
message: res.message,
});
if (gap > 0 && i < targets.length - 1) {
await new Promise(resolve => setTimeout(resolve, gap));
}
}
return result;
}
}
module.exports = OutboundOrderPushService;

View File

@ -1,12 +1,14 @@
'use strict';
const stock = require('./stock');
const { applyStockChange } = require('./stockRecord');
/**
* 完成入库:把「已推送(3)」的入库单置为「已完成(4)」,并按明细增加系统库存。
* - 幂等:已完成的单据直接返回成功(不重复加库存),供 WMS 回调重复推送时安全复用
* - 明细为空时拒绝,避免「空单据」走完流程却不产生任何库存
* - 行级库存类型:inventory_type=CC → product_stocks.item_type='CC',其余(ZP 等)归为正品 ZC
* - 每次增加库存同步写一条 `stock_records` 出入库记录(biz_type=inbound_increase),
* 记录本次入库数量与变动后总数量/锁定数量/可用数量
* 复用入口:① 控制器手工「完成」 ② WMS 回调 entryorder.confirm(外部回推驱动)
* @param {Egg.Context} ctx
* @param {Object} order 入库单 model 实例(需含 id / principal_id / status)
@ -22,7 +24,7 @@ module.exports = async function completeInbound(ctx, order) {
const items = await ctx.model.StockItem.findAll({
where: { bill_type: 1, bill_id: order.id, product_id: { [ctx.app.Sequelize.Op.ne]: null } },
attributes: [ 'product_id', 'quantity', 'inventory_type' ],
attributes: [ 'product_id', 'code', 'name', 'quantity', 'inventory_type' ],
order: [[ 'product_id', 'ASC' ]],
});
if (!items.length) {
@ -35,7 +37,21 @@ module.exports = async function completeInbound(ctx, order) {
const p = it.get ? it.get({ plain: true }) : it;
// 行级库存类型:CC=残次 -> product_stocks 的 item_type='CC',其余(ZP等)归为正品 ZC
const itemType = p.inventory_type === 'CC' ? 'CC' : 'ZC';
await stock.increase(ctx, order.principal_id, Number(p.product_id), Number(p.quantity) || 0, transaction, itemType);
// 增加库存 + 写一条入库记录(recordStockChange 与库存变动同事务)
await applyStockChange(ctx, {
bizType: 'inbound_increase',
principalId: order.principal_id,
warehouseId: order.warehouse_id,
productId: Number(p.product_id),
itemCode: p.code,
itemName: p.name,
itemType,
quantity: Number(p.quantity) || 0,
billId: order.id,
billNo: order.bill_no,
remark: '入库确认增加库存',
transaction,
});
}
await order.update({ status: 4 }, { transaction });
await transaction.commit();

View File

@ -0,0 +1,179 @@
'use strict';
const { applyStockChange } = require('./stockRecord');
/**
* 发货单(订单)库存动作:审核锁定 / 释放 / 发货确认扣减。
*
* 与 WMS 侧 `deliveryorder.create` 的库存预占对齐,OMS 侧统一在以下时机动库存(均写 stock_records 流水):
* - **审核(1→2)**:按明细锁定库存(order_lock),可用不足则审核失败
* - **推送失败退回 / 驳回 / 取消 / 作废**:释放锁定(order_unlock)
* - **WMS 发货确认(deliveryorder.confirm, 3→4)**:扣减库存(总数量与锁定同减,order_deduct)
*
* 幂等与兼容依据是 `order_deliveries.stock_locked`:
* - lock:已锁定(1) 直接跳过,不重复占用
* - release/deduct:未锁定(0) 直接跳过 —— 历史单据(本能力上线前已审核/已推送)不会被凭空释放/扣减
*
* 明细商品解析:`order_delivery_items` 未存 product_id,按 `item_code` 关联 `products`
* (主体隔离),匹配不到的明细行会被跳过并返回 skippedLines 供调用方提示。
*/
/** 动作 → 出入库记录业务动作(常量见 app/utils/stockRecord.js#BIZ_TYPES) */
const ACTION_BIZ_TYPES = {
lock: 'order_lock',
release: 'order_unlock',
deduct: 'order_deduct',
};
/** 默认备注 */
const DEFAULT_REMARKS = {
lock: '订单审核锁定库存',
release: '订单释放锁定库存',
deduct: '订单发货确认扣减库存',
};
/**
* 取发货单明细并解析系统商品
* @param {Object} ctx egg context
* @param {Object} order 发货单实例(需含 id / principal_id)
* @param {Object} [transaction] Sequelize 事务
* @return {Promise<Array<Object>>} [{ product_id, item_code, item_name, plan_qty, inventory_type }]
*/
async function loadOrderLines(ctx, order, transaction) {
const Op = ctx.app.Sequelize.Op;
const items = await ctx.model.OrderDeliveryItem.findAll({
where: { order_delivery_id: order.id },
attributes: [ 'id', 'order_line_no', 'item_code', 'item_name', 'plan_qty', 'inventory_type' ],
order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]],
transaction,
});
if (!items.length) return [];
const codes = [ ...new Set(items.map(i => i.item_code).filter(v => v != null && String(v).trim() !== '')) ];
const products = codes.length
? await ctx.model.Product.findAll({
where: { principal_id: order.principal_id, item_code: { [Op.in]: codes } },
attributes: [ 'id', 'item_code', 'item_name' ],
transaction,
})
: [];
const byCode = new Map(products.map(p => [ p.item_code, p ]));
return items.map(it => {
const row = it.get ? it.get({ plain: true }) : it;
const product = row.item_code ? byCode.get(row.item_code) : null;
return {
product_id: product ? Number(product.id) : null,
item_code: row.item_code,
item_name: row.item_name || (product && product.item_name) || null,
plan_qty: Number(row.plan_qty) || 0,
inventory_type: row.inventory_type,
};
});
}
/**
* 执行发货单库存动作(账实同事务)
* @param {Object} ctx egg context
* @param {Object} order 发货单实例(需含 id / principal_id / warehouse_id / delivery_order_code / stock_locked)
* @param {String} action lock(审核锁定)/ release(释放锁定)/ deduct(发货确认扣减)
* @param {Object} [options] 选项
* @param {Number} [options.createdBy] 操作人ID
* @param {String} [options.remark] 备注(不传用默认备注)
* @param {Object} [options.transaction] 外部事务;不传时内部自建并提交/回滚
* @return {Promise<{action: String, affected: Number, skipped: Boolean, skippedLines: Array<String>}>}
* affected = 实际发生库存变动的明细行数;skippedLines = 未匹配到系统商品(无 product_id 或数量为 0)的 item_code
*/
async function execute(ctx, order, action, options = {}) {
const bizType = ACTION_BIZ_TYPES[action];
if (!bizType) throw new Error(`未知的发货单库存动作:${action}`);
const locked = Number(order.stock_locked) === 1;
// 幂等/兼容:已锁定不再加锁;未锁定不释放、不扣减
if (action === 'lock' && locked) return { action, affected: 0, skipped: true, skippedLines: [] };
if (action !== 'lock' && !locked) return { action, affected: 0, skipped: true, skippedLines: [] };
const ownTransaction = !options.transaction;
const transaction = options.transaction || await ctx.model.transaction();
try {
const lines = await loadOrderLines(ctx, order, transaction);
const hit = lines.filter(l => l.product_id && l.plan_qty > 0);
// 仅把「未匹配到系统商品」的明细计入 skippedLines(数量为空/0 的明细直接忽略,属数据异常)
const skippedLines = lines.filter(l => !l.product_id).map(l => l.item_code || `#${l.product_id || '?'}`);
if (!hit.length) {
throw new Error('发货单明细未匹配到系统商品(按 item_code 关联 products),无法进行库存操作');
}
for (const line of hit) {
await applyStockChange(ctx, {
bizType,
principalId: order.principal_id,
warehouseId: order.warehouse_id,
productId: line.product_id,
itemCode: line.item_code,
itemName: line.item_name,
itemType: line.inventory_type === 'CC' ? 'CC' : 'ZC',
quantity: line.plan_qty,
billId: order.id,
billNo: order.delivery_order_code,
createdBy: options.createdBy,
remark: options.remark || DEFAULT_REMARKS[action],
transaction,
});
}
// 锁定标记与库存动作同事务:lock → 1,release/deduct → 0
await order.update({ stock_locked: action === 'lock' ? 1 : 0 }, { transaction });
if (ownTransaction) await transaction.commit();
if (skippedLines.length) {
ctx.logger.warn(`[delivery-stock] 发货单 ${order.delivery_order_code} ${action} 跳过未匹配系统商品的明细:${skippedLines.join(', ')}`);
}
return { action, affected: hit.length, skipped: false, skippedLines };
} catch (err) {
if (ownTransaction) await transaction.rollback();
throw err;
}
}
/**
* 审核锁定库存(可用不足抛 INSUFFICIENT_STOCK,由调用方转 400)
* @param {Object} ctx egg context
* @param {Object} order 发货单实例(需含 id / principal_id / warehouse_id / delivery_order_code / stock_locked)
* @param {Object} [options] { createdBy, remark, transaction }
* @return {Promise<Object>} execute 的返回(action / affected / skipped / skippedLines)
*/
function lockDeliveryStock(ctx, order, options = {}) {
return execute(ctx, order, 'lock', options);
}
/**
* 释放锁定库存(推送失败退回 / 驳回 / 取消 / 作废)
* @param {Object} ctx egg context
* @param {Object} order 发货单实例(需含 id / principal_id / warehouse_id / delivery_order_code / stock_locked)
* @param {Object} [options] { createdBy, remark, transaction }
* @return {Promise<Object>} execute 的返回(action / affected / skipped / skippedLines)
*/
function releaseDeliveryStock(ctx, order, options = {}) {
return execute(ctx, order, 'release', options);
}
/**
* 发货确认扣减库存(WMS 回推 deliveryorder.confirm,3→4)
* @param {Object} ctx egg context
* @param {Object} order 发货单实例(需含 id / principal_id / warehouse_id / delivery_order_code / stock_locked)
* @param {Object} [options] { createdBy, remark, transaction }
* @return {Promise<Object>} execute 的返回(action / affected / skipped / skippedLines)
*/
function deductDeliveryStock(ctx, order, options = {}) {
return execute(ctx, order, 'deduct', options);
}
module.exports = {
ACTION_BIZ_TYPES,
DEFAULT_REMARKS,
loadOrderLines,
lockDeliveryStock,
releaseDeliveryStock,
deductDeliveryStock,
};

View File

@ -0,0 +1,236 @@
'use strict';
const stock = require('./stock');
/**
* 出入库记录(stock_records)写入工具。
*
* 出入库记录与 product_stocks 余量表互补:余量表只存「当前是多少」,本模块在每次库存变动的
* 同一事务内追加一行流水,记录业务动作、单据来源、变动数量与变动前后的总数量/锁定数量/可用数量。
*
* 业务动作(BIZ_TYPES,唯一常量来源;前端下拉与说明以此为准):
* - outbound_lock 出库推送锁定(出库单 push:可用 → 锁定)
* - outbound_unlock 出库解锁(推送失败释放 / 驳回 / 取消回滚)
* - outbound_deduct 出库确认扣减(WMS 回推 stockout.confirm / notify.delivery:总数量与锁定同减)
* - outbound_restore 出库驳回回补(已扣减过的出库单驳回时回补总数量)
* - inbound_increase 入库确认增加(WMS 回推 entryorder.confirm:总数量增加)
* - order_lock 订单(发货单)审核锁定(审核 1→2:可用 → 锁定)
* - order_unlock 订单解锁(推送失败退回 / 驳回 / 取消 / 作废)
* - order_deduct 订单发货确认扣减(WMS 回推 deliveryorder.confirm:总数量与锁定同减)
*
* 统一入口 `applyStockChange(ctx, options)`:先锁定库存行取变动前余量 → 调 app/utils/stock.js
* 对应动作 → 按「实际前后差值」写记录(残次/正品、扣减时的下限截断都能如实反映)。
* 记录写入与库存变动共用同一事务,保证账实一致。
*/
/**
* 业务动作定义
* - label 中文名
* - direction 业务方向(1入库方向 2出库方向)
* - billType 单据类型(1入库单 2出库单 3发货单/订单)
*/
const BIZ_TYPES = {
outbound_lock: { label: '出库推送锁定', direction: 2, billType: 2 },
outbound_unlock: { label: '出库解锁', direction: 2, billType: 2 },
outbound_deduct: { label: '出库确认扣减', direction: 2, billType: 2 },
outbound_restore: { label: '出库驳回回补', direction: 2, billType: 2 },
inbound_increase: { label: '入库确认增加', direction: 1, billType: 1 },
order_lock: { label: '订单审核锁定', direction: 2, billType: 3 },
order_unlock: { label: '订单解锁', direction: 2, billType: 3 },
order_deduct: { label: '订单发货确认扣减', direction: 2, billType: 3 },
};
/** 出入方向中文名 */
const DIRECTION_LABELS = { 1: '入库', 2: '出库' };
/** 业务动作 → app/utils/stock.js 的具体动作函数 */
const STOCK_ACTIONS = {
outbound_lock: (ctx, principalId, productId, qty, transaction, itemType) => stock.lock(ctx, principalId, productId, qty, transaction, itemType),
outbound_unlock: (ctx, principalId, productId, qty, transaction, itemType) => stock.unlock(ctx, principalId, productId, qty, transaction, itemType),
outbound_deduct: (ctx, principalId, productId, qty, transaction, itemType) => stock.deduct(ctx, principalId, productId, qty, transaction, itemType),
outbound_restore: (ctx, principalId, productId, qty, transaction, itemType) => stock.increase(ctx, principalId, productId, qty, transaction, itemType),
inbound_increase: (ctx, principalId, productId, qty, transaction, itemType) => stock.increase(ctx, principalId, productId, qty, transaction, itemType),
// 发货单(订单):审核锁定 / 解锁 / 发货确认扣减,与出库单同源动作
order_lock: (ctx, principalId, productId, qty, transaction, itemType) => stock.lock(ctx, principalId, productId, qty, transaction, itemType),
order_unlock: (ctx, principalId, productId, qty, transaction, itemType) => stock.unlock(ctx, principalId, productId, qty, transaction, itemType),
order_deduct: (ctx, principalId, productId, qty, transaction, itemType) => stock.deduct(ctx, principalId, productId, qty, transaction, itemType),
};
/** 业务动作列表(供接口下拉/校验使用) */
const BIZ_TYPE_LIST = Object.keys(BIZ_TYPES).map(value => ({
value,
label: BIZ_TYPES[value].label,
direction: BIZ_TYPES[value].direction,
bill_type: BIZ_TYPES[value].billType,
}));
/**
* 库存维度统一为 ZC/CC(stock_items 的 ZP 在写入库存时映射为 ZC)
* @param {String} itemType 库存类型(ZP/CC/其他)
* @return {String} ZC 或 CC
*/
function normalizeItemType(itemType) {
return String(itemType || '').toUpperCase() === 'CC' ? 'CC' : 'ZC';
}
/**
* 取库存行的余量快照
* @param {Object} row product_stocks 行(可为空)
* @return {{quantity: Number, lock: Number, available: Number}} 变动前/后的余量
*/
function snapshot(row) {
const quantity = Number(row && row.quantity) || 0;
const lockQuantity = Number(row && row.lock_quantity) || 0;
return {
quantity,
lock: lockQuantity,
// available 以行上冗余列为准(stock.js 每次变动都会重算),缺列时按 总-锁 兜底
available: row && row.available != null ? Number(row.available) : quantity - lockQuantity,
};
}
/**
* 写入一条出入库记录
* @param {Object} ctx egg context
* @param {Object} payload 记录内容
* @param {String} payload.bizType 业务动作(BIZ_TYPES 的 key,必填)
* @param {Number} payload.principalId 主体ID(必填)
* @param {Number} [payload.warehouseId] 仓库ID
* @param {Number} [payload.productId] 系统商品ID
* @param {String} [payload.itemCode] 商品编码快照
* @param {String} [payload.itemName] 商品名称快照
* @param {String} [payload.itemType] 库存类型 ZC/CC,默认 ZC
* @param {Number} payload.quantity 本次变动数量(恒记正数,方向见 bizType/direction)
* @param {Number} payload.quantityBefore 变动前总数量
* @param {Number} payload.quantityAfter 变动后总数量
* @param {Number} payload.lockBefore 变动前锁定数量
* @param {Number} payload.lockAfter 变动后锁定数量
* @param {Number} payload.availableBefore 变动前可用数量
* @param {Number} payload.availableAfter 变动后可用数量
* @param {Number} [payload.billId] 单据头ID
* @param {String} [payload.billNo] 单据号(入库单 RK_ / 出库单 CK_ / 发货单 FH_)
* @param {Number} [payload.createdBy] 操作人ID
* @param {String} [payload.remark] 备注
* @param {Object} [payload.transaction] Sequelize 事务(与库存变动同事务)
* @return {Promise<Object>} 记录实例
*/
async function recordStockChange(ctx, payload) {
const {
bizType, principalId, warehouseId, productId, itemCode, itemName, itemType,
quantity, quantityBefore, quantityAfter, lockBefore, lockAfter, availableBefore, availableAfter,
billId, billNo, createdBy, remark, transaction,
} = payload || {};
const meta = BIZ_TYPES[bizType];
if (!meta) throw new Error(`未知的出入库记录业务类型:${bizType}`);
if (principalId == null) throw new Error('出入库记录缺少所属主体(principalId)');
const qtyBefore = Number(quantityBefore) || 0;
const qtyAfter = Number(quantityAfter) || 0;
const lockB = Number(lockBefore) || 0;
const lockA = Number(lockAfter) || 0;
return ctx.model.StockRecord.create({
principal_id: Number(principalId),
warehouse_id: warehouseId == null || warehouseId === '' ? null : Number(warehouseId),
product_id: productId == null || productId === '' ? null : Number(productId),
item_code: itemCode ? String(itemCode).slice(0, 100) : null,
item_name: itemName ? String(itemName).slice(0, 255) : null,
item_type: normalizeItemType(itemType),
biz_type: bizType,
direction: meta.direction,
bill_type: meta.billType,
bill_id: billId == null || billId === '' ? null : Number(billId),
bill_no: billNo ? String(billNo).slice(0, 50) : null,
// 变动数量恒记正数;锁定变动量用前后差值(正=加锁 负=解锁)
quantity: Math.abs(Number(quantity) || 0),
quantity_before: qtyBefore,
quantity_after: qtyAfter,
lock_quantity: lockA - lockB,
lock_before: lockB,
lock_after: lockA,
available_before: Number(availableBefore) || 0,
available_after: Number(availableAfter) || 0,
remark: remark ? String(remark).slice(0, 255) : null,
created_by: createdBy == null || createdBy === '' ? null : Number(createdBy),
}, { transaction });
}
/**
* 执行库存变动并写入出入库记录(账实同事务)
*
* 与直接调用 app/utils/stock.js 的区别:本函数额外落一条流水,供「出入库记录」页面查询。
* 库存不足(INSUFFICIENT_STOCK)等异常由 stock.js 抛出,此时不会写记录。
*
* @param {Object} ctx egg context
* @param {Object} options 参数
* @param {String} options.bizType 业务动作(BIZ_TYPES 的 key,必填)
* @param {Number} options.principalId 主体ID(必填)
* @param {Number} options.productId 系统商品ID(必填)
* @param {Number} options.quantity 变动数量(必填,需 > 0)
* @param {String} [options.itemType] 库存类型 ZC/CC,默认 ZC
* @param {Number} [options.warehouseId] 仓库ID
* @param {String} [options.itemCode] 商品编码快照
* @param {String} [options.itemName] 商品名称快照
* @param {Number} [options.billId] 单据头ID
* @param {String} [options.billNo] 单据号
* @param {Number} [options.createdBy] 操作人ID
* @param {String} [options.remark] 备注
* @param {Object} options.transaction Sequelize 事务
* @return {Promise<Object|null>} 变动后的库存行(数量 <= 0 或未命中动作时返回 null)
*/
async function applyStockChange(ctx, options) {
const {
bizType, principalId, productId, quantity, itemType,
warehouseId, itemCode, itemName, billId, billNo, createdBy, remark, transaction,
} = options || {};
const action = STOCK_ACTIONS[bizType];
if (!action) throw new Error(`未知的出入库记录业务类型:${bizType}`);
const qty = Number(quantity) || 0;
if (qty <= 0 || productId == null || productId === '') return null;
const type = normalizeItemType(itemType);
const pid = Number(productId);
// 先取(或建)库存行并锁定:拿到变动前余量,用于记录「变动前/后」
const before = await stock.getOrCreate(ctx, principalId, pid, type, transaction);
const beforeSnap = snapshot(before);
const row = await action(ctx, principalId, pid, qty, transaction, type);
const afterSnap = snapshot(row || before);
await recordStockChange(ctx, {
bizType,
principalId,
warehouseId,
productId: pid,
itemCode,
itemName,
itemType: type,
quantity: qty,
quantityBefore: beforeSnap.quantity,
quantityAfter: afterSnap.quantity,
lockBefore: beforeSnap.lock,
lockAfter: afterSnap.lock,
availableBefore: beforeSnap.available,
availableAfter: afterSnap.available,
billId,
billNo,
createdBy,
remark,
transaction,
});
return row;
}
module.exports = {
BIZ_TYPES,
BIZ_TYPE_LIST,
DIRECTION_LABELS,
normalizeItemType,
recordStockChange,
applyStockChange,
};

View File

@ -0,0 +1,93 @@
'use strict';
/**
* 出入库记录表(库存流水):stock_records
*
* 与 product_stocks(库存余量表)互补——product_stocks 只存当前余量,本表存「每一次库存变动」的
* 发生时间、单据来源、变动数量与变动前后的总数量/锁定数量/可用数量,用于对账与排查。
*
* 记录的业务动作(biz_type,常量单一来源 app/utils/stockRecord.js):
* - outbound_lock 出库单推送锁定(出库单 push:可用 → 锁定)
* - outbound_unlock 出库解锁(推送失败释放 / 驳回 / 取消回滚)
* - outbound_deduct 出库确认扣减(WMS 回调 stockout.confirm / notify.delivery:总数量与锁定同减)
* - inbound_increase 入库确认增加(WMS 回调 entryorder.confirm:总数量增加)
*
* 数量口径(DECIMAL(15,3),与 product_stocks 一致):
* - quantity 本次变动数量(入库为增加量;出库锁定/扣减为占用量,恒为正数)
* - quantity_before/after 变动前/后总数量
* - lock_quantity 本次锁定变动量(正=加锁,负=解锁,由 lock_before/after 差值反推)
* - lock_before/after 变动前/后锁定数量
* - available_before/after 变动前/后可用数量(= 总数量 - 锁定数量)
*
* 库存维度 item_type:ZC=正品 / CC=残次品(与 product_stocks.item_type 对齐,
* 与 stock_items.inventory_type 的 ZP/CC 不同层:ZP 会在写入库存时映射为 ZC)。
*/
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable(
'stock_records',
{
id: {
type: Sequelize.BIGINT.UNSIGNED,
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
principal_id: {
type: Sequelize.BIGINT.UNSIGNED,
allowNull: false,
comment: '所属主体ID',
references: { model: 'principals', key: 'id' },
},
warehouse_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '仓库ID(关联 warehouses)' },
product_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '系统商品ID(关联 products)' },
item_code: { type: Sequelize.STRING(100), allowNull: true, comment: '商品编码(快照)' },
item_name: { type: Sequelize.STRING(255), allowNull: true, comment: '商品名称(快照)' },
item_type: {
type: Sequelize.STRING(4),
allowNull: false,
defaultValue: 'ZC',
comment: '库存类型:ZC=正品 CC=残次品(与 product_stocks.item_type 对齐)',
},
biz_type: { type: Sequelize.STRING(30), allowNull: false, comment: '业务动作:outbound_lock / outbound_unlock / outbound_deduct / inbound_increase' },
direction: { type: Sequelize.TINYINT, allowNull: false, comment: '出入方向:1入库 2出库(便于按方向筛选)' },
bill_type: { type: Sequelize.TINYINT, allowNull: false, comment: '单据类型:1入库单 2出库单(对齐 stock_items.bill_type)' },
bill_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '单据头ID(inbound_orders.id / outbound_orders.id)' },
bill_no: { type: Sequelize.STRING(50), allowNull: true, comment: '单据号(RK_{id} / CK_{id})' },
quantity: { type: Sequelize.DECIMAL(15, 3), allowNull: false, defaultValue: 0, comment: '本次变动数量(恒为正数,方向见 direction / biz_type)' },
quantity_before: { type: Sequelize.DECIMAL(15, 3), allowNull: false, defaultValue: 0, comment: '变动前总数量' },
quantity_after: { type: Sequelize.DECIMAL(15, 3), allowNull: false, defaultValue: 0, comment: '变动后总数量' },
lock_quantity: { type: Sequelize.DECIMAL(15, 3), allowNull: false, defaultValue: 0, comment: '本次锁定变动量(正=加锁 负=解锁)' },
lock_before: { type: Sequelize.DECIMAL(15, 3), allowNull: false, defaultValue: 0, comment: '变动前锁定数量' },
lock_after: { type: Sequelize.DECIMAL(15, 3), allowNull: false, defaultValue: 0, comment: '变动后锁定数量' },
available_before: { type: Sequelize.DECIMAL(15, 3), allowNull: false, defaultValue: 0, comment: '变动前可用数量' },
available_after: { type: Sequelize.DECIMAL(15, 3), allowNull: false, defaultValue: 0, comment: '变动后可用数量' },
remark: { type: Sequelize.STRING(255), allowNull: true, comment: '备注(如推送失败释放、驳回回滚、WMS 回推确认等)' },
created_by: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '操作人ID(系统自动写入为空)' },
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '记录时间(业务发生时间)',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
},
},
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '出入库记录(库存流水)表' }
);
await queryInterface.addIndex('stock_records', { fields: [ 'principal_id' ], name: 'idx_sr_principal' });
await queryInterface.addIndex('stock_records', { fields: [ 'product_id' ], name: 'idx_sr_product' });
await queryInterface.addIndex('stock_records', { fields: [ 'warehouse_id' ], name: 'idx_sr_warehouse' });
await queryInterface.addIndex('stock_records', { fields: [ 'bill_no' ], name: 'idx_sr_bill_no' });
await queryInterface.addIndex('stock_records', { fields: [ 'biz_type' ], name: 'idx_sr_biz_type' });
await queryInterface.addIndex('stock_records', { fields: [ 'created_at' ], name: 'idx_sr_created' });
},
async down(queryInterface) {
await queryInterface.dropTable('stock_records');
},
};

View File

@ -0,0 +1,62 @@
'use strict';
/**
* 新增「出入库记录」菜单:挂在「库存管理」目录下,指向 views/StockRecord/Index.vue
*
* 该页面只读展示库存流水(stock_records):出库推送锁定、出库解锁、出库确认扣减、
* 出库驳回回补、入库确认增加。菜单按 name + parent_id 判重,可重复执行。
*/
const PARENT_NAME = '库存管理';
const MENU = {
name: '出入库记录',
type: 2,
path: '/stock-record',
icon: 'Finished',
permission: 'stockRecord:list',
component: 'views/StockRecord/Index.vue',
sort: 65,
};
module.exports = {
async up(queryInterface) {
const sequelize = queryInterface.sequelize;
const [ parent ] = await sequelize.query(
'SELECT id FROM menus WHERE name = ? AND parent_id = 0 LIMIT 1',
{ replacements: [ PARENT_NAME ], type: sequelize.QueryTypes.SELECT }
);
if (!parent) return;
const parentId = Number(parent.id);
const [ exist ] = await sequelize.query(
'SELECT id FROM menus WHERE name = ? AND parent_id = ? LIMIT 1',
{ replacements: [ MENU.name, parentId ], type: sequelize.QueryTypes.SELECT }
);
if (exist) return;
await sequelize.query(
`INSERT INTO menus
(parent_id, name, type, path, icon, permission, component, sort, status, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, NOW(), NOW())`,
{
replacements: [
parentId,
MENU.name,
MENU.type,
MENU.path,
MENU.icon,
MENU.permission,
MENU.component,
MENU.sort,
],
}
);
},
async down(queryInterface) {
const sequelize = queryInterface.sequelize;
await sequelize.query('DELETE FROM menus WHERE name = ? AND path = ?', {
replacements: [ MENU.name, MENU.path ],
});
},
};

View File

@ -0,0 +1,39 @@
'use strict';
/**
* 发货单(订单)库存锁定标记:order_deliveries.stock_locked
*
* 背景:发货单推送到 WMS 后,WMS 侧 deliveryorder.create 会对库存做预占;OMS 侧原先完全不碰库存,
* 导致「订单创建/审核 → 推送 → 发货确认」这条链路没有库存流水。现按以下口径补齐(与出库单同源,
* 库存动作统一走 app/utils/stockRecord.js#applyStockChange,与 stock_records 同事务):
* - 审核(1→2):按明细锁定库存(product_stocks.lock_quantity 增加)并写流水 biz_type=order_lock
* - 推送失败退回待审核 / 驳回(2→1) / 取消(1|2|3→9) / 作废(2→5):释放锁定并写流水 biz_type=order_unlock
* - WMS 发货确认(deliveryorder.confirm, 3→4):扣减库存(总数量与锁定同减)并写流水 biz_type=order_deduct
*
* stock_locked 作为幂等与兼容依据:
* - 1 = 该单当前占用着锁定库存(审核成功后置 1)
* - 0 = 未锁定 / 已释放 / 已扣减
* 历史单据(本迁移之前已审核/已推送)落 0 → 发货确认时跳过扣减,避免「没有锁定却扣总数量」。
*
* 幂等:迁移可重复执行(先 describeTable 判断列是否存在)。
*/
module.exports = {
async up(queryInterface, Sequelize) {
const columns = await queryInterface.describeTable('order_deliveries');
if (columns.stock_locked) return;
await queryInterface.addColumn('order_deliveries', 'stock_locked', {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '库存锁定标记:1=审核时已锁定库存(推送失败/驳回/取消/作废释放,发货确认扣减),0=未锁定',
after: 'status',
});
},
async down(queryInterface) {
const columns = await queryInterface.describeTable('order_deliveries');
if (!columns.stock_locked) return;
await queryInterface.removeColumn('order_deliveries', 'stock_locked');
},
};

View File

@ -0,0 +1,45 @@
'use strict';
/**
* 多运单号留存:outbound_orders.express_codes / order_deliveries.express_codes(JSON 数组)
*
* 背景:WMS 出库确认(stockout.confirm)与发货确认(deliveryorder.confirm)的报文中
* `packages.package` 是**数组**(一单可拆多个包裹、每个包裹一个运单号,如 CK_4 一单两个运单号)。
* 但 OMS 侧 order_deliveries.express_code 是单值列(只落第一个运单号),outbound_orders 更是没有运单号列,
* 多运单只能翻 wms_push_result.confirm.packages[] 的 JSON,无法在列表/筛选/导出/对外接口里用。
* 故两表各加一个 express_codes(JSON 数组)留存全部运单号;单值字段(express_code)保留,
* 继续表示「首个运单号」,兼容既有口径与前端展示。
*
* 幂等:迁移可重复执行(先 describeTable 判断列是否存在)。
*/
module.exports = {
async up(queryInterface, Sequelize) {
const outboundColumns = await queryInterface.describeTable('outbound_orders');
if (!outboundColumns.express_codes) {
await queryInterface.addColumn('outbound_orders', 'express_codes', {
type: Sequelize.JSON,
allowNull: true,
comment: '运单号集合(WMS 出库确认 packages.package[].expressCode,多包裹时为数组)',
after: 'stock_deducted',
});
}
const deliveryColumns = await queryInterface.describeTable('order_deliveries');
if (!deliveryColumns.express_codes) {
await queryInterface.addColumn('order_deliveries', 'express_codes', {
type: Sequelize.JSON,
allowNull: true,
comment: '运单号集合(WMS 发货确认 packages.package[].expressCode,多包裹时为数组)',
after: 'express_code',
});
}
},
async down(queryInterface) {
const outboundColumns = await queryInterface.describeTable('outbound_orders');
if (outboundColumns.express_codes) await queryInterface.removeColumn('outbound_orders', 'express_codes');
const deliveryColumns = await queryInterface.describeTable('order_deliveries');
if (deliveryColumns.express_codes) await queryInterface.removeColumn('order_deliveries', 'express_codes');
},
};

View File

@ -0,0 +1,49 @@
'use strict';
/**
* 发货单(订单)回传平台店铺的同步状态与重试次数:
* order_deliveries.shop_sync_status 0未同步 1同步中 2同步成功 3同步失败
* order_deliveries.shop_sync_retry_count 回传失败后的累计重试次数
*
* 背景:发货单完成后需要把发货结果(运单号/发货状态)回传平台店铺(shops 表对应的淘宝/抖音等)。
* 此前 OMS 侧只有 `wms_push_result`(JSON,推送 WMS 的结果)与 `pushed_at`(最近一次 WMS 推送时间),
* 没有任何「回传平台店铺」的状态列可查(链路尚未实现),故先落字段与状态机基线,
* 实际回传(OMS → 平台)后续接入时直接读写这两列即可。
*
* 口径来源:app/lib/shopSyncStatus.js(枚举单一来源,前端/服务端共用)
* 范围:**只** order_deliveries —— 入库单(inbound_orders)的库存由 OMS 侧自行管理、
* 出库单(outbound_orders)也不涉及平台店铺回传,均不加这两个字段。
*
* 幂等:迁移可重复执行(先 describeTable 判断列是否存在)。
*/
module.exports = {
async up(queryInterface, Sequelize) {
const columns = await queryInterface.describeTable('order_deliveries');
if (!columns.shop_sync_status) {
await queryInterface.addColumn('order_deliveries', 'shop_sync_status', {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '回传平台店铺状态:0未同步 1同步中 2同步成功 3同步失败',
after: 'stock_locked',
});
}
if (!columns.shop_sync_retry_count) {
await queryInterface.addColumn('order_deliveries', 'shop_sync_retry_count', {
type: Sequelize.INTEGER.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '回传平台店铺的重试次数(每次失败后 +1,重试成功不清零以便追溯)',
after: 'shop_sync_status',
});
}
},
async down(queryInterface) {
const columns = await queryInterface.describeTable('order_deliveries');
if (columns.shop_sync_retry_count) await queryInterface.removeColumn('order_deliveries', 'shop_sync_retry_count');
if (columns.shop_sync_status) await queryInterface.removeColumn('order_deliveries', 'shop_sync_status');
},
};

View File

@ -0,0 +1,70 @@
'use strict';
/**
* 出库单补齐 stockout.create 所需字段:快递公司(express_code / express_name)+ 收件人(receiver_* 13 列)
*
* 背景:比对 WMS `stockout.create` 的请求报文(D:/wms/methods/openapi.json#stockout.create)发现,
* OMS 出库单(outbound_orders)只有 `customer`(客户/收货方)一个笼统字段,缺:
* - deliveryOrder.logisticsCode → express_code / express_name
* - deliveryOrder.receiverInfo(13 个字段) → receiver_*
* 这导致 OMS 建单时无处录入、推送时报文也带不过去(WMS 侧会落到 wms_order_stockout 的
* receiver_* 列,"供转订单与确认回传使用")。
*
* 命名口径:**对齐 WMS 对应表 `wms_order_stockout`**(见 D:/wms/app/model/order_stockout.js):
* express_code 快递公司编码(推送为 deliveryOrder.logisticsCode,如 SF/STO)
* express_name 快递公司名称(OMS 侧按 express_companies 字典解析的快照)
* receiver_name / receiver_company / receiver_zip_code / receiver_tel / receiver_mobile /
* receiver_email / receiver_country_code / receiver_province / receiver_city / receiver_area /
* receiver_town / receiver_detail_address / receiver_id(收件人证件号,奇门字段名为 id)
* (发货单 order_deliveries 的收件人是"扁平无前缀"命名,那是为对齐 wms_order_delivery,两者各自对齐各自的表)
*
* 明细侧无缺失(orderLineNo/ownerCode/itemCode/itemId/itemName/planQty/inventoryType 均已具备)。
* 幂等:迁移可重复执行(先 describeTable 判断列是否存在)。
*/
module.exports = {
async up(queryInterface, Sequelize) {
const { STRING } = Sequelize;
const existing = await queryInterface.describeTable('outbound_orders');
// 收件人列(字段名 → [类型长度, 注释],顺序即建列顺序)
const columns = [
[ 'express_code', [ STRING(50), '快递公司编码(推送 deliveryOrder.logisticsCode,如 SF/STO)' ] ],
[ 'express_name', [ STRING(200), '快递公司名称(按 express_companies 字典解析的快照)' ] ],
[ 'receiver_name', [ STRING(50), '收件人姓名(receiverInfo.name)' ] ],
[ 'receiver_company', [ STRING(200), '收件人公司名称(receiverInfo.company)' ] ],
[ 'receiver_tel', [ STRING(50), '收件人固定电话(receiverInfo.tel)' ] ],
[ 'receiver_mobile', [ STRING(50), '收件人移动电话(receiverInfo.mobile)' ] ],
[ 'receiver_email', [ STRING(100), '收件人邮箱(receiverInfo.email;WMS 侧为 50,此处放宽)' ] ],
[ 'receiver_country_code', [ STRING(50), '收件人国家二字码(receiverInfo.countryCode)' ] ],
[ 'receiver_province', [ STRING(50), '收件人省份(receiverInfo.province)' ] ],
[ 'receiver_city', [ STRING(50), '收件人城市(receiverInfo.city)' ] ],
[ 'receiver_area', [ STRING(50), '收件人区县(receiverInfo.area)' ] ],
[ 'receiver_town', [ STRING(50), '收件人街道/镇(receiverInfo.town)' ] ],
[ 'receiver_detail_address', [ STRING(200), '收件人详细地址(receiverInfo.detailAddress)' ] ],
[ 'receiver_zip_code', [ STRING(50), '收件人邮编(receiverInfo.zipCode)' ] ],
[ 'receiver_id', [ STRING(50), '收件人证件号(receiverInfo.id)' ] ],
];
let after = 'remark';
for (const [ name, [ type, comment ] ] of columns) {
if (existing[name]) {
after = name;
continue;
}
await queryInterface.addColumn('outbound_orders', name, { type, allowNull: true, comment, after });
after = name;
}
},
async down(queryInterface) {
const existing = await queryInterface.describeTable('outbound_orders');
const names = [
'receiver_id', 'receiver_zip_code', 'receiver_detail_address', 'receiver_town', 'receiver_area',
'receiver_city', 'receiver_province', 'receiver_country_code', 'receiver_email', 'receiver_mobile',
'receiver_tel', 'receiver_company', 'receiver_name', 'express_name', 'express_code',
];
for (const name of names) {
if (existing[name]) await queryInterface.removeColumn('outbound_orders', name);
}
},
};

View File

@ -0,0 +1,66 @@
'use strict';
/**
* 出库单「运单号集合」列改名:outbound_orders.express_codes → waybill_codes(并回填存量)
*
* 背景(命名冲突,2026-09-14 核对 WMS 源码发现):
* WMS `wms_order_stockout` 的列口径是
* express_code / express_name → **快递公司**编码/名称(回传为 logisticsCode/logisticsName)
* waybill_code / waybill_codes → **运单号**(单个 / 列表,支持多包裹)
* express_codes → 已废弃(注释:@deprecated 运单号列表,请使用 waybill_codes)
* OMS 出库单此前把「运单号集合」放在 `express_codes`,与 WMS 现行命名正好撞车 ——
* 一旦同表再加上 `express_code`(快递公司编码,见 20260915001600 迁移),
* `express_code`(快递公司) 与 `express_codes`(运单号集合) 并存就是 WMS 自己已经废弃的那个坑,故改名对齐。
*
* 本迁移做三件事(幂等,可重复执行):
* ① outbound_orders.express_codes → waybill_codes(列重命名)
* ② 回填 outbound_orders.waybill_codes:历史单的列还是 NULL,但确认摘要 JSON 里已有运单号列表
* (兼容旧键 confirm.express_codes 与新键 confirm.waybill_codes)
* ③ 回填 order_deliveries.express_codes:发货单只有一个运单号列(express_code),
* 多值列为空时按单元素数组补齐,保证两列口径一致
*
* 注:`order_deliveries.express_codes` **不改名** —— 该表没有 WMS 对应列(wms_order_delivery 只有
* express_code=面单号),且本表内 express_code(运单号) / express_codes(运单号集合) 是自洽的单值/多值对。
*/
module.exports = {
async up(queryInterface) {
const outbound = await queryInterface.describeTable('outbound_orders');
// ① 列重命名
if (outbound.express_codes && !outbound.waybill_codes) {
await queryInterface.renameColumn('outbound_orders', 'express_codes', 'waybill_codes');
}
// ② 出库单回填:从确认摘要 JSON 取(先新键后旧键)
await queryInterface.sequelize.query(`
UPDATE outbound_orders
SET waybill_codes = COALESCE(
JSON_EXTRACT(wms_push_result, '$.confirm.waybill_codes'),
JSON_EXTRACT(wms_push_result, '$.confirm.express_codes')
)
WHERE waybill_codes IS NULL
AND wms_push_result IS NOT NULL
AND COALESCE(
JSON_EXTRACT(wms_push_result, '$.confirm.waybill_codes'),
JSON_EXTRACT(wms_push_result, '$.confirm.express_codes')
) IS NOT NULL
`);
// ③ 发货单回填:单值 express_code → [express_code]
await queryInterface.sequelize.query(`
UPDATE order_deliveries
SET express_codes = JSON_ARRAY(express_code)
WHERE express_codes IS NULL
AND express_code IS NOT NULL
AND express_code <> ''
`);
},
async down(queryInterface) {
const outbound = await queryInterface.describeTable('outbound_orders');
if (outbound.waybill_codes && !outbound.express_codes) {
await queryInterface.renameColumn('outbound_orders', 'waybill_codes', 'express_codes');
}
// 回填属数据修正,不反向撤销(撤销只会丢掉运单号,无业务意义)
},
};

View File

@ -0,0 +1,33 @@
'use strict';
/**
* 出库单运单号补充回填:从确认摘要的「单值运单号」补齐 waybill_codes
*
* 背景:`20260915001700` 的回填只认摘要 JSON 里的运单号**列表**(confirm.waybill_codes /
* confirm.express_codes 两个键),但 20260915001400~01700 之间写的早期摘要里只有根节点
* **单值** `confirm.express_code`(当时还没有列表键),这些单的 `waybill_codes` 仍未回填。
*
* 回填规则(只在能确认「运单号集合完整」时才写,避免以偏概全):
* 摘要 `confirm.packages` 数组**恰好 1 个包裹**,且根节点 `confirm.express_code` 非空
* → waybill_codes = [ 该单值运单号 ](唯一包裹即全部运单号)
* 多包裹的历史摘要若缺列表键则不动(信息不全,宁可留空等 WMS 重推时由回调补写)。
*
* 幂等:只更新 waybill_codes IS NULL 的行;可重复执行。
*/
module.exports = {
async up(queryInterface) {
await queryInterface.sequelize.query(`
UPDATE outbound_orders
SET waybill_codes = JSON_ARRAY(JSON_UNQUOTE(JSON_EXTRACT(wms_push_result, '$.confirm.express_code')))
WHERE waybill_codes IS NULL
AND wms_push_result IS NOT NULL
AND JSON_LENGTH(JSON_EXTRACT(wms_push_result, '$.confirm.packages')) = 1
AND JSON_EXTRACT(wms_push_result, '$.confirm.express_code') IS NOT NULL
AND JSON_UNQUOTE(JSON_EXTRACT(wms_push_result, '$.confirm.express_code')) <> ''
`);
},
async down() {
// 回填属数据修正,不反向撤销(撤销只会丢掉运单号,无业务意义)
},
};

View File

@ -0,0 +1,58 @@
'use strict';
/**
* 补齐 WMS 侧存在、OMS 字典缺失的快递公司编码(对齐 `wms_express`)
*
* 背景:2026-09-14 加「回传快递编码必须在字典里」的校验后,若字典缺编码会导致
* WMS 正常回传的确认回调被拒绝。实测 WMS 库 `wms_express` 有 21 条,OMS `express_companies`
* 只有 12 条且与之不一致(例如 WMS 回传过的 `ZT` 自提 / `OTHER` 其他 在 OMS 里都没有),
* 故先把 WMS 有而 OMS 没有的编码补进来(名称取 WMS 的 `wms_express.name`)。
*
* 口径:
* - 只 **新增**(INSERT IGNORE,依赖唯一索引 uk_express_companies_code),**不改动**已有行:
* 已在 OMS 的编码(含 `HTKY`=百世快递、`YD`=韵达速递 等与 WMS 语义不符的)留待人工决定是否改名/停用
* - 幂等:已存在的编码不会被覆盖,可重复执行
* - 补的是 WMS 现行 21 条里 OMS 缺失的 14 条;如后续 WMS 字典新增,需同步维护
* (长期方案是加开放接口 + 定时同步,见会话记录)
*/
const MISSING_FROM_WMS = [
{ code: 'ANKY', name: '安能', sort: 130 },
{ code: 'DBWL', name: '德邦物流', sort: 140 },
{ code: 'FENGWANG', name: '丰网速运', sort: 150 },
{ code: 'HTKD', name: '百世极兔', sort: 160 },
{ code: 'KYE', name: '跨越物流', sort: 170 },
{ code: 'SFKY', name: '顺丰快运', sort: 180 },
{ code: 'SZKKE', name: '京广快运', sort: 190 },
{ code: 'TTKDEX', name: '天天快递', sort: 200 },
{ code: 'YUNDA', name: '韵达快递', sort: 210 },
{ code: 'ZTKY', name: '中通快运', sort: 220 },
{ code: 'POSTB', name: '邮政小包', sort: 230 },
{ code: 'POST_DSBK', name: '邮政电商标快', sort: 240 },
{ code: 'ZT', name: '自提', sort: 250 },
{ code: 'OTHER', name: '其他', sort: 260 },
];
module.exports = {
async up(queryInterface) {
const now = new Date();
await queryInterface.bulkInsert(
'express_companies',
MISSING_FROM_WMS.map(c => ({
code: c.code,
name: c.name,
sort: c.sort,
status: 1,
remark: '对齐 WMS wms_express 快递字典(2026-09-14)',
created_at: now,
updated_at: now,
})),
{ ignoreDuplicates: true }
);
},
async down(queryInterface, Sequelize) {
await queryInterface.bulkDelete('express_companies', {
code: { [Sequelize.Op.in]: MISSING_FROM_WMS.map(c => c.code) },
});
},
};

View File

@ -0,0 +1,45 @@
'use strict';
/**
* 出库单快递公司列注释同步:express_code / express_name
*
* 背景:WMS 可能「转快递」处理(推送 ZT 自提、实际发 YTO 圆通),`stockout.confirm` 回传的
* `packages[].logisticsCode/logisticsName` 才是实际承运;OMS 现按回传值**覆盖**这两列
* (见 app/lib/orderCallback.js#buildExpressOverride),故列语义由「推送值」变为「以回传为准」。
*
* 幂等:仅当现有注释与目标评论不同时才 MODIFY(可重复执行)。
*/
const TARGET = {
express_code: '快递公司编码:推送为 deliveryOrder.logisticsCode,出库确认回传后按 WMS 实际承运覆盖(可能转快递)',
express_name: '快递公司名称:推送时按字典解析,出库确认回传后按 WMS 实际承运覆盖',
};
module.exports = {
async up(queryInterface, Sequelize) {
const columns = await queryInterface.describeTable('outbound_orders');
for (const [ name, comment ] of Object.entries(TARGET)) {
const col = columns[name];
if (!col || col.comment === comment) continue;
await queryInterface.changeColumn('outbound_orders', name, {
type: name === 'express_code' ? Sequelize.STRING(50) : Sequelize.STRING(200),
allowNull: true,
comment,
});
}
},
async down(queryInterface, Sequelize) {
// 注释回滚到改动前的文本(列本身不新增/不删除)
const previous = {
express_code: '快递公司编码(推送 deliveryOrder.logisticsCode,如 SF/STO)',
express_name: '快递公司名称(按 express_companies 字典解析的快照)',
};
for (const [ name, comment ] of Object.entries(previous)) {
await queryInterface.changeColumn('outbound_orders', name, {
type: name === 'express_code' ? Sequelize.STRING(50) : Sequelize.STRING(200),
allowNull: true,
comment,
});
}
},
};

View File

@ -0,0 +1,50 @@
'use strict';
/**
* 仓库快递映射表 warehouse_express_mappings
*
* 背景:外部(WMS 等)回传的快递编码不一定是 OMS/标准编码,可能是仓库维度的「自定义编码」
* (对齐 WMS `wms_express_setting`:`code`=业务自定义编码如 SF.KY/KYSF,`express_code`=系统标准编码)。
* 出库确认(stockout.confirm)/ 发货确认(deliveryorder.confirm)回传时按以下顺序解析:
* ① 命中本表映射(warehouse_id + custom_code)→ 用映射到的「默认快递编码」;
* ② 未命中映射 → 外部编码若本身就在快递公司字典(express_companies)里,直接兜底使用;
* ③ 两者都没有 → 报错「外部传入的快递编码(xxx)没有关联映射,请到 OMS 外部仓库完成映射配置」。
*
* 幂等:showTable 判断表是否存在。
*/
module.exports = {
async up(queryInterface, Sequelize) {
const tables = await queryInterface.showAllTables();
const exists = tables
.map(t => (typeof t === 'string' ? t : (t.tableName || t.TABLE_NAME)))
.includes('warehouse_express_mappings');
if (exists) return;
const { BIGINT, STRING, TINYINT, DATE } = Sequelize;
await queryInterface.createTable('warehouse_express_mappings', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID(冗余仓库主体,便于隔离)' },
warehouse_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '仓库ID(关联 warehouses,映射按仓库维度)' },
express_code: { type: STRING(50), allowNull: false, comment: '默认快递编码(OMS/标准编码,关联 express_companies.code,如 SF/ZT)' },
custom_code: { type: STRING(50), allowNull: false, comment: '自定义编码(外部传入的快递编码,如 SF.KY/KYSF)' },
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用(仅启用参与回传解析)' },
remark: { type: STRING(255), allowNull: true, comment: '备注' },
created_at: { type: DATE, allowNull: true, comment: '创建时间' },
updated_at: { type: DATE, allowNull: true, comment: '更新时间' },
}, {
comment: '仓库快递映射表(外部快递编码 → OMS 默认快递编码)',
indexes: [
{ name: 'uk_wem_warehouse_custom', unique: true, fields: [ 'warehouse_id', 'custom_code' ] },
{ name: 'idx_wem_principal_warehouse', fields: [ 'principal_id', 'warehouse_id' ] },
],
});
},
async down(queryInterface) {
const tables = await queryInterface.showAllTables();
const exists = tables
.map(t => (typeof t === 'string' ? t : (t.tableName || t.TABLE_NAME)))
.includes('warehouse_express_mappings');
if (exists) await queryInterface.dropTable('warehouse_express_mappings');
},
};

View File

@ -0,0 +1,80 @@
'use strict';
/**
* 新增「创建出库单」「创建入库单」菜单:挂在「库存管理」目录下,各指向独立创建页
* views/OutboundOrder/Create.vue(path /outbound-order-create)
* views/InboundOrder/Create.vue(path /inbound-order-create)
*
* 背景:创建出入库单改为独立整页(单据信息 + 商品明细内联,不再用弹窗),
* 并按「创建发货单」的紧凑排版提高信息密度(原弹窗为 880px 宽、字段两列、密度偏低)。
* 菜单按 name + parent_id 判重,可重复执行。
*/
const PARENT_NAME = '库存管理';
const MENUS = [
{
name: '创建出库单',
type: 2,
path: '/outbound-order-create',
icon: 'Plus',
permission: 'outboundOrder:create',
component: 'views/OutboundOrder/Create.vue',
sort: 71,
},
{
name: '创建入库单',
type: 2,
path: '/inbound-order-create',
icon: 'Plus',
permission: 'inboundOrder:create',
component: 'views/InboundOrder/Create.vue',
sort: 76,
},
];
module.exports = {
async up(queryInterface) {
const sequelize = queryInterface.sequelize;
const [ parent ] = await sequelize.query(
'SELECT id FROM menus WHERE name = ? AND parent_id = 0 LIMIT 1',
{ replacements: [ PARENT_NAME ], type: sequelize.QueryTypes.SELECT }
);
if (!parent) return; // 父菜单缺失(异常数据)时跳过,避免挂错层级
const parentId = Number(parent.id);
for (const menu of MENUS) {
const [ exist ] = await sequelize.query(
'SELECT id FROM menus WHERE name = ? AND parent_id = ? LIMIT 1',
{ replacements: [ menu.name, parentId ], type: sequelize.QueryTypes.SELECT }
);
if (exist) continue;
await sequelize.query(
`INSERT INTO menus
(parent_id, name, type, path, icon, permission, component, sort, status, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, NOW(), NOW())`,
{
replacements: [
parentId,
menu.name,
menu.type,
menu.path,
menu.icon,
menu.permission,
menu.component,
menu.sort,
],
}
);
}
},
async down(queryInterface) {
const sequelize = queryInterface.sequelize;
for (const menu of MENUS) {
await sequelize.query('DELETE FROM menus WHERE name = ? AND path = ?', {
replacements: [ menu.name, menu.path ],
});
}
},
};

View File

@ -0,0 +1,37 @@
'use strict';
/**
* 出库单库存锁定标记:outbound_orders.stock_locked
*
* 背景:出库单改为「审核(1→2) 入队 → 定时任务自动推送(2→3)」后,推送可能失败并退回「待出库(1)」,
* 而库存锁定发生在推送过程中(占用可用,防超卖)。为了让「锁了就必须有人释放」可判定,这里补一个标记列
* (与 order_deliveries.stock_locked 同口径):
* - 1 = 该单当前占用着推送时锁定的库存(推送成功后保持,出库确认扣减时清零;推送失败退回/取消/作废/驳回时释放并清零)
* - 0 = 未锁定 / 已释放 / 已扣减
*
* 之所以需要它:推送无响应(超时)时单据保留在「已审核(2)」等待重试,此时库存是已锁定状态,
* 若重试时再次锁定会重复占用;若用户此时取消/作废,也需要按标记释放库存。
* 历史单据(本迁移之前)落 0:其状态为 3 时的取消/驳回路径仍按原有「已推送即已锁定」口径处理。
*
* 幂等:可重复执行(先 describeTable 判断列是否存在)。
*/
module.exports = {
async up(queryInterface, Sequelize) {
const columns = await queryInterface.describeTable('outbound_orders');
if (columns.stock_locked) return;
await queryInterface.addColumn('outbound_orders', 'stock_locked', {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '推送锁定库存标记:1=已锁定(重试不重复锁定,确认扣减/释放后置 0),0=未锁定',
after: 'stock_deducted',
});
},
async down(queryInterface) {
const columns = await queryInterface.describeTable('outbound_orders');
if (!columns.stock_locked) return;
await queryInterface.removeColumn('outbound_orders', 'stock_locked');
},
};