- 新增 order_index 索引表 + 6 张同构状态表(待审核/异常/委外中/配送/已作废/已取消)与历史表, 订单 ID 全局唯一,状态由业务事务推动:审核、驳回、取消、作废、恢复、归档 - 明细表 order_status_items、收件人文本智能解析、批量切换仓库/店铺并刷新快照 - WMS deliveryorder.create 推送(单条/批量)、推送失败定时重试、订单归档定时任务 - 迁移:建表、旧发货单数据迁入新表、菜单合并与迁移记录清理 - routes / swagger contract 补充订单状态接口 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
183 lines
7.3 KiB
JavaScript
183 lines
7.3 KiB
JavaScript
'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 }]
|
||
*/
|
||
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 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) : (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,
|
||
};
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 执行订单库存动作(账实同事务)
|
||
* @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 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 || '#?');
|
||
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.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,
|
||
};
|