refactor(backend): 出库单推送逻辑下沉到 outboundOrderPush 服务

- 控制器 push() 收敛为薄封装,改调 ctx.service.outboundOrderPush.pushOne / unlockStock
- 推送重试、库存锁定与释放统一由 app/service/outboundOrderPush.js 实现(与发货单推送服务同结构)
This commit is contained in:
liufumingren 2026-09-14 01:00:01 +08:00
parent 23d372aa52
commit 92be712dbc

View File

@ -354,199 +354,8 @@ class OutboundOrderController extends Controller {
};
}
/**
* 推送:已审核(2) -> 已推送(3),锁定库存(占用可用,防超卖)并递交 WMS(stockout.create)
* 失败时不流转状态,直接返回 WMS 错误信息;推送失败会释放已锁定库存,可重试
* 完成出库:已推送(3) -> 完成(4),需有明细(已推送单必然有,此处兜底)
*/
async push() {
const { ctx } = this;
const orderId = Number(ctx.params.id);
const principalId = ctx.state.principalId;
const order = await ctx.model.OutboundOrder.findByPk(orderId, {
include: [
{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] },
{ model: ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] },
],
});
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 api = await ctx.model.WarehouseApi.findOne({
where: { warehouse_id: order.warehouse_id, principal_id: principalId, type: API_TYPE_QIMEN, status: 1 },
order: [[ 'id', 'ASC' ]],
});
if (!api) {
ctx.status = 400;
ctx.body = { code: 400, message: '该仓库未配置启用的类奇门接口(缺少 app_key / app_secret / base_url)' };
return;
}
const items = await ctx.model.StockItem.findAll({
where: { bill_type: 2, bill_id: order.id, product_id: { [ctx.app.Sequelize.Op.ne]: null } },
include: [ { model: ctx.model.Product, as: 'product', attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'retail_price' ] } ],
order: [[ 'id', 'ASC' ]],
});
// 无明细不允许推送(否则既不会锁定库存,也不会向 WMS 发出有效出库单)
if (!items.length) {
ctx.status = 400;
ctx.body = { code: 400, message: '单据无明细,无法推送' };
return;
}
const productIds = items.map(i => Number(i.product_id));
const productMap = productIds.length
? await ctx.model.Product.findAll({ where: { id: { [ctx.app.Sequelize.Op.in]: productIds } }, attributes: [ 'id', 'item_code', 'item_name' ] })
: [];
const pmap = new Map(productMap.map(p => [ Number(p.id), p ]));
// stockout.create 的明细行 itemId 为必填:取该仓库已推送商品的 WMS 商品ID
const links = productIds.length
? await ctx.model.WarehouseProduct.findAll({
where: { principal_id: principalId, warehouse_id: order.warehouse_id, product_id: { [ctx.app.Sequelize.Op.in]: productIds } },
attributes: [ 'product_id', 'wms_item_id' ],
})
: [];
const wmsItemIdByProduct = {};
for (const l of links) {
if (l.wms_item_id != null) wmsItemIdByProduct[Number(l.product_id)] = Number(l.wms_item_id);
}
// 先锁定库存(占用可用,防止超卖);WMS 推送失败则回滚释放
const reserveTx = await ctx.model.transaction();
try {
for (const it of items) {
const pid = Number(it.product_id);
const qty = Number(it.quantity) || 0;
try {
// 行级库存类型:CC=残次 -> 锁定残次库存,其余(ZP等)归为正品 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);
err.message = `库存不足:${p ? `${p.item_name}(${p.item_code})` : '商品#' + pid},可用 ${err.available},需 ${err.require}`;
}
throw err;
}
}
await reserveTx.commit();
} catch (err) {
await reserveTx.rollback();
if (err.code === 'INSUFFICIENT_STOCK') {
ctx.status = 400;
ctx.body = { code: 400, message: err.message };
return;
}
ctx.status = 500;
ctx.body = { code: 500, message: '库存锁定失败,请稍后重试' };
return;
}
// 递交外部 WMS(stockout.create)
const client = new QimenWmsClient(api, this.app);
const externalOrderCode = order.bill_no;
try {
const resp = await client.createStockout(order, items, { warehouse: order.warehouse, wmsItemIdByProduct });
const success = client.isSuccess(resp);
const pushResult = {
success,
code: resp && resp.code,
message: resp && resp.message,
flag: resp && resp.flag,
deliveryOrderCode: externalOrderCode,
warehouseApiId: api.id,
apiType: api.type,
response: resp,
pushedAt: new Date().toISOString(),
};
if (!success) {
// 推送失败:释放锁定库存,并调 order.cancel 冲正(外部可能已建单)
await this._releaseStock(order, items).catch(() => {});
pushResult.cancelResult = await client.cancelOrder(order)
.catch(err => ({ code: 'EXCEPTION', message: err.message }));
await order.update({ wms_push_result: pushResult, pushed_at: new Date() });
ctx.status = 502;
ctx.body = { code: 502, message: `WMS 返回失败: ${resp && (resp.message || resp.code)}` };
return;
}
await order.update({
status: 3,
operate_time: new Date(),
pushed_at: new Date(),
wms_push_result: pushResult,
});
ctx.body = { code: 0, message: 'success', data: { id: order.id, wms_response: resp } };
} catch (err) {
// 请求异常:释放锁定库存,同样调 order.cancel 冲正,状态保持「已审核」可重试
await this._releaseStock(order, items).catch(() => {});
const cancelResult = await client.cancelOrder(order)
.catch(e => ({ code: 'EXCEPTION', message: e.message }));
const failResult = {
success: false,
deliveryOrderCode: externalOrderCode,
warehouseApiId: api.id,
apiType: api.type,
error: err.message,
cancelResult,
pushedAt: new Date().toISOString(),
};
await order.update({ wms_push_result: failResult, pushed_at: new Date() }).catch(() => {});
ctx.status = 502;
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 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) {
await transaction.rollback();
throw err;
}
}
/** 完成出库:已推送(3) -> 完成(4),需有明细(已推送单必然有,此处兜底) */
async complete() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
@ -583,37 +392,14 @@ class OutboundOrderController extends Controller {
ctx.body = { code: 400, message: '已完成单据不能取消' };
return;
}
// 已推送(3)的单据取消时释放已锁定库存
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', 'code', 'name', 'quantity', 'inventory_type' ],
order: [[ 'product_id', 'ASC' ]],
});
const transaction = await ctx.model.transaction();
// 已推送(3)、或推送未成功但已锁定库存(stock_locked=1,如推送超时待重试)的单据:取消时释放锁定库存
if (order.status === 3 || Number(order.stock_locked) === 1) {
try {
for (const it of items) {
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();
await ctx.service.outboundOrderPush.unlockStock(order, null, '出库单取消释放锁定库存');
await order.update({ status: 9 });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
} catch (err) {
await transaction.rollback();
ctx.logger.error(`[outbound] 取消释放锁定库存失败 id=${order.id}`, err);
ctx.status = 500;
ctx.body = { code: 500, message: '取消失败,请稍后重试' };
}
@ -641,7 +427,8 @@ class OutboundOrderController extends Controller {
}
/**
* @summary 作废出库单
* @description 仅「已审核(2)」状态可作废;状态置为已作废(5),记录作废人/时间/原因,不可恢复也禁止删除
* @description 仅「已审核(2)」状态可作废;状态置为已作废(5),记录作废人/时间/原因,不可恢复也禁止删除。
* 若该单已锁定库存(推送未成功但库存已占用,如推送超时待重试),作废时一并释放;释放失败则不流转状态
* @router post /api/outbound-orders/{id}/void
* @apikey
* @request path integer *id 出库单主键ID
@ -661,6 +448,17 @@ class OutboundOrderController extends Controller {
ctx.body = { code: 400, message: '只有「已审核」状态的单据可以作废' };
return;
}
// 推送未成功但已锁定库存(如超时待重试):作废前释放,避免锁定无人释放
if (Number(order.stock_locked) === 1) {
try {
await ctx.service.outboundOrderPush.unlockStock(order, null, '出库单作废释放锁定库存');
} catch (err) {
ctx.logger.error(`[outbound] 作废释放锁定库存失败 id=${order.id}`, err);
ctx.status = 500;
ctx.body = { code: 500, message: '作废失败,请稍后重试' };
return;
}
}
const body = ctx.request.body || {};
const reason = body.void_reason ? String(body.void_reason).trim() : '';
await order.update({
@ -702,10 +500,21 @@ class OutboundOrderController extends Controller {
ctx.body = { code: 400, message: '只有「已审核」「已推送」状态的单据可以驳回' };
return;
}
// 仅「已审核」:直接回退,未锁定库存
// 仅「已审核」:直接回退(推送未成功但已锁定库存的先释放)
if (order.status !== 3) {
if (Number(order.stock_locked) === 1) {
try {
await ctx.service.outboundOrderPush.unlockStock(order, null, '出库单驳回释放锁定库存');
} catch (err) {
ctx.logger.error(`[outbound] 驳回释放锁定库存失败 id=${order.id}`, err);
ctx.status = 500;
ctx.body = { code: 500, message: '驳回失败,请稍后重试' };
return;
}
}
const newBillNo = nextRejectedBillNo(order.bill_no, order.id, OUTBOUND_BILL_PREFIX);
await order.update({ status: 1, bill_no: newBillNo });
// 清空推送痕迹(重新审核后重试计数从 0 开始)
await order.update({ status: 1, bill_no: newBillNo, pushed_at: null, wms_push_result: null });
ctx.body = { code: 0, message: 'success', data: { id: order.id, bill_no: order.bill_no } };
return;
}
@ -787,6 +596,7 @@ class OutboundOrderController extends Controller {
status: 1,
bill_no: newBillNo,
stock_deducted: 0,
stock_locked: 0,
pushed_at: null,
wms_push_result: null,
}, { transaction });