oms/backend/app/utils/completeInbound.js
liufumingren 39c19a4de7 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 为本地生成、不入库)
2026-09-14 00:59:23 +08:00

64 lines
2.8 KiB
JavaScript
Raw Permalink 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');
/**
* 完成入库:把「已推送(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)
* @return {Promise<{ok: boolean, already?: boolean, code?: number, message?: string}>}
*/
module.exports = async function completeInbound(ctx, order) {
if (!order) return { ok: false, code: 404, message: '入库单不存在' };
// 幂等:已完成直接返回
if (order.status === 4) return { ok: true, already: true };
if (order.status !== 3) {
return { ok: false, code: 400, message: '只有「已推送」状态的单据可以完成入库' };
}
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', 'code', 'name', 'quantity', 'inventory_type' ],
order: [[ 'product_id', 'ASC' ]],
});
if (!items.length) {
return { ok: false, code: 400, message: '单据无明细,无法完成入库' };
}
const transaction = await ctx.model.transaction();
try {
for (const it of items) {
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';
// 增加库存 + 写一条入库记录(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();
return { ok: true };
} catch (err) {
await transaction.rollback();
throw err;
}
};