oms/backend/app/utils/orderStock.js
liufumingren 2b2ea066ea 商品增加「不用发货」标记
- products 新增 no_need_ship(默认 0),商品编辑页可开关,列表展示「免发货」标签
- 命中该商品的订单明细:审核不锁库存、发货不扣库存、推送 WMS 时不进入报文
- 整单明细都是这类商品时:审核报错提示、推送按永久失败转异常
- 补单测(推送明细过滤)与迁移

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-24 01:07:24 +08:00

207 lines
8.8 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 { applyStockChange } = require('./stockRecord');
const { orderModelName } = require('../lib/orderStatus');
/**
* 订单(新表)库存动作:审核锁定 / 释放 / 发货确认扣减。
*
* 与老发货单模块(app/utils/deliveryStock.js)口径完全一致,只是数据源换成新表:
* - **审核**:按明细锁定库存(order_lock),可用不足则审核失败
* - **推送失败 / 驳回 / 取消 / 作废**:释放锁定(order_unlock)
* - **WMS 发货确认**:扣减库存(总数量与锁定同减,order_deduct)
*
* 幂等依据是状态表上的 `stock_locked` 标记:
* - lock:已锁定(1) 直接跳过,不重复占用
* - release/deduct:未锁定(0) 直接跳过(老数据搬迁进来的单据保持 0,不会被凭空释放/扣减)
*
* 明细商品解析:order_status_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, no_need_ship }]
*/
async function loadOrderLines(ctx, order, transaction) {
const Op = ctx.app.Sequelize.Op;
const items = await ctx.model.OrderStatusItem.findAll({
where: { order_id: order.id, principal_id: order.principal_id },
attributes: [ 'id', 'order_line_no', 'item_code', 'item_name', 'plan_qty', 'inventory_type', 'product_id' ],
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 ids = [ ...new Set(items.map(i => Number(i.product_id)).filter(id => Number.isInteger(id) && id > 0)) ];
const or = [];
if (codes.length) or.push({ item_code: { [Op.in]: codes } });
if (ids.length) or.push({ id: { [Op.in]: ids } });
// 同时按编码与已回填的商品ID查,才能拿到「不用发货」标记(虚拟商品不参与锁/扣库存)
const products = or.length
? await ctx.model.Product.findAll({
where: { principal_id: order.principal_id, [Op.or]: or },
attributes: [ 'id', 'item_code', 'item_name', 'no_need_ship' ],
transaction,
})
: [];
const byCode = new Map(products.filter(p => p.item_code).map(p => [ p.item_code, p ]));
const byId = new Map(products.map(p => [ Number(p.id), 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)
|| (row.product_id != null ? byId.get(Number(row.product_id)) : null)
|| null;
return {
product_id: product ? Number(product.id) : (row.product_id != null ? Number(row.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,
no_need_ship: !!(product && Number(product.no_need_ship) === 1),
};
});
}
/**
* 执行订单库存动作(账实同事务)
* @param {Object} ctx egg context
* @param {Object} order 订单(状态表行,需含 id / principal_id / warehouse_id / order_no / 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 = 未匹配到系统商品的 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 shippable = lines.filter(l => !l.no_need_ship);
const hit = shippable.filter(l => l.product_id && l.plan_qty > 0);
// 仅把「未匹配到系统商品」的明细计入 skippedLines(数量为空/0 的明细直接忽略,属数据异常)
const skippedLines = shippable.filter(l => !l.product_id).map(l => l.item_code || '#?');
if (!hit.length) {
const virtualOnly = shippable.length === 0 && lines.length > 0;
if (virtualOnly) {
if (action === 'lock') {
throw new Error('订单明细全部为「不用发货」商品,无需锁定库存:请取消该单,或改为手工发货');
}
// 释放/扣减时没有可操作明细:只清锁定标记,避免卡住状态流转
await ctx.model[orderModelName(order.status)].update(
{ stock_locked: 0 },
{ where: { id: order.id, principal_id: order.principal_id }, transaction }
);
if (ownTransaction) await transaction.commit();
return { action, affected: 0, skipped: true, skippedLines };
}
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.order_no,
createdBy: options.createdBy,
remark: options.remark || DEFAULT_REMARKS[action],
transaction,
});
}
// 锁定标记与库存动作同事务:lock → 1,release/deduct → 0
const Model = ctx.model[orderModelName(order.status)];
await Model.update(
{ stock_locked: action === 'lock' ? 1 : 0 },
{ where: { id: order.id, principal_id: order.principal_id }, transaction }
);
if (ownTransaction) await transaction.commit();
if (skippedLines.length) {
ctx.logger.warn(`[order-stock] 订单 ${order.order_no} ${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 订单(状态表行)
* @param {Object} [options] { createdBy, remark, transaction }
* @return {Promise<Object>} execute 的返回
*/
function lockOrderStock(ctx, order, options = {}) {
return execute(ctx, order, 'lock', options);
}
/**
* 释放锁定库存(推送失败 / 驳回 / 取消 / 作废)
* @param {Object} ctx egg context
* @param {Object} order 订单(状态表行)
* @param {Object} [options] { createdBy, remark, transaction }
* @return {Promise<Object>} execute 的返回
*/
function releaseOrderStock(ctx, order, options = {}) {
return execute(ctx, order, 'release', options);
}
/**
* 发货确认扣减库存(WMS 回传 deliveryorder.confirm)
* @param {Object} ctx egg context
* @param {Object} order 订单(状态表行)
* @param {Object} [options] { createdBy, remark, transaction }
* @return {Promise<Object>} execute 的返回
*/
function deductOrderStock(ctx, order, options = {}) {
return execute(ctx, order, 'deduct', options);
}
module.exports = {
loadOrderLines,
lockOrderStock,
releaseOrderStock,
deductOrderStock,
};