'use strict'; const stock = require('../utils/stock'); const completeInbound = require('../utils/completeInbound'); /** * 外部回调(对外通用回调接口 /openapi)驱动 OMS 单据的共用处理逻辑。 * * 调用方:① app/lib/openapiMethods.js 注册的 method 处理器(WMS/第三方 POST /openapi) * ② app/controller/wmsNotify.js(WMS 出站通知 /wms/notify) * 因此「写回实际数量」「按单号定位单据」只保留这一份实现。 * * 单据定位规则:app_key 已在控制器侧定位到「主体 + 仓库」,此处按 * bill_no(WMS entryOrderCode / deliveryOrderCode / stockoutOrderCode)+ principal_id 查单, * 并校验单据的 warehouse_id 与 app_key 定位到的仓库一致,避免跨仓库误处理。 * * 报文结构兼容(见 unwrapPayload):openapi 出站回调整体包一层 request(request.entryOrder.entryOrderCode), * 出站通知 /wms/notify 整体包一层 data,两种结构都会先归一化再按同一组路径取值。 */ /** 入库单单号候选字段(支持嵌套路径) */ const INBOUND_CODE_PATHS = [ 'entryOrderCode', 'entryOrder.entryOrderCode', 'orderCode', 'order.orderCode', ]; /** 出库单单号候选字段(支持嵌套路径) */ const OUTBOUND_CODE_PATHS = [ 'deliveryOrderCode', 'deliveryOrder.deliveryOrderCode', 'stockoutOrderCode', 'stockoutOrder.stockoutOrderCode', 'stockout.stockoutOrderCode', 'orderCode', 'order.orderCode', ]; /** 入库单匹配信息候选字段 */ const MATCH_INFO_PATHS = { match_type: [ 'matchType', 'match_type' ], receiving_number: [ 'receivingNumber', 'receiving.receivingNumber' ], matched_at: [ 'completedAt', 'matchedAt', 'operateTime' ], }; /** * 归一化回调报文,兼容两种外层包裹: * - openapi 出站回调(WMS → OMS `POST /openapi?method=...`)整体包一层 request,如 * `{ request: { entryOrder: { entryOrderCode: 'RK_2_2' }, orderLines: [...] } }` * - 出站通知 `/wms/notify` 整体包一层 data,如 `{ code: 200, data: { entryOrderCode: 'RK_1' } }` * 内层字段优先(同名时覆盖顶层),归一化后调用方按同一组路径取值即可。 * @param {Object} data 原始回调报文 * @return {Object} 归一化后的报文 */ function unwrapPayload(data) { const source = data && typeof data === 'object' && !Array.isArray(data) ? data : {}; const inner = [ source.request, source.data ].find(v => v && typeof v === 'object' && !Array.isArray(v)); return inner ? { ...source, ...inner } : source; } /** * 按点号路径取值 * @param {Object} obj 源对象 * @param {String} path 形如 entryOrder.entryOrderCode * @return {*} 取到的值 */ function pickPath(obj, path) { return String(path).split('.').reduce((acc, key) => (acc === null || acc === undefined ? acc : acc[key]), obj); } /** * 按候选字段(支持嵌套路径)取第一个非空字符串 * @param {Object} data 回调报文 * @param {Array} paths 候选字段路径 * @return {String} 值(无则空串) */ function pickFirst(data, paths) { for (const path of paths) { const value = pickPath(data, path); if (value !== undefined && value !== null && String(value).trim() !== '') return String(value).trim(); } return ''; } /** * 从回调报文中提取明细行数组(兼容 orderLines.orderLine / orderLines / items 等结构) * @param {Object} data 回推报文 * @return {Array} 明细行数组 */ function extractLines(data) { const source = data || {}; const raw = source.orderLines || (source.entryOrder && source.entryOrder.orderLines) || (source.deliveryOrder && source.deliveryOrder.orderLines) || (source.stockoutOrder && source.stockoutOrder.orderLines) || source.items || []; if (Array.isArray(raw)) return raw; if (raw && Array.isArray(raw.orderLine)) return raw.orderLine; if (raw && Array.isArray(raw.orderLines)) return raw.orderLines; return []; } /** * 把外部回推的实际数量写回单据明细的「已入/已出」数量(按 itemCode 匹配明细行) * @param {Object} ctx egg context * @param {Number} orderId 单据头ID * @param {Number} billType 1入库 2出库 * @param {String} field actual_in_qty / actual_out_qty * @param {Array} lines 回推明细行 * @return {Promise} 实际更新的明细行数 */ async function applyActualQty(ctx, orderId, billType, field, lines) { if (!Array.isArray(lines) || !lines.length) return 0; let updated = 0; for (const line of lines) { if (!line) continue; const itemCode = line.itemCode || line.item_code || (line.item && line.item.itemCode); if (!itemCode) continue; const raw = line.actualQty != null ? line.actualQty : (line.actual_qty != null ? line.actual_qty : (line.quantity != null ? line.quantity : line.planQty)); const qty = Number(raw); if (!Number.isFinite(qty)) continue; const [ affected ] = await ctx.model.StockItem.update( { [field]: qty }, { where: { bill_type: billType, bill_id: orderId, code: itemCode } } ); updated += affected; } return updated; } /** * 按单号 + 主体定位单据,并校验其归属仓库与 app_key 定位到的仓库一致 * @param {Object} ctx egg context * @param {Object} options 查询参数 * @param {String} options.model 模型名(InboundOrder / OutboundOrder) * @param {String} options.code 单据号(bill_no) * @param {Number} options.principalId 主体ID * @param {Number} options.warehouseId app_key 定位到的仓库ID * @return {Promise<{order?: Object, error?: String}>} 定位结果 */ async function findBill(ctx, { model, code, principalId, warehouseId }) { const order = await ctx.model[model].findOne({ where: { bill_no: code, principal_id: principalId } }); if (!order) return { error: `未找到${model === 'InboundOrder' ? '入库' : '出库'}单:${code}` }; // 历史单据可能没有 warehouse_id,仅在双方都有值时校验仓库归属 if (order.warehouse_id && warehouseId && Number(order.warehouse_id) !== Number(warehouseId)) { return { error: `单据 ${code} 不属于当前 app_key 对应的仓库` }; } return { order }; } /** * 入库单确认(entryorder.confirm):WMS 收货完成 * 写回明细「已入数量」,并把「已推送(3)」的单据完成入库(增加系统库存,幂等) * @param {Object} ctx egg context * @param {Object} options 处理参数 * @param {Number} options.principalId 主体ID * @param {Number} options.warehouseId app_key 定位到的仓库ID * @param {Object} options.data 回调报文 * @return {Promise<{ok: Boolean, message: String, data?: Object}>} 处理结果 */ async function confirmInbound(ctx, { principalId, warehouseId, data }) { const payload = unwrapPayload(data); const code = pickFirst(payload, INBOUND_CODE_PATHS); if (!code) return { ok: false, message: '缺少入库单号(entryOrderCode / orderCode)' }; const found = await findBill(ctx, { model: 'InboundOrder', code, principalId, warehouseId }); if (found.error) return { ok: false, message: found.error }; const order = found.order; const actualUpdated = await applyActualQty(ctx, order.id, 1, 'actual_in_qty', extractLines(payload)); const result = await completeInbound(ctx, order); if (!result.ok) return { ok: false, message: result.message }; const data_ = { bill_id: order.id, bill_no: order.bill_no, status: result.already ? order.status : 4, already_completed: !!result.already, actual_qty_updated: actualUpdated, }; ctx.logger.info('[order-callback] entryorder.confirm 完成', data_); return { ok: true, message: 'ok', data: data_ }; } /** * 入库单匹配(entryorder.match):WMS 反馈入库单与收货单匹配结果 * 仅写回明细「已入数量」并返回匹配信息,不改变单据状态、不增加库存(匹配 ≠ 收货完成) * @param {Object} ctx egg context * @param {Object} options 处理参数 * @param {Number} options.principalId 主体ID * @param {Number} options.warehouseId app_key 定位到的仓库ID * @param {Object} options.data 回调报文 * @return {Promise<{ok: Boolean, message: String, data?: Object}>} 处理结果 */ async function matchInbound(ctx, { principalId, warehouseId, data }) { const payload = unwrapPayload(data); const code = pickFirst(payload, INBOUND_CODE_PATHS); if (!code) return { ok: false, message: '缺少入库单号(entryOrderCode / orderCode)' }; const found = await findBill(ctx, { model: 'InboundOrder', code, principalId, warehouseId }); if (found.error) return { ok: false, message: found.error }; const order = found.order; const actualUpdated = await applyActualQty(ctx, order.id, 1, 'actual_in_qty', extractLines(payload)); const result = { bill_id: order.id, bill_no: order.bill_no, status: order.status, actual_qty_updated: actualUpdated, match_type: pickFirst(payload, MATCH_INFO_PATHS.match_type), receiving_number: pickFirst(payload, MATCH_INFO_PATHS.receiving_number), matched_at: pickFirst(payload, MATCH_INFO_PATHS.matched_at), }; ctx.logger.info('[order-callback] entryorder.match 匹配登记', result); return { ok: true, message: 'ok', data: result }; } /** * 出库单确认(deliveryorder.confirm / stockout.confirm):WMS 已发货出库 * 写回明细「已出数量」,扣减系统库存(总数量与锁定各减明细数量,幂等),并置「已完成(4)」 * @param {Object} ctx egg context * @param {Object} options 处理参数 * @param {Number} options.principalId 主体ID * @param {Number} options.warehouseId app_key 定位到的仓库ID * @param {Object} options.data 回调报文 * @return {Promise<{ok: Boolean, message: String, data?: Object}>} 处理结果 */ async function confirmOutbound(ctx, { principalId, warehouseId, data }) { const payload = unwrapPayload(data); const code = pickFirst(payload, OUTBOUND_CODE_PATHS); if (!code) return { ok: false, message: '缺少出库单号(deliveryOrderCode / stockoutOrderCode / orderCode)' }; const found = await findBill(ctx, { model: 'OutboundOrder', code, principalId, warehouseId }); if (found.error) return { ok: false, message: found.error }; const order = found.order; const actualUpdated = await applyActualQty(ctx, order.id, 2, 'actual_out_qty', extractLines(payload)); // 幂等:已完成且已扣减库存的单据不再重复处理 if (order.status === 4 && order.stock_deducted) { const done = { bill_id: order.id, bill_no: order.bill_no, status: order.status, already_completed: true, actual_qty_updated: actualUpdated, }; ctx.logger.info('[order-callback] 出库单已完成,跳过', done); return { ok: true, message: 'ok', data: done }; } if (order.status !== 3 && order.status !== 4) { return { ok: false, message: `单据 ${order.bill_no} 当前状态(${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' ]], }); if (!items.length) return { ok: false, message: `单据 ${order.bill_no} 无明细,无法完成出库` }; const transaction = await ctx.model.transaction(); try { if (!order.stock_deducted) { for (const it of items) { const p = it.get ? it.get({ plain: true }) : it; const itemType = p.inventory_type === 'CC' ? 'CC' : 'ZC'; await stock.deduct(ctx, principalId, Number(p.product_id), Number(p.quantity) || 0, transaction, itemType); } } await order.update({ status: 4, stock_deducted: 1 }, { transaction }); await transaction.commit(); } catch (err) { await transaction.rollback(); throw err; } const result = { bill_id: order.id, bill_no: order.bill_no, status: 4, stock_deducted: 1, already_completed: false, actual_qty_updated: actualUpdated, }; ctx.logger.info('[order-callback] 出库确认完成', result); return { ok: true, message: 'ok', data: result }; } /** * 订单取消通知(order.cancel):外部已取消该单据 * 未完成(≠4)的单据置为「已取消(9)」;出库单若已推送(3)则同时释放锁定库存 * @param {Object} ctx egg context * @param {Object} options 处理参数 * @param {Number} options.principalId 主体ID * @param {Number} options.warehouseId app_key 定位到的仓库ID * @param {Object} options.data 回调报文 * @return {Promise<{ok: Boolean, message: String, data?: Object}>} 处理结果 */ async function cancelOrder(ctx, { principalId, warehouseId, data }) { const payload = unwrapPayload(data); const code = pickFirst(payload, [ ...OUTBOUND_CODE_PATHS, ...INBOUND_CODE_PATHS ]); if (!code) return { ok: false, message: '缺少单号(orderCode / deliveryOrderCode / entryOrderCode)' }; // 先按出库单定位,再按入库单定位 let billType = 2; let found = await findBill(ctx, { model: 'OutboundOrder', code, principalId, warehouseId }); if (found.error) { billType = 1; found = await findBill(ctx, { model: 'InboundOrder', code, principalId, warehouseId }); } if (found.error) { return { ok: false, message: `未找到可取消的单据:${code}(出入库单均无此单号或不属于当前仓库)` }; } const order = found.order; if (order.status === 4) return { ok: false, message: `单据 ${code} 已完成,不能取消` }; if (order.status === 9) { return { ok: true, message: 'ok', data: { bill_id: order.id, bill_no: order.bill_no, bill_type: billType, status: 9, already_cancelled: true } }; } // 出库单已推送(3)且未扣减库存:取消时释放锁定库存 if (billType === 2 && order.status === 3 && !order.stock_deducted) { 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 p = it.get ? it.get({ plain: true }) : it; const itemType = p.inventory_type === 'CC' ? 'CC' : 'ZC'; await stock.unlock(ctx, principalId, Number(p.product_id), Number(p.quantity) || 0, transaction, itemType); } await order.update({ status: 9 }, { transaction }); await transaction.commit(); } catch (err) { await transaction.rollback(); throw err; } } else { await order.update({ status: 9 }); } const result = { bill_id: order.id, bill_no: order.bill_no, bill_type: billType, status: 9, already_cancelled: false, cancel_reason: pickFirst(data, [ 'cancelReason', 'reason', 'remark' ]), }; ctx.logger.info('[order-callback] order.cancel 已取消', result); return { ok: true, message: 'ok', data: result }; } module.exports = { pickFirst, extractLines, applyActualQty, confirmInbound, matchInbound, confirmOutbound, cancelOrder, };