oms/backend/app/controller/outboundOrder.js
liufumingren ec81f8b3cd feat(backend): 入库单/出库单全流程与 WMS 对接
- 入库单、出库单控制器与模型(状态流转、审核、驳回换号、作废、删除约束)
- 明细共用 stock_items:应/已数量、行级库存类型 ZP/CC、明细锁定
- lib/wms:单据类型常量(orderTypes)、奇门/openapi 客户端(qimenClient)、签名(sign)
- 库存联动:utils/stock.js、utils/completeInbound.js(入库完成加库存,幂等)
- 驳回换号:utils/rejectBillNo.js;旧 orders 模块同步调整
- 相关迁移:入库单 WMS 字段/审核/推送结果、明细计划与实际数量、单据类型落 WMS 编码、出库库存扣减标记等
2026-09-13 02:23:44 +08:00

680 lines
27 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { Controller } = require('egg');
const recalcStock = require('../utils/recalcStock');
const stock = require('../utils/stock');
const nextRejectedBillNo = require('../utils/rejectBillNo');
const { parsePagination, buildPageResult } = require('../lib/pagination');
const QimenWmsClient = require('../lib/wms/qimenClient');
const { DEFAULT_OUTBOUND_ORDER_TYPE, OUTBOUND_ORDER_TYPE_LIST, normalizeOutboundOrderType } = require('../lib/wms/orderTypes');
/** 仓库接口类型:当前系统仅对接类奇门JSON接口 */
const API_TYPE_QIMEN = 'qimen';
/** 出库单单号前缀,未提供单据号时由系统按 {前缀}_{自增id} 自动生成(如 CK_123) */
const OUTBOUND_BILL_PREFIX = 'CK';
/**
* 单号与状态/生命周期字段由系统与业务事务(创建 / 审核 / 推送 / 完成 / 驳回 / 作废 / 取消 / 库存回调)推动,
* 禁止通过新增、更新等通用接口直接写入,避免破坏单据对外标识(WMS deliveryOrderCode=bill_no)或绕过状态机。
*/
const MANAGED_FIELDS = [
'bill_no', 'status', 'pushed_at', 'wms_push_result',
'void_at', 'void_by', 'void_reason', 'stock_deducted', 'item_total', 'item_kind',
];
/**
* @controller OutboundOrderController 出库单管理
* 单据头 outbound_orders;明细由 stock_items(bill_type=2)承载,随单据在同一事务内创建
*/
class OutboundOrderController extends Controller {
/**
* @summary 出库单列表
* @router get /api/outbound-orders
* @apikey
* @request query integer page 页码,默认 1
* @request query integer pageSize 每页条数,默认 20
* @request query string bill_no 出库单号,支持模糊匹配
* @request query integer status 状态:1待出库 2已出库 3已取消
* @request query string outbound_type 出库类型(WMS 编码):PTCK 普通出库单 / DBCK 调拨出库 / B2BCK B2B出库 / QTCK 其他出库 / CGTH 采购退货出库单
* @request query integer shop_id 店铺/仓库ID
* @response 200 outboundOrderListResponse success
*/
async index() {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
const { bill_no: billNo, status, outbound_type: outboundType, shop_id: shopId } = ctx.query;
const principalId = ctx.state.principalId;
const where = { principal_id: principalId };
if (billNo) where.bill_no = { [Op.like]: `%${billNo}%` };
if (status !== undefined && status !== '') where.status = Number(status);
if (outboundType !== undefined && outboundType !== '') where.outbound_type = String(outboundType).trim().toUpperCase();
if (shopId) where.shop_id = Number(shopId);
const { count, rows } = await ctx.model.OutboundOrder.findAndCountAll({
where,
offset,
limit,
order: [[ 'id', 'DESC' ]],
include: [
{ model: ctx.model.Shop, as: 'shop', attributes: [ 'id', 'name' ] },
{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] },
{ model: ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] },
],
});
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
}
/**
* @summary 出库单详情
* @router get /api/outbound-orders/{id}
* @apikey
* @request path integer *id 出库单主键ID
* @response 200 baseResponse success
*/
async show() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id, {
include: [
{ model: ctx.model.Shop, as: 'shop', attributes: [ 'id', 'name', 'platform' ] },
{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] },
{ model: ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] },
{ model: ctx.model.User, as: 'voider', attributes: [ 'id', 'nickname', 'username' ] },
],
});
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
const items = await ctx.model.StockItem.findAll({
where: { bill_type: 2, bill_id: order.id },
include: [
{ model: ctx.model.Product, as: 'product', attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ] },
{ model: ctx.model.ComboProduct, as: 'comboProduct', attributes: [ 'id', 'code', 'name' ] },
],
});
const data = order.toJSON();
data.items = items;
ctx.body = { code: 0, message: 'success', data };
}
/**
* @summary 新增出库单
* @description 单号由系统按 CK_{自增id} 自动生成(不接受传入);可同时传入 items(stock_items, bill_type=2)一次性写入明细
* @router post /api/outbound-orders
* @apikey
* @request body createOutboundOrderRequest *body
* @response 200 baseResponse success
*/
async create() {
const { ctx } = this;
const { items, warehouse_id: warehouseId } = ctx.request.body;
const principalId = ctx.state.principalId;
if (!warehouseId) {
ctx.status = 400;
ctx.body = { code: 400, message: 'warehouse_id(仓库)为必填项' };
return;
}
const payload = { ...ctx.request.body };
delete payload.items;
// 单号(bill_no)在 MANAGED_FIELDS 内被剥离:一律由系统生成,不接受前端传入
for (const f of MANAGED_FIELDS) delete payload[f];
// 出库单类型:直接落库 WMS 编码(CK 组),非法值拒绝;不传时默认 PTCK(普通出库单)
const outboundType = normalizeOutboundOrderType(payload.outbound_type);
if (payload.outbound_type != null && String(payload.outbound_type).trim() !== '' && !outboundType) {
ctx.status = 400;
ctx.body = { code: 400, message: `outbound_type(出库类型)不合法,支持:${OUTBOUND_ORDER_TYPE_LIST.join(' / ')}` };
return;
}
payload.outbound_type = outboundType || DEFAULT_OUTBOUND_ORDER_TYPE;
// 校验明细关联商品均存在且已启用
const productIds = (items || []).map((i) => i.product_id).filter(Boolean);
if (productIds.length) {
const validProducts = await ctx.model.Product.findAll({
where: { id: productIds, status: 1 },
attributes: [ 'id' ],
});
const validIds = new Set(validProducts.map((p) => p.id));
if (productIds.some((id) => !validIds.has(id))) {
ctx.status = 400;
ctx.body = { code: 400, message: '明细关联的商品不存在或已禁用,无法创建单据' };
return;
}
}
const transaction = await ctx.model.transaction();
try {
const totalAmount = Number(payload.total_amount) || 0;
// 先用临时单号落库以取得自增 id,随后更新为 CK_{id}
const order = await ctx.model.OutboundOrder.create({
status: 1,
...payload,
bill_no: `CK_TMP_${Date.now()}_${Math.floor(Math.random() * 100000)}`,
principal_id: principalId,
warehouse_id: warehouseId,
created_by: ctx.userId,
total_amount: totalAmount,
}, { transaction });
if (Array.isArray(items) && items.length) {
await ctx.model.StockItem.bulkCreate(items.map(item => ({
principal_id: principalId,
bill_type: 2,
bill_id: order.id,
shop_id: item.shop_id || order.shop_id || null,
product_id: item.product_id || null,
combo_product_id: item.combo_product_id || null,
shop_product_id: item.shop_product_id || null,
name: item.name || null,
code: item.code || null,
inventory_type: item.inventory_type === 'CC' ? 'CC' : 'ZP',
spec: item.spec || null,
unit: item.unit || null,
quantity: item.quantity || 0,
plan_out_qty: item.quantity || 0,
price: item.price == null ? null : item.price,
total_amount: Number((Number(item.quantity || 0) * Number(item.price || 0)).toFixed(2)),
remark: item.remark || null,
})), { transaction });
}
// 系统生成单据号:CK_{自增id}
await order.update({ bill_no: `${OUTBOUND_BILL_PREFIX}_${order.id}` }, { transaction });
await transaction.commit();
await recalcStock(ctx, 2, order.id);
ctx.body = { code: 0, message: 'success', data: { id: order.id, bill_no: order.bill_no } };
} catch (err) {
await transaction.rollback();
ctx.status = 500;
ctx.body = { code: 500, message: '新增出库单失败,请稍后重试' };
}
}
/**
* @summary 更新出库单
* @description 仅「待出库(1)」可编辑;只更新单据头字段(不含明细与单号/状态等系统托管字段)
* @router put /api/outbound-orders/{id}
* @apikey
* @request path integer *id 出库单主键ID
* @request body updateOutboundOrderRequest *body
* @response 200 baseResponse success
*/
async update() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
// 仅「待出库」可编辑:与明细锁定规则一致,已审核及之后禁止改动(可先驳回再修改)
if (order.status !== 1) {
ctx.status = 400;
ctx.body = { code: 400, message: '仅「待出库」状态的单据可以编辑,如需修改请先驳回' };
return;
}
delete ctx.request.body.principal_id;
delete ctx.request.body.created_by;
for (const f of MANAGED_FIELDS) delete ctx.request.body[f];
// 出库单类型:同样存储 WMS 编码(CK 组),非法值拒绝(影响后续推送与取消的口径一致)
if (ctx.request.body.outbound_type != null && String(ctx.request.body.outbound_type).trim() !== '') {
const outboundType = normalizeOutboundOrderType(ctx.request.body.outbound_type);
if (!outboundType) {
ctx.status = 400;
ctx.body = { code: 400, message: `outbound_type(出库类型)不合法,支持:${OUTBOUND_ORDER_TYPE_LIST.join(' / ')}` };
return;
}
ctx.request.body.outbound_type = outboundType;
} else {
delete ctx.request.body.outbound_type;
}
await order.update(ctx.request.body);
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/**
* @summary 删除出库单
* @description 物理删除单据,并级联删除其明细(stock_items, bill_type=2)。仅「待出库(1)」「已取消(9)」可删除;
* 已审核(2) 及之后的单据禁止删除,请使用作废接口
* @router delete /api/outbound-orders/{id}
* @apikey
* @request path integer *id 出库单主键ID
* @response 200 baseResponse success
*/
async destroy() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
if (order.status !== 1 && order.status !== 9) {
ctx.status = 400;
ctx.body = { code: 400, message: '已审核及之后的单据禁止删除,请使用「作废」' };
return;
}
const transaction = await ctx.model.transaction();
try {
await ctx.model.StockItem.destroy({ where: { bill_type: 2, bill_id: order.id }, transaction });
await order.destroy({ transaction });
await transaction.commit();
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
} catch (err) {
await transaction.rollback();
ctx.status = 500;
ctx.body = { code: 500, message: '删除失败,请稍后重试' };
}
}
/** 审核:已创建(1) -> 已审核(2),需先录入明细 */
async audit() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
if (order.status !== 1) {
ctx.status = 400;
ctx.body = { code: 400, message: '只有「已创建」状态的单据可以审核' };
return;
}
const itemCount = await ctx.model.StockItem.count({ where: { bill_type: 2, bill_id: order.id } });
if (!itemCount) {
ctx.status = 400;
ctx.body = { code: 400, message: '单据无明细,无法审核' };
return;
}
await order.update({ status: 2 });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/**
* 推送:已审核(2) -> 已推送(3),锁定库存(占用可用,防超卖)并递交 WMS(stockout.create)
* 失败时不流转状态,直接返回 WMS 错误信息;推送失败会释放已锁定库存,可重试
*/
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
await stock.lock(ctx, order.principal_id, pid, qty, reserveTx, it.inventory_type === 'CC' ? 'CC' : 'ZC');
} 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 stock.unlock(ctx, order.principal_id, Number(it.product_id), Number(it.quantity) || 0, transaction, it.inventory_type === 'CC' ? 'CC' : 'ZC');
}
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);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
if (order.status !== 3) {
ctx.status = 400;
ctx.body = { code: 400, message: '只有「已推送」状态的单据可以完成出库' };
return;
}
const itemCount = await ctx.model.StockItem.count({ where: { bill_type: 2, bill_id: order.id } });
if (!itemCount) {
ctx.status = 400;
ctx.body = { code: 400, message: '单据无明细,无法完成出库' };
return;
}
await order.update({ status: 4 });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/** 取消:任意非完成态 -> 已取消(9) */
async cancel() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
if (order.status === 4) {
ctx.status = 400;
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', '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 order.update({ status: 9 }, { transaction });
await transaction.commit();
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
} catch (err) {
await transaction.rollback();
ctx.status = 500;
ctx.body = { code: 500, message: '取消失败,请稍后重试' };
}
return;
}
await order.update({ status: 9 });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/** 恢复:已取消(9) -> 已创建(1) */
async restore() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
if (order.status !== 9) {
ctx.status = 400;
ctx.body = { code: 400, message: '只有「已取消」的单据可以恢复' };
return;
}
await order.update({ status: 1 });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/**
* @summary 作废出库单
* @description 仅「已审核(2)」状态可作废;状态置为已作废(5),记录作废人/时间/原因,不可恢复也禁止删除
* @router post /api/outbound-orders/{id}/void
* @apikey
* @request path integer *id 出库单主键ID
* @request body voidOutboundOrderRequest *body
* @response 200 baseResponse success
*/
async voidOrder() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
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 body = ctx.request.body || {};
const reason = body.void_reason ? String(body.void_reason).trim() : '';
await order.update({
status: 5,
void_at: new Date(),
void_by: ctx.userId,
void_reason: reason || null,
});
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/**
* @summary 驳回出库单
* @description 审核的反向操作:已审核(2) / 已推送(3) 且未完成(4) 的单据可驳回,驳回后回到「待出库(1)」;
* 驳回会变更单号(在基础单号后追加/递增 `_N`,首次 `_1`、再次 `_2`);
* 已推送的会先调用 WMS order.cancel 取消外部出库单,再按是否已被发货通知扣减回滚库存
* @router post /api/outbound-orders/{id}/reject
* @apikey
* @request path integer *id 出库单主键ID
* @response 200 baseResponse success
*/
async reject() {
const { ctx } = this;
const principalId = ctx.state.principalId;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id, {
include: [{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] }],
});
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
if (order.status === 4) {
ctx.status = 400;
ctx.body = { code: 400, message: '已完成出库的单据不能驳回' };
return;
}
if (order.status !== 2 && order.status !== 3) {
ctx.status = 400;
ctx.body = { code: 400, message: '只有「已审核」「已推送」状态的单据可以驳回' };
return;
}
// 仅「已审核」:直接回退,未锁定库存
if (order.status !== 3) {
const newBillNo = nextRejectedBillNo(order.bill_no, order.id, OUTBOUND_BILL_PREFIX);
await order.update({ status: 1, bill_no: newBillNo });
ctx.body = { code: 0, message: 'success', data: { id: order.id, bill_no: order.bill_no } };
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 client = new QimenWmsClient(api, this.app);
let resp;
try {
resp = await client.cancelOrder(order);
} catch (err) {
ctx.status = 502;
ctx.body = { code: 502, message: `取消外部单据失败:${err.message}` };
return;
}
if (!client.isSuccess(resp)) {
ctx.status = 502;
ctx.body = { code: 502, message: `取消外部单据失败:${resp && (resp.message || resp.code)}` };
return;
}
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' ],
order: [[ 'product_id', 'ASC' ]],
});
const transaction = await ctx.model.transaction();
try {
for (const it of items) {
const pid = Number(it.product_id);
const qty = Number(it.quantity) || 0;
// 行级库存类型: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);
} else {
// 仅推送锁定、尚未扣减:释放锁定
await stock.unlock(ctx, order.principal_id, pid, qty, transaction, itemType);
}
}
const newBillNo = nextRejectedBillNo(order.bill_no, order.id, OUTBOUND_BILL_PREFIX);
await order.update({
status: 1,
bill_no: newBillNo,
stock_deducted: 0,
pushed_at: null,
wms_push_result: null,
}, { transaction });
await transaction.commit();
ctx.body = { code: 0, message: 'success', data: { id: order.id, bill_no: order.bill_no } };
} catch (err) {
await transaction.rollback();
ctx.status = 500;
ctx.body = { code: 500, message: '驳回失败,请稍后重试' };
}
}
}
module.exports = OutboundOrderController;