'use strict'; const Service = require('egg').Service; /** * 非收货单途径入库直接记录服务(导入/PDA入库)。 * * 职责: * 1. 根据入库单号获取入库明细(含已记录的导入/PDA 入库记录) * 2. 按商品增量添加导入/PDA 入库记录,超计划数量时拒绝 * 3. 提交确认完成入库,写入库存并触发奇门/API 回传 */ class InboundDirectLogService extends Service { /** * 获取入库单的受控入库信息(精简版)。 * 返回入库单基本信息、明细列表(含计划数量与已完成数量)、收货单绑定关系。 * @param {number} entryOrderId 入库单ID(必填) * @return {Promise} code/data/message 结构 * - data.entryOrder: { id, entry_order_code, order_status, store_remask } * - data.items: [{ id, stock_id, planned, completed, stock, bindings }] * - data.receivingBindings: 收货单绑定关系列表 */ async getItems(entryOrderId) { const { ctx, app } = this; const id = Number(entryOrderId || 0); if (!id) { return { code: 400, message: 'id 参数不能为空', data: null }; } const entryOrder = await ctx.model.EntryOrder.findByPk(id, { include: [ { model: ctx.model.EntryItems, as: 'items', required: false, include: [ { model: ctx.model.StockWarehouse, as: 'stock', attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], required: false, }, ], }, { model: ctx.model.EntryOrderReceiving, as: 'receivingBindings', required: false, include: [ { model: ctx.model.Receiving, as: 'receiving', attributes: [ 'id', 'receiving_number', 'status', 'storage_status', 'created_at' ], required: false, }, ], }, ], }); if (!entryOrder) { return { code: 404, message: '入库单不存在', data: null }; } // 校验仓库权限 if (entryOrder.warehouse_id !== ctx.user.store_id || !entryOrder.is_enabled) { return { code: 404, message: '入库单不存在或无权访问', data: null }; } // 查询货主商家备注 const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ where: { store_id: entryOrder.store_id, warehouse_id: entryOrder.warehouse_id }, attributes: [ 'store_remask' ], raw: true, }); // 查询该入库单下已有的导入/PDA 入库记录(显式过滤软删除,仅统计未删除记录) const directLogs = await ctx.model.InboundDirectLog.findAll({ where: { entry_order_id: entryOrder.id, deleted_at: null }, order: [[ 'created_at', 'ASC' ]], }); // 将直接入库记录按 entry_item_id 关联到明细 // 优先使用 entry_item_id 精确匹配(绑定模式),其次回退到 stock_id 匹配(非绑定模式) const itemDirectLogs = {}; for (const log of directLogs) { // 绑定模式下 entry_item_id 已设置,优先用它定位明细行 const itemByEntryItemId = log.entry_item_id ? entryOrder.items.find(i => String(i.id) === String(log.entry_item_id)) : null; const item = itemByEntryItemId || entryOrder.items.find( i => String(i.stock_id) === String(log.stock_id) ); const key = item ? String(item.id) : `stock_${log.stock_id}`; if (!itemDirectLogs[key]) itemDirectLogs[key] = []; itemDirectLogs[key].push({ id: log.id, stock_id: log.stock_id, quantity: log.quantity, inbound_type: log.inbound_type, space_id: log.space_id, remark: log.remark, operator_id: log.operator_id, operator_name: log.operator_name, created_at: log.created_at, }); } // 将入库单层级的收货单绑定扁平化(不再按明细维度) const receivingBindings = (entryOrder.receivingBindings && entryOrder.receivingBindings.length > 0) ? entryOrder.receivingBindings.map(rb => ({ id: rb.id, receiving_id: rb.receiving_id, receiving: rb.receiving || null, })) : []; // 收集所有 stock_id,通过 getStockDetails 批量获取带缓存的商品详情 const stockIds = [ ...new Set( (entryOrder.items || []) .map(item => Number(item.stock_id)) .filter(id => id && id > 0) ) ]; /** @type {Map} */ const stockMap = new Map(); if (stockIds.length > 0) { const warehouseId = ctx.user.store_id; const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); for (const detail of stockDetails) { stockMap.set(detail.id, detail); } } // 组装明细(精简字段,突出已入/总数) const items = (entryOrder.items || []).map(item => { const planQty = Number(item.count) || 0; const logKey = String(item.id); const logs = itemDirectLogs[logKey] || []; const directInQty = logs.reduce((sum, l) => sum + Number(l.quantity), 0); // 优先使用已持久化的 received_quantity(commit 后由系统写入), // 若为 0 则回退到 InboundDirectLog 汇总(尚未提交时的导入量), // 确保绑定收货明细场景下 completed 口径与 received_quantity 一致。 const receivedQty = Number(item.received_quantity) || 0; const completed = receivedQty > 0 ? receivedQty : directInQty; return { id: item.id, stock_id: item.stock_id, planned: planQty, completed, stock: stockMap.get(Number(item.stock_id)) || null, }; }); // 收集所有 InboundDirectLog 中的 space_id,批量查询库位名称 /** @type {Map} space_id -> space_name */ const spaceNameMap = new Map(); const allSpaceIds = [ ...new Set( Object.values(itemDirectLogs) .flat() .map(log => log.space_id) .filter(id => id != null) ) ]; if (allSpaceIds.length > 0) { const spaces = await ctx.model.LocationSpace.findAll({ where: { id: { [app.Sequelize.Op.in]: allSpaceIds } }, attributes: [ 'id', 'custom_name', 'space_code' ], raw: true, }); for (const sp of spaces) { spaceNameMap.set(sp.id, sp.custom_name || sp.space_code || ''); } } // 批量查询已绑定的收货明细列表 const entryItemIds = items.map(i => i.id).filter(Boolean); /** @type {Map>} 按 entry_item_id 分组 */ const bindingsMap = new Map(); if (entryItemIds.length > 0) { // 1. 查绑定关系表(从 InboundDirectLog 中筛选有 receiving_detail_id 的记录) const bindingRows = await ctx.model.InboundDirectLog.findAll({ where: { entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, receiving_detail_id: { [app.Sequelize.Op.ne]: null }, deleted_at: null, }, attributes: [ 'id', 'entry_item_id', 'receiving_detail_id', 'quantity', 'status' ], raw: true, }); if (bindingRows.length > 0) { // 2. 验证收货明细存在性(仅校验,不取冗余字段) const detailIds = [ ...new Set(bindingRows.map(b => b.receiving_detail_id).filter(Boolean)) ]; const validDetailIds = new Set(); if (detailIds.length > 0) { const details = await ctx.model.ReceivingDetail.findAll({ where: { id: { [app.Sequelize.Op.in]: detailIds } }, attributes: [ 'id' ], raw: true, }); for (const d of details) { validDetailIds.add(d.id); } } // 3. 按 entry_item_id 分组,只保留核心字段 for (const b of bindingRows) { const key = b.entry_item_id; if (!bindingsMap.has(key)) { bindingsMap.set(key, []); } bindingsMap.get(key).push({ detail_id: b.receiving_detail_id, binding_id: b.id, allocated_quantity: b.quantity || 0, }); } } } // 将 bindings 挂到对应 item,并补充库位信息(space_id/space_name 来自 InboundDirectLog) for (const item of items) { const bindings = bindingsMap.get(item.id) || []; const logKey = String(item.id); const directLogs = itemDirectLogs[logKey] || []; // 从 InboundDirectLog 中提取 space_id,并解析库位名称 // 如果 bindings 为空但有 directLog 带 space_id,则构造一条 binding 展示库位信息 if (bindings.length === 0 && directLogs.length > 0) { const firstWithSpace = directLogs.find(l => l.space_id); if (firstWithSpace) { item.bindings = [{ space_id: firstWithSpace.space_id, space_name: spaceNameMap.get(Number(firstWithSpace.space_id)) || '', }]; } else { item.bindings = []; } } else { // 如果有 bindings,取第一条带 space_id 的 directLog 补充 const firstWithSpace = directLogs.find(l => l.space_id); const sid = firstWithSpace ? firstWithSpace.space_id : null; item.bindings = bindings.map(b => ({ ...b, space_id: sid, space_name: sid != null ? (spaceNameMap.get(Number(sid)) || '') : '', })); } } return { code: 200, message: '查询成功', data: { entryOrder: { id: entryOrder.id, entry_order_code: entryOrder.entry_order_code, order_status: entryOrder.order_status, store_remask: (storeWarehouse && storeWarehouse.store_remask) || '', }, items, receivingBindings, }, }; } /** * 单条校验并写入一条导入/PDA 入库记录。 * @param {Object} ctx Egg.js 上下文对象 * @param {Object} entryOrder 入库单实例 * @param {Object} item 入库项,包含 stock_id、quantity、inbound_type、remark、space_id * @param {Object} [transaction] Sequelize 事务对象,可选 * @return {Promise<{ok: boolean, log?: Object, error?: Object}>} 返回操作结果,ok 为 true 时 log 包含入库记录详情,ok 为 false 时 error 包含错误信息 */ async _addSingleItem(ctx, entryOrder, item, transaction) { const stockId = Number(item.stock_id || 0); const quantity = Number(item.quantity || 0); const inboundType = String(item.inbound_type || '').trim().toLowerCase(); const remark = item.remark ? String(item.remark).trim() : ''; const spaceId = item.space_id ? Number(item.space_id) : null; const receivingDetailId = Number(item.receiving_detail_id || 0); const isBindingMode = receivingDetailId > 0; if (!stockId) { return { ok: false, error: { code: 400, message: 'items[].stock_id 必填' } }; } // 绑定模式下必须传 space_id if (isBindingMode && !spaceId) { return { ok: false, error: { code: 400, message: '绑定收货明细时必须指定 space_id' } }; } // 非绑定模式下校验 quantity 必填且为正整数 if (!isBindingMode) { if (!quantity || quantity <= 0 || !Number.isFinite(quantity)) { return { ok: false, error: { code: 400, message: 'items[].quantity 必须为正整数' } }; } } if (![ 'import', 'pda' ].includes(inboundType)) { return { ok: false, error: { code: 400, message: 'items[].inbound_type 必须为 import 或 pda' } }; } // 确定有效数量:绑定模式下自动计算收货明细的可用数量(actual_quantity - 已绑定数量) let effectiveQuantity = quantity; if (isBindingMode) { // 查询收货明细 const receivingDetail = await ctx.model.ReceivingDetail.findOne({ where: { id: receivingDetailId }, ...(transaction ? { transaction } : {}), }); if (!receivingDetail) { return { ok: false, error: { code: 400, message: `收货明细不存在(id=${receivingDetailId})` } }; } // 绑定模式下 stock_id 必须匹配收货明细的 system_product_id if (receivingDetail.system_product_id !== stockId) { return { ok: false, error: { code: 400, message: `收货明细的商品(system_product_id=${receivingDetail.system_product_id})与传入的 stock_id(${stockId})不匹配` } }; } // 查询该收货明细已被占用的数量(pending + committed),从 InboundDirectLog 查 const allocatedSum = await ctx.model.query( `SELECT COALESCE(SUM(quantity), 0) AS total FROM wms_inbound_direct_log WHERE receiving_detail_id = :rdId AND status IN ('pending', 'committed') AND deleted_at IS NULL`, { replacements: { rdId: receivingDetailId }, type: ctx.model.QueryTypes.SELECT, ...(transaction ? { transaction } : {}), } ); const usedQty = Number(allocatedSum?.[0]?.total || 0); const actualQty = Number(receivingDetail.actual_quantity) || 0; effectiveQuantity = actualQty - usedQty; if (effectiveQuantity <= 0) { return { ok: false, error: { code: 400, message: `收货明细可用数量不足:实际数量 ${actualQty},已占用 ${usedQty},可用 ${effectiveQuantity}`, }, }; } } // 查找入库单中该 stock_id 对应的所有明细,累加计划数量 const entryItems = await ctx.model.EntryItems.findAll({ where: { order_id: entryOrder.id, stock_id: stockId }, ...(transaction ? { transaction } : {}), }); if (!entryItems || entryItems.length === 0) { return { ok: false, error: { code: 400, message: `入库单中不存在 stock_id=${stockId} 的商品` } }; } // 计算该 stock_id 在入库单明细中的计划总数与已收货总数 const totalPlanQty = entryItems.reduce((sum, ei) => sum + (Number(ei.count) || 0), 0); const totalReceivedQty = entryItems.reduce((sum, ei) => sum + (Number(ei.received_quantity) || 0), 0); // 计算该 stock_id 在该入库单下已有的导入/PDA 入库总量 const logWhere = { entry_order_id: entryOrder.id, stock_id: stockId }; const existingLogs = await ctx.model.InboundDirectLog.findAll({ where: logWhere, attributes: [ 'quantity' ], raw: true, ...(transaction ? { transaction } : {}), }); const existingTotal = existingLogs.reduce((sum, log) => sum + Number(log.quantity), 0); // 绑定模式和非绑定模式均受可入库数量限制 // CREATED 人工导入允许超过计划数量 const isManualImport = entryOrder.order_status === 'CREATED' && !isBindingMode; if (!isManualImport) { const maxAllowed = totalPlanQty - existingTotal; if (maxAllowed <= 0) { return { ok: false, error: { code: 400, message: `入库数量超过计划:商品计划 ${totalPlanQty},已入库 ${existingTotal},本次 ${effectiveQuantity},合计 ${existingTotal + effectiveQuantity}`, data: { stock_id: stockId, plan_quantity: totalPlanQty, existing_quantity: existingTotal, requested_quantity: effectiveQuantity, exceeded_by: effectiveQuantity, }, }, }; } if (effectiveQuantity > maxAllowed) { effectiveQuantity = maxAllowed; } } // 剩余可入库数 = 计划数 - max(已收货量, 已写入 direct_log 的待入库量) // 避免多次 addItem 之间 received_quantity 始终为 0 导致的重复入库漏拦截 { const occupiedQuantity = Math.max(totalReceivedQty, existingTotal); const remainingQuantity = Math.max(0, totalPlanQty - occupiedQuantity); if (remainingQuantity <= 0) { return { ok: false, error: { code: 400, message: `商品 stock_id=${stockId} 无可入库数量:计划 ${totalPlanQty},已收货 ${totalReceivedQty}`, }, }; } if (effectiveQuantity > remainingQuantity) { effectiveQuantity = remainingQuantity; } } const newTotal = existingTotal + effectiveQuantity; // 绑定模式:只由 _bindReceivingDetail 负责写入(status='pending'),避免重复插入两条记录 if (isBindingMode) { item.allocated_quantity = effectiveQuantity; const receivingBindResult = await this._bindReceivingDetail( ctx, entryOrder, item, stockId, receivingDetailId, effectiveQuantity, transaction ); if (receivingBindResult && receivingBindResult.error) { return { ok: false, error: { code: 400, message: receivingBindResult.error } }; } return { ok: true, log: { id: receivingBindResult?.binding_id || 0, stock_id: stockId, quantity: effectiveQuantity, inbound_type: inboundType, space_id: spaceId, plan_quantity: totalPlanQty, existing_before: existingTotal, existing_after: newTotal, remaining: Math.max(0, totalPlanQty - newTotal), receivingBindResult, }, }; } // 非绑定模式:直接写入一条无收货明细绑定的入库记录 const log = await ctx.model.InboundDirectLog.create({ warehouse_id: entryOrder.warehouse_id, store_id: entryOrder.store_id, stock_id: stockId, quantity: effectiveQuantity, inbound_type: inboundType, entry_order_id: entryOrder.id, entry_order_code: entryOrder.entry_order_code, space_id: spaceId, remark, operator_id: ctx.user?.employees_id || ctx.user?.id || null, operator_name: ctx.user?.employees_name || '', created_at: new Date(), }, transaction ? { transaction } : {}); return { ok: true, log: { id: log.id, stock_id: stockId, quantity: effectiveQuantity, inbound_type: inboundType, space_id: spaceId, plan_quantity: totalPlanQty, existing_before: existingTotal, existing_after: newTotal, remaining: Math.max(0, totalPlanQty - newTotal), }, }; } /** * 将入库直接记录绑定到收货单明细(预占模式,status='pending')。 * 校验收货明细存在、未取消、可用数量足够后,写入 wms_inbound_direct_log 并确保主表绑定存在。 * @param {Object} ctx Egg.js 上下文对象 * @param {Object} entryOrder 入库单实例 * @param {Object} item 入库项参数,包含 allocated_quantity、item_code 等可选字段 * @param {number} stockId 商品SKU ID * @param {number} receivingDetailId 收货单明细ID * @param {number} quantity 本次入库数量 * @param {Object} [transaction] Sequelize 事务对象,可选 * @return {Promise} 返回绑定结果 { binding_id, receiving_detail_id, allocated_quantity, status } */ async _bindReceivingDetail(ctx, entryOrder, item, stockId, receivingDetailId, quantity, transaction) { // 确定预分配数量:优先用 allocated_quantity,否则回退到 quantity let allocatedQty = Number(item.allocated_quantity || 0); if (!allocatedQty || allocatedQty <= 0) { allocatedQty = quantity; } if (!Number.isFinite(allocatedQty) || allocatedQty <= 0) { return { error: 'allocated_quantity 必须为正整数' }; } if (allocatedQty > quantity) { return { error: `allocated_quantity(${allocatedQty}) 不能大于入库数量(${quantity})` }; } // 1. 查询收货明细行(锁定) const receivingDetail = await ctx.model.ReceivingDetail.findOne({ where: { id: receivingDetailId }, ...(transaction ? { lock: transaction.LOCK?.UPDATE, transaction } : {}), }); if (!receivingDetail) { return { error: `收货明细不存在(id=${receivingDetailId})` }; } // 2. 查询已占用(pending + committed)的分配量,从 InboundDirectLog 查 const allocatedSum = await ctx.model.query( `SELECT COALESCE(SUM(quantity), 0) AS total FROM wms_inbound_direct_log WHERE receiving_detail_id = :rdId AND status IN ('pending', 'committed') AND deleted_at IS NULL`, { replacements: { rdId: receivingDetailId }, type: ctx.model.QueryTypes.SELECT, ...(transaction ? { transaction } : {}), } ); const usedQty = Number(allocatedSum?.[0]?.total || 0); const availableQty = (Number(receivingDetail.actual_quantity) || 0) - usedQty; if (allocatedQty > availableQty) { return { error: `收货明细可用数量不足: 可用${availableQty}, 请求${allocatedQty}`, available_quantity: availableQty, requested_quantity: allocatedQty, }; } // 3. 查找入库明细行(entry_item_id) const entryItem = await ctx.model.EntryItems.findOne({ where: { order_id: entryOrder.id, stock_id: stockId, }, ...(transaction ? { transaction } : {}), }); // 4. 写入绑定到 InboundDirectLog(status='pending',预占不提交) const binding = await ctx.model.InboundDirectLog.create({ warehouse_id: entryOrder.warehouse_id, store_id: entryOrder.store_id, stock_id: stockId, quantity: allocatedQty, inbound_type: item.inbound_type || 'import', entry_order_id: entryOrder.id, entry_order_code: entryOrder.entry_order_code, entry_item_id: entryItem?.id || 0, receiving_detail_id: receivingDetailId, space_id: item.space_id ? Number(item.space_id) : null, status: 'pending', creator_id: ctx.user?.id || 0, operator_id: ctx.user?.employees_id || ctx.user?.id || null, operator_name: ctx.user?.employees_name || '', }, transaction ? { transaction } : {}); return { binding_id: binding.id, receiving_detail_id: receivingDetailId, allocated_quantity: allocatedQty, status: 'pending', }; } /** * 按商品增量添加导入/PDA 入库记录(支持单条和批量)。 * * 单条模式(兼容旧调用): * { entry_order_id, stock_id, quantity, inbound_type, remark } * * 批量模式(推荐): * { entry_order_id, items: [{ stock_id, quantity, inbound_type, remark }] } * * 批量模式下所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。 * 若该商品在当前入库单中的累计入库量超过计划数量则拒绝。 * * 可选收货单明细绑定(批量模式下 items 元素支持): * { ..., receiving_detail_id, allocated_quantity } * 传入 receiving_detail_id 后,将校验收货明细可用数量并写入 wms_entry_receiving_binding(status='pending' 预占)。 * @param {Object} params 请求参数对象 * @param {number} params.entry_order_id 入库单ID * @param {number} [params.stock_id] 商品SKU ID(单条模式) * @param {number} [params.quantity] 本次入库数量(单条模式) * @param {string} [params.inbound_type] 入库方式(单条模式) * @param {Array} [params.items] 商品列表(批量模式) * @param {string} [params.remark] 备注(单条模式) * @param {number} [params.receiving_detail_id] 收货单明细ID(单条模式,可选,传入后触发预占绑定) * @param {number} [params.allocated_quantity] 预分配数量(单条模式,可选,默认等于 quantity) * @return {Promise} 返回 { code, message, data },code=200 表示成功 */ async addItem(params) { const { ctx } = this; const warehouseId = ctx.user.store_id; const entryOrderId = Number(params.entry_order_id) || 0; if (!entryOrderId || entryOrderId <= 0) { return { code: 400, message: 'entry_order_id 必填', data: null }; } // 判断批量/单条模式 const isBatch = Array.isArray(params.items) && params.items.length > 0; const items = isBatch ? params.items : [{ stock_id: params.stock_id, space_id: params.space_id, quantity: params.quantity, inbound_type: params.inbound_type, remark: params.remark, receiving_detail_id: params.receiving_detail_id, allocated_quantity: params.allocated_quantity, }]; // 通过主键查找入库单 const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId); if (!entryOrder || entryOrder.warehouse_id !== warehouseId) { return { code: 404, message: '入库单不存在或无权访问', data: null }; } // 检查入库单状态 if (entryOrder.order_status === 'CANCELLED') { return { code: 400, message: '已作废入库单不允许操作', data: null }; } if (entryOrder.order_status === 'COMPLETED') { return { code: 400, message: '已完成的入库单不允许操作', data: null }; } // 检查接入库单是否已绑定收货单 const hasReceivingBindings = await ctx.model.EntryOrderReceiving.findOne({ where: { entry_order_id: entryOrder.id, deleted_at: null }, }); // CREATED + 已绑定 → 拒绝(需先走 reviewEntry 审核) if (entryOrder.order_status === 'CREATED' && hasReceivingBindings) { return { code: 400, message: '入库单已绑定收货单且状态为 CREATED,请先审核后再进行上架操作', data: null }; } // PENDING 状态:允许导入。items 可传 receiving_detail_id 走绑定模式(预占收货明细), // 也可不传走非绑定模式(数量受计划数量限制),不再强制绑定收货单、不再强制传收货单 ID; // 绑定模式下的 space_id/明细可用数量等校验由 _addSingleItem 统一处理。 // 批量模式下用事务包裹,任一失败整批回退 const useTransaction = isBatch; const txn = useTransaction ? await ctx.model.transaction() : null; try { const results = []; for (const item of items) { const result = await this._addSingleItem(ctx, entryOrder, item, txn); if (!result.ok) { if (txn) await txn.rollback(); return result.error; } results.push(result.log); } if (txn) await txn.commit(); // 非阻塞记录操作日志(批量模式只记一条汇总) if (results.length > 0) { const totalQty = results.reduce((s, r) => s + r.quantity, 0); const types = [ ...new Set(results.map(r => r.inbound_type)) ].join(','); setImmediate(() => { ctx.service.systems.operationLog.createOperationLog({ businessType: 'entry_order', businessId: entryOrder.id, operationCode: 'DIRECT_INBOUND_ADD', operator: { id: ctx.user?.employees_id || ctx.user?.id, name: ctx.user?.employees_name || '', }, extras: { warehouseId: entryOrder.warehouse_id, message: `导入/PDA入库添加 ${results.length} 种商品,总数量 ${totalQty},方式 ${types}`, }, }).catch(err => { ctx.logger.error(`[InboundDirectLog] 记录操作日志失败: ${err.message}`); }); }); } if (!isBatch) { const r = results[0]; return { code: 200, message: '添加成功', data: { ...r }, }; } return { code: 200, message: `添加成功,共 ${results.length} 项`, data: { count: results.length, total_quantity: results.reduce((s, r) => s + r.quantity, 0), items: results, }, }; } catch (error) { if (txn && typeof txn.rollback === 'function') { await txn.rollback(); } throw error; } } /** * 移除一条导入/PDA 入库记录(仅限未提交的入库单)。 * @param {Object} params 请求参数对象 * @param {number} params.id 入库记录ID(wms_inbound_direct_log.id) * @return {Promise} 返回 { code, message, data },code=200 表示移除成功 */ async removeItem(params) { const { ctx } = this; const logId = Number(params.id || 0); if (!logId) { return { code: 400, message: 'id 必填', data: null }; } const log = await ctx.model.InboundDirectLog.findByPk(logId); if (!log) { return { code: 404, message: '入库记录不存在', data: null }; } // 检查所属入库单状态 const entryOrder = await ctx.model.EntryOrder.findOne({ where: { id: log.entry_order_id, warehouse_id: ctx.user.store_id, is_enabled: 1, deleted_at: null, }, }); if (!entryOrder) { return { code: 404, message: '关联入库单不存在或无权访问', data: null }; } if (entryOrder.order_status === 'CANCELLED') { return { code: 400, message: '已作废入库单不允许操作', data: null }; } if (entryOrder.order_status === 'COMPLETED') { return { code: 400, message: '已完成的入库单不允许移除记录', data: null }; } // 软删除该记录 await log.destroy(); // 非阻塞记录操作日志 setImmediate(() => { ctx.service.systems.operationLog.createOperationLog({ businessType: 'entry_order', businessId: entryOrder.id, operationCode: 'DIRECT_INBOUND_REMOVE', operator: { id: ctx.user?.employees_id || ctx.user?.id, name: ctx.user?.employees_name || '', }, extras: { warehouseId: entryOrder.warehouse_id, message: `移除导入/PDA入库记录 id=${logId},stock_id=${log.stock_id},数量 ${log.quantity},方式 ${log.inbound_type}`, }, }).catch(err => { ctx.logger.error(`[InboundDirectLog] 记录操作日志失败: ${err.message}`); }); }); return { code: 200, message: '移除成功', data: { id: logId, stock_id: log.stock_id, quantity: log.quantity, inbound_type: log.inbound_type, }, }; } /** * 提交确认完成入库(先同步后写库模式)。 * 先调用 qimenEntrySync 进行奇门/API 回传,成功后在 onSuccess 回调内开启事务写入库存。 * 同步失败则只写 FAILED 状态 + 操作日志,不写库存。 * @param {number} entryOrderId 入库单 ID * @param {number} [noNeedNotice=0] 是否跳过入库完成通知:0 通知,1 不通知(默认 0) * @return {Promise} code/data/message 结构 */ async commit(entryOrderId, noNeedNotice = 0) { const { ctx, app } = this; const warehouseId = ctx.user.store_id; const entryOrderIdNum = Number(entryOrderId) || 0; if (!entryOrderIdNum || entryOrderIdNum <= 0) { return { code: 400, message: 'entry_order_id 必填', data: null }; } // 通过主键查找入库单 const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderIdNum); if (!entryOrder || entryOrder.warehouse_id !== warehouseId) { return { code: 404, message: '入库单不存在或无权访问', data: null }; } if (entryOrder.order_status === 'CANCELLED') { return { code: 400, message: '已作废入库单不允许完成', data: null }; } if (entryOrder.order_status === 'COMPLETED') { return { code: 400, message: '入库单已完成,请勿重复提交', data: null }; } // 查询该入库单下所有未删除的导入/PDA 入库记录 const directLogs = await ctx.model.InboundDirectLog.findAll({ where: { entry_order_id: entryOrder.id, deleted_at: null }, }); if (!directLogs || directLogs.length === 0) { return { code: 400, message: '暂无导入/PDA 入库记录,请先添加商品', data: null }; } // 按 stock_id 汇总入库数量 const stockSummary = {}; for (const log of directLogs) { const key = String(log.stock_id); if (!stockSummary[key]) stockSummary[key] = 0; stockSummary[key] += Number(log.quantity); } // 查询入库单所有明细 const entryItems = await ctx.model.EntryItems.findAll({ where: { order_id: entryOrder.id }, }); if (!entryItems.length) { return { code: 400, message: '入库单无明细', data: null }; } const storeId = entryOrder.store_id; // ===== 阶段一:先同步奇门/API(事务外) ===== const items = entryItems.map((item, idx) => ({ orderLineNo: idx + 1, ownerCode: item.owner_code || '', itemCode: item.item_code || '', itemId: item.item_id || '', inventoryType: item.inventory_type || 'ZP', planQty: Number(item.count) || 0, actualQty: stockSummary[String(item.stock_id)] || 0, })); const syncResult = await this.qimenEntrySync({ entryOrder, orderLines: items, outBizCode: `DIRECT_INBOUND_${Date.now()}`, remark: '导入/PDA直接入库提交', operator: { id: ctx.user?.employees_id || ctx.user?.id, name: ctx.user?.employees_name || '', }, // ===== 阶段二:同步成功后在 onSuccess 内开启事务写入库存 ===== onSuccess: async eo => { const transaction = await ctx.model.transaction(); try { const processedStockIds = new Set(); // 查询 pending 绑定:entry_item_id → 收货明细ID(从 InboundDirectLog 查) const entryItemIds = entryItems.map(ei => ei.id); const pendingBindings = await ctx.model.InboundDirectLog.findAll({ where: { entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, receiving_detail_id: { [app.Sequelize.Op.ne]: null }, status: 'pending', deleted_at: null, }, attributes: [ 'id', 'entry_item_id', 'receiving_detail_id' ], raw: true, }); // 查收货明细详情,构建 entry_item_id → 明细信息 的映射 const detailIds = [ ...new Set(pendingBindings.map(b => b.receiving_detail_id)) ]; const bindingDetailMap = new Map(); if (detailIds.length > 0) { const details = await ctx.model.ReceivingDetail.findAll({ where: { id: detailIds }, attributes: [ 'id', 'receiving_id', 'batch_number', 'production_date', 'expiry_date', 'actual_quantity' ], raw: true, }); const detailById = new Map(details.map(d => [ d.id, d ])); for (const b of pendingBindings) { const d = detailById.get(b.receiving_detail_id); if (!d) continue; // 多条绑定取最后一条明细信息,用于批次/生产日期/到期日期等展示字段 bindingDetailMap.set(b.entry_item_id, d); } } // 按 entry_item_id 汇总 wms_inbound_direct_log 的入库数量 const itemDirectLogQtyMap = {}; for (const log of directLogs) { if (log.entry_item_id) { const itemKey = String(log.entry_item_id); if (!itemDirectLogQtyMap[itemKey]) itemDirectLogQtyMap[itemKey] = 0; itemDirectLogQtyMap[itemKey] += Number(log.quantity); } } // 逐商品写入库存 // 非绑定模式下同一 stock_id 可能对应多个 entryItem,按顺序: // 第一个 entryItem 写库存和 received_quantity,后续同 stock_id 的 entryItem 仅写 received_quantity=0 const nonBindingStockProcessed = new Set(); for (const item of entryItems) { const stockId = item.stock_id; if (!stockId) continue; // 按 entry_item 维度获取该明细的直接入库汇总数量 const itemDirectQty = itemDirectLogQtyMap[String(item.id)] || 0; const isBinding = itemDirectQty > 0; const inboundQty = isBinding ? itemDirectQty : (stockSummary[String(stockId)] || 0); if (inboundQty <= 0) continue; // 判断是否为绑定模式:比较收货明细数量合计与入库记录数量 const bindInfo = bindingDetailMap.get(item.id); let itemReceivedQty = inboundQty; if (bindInfo) { // 绑定模式下 received_quantity 与库存流水保持一致: // 统一按实际入库记录量(inboundQty,绑定模式下即 itemDirectQty)写入, // 不再因收货明细 actual_quantity 较小而缩减 itemReceivedQty = inboundQty; } // 非绑定模式:同一 stock_id 只对第一个 entryItem 写入 received_quantity,后续写 0 if (!isBinding && nonBindingStockProcessed.has(String(stockId))) { itemReceivedQty = 0; } // 更新入库明细的 received_quantity await ctx.model.EntryItems.update({ received_quantity: itemReceivedQty, }, { where: { id: item.id }, transaction, }); // 同一 stock_id 只写一次 StockWarehouse 总库存(聚合量),但 Storage 按入库记录逐条写入 const isStockWarehouseDone = processedStockIds.has(String(stockId)); if (isStockWarehouseDone && !isBinding) { // 非绑定模式:StockWarehouse 已写但 Storage 还未写,不能 continue,继续写 Storage } else if (isStockWarehouseDone) { continue; } if (!isStockWarehouseDone) { processedStockIds.add(String(stockId)); if (!isBinding) { nonBindingStockProcessed.add(String(stockId)); } } // 使用入库单号作为批次号;若有收货绑定则使用收货明细信息 const rdReceivingId = bindInfo ? bindInfo.receiving_id : null; const effectiveBatchNo = bindInfo?.batch_number || eo.entry_order_code; const rdProductionDate = bindInfo?.production_date || null; const rdExpiryDate = bindInfo?.expiry_date || null; const batchNo = eo.entry_order_code; const inventoryType = item.inventory_type || 'ZP'; // StockWarehouse 总库存:每个 stock_id 聚合写入一次 if (!isStockWarehouseDone) { // 锁定并更新 StockWarehouse 总库存 const stockRecord = await ctx.model.StockWarehouse.findOne({ where: { id: stockId, is_valid: 'Y', deleted_at: null }, lock: transaction.LOCK.UPDATE, transaction, }); if (!stockRecord) { throw new Error(`商品库存记录不存在或已失效,无法入库: stock_id=${stockId}`); } const beforeQuantity = Number(stockRecord.quantity) || 0; const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true }); await stockRecord.reload({ transaction }); // 负库存回填:按 SW 非负增量冲销 GAP 补建行挂账(平账,拦截锁定回归真实数据) if (beforeQuantity <= 0) { const nonNegativeDelta = Math.max(0, Number(stockRecord.quantity) || 0) - Math.max(0, beforeQuantity); await ctx.service.systems.storage.index.offsetGapOnInbound(stockId, inboundQty, { transaction, maxOffset: nonNegativeDelta, orderNo: eo.entry_order_code || 'DIRECT_INBOUND', orderId: eo.id, operatorId: String(ctx.user?.employees_id || ctx.user?.id || ''), operatorName: ctx.user?.employees_name || '', }); } const afterQuantity = Number(stockRecord.quantity) || 0; const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; // 写入库存流水(聚合维度) await ctx.service.systems.stockTransaction.create({ transaction_type: 'INBOUND', warehouse_id: warehouseId, store_id: storeId, stock_id: stockId, quantity: inboundQty, batch_no: batchNo, inventory_type: inventoryType, order_type: eo.order_type, order_no: eo.entry_order_code, entry_order_id: eo.id, operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), operator_name: ctx.user?.employees_name || '', remark: '导入/PDA直接入库提交', before_quantity: beforeQuantity, after_quantity: afterQuantity, before_locked_quantity: beforeLockedQuantity, after_locked_quantity: afterLockedQuantity, created_at: new Date(), }, { transaction }); } /** * 写入 Storage 库位库存 + storage_transaction 的通用函数 * @param {number} spaceId 库位ID * @param {number} qty 入库数量 * @param {number|null} rdId 收货单ID * @param {string|null} prodDate 生产日期 * @param {string|null} expDate 到期日期 */ const writeStorageRecord = async (spaceId, qty, rdId, prodDate, expDate) => { if (qty <= 0) return; const sRecord = await ctx.model.Storage.findOne({ where: { space_id: spaceId, stock_id: stockId, batch_no: effectiveBatchNo, inventory_type: inventoryType, is_enabled: 1, delete_at: null, }, lock: transaction.LOCK.UPDATE, transaction, }); let sId = null; let sBeforeQty = 0; let sAfterQty = 0; let sBeforeLockedQty = 0; let sAfterLockedQty = 0; let sBeforeInterceptQty = 0; let sAfterInterceptQty = 0; if (sRecord) { if (Number(sRecord.stock_id) !== Number(stockId)) { throw new Error( `入库库存归属冲突: storage_id=${sRecord.id} 当前 stock_id=${sRecord.stock_id}, ` + `本次入库 stock_id=${stockId}, space_id=${spaceId}, batch_no=${effectiveBatchNo}` ); } sBeforeQty = Number(sRecord.quantity) || 0; sAfterQty = sBeforeQty + qty; sBeforeLockedQty = Number(sRecord.locked_quantity) || 0; sAfterLockedQty = sBeforeLockedQty; sBeforeInterceptQty = Number(sRecord.intercept_locked_quantity) || 0; sAfterInterceptQty = sBeforeInterceptQty; await ctx.model.Storage.update({ quantity: app.Sequelize.literal(`quantity + ${qty}`), available_quantity: app.Sequelize.literal(`available_quantity + ${qty}`), entry_order_id: eo.id, inbound_time: new Date(), inbound_order_no: eo.entry_order_code, production_date: prodDate, expiry_date: expDate, receiving_id: rdId, updated_at: new Date(), }, { where: { id: sRecord.id }, transaction, }); sId = sRecord.id; } else { sBeforeQty = 0; sAfterQty = qty; sBeforeLockedQty = 0; sAfterLockedQty = 0; const createdStorage = await ctx.model.Storage.create({ warehouse_id: warehouseId, store_id: storeId, space_id: spaceId, stock_id: stockId, batch_no: effectiveBatchNo, inventory_type: inventoryType, quantity: qty, locked_quantity: 0, available_quantity: qty, inbound_time: new Date(), inbound_order_no: eo.entry_order_code, receiving_id: rdId, entry_order_id: eo.id, supplier_id: null, supplier_batch_no: null, production_date: prodDate, expiry_date: expDate, is_enabled: 1, created_at: new Date(), updated_at: new Date(), }, { transaction }); sId = createdStorage.id; } // 写入库位维度库存流水 await ctx.model.StorageTransaction.create({ transaction_type: 'INBOUND', warehouse_id: warehouseId, store_id: storeId, stock_id: stockId, storage_id: sId, space_id: spaceId, quantity: qty, before_quantity: sBeforeQty, after_quantity: sAfterQty, before_locked_quantity: sBeforeLockedQty, after_locked_quantity: sAfterLockedQty, before_intercept_locked_quantity: sBeforeInterceptQty, after_intercept_locked_quantity: sAfterInterceptQty, batch_no: effectiveBatchNo, inventory_type: inventoryType, order_type: 'entry_order', order_no: eo.entry_order_code, order_id: eo.id, operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), operator_name: ctx.user?.employees_name || '', remark: '导入/PDA直接入库提交', created_at: new Date(), }, { transaction }); }; if (isBinding) { // 绑定模式:按 entryItem 维度写 Storage(与收货明细绑定,space_id 取第一条入库记录的库位) const logForSpace = directLogs.find(l => String(l.stock_id) === String(stockId) && l.space_id); const spaceId = logForSpace ? Number(logForSpace.space_id) : 1; await writeStorageRecord(spaceId, inboundQty, rdReceivingId, rdProductionDate, rdExpiryDate); } else { // 非绑定模式:按每个 InboundDirectLog 记录独立写 Storage,每条记录保有自己指定的 space_id 和 quantity const stockDirectLogs = directLogs.filter(l => String(l.stock_id) === String(stockId) && Number(l.quantity) > 0); for (const dlog of stockDirectLogs) { const dlogSpaceId = dlog.space_id || 1; const dlogQty = Number(dlog.quantity) || 0; await writeStorageRecord(dlogSpaceId, dlogQty, null, null, null); } } } // 将 pending 绑定升级为 committed(在 InboundDirectLog 中更新状态) if (pendingBindings.length > 0) { await ctx.model.InboundDirectLog.update( { status: 'committed', updated_at: new Date() }, { where: { id: pendingBindings.map(b => b.id) }, transaction } ); } // 回写收货单和收货明细的入库状态(绑定模式:按 receiving_detail_id 优先扣减) await this._syncReceivingStorageStatus({ entryItemIds, transaction, entryOrderId: eo.id }); // 非绑定模式剩余导入量:按 stock_id 匹配绑定收货单明细占用(绑定模式优先,剩余兜底) await this._applyReceivingStockOccupancy({ entryOrder: eo, directLogs, transaction }); // 更新入库单状态为 COMPLETED await eo.update({ order_status: 'COMPLETED', sync_status: 'SUCCESS', sync_message: JSON.stringify({ completedAt: new Date(), totalQuantity: Object.values(stockSummary).reduce((s, q) => s + q, 0), itemCount: processedStockIds.size, source: 'direct_inbound', }), updated_at: new Date(), }, { transaction }); // 记录操作日志(事务内) const totalQty = Object.values(stockSummary).reduce((s, q) => s + q, 0); await ctx.service.systems.operationLog.createOperationLog({ businessType: 'entry_order', businessId: eo.id, operationCode: 'DIRECT_INBOUND_COMMIT', operator: { id: ctx.user?.employees_id || ctx.user?.id, name: ctx.user?.employees_name || '', }, extras: { warehouseId: eo.warehouse_id, message: `导入/PDA入库提交完成,共 ${processedStockIds.size} 种商品,总数量 ${totalQty}`, }, transaction, }); await transaction.commit(); // 入库完成通知货主(失败不影响主流程);noNeedNotice=1 时跳过通知 if (Number(noNeedNotice) !== 1) { try { await this.notifyEntryOrderCompleted(eo); } catch (noticeErr) { ctx.logger.warn('[inbound_direct_log.commit] 入库完成通知货主失败,不影响业务', noticeErr); } } } catch (error) { if (transaction && typeof transaction.rollback === 'function') { await transaction.rollback(); } throw error; } }, }); if (!syncResult.success) { ctx.logger.warn(`[InboundDirectLog] commit 同步失败 entryOrderId=${entryOrder.id}: ${syncResult.message}`); return { code: 500, message: syncResult.message, data: { id: entryOrder.id, entry_order_code: entryOrder.entry_order_code, sync_status: 'FAILED', }, }; } return { code: 200, message: '入库完成', data: { id: entryOrder.id, entry_order_code: entryOrder.entry_order_code, order_status: 'COMPLETED', sync_status: 'SUCCESS', items_count: entryItems.length, total_quantity: Object.values(stockSummary).reduce((s, q) => s + q, 0), }, }; } /** * 发送入库单完成入库通知(entry_order_completed)。 * 文案格式: * 首行「入库单号{入库单号}」; * 明细行「{商品名称} {商家编码} {规格} 数量:{数量}」,行间以「---」分隔; * 末尾行「已入库完毕」。 * 明细通过入库单ID查询 wms_entry_items 及关联商品数据,仅展示已入库数量大于 0 的行。 * 路由由 notice 固定订阅回退链处理:货主收货群 → 无则货主售后群 → 均无则仓库异常群。 * 通知失败不影响入库主流程(由调用方 try/catch 包裹)。 * @param {Object} entryOrder 入库单快照(含 id / entry_order_code / warehouse_id / store_id) * @return {Promise} 通知发送结果,通知服务不可用或参数不完整时返回 null */ async notifyEntryOrderCompleted(entryOrder = {}) { const { ctx } = this; const { id = null, entry_order_code: entryOrderCodeRaw = '', warehouse_id: warehouseIdRaw = 0, store_id: storeIdRaw = 0, } = entryOrder || {}; const rawNoticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice; const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function' ? rawNoticeService : (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function' ? rawNoticeService.index : null); if (!noticeService) return null; const warehouseId = Number(warehouseIdRaw || (ctx.user && ctx.user.store_id) || 0); const storeId = Number(storeIdRaw || 0); if (!Number.isFinite(warehouseId) || warehouseId <= 0 || !Number.isFinite(storeId) || storeId <= 0) { return null; } const entryOrderCode = String(entryOrderCodeRaw || id || '').trim(); if (!entryOrderCode) return null; // 组装明细文案:明细查询失败时降级为无明细行,仍发送首行 + 结尾行,保证通知可达 let detailLines = []; try { const completedItems = await this._queryCompletedEntryItems(id); detailLines = this._buildCompletedItemLines(completedItems); } catch (detailErr) { ctx.logger.warn('[inbound_direct_log.notifyEntryOrderCompleted] 查询入库明细失败,通知降级为不含明细文案', detailErr); } const contentLines = [ `入库单号${entryOrderCode}` ]; for (let i = 0; i < detailLines.length; i++) { contentLines.push(` ${detailLines[i]}`); if (i < detailLines.length - 1) contentLines.push('---'); } contentLines.push(' 已入库完毕'); const content = contentLines.join('\n'); return await noticeService.send({ warehouseId, storeId, messageType: 'text', businessName: 'entry_order', event: 'entry_order_completed', channel: 'warehouse', title: `入库单${entryOrderCode}已完成入库`, content, storeContent: content, businessId: id, subject: { id: warehouseId, type: 'warehouse', name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''), }, sender: { id: (ctx.user && (ctx.user.employees_id || ctx.user.id)) || null, name: (ctx.user && ctx.user.employees_name) || '', }, metadata: { entryOrderId: id, entryOrderCode, warehouseId, storeId, }, }); } /** * 查询入库单明细(含商品资料),用于组装完成入库通知文案。 * 复用 EntryItems → StockWarehouse 的既有模型关联,不直接写 SQL。 * @param {number} entryOrderId 入库单ID * @return {Promise>} 入库明细列表(含 stock 关联数据),入参无效时返回空数组 */ async _queryCompletedEntryItems(entryOrderId) { const { ctx } = this; const orderId = Number(entryOrderId || 0); if (!Number.isFinite(orderId) || orderId <= 0) return []; return await ctx.model.EntryItems.findAll({ where: { order_id: orderId }, include: [ { model: ctx.model.StockWarehouse, as: 'stock', required: false, attributes: [ 'id', 'item_name', 'sku_property' ], }, ], order: [[ 'order_line_no', 'ASC' ]], }); } /** * 将入库明细组装为通知文案明细行。 * 每行格式:{商品名称} {商家编码} {规格} 数量:{数量}, * 仅展示已入库数量(received_quantity)大于 0 的明细行。 * 字段来源:商品名称=stock.item_name、商家编码=item.item_code、规格=stock.sku_property、数量=item.received_quantity。 * @param {Array} entryItems 入库明细列表(含 stock 关联数据) * @return {Array} 通知文案明细行列表 */ _buildCompletedItemLines(entryItems = []) { const lines = []; for (const item of entryItems || []) { const inboundQty = Number(item.received_quantity) || 0; if (inboundQty <= 0) continue; const stock = item.stock || {}; const itemName = String(stock.item_name || '').trim(); const merchantCode = String(item.item_code || '').trim(); const skuProperty = String(stock.sku_property || '').trim(); lines.push(`${itemName} ${merchantCode} ${skuProperty} 数量:${inboundQty}`); } return lines; } /** * 组装 entryorder.confirm 业务报文(与奇门 taobao.qimen.entryorder.confirm 同层级)。 * 返回 { entryOrder, orderLines },不包含外层 request 包装, * 字段与取值逻辑以奇门分支为唯一基准,奇门与 OpenAPI 回传共用。 * @param {Object} entryOrder 入库单对象 * @param {Array} orderLines 入库明细行数组 * @param {Object} [options] 可选配置 * @param {string} [options.outBizCode] 外部业务编码,缺省时自动生成 DIRECT_INBOUND_时间戳 * @param {boolean} [options.isFin=true] 是否最终确认(confirmType 0=最终 / 1=部分,status FULFILLED / PARTFULFILLED) * @param {string} [options.remark] 备注 * @return {{ entryOrder: Object, orderLines: Array }} 组装后的业务报文 */ buildEntryOrderConfirmRequest(entryOrder, orderLines, options = {}) { const { app } = this; const { outBizCode, isFin = true, remark } = options; return { entryOrder: { entryOrderCode: entryOrder.entry_order_code, ownerCode: entryOrder.qimen_owner_code || '', warehouseCode: entryOrder.qimen_warehouse_code || '', entryOrderId: entryOrder.id, entryOrderType: entryOrder.order_type, outBizCode: outBizCode || `DIRECT_INBOUND_${Date.now()}`, confirmType: isFin ? 0 : 1, status: isFin ? 'FULFILLED' : 'PARTFULFILLED', freight: 0, operateTime: app.formatDate(new Date()), remark: remark || '', }, orderLines, }; } /** * OpenAPI 回传:查询 ApiApp 回调地址并 POST 回传。 * 报文体与奇门同层级({ request: { entryOrder, orderLines } },外层 request 由发送端自动包裹), * 与奇门分支共用 buildEntryOrderConfirmRequest 组装。 * @param {Object} entryOrder 入库单 * @param {Object} [options] 可选配置 * @param {Object} options.request 奇门同层级业务报文 { entryOrder, orderLines }(由 buildEntryOrderConfirmRequest 组装) * @param {boolean} [options.throwOnError=false] 失败时是否向外抛出异常 * @return {Promise} 返回回传结果 { success, error?, statusCode?, body? },异常时返回 null */ async _sendOpenApiCallback(entryOrder, options = {}) { const { ctx, app } = this; const { request, throwOnError = false } = options; try { const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ where: { store_id: entryOrder.store_id, warehouse_id: entryOrder.warehouse_id, auth_status: 2, }, attributes: [ 'id' ], raw: true, }); if (!storeWarehouse) { const warnMsg = `[InboundDirectLog] OpenAPI回传:未找到授权关系 entryOrderId=${entryOrder.id}`; ctx.logger.warn(warnMsg); console.log('[quickInbound] _sendOpenApiCallback 最终返回:', { success: false, error: '未找到授权关系' }); if (throwOnError) { throw new Error(warnMsg); } return null; } const apiApp = await ctx.model.ApiApp.findOne({ where: { contract_id: storeWarehouse.id, is_enabled: 1, callback_url: { [ app.Sequelize.Op.and ]: [ { [ app.Sequelize.Op.ne ]: null }, { [ app.Sequelize.Op.ne ]: '' }, ], }, }, attributes: [ 'self_app_key', 'self_app_secret', 'callback_url' ], raw: true, }); if (!apiApp || !apiApp.callback_url) { const warnMsg = `[InboundDirectLog] OpenAPI回传:未找到有效ApiApp配置 entryOrderId=${entryOrder.id}`; ctx.logger.warn(warnMsg); console.log('[quickInbound] _sendOpenApiCallback 最终返回:', { success: false, error: '未找到ApiApp配置' }); if (throwOnError) { throw new Error(warnMsg); } return null; } console.log('[quickInbound] _sendOpenApiCallback 发送前:', { entryOrderId: entryOrder.id, callbackUrl: apiApp.callback_url, appKey: apiApp.self_app_key, request, }); const result = await ctx.service.openapi.callback.sendWithRetry({ callbackUrl: apiApp.callback_url, appKey: apiApp.self_app_key, selfAppSecret: apiApp.self_app_secret || '', event: 'entryorder.confirm', request, }); console.log('[quickInbound] _sendOpenApiCallback 响应:', { entryOrderId: entryOrder.id, success: result?.success, statusCode: result?.statusCode, error: result?.error, body: typeof result?.body === 'string' ? result.body.substring(0, 500) : JSON.stringify(result?.body || {}).substring(0, 500), }); if (result.success) { ctx.logger.info( `[InboundDirectLog] OpenAPI回传成功 entryOrderId=${entryOrder.id} ` + `callbackUrl=${apiApp.callback_url}` ); } else { const failMsg = `[InboundDirectLog] OpenAPI回传失败 entryOrderId=${entryOrder.id} error=${result.error}`; ctx.logger.warn(failMsg); if (throwOnError) { throw new Error(failMsg); } } console.log('[quickInbound] _sendOpenApiCallback 最终返回:', result); return result; } catch (error) { ctx.logger.error(`[InboundDirectLog] OpenAPI回传异常: ${error.message}`, error.stack); console.log('[quickInbound] _sendOpenApiCallback 最终返回 (异常):', { success: false, error: error.message }); if (throwOnError) { throw error; } return null; } } /** * 奇门入库同步(统一入口)。 * 先发奇门 entryorder.confirm 请求,成功才执行本地回调,失败则写操作日志并返回失败。 * * @param {Object} params 参数对象 * @param {Object} params.entryOrder - 入库单完整对象(EntryOrder model instance) * @param {Array} params.orderLines - 明细行数组 [{ orderLineNo, ownerCode, itemCode, itemId, inventoryType, planQty, actualQty }] * @param {string} params.outBizCode - 外部业务编码(如 DIRECT_INBOUND_xxx) * @param {string} params.remark - 备注(如 "导入/PDA直接入库提交") * @param {boolean} [params.isFin=true] - 是否最终确认(confirmType: 0=最终, 1=部分) * @param {Function} params.onSuccess - 同步成功后执行的回调(接收 entryOrder),在独立事务中执行,应包含业务写库 + operationLog(QUICK_INBOUND) * @param {Object} params.operator - 操作人 { id, name },用于 operationLog * @return {Promise} { success: boolean, message: string, data?: any } */ async qimenEntrySync(params) { const { ctx, app } = this; const { entryOrder, orderLines, outBizCode, remark, isFin = true, onSuccess, operator, } = params; console.log('[qimenEntrySync] 进入:', { entryOrderId: entryOrder?.id, entryOrderCode: entryOrder?.entry_order_code, sourceType: entryOrder?.source_type, orderLinesCount: orderLines?.length, isFin, }); // 1. 校验 if (!orderLines || orderLines.length === 0) { console.log('[qimenEntrySync] 最终判定: failure (行不能为空)'); return { success: false, message: '行不能为空' }; } // 2. 按来源类型分别处理 const sourceType = String(entryOrder.source_type || '').toUpperCase(); if (sourceType !== 'QM' && sourceType !== 'API') { const skipMsg = `来源类型 ${sourceType} 不支持回传`; console.log(`[qimenEntrySync] 最终判定: 跳过 (${skipMsg})`); ctx.logger.info(`[qimenEntrySync] ${skipMsg} entryOrderId=${entryOrder.id}`); // 不需要回传的来源类型,直接执行回调 if (onSuccess) { await onSuccess(entryOrder); } return { success: true, message: `无需同步,来源类型: ${sourceType}` }; } // 3. 构造 queryData 并发请求(事务外) if (sourceType === 'QM') { const queryData = { request: this.buildEntryOrderConfirmRequest(entryOrder, orderLines, { outBizCode, remark, isFin, }), }; console.log('[qimenEntrySync] 奇门请求发送前:', { entryOrderId: entryOrder.id, api: 'taobao.qimen.entryorder.confirm', ownerCode: entryOrder.qimen_owner_code, queryData, }); let qimenResult; try { const result = await app.qimenClient.send( 'taobao.qimen.entryorder.confirm', entryOrder.qimen_owner_code, queryData, { ctx } ); qimenResult = result?.xmlArray?.response; } catch (err) { qimenResult = { flag: 'error', code: '-1', message: err.message }; } console.log('[qimenEntrySync] 奇门响应:', { entryOrderId: entryOrder.id, flag: qimenResult?.flag, code: qimenResult?.code, message: qimenResult?.message, }); const isQimenSuccess = qimenResult && String(qimenResult.flag) === 'success'; if (!isQimenSuccess) { const failMsg = qimenResult?.message || '奇门同步失败'; console.log(`[qimenEntrySync] 最终判定: failure (${failMsg})`); const txn = await ctx.model.transaction(); try { await entryOrder.update({ sync_status: 'FAILED', sync_message: JSON.stringify({ error: failMsg, errorCode: 'QIMEN_FAILED', errorTime: new Date().toISOString(), source: 'qimenEntrySync', }), updated_at: new Date(), }, { transaction: txn }); await ctx.service.systems.operationLog.createOperationLog({ businessType: 'entry_order', businessId: entryOrder.id, operationCode: 'QUICK_INBOUND_FAILED', operator: operator || {}, extras: { warehouseId: entryOrder.warehouse_id, message: failMsg }, transaction: txn, }); await txn.commit(); } catch (e) { await txn.rollback(); ctx.logger.error(`[qimenEntrySync] 失败日志写入异常: ${e.message}`); } return { success: false, message: failMsg }; } // 4. 成功:执行回调 ctx.logger.info(`[qimenEntrySync] 奇门回传成功 entryOrderId=${entryOrder.id}`); console.log('[qimenEntrySync] 最终判定: success'); if (onSuccess) { await onSuccess(entryOrder); } return { success: true, message: '同步成功' }; } // API 来源:调用 OpenAPI 回传 if (sourceType === 'API') { console.log('[qimenEntrySync] OpenAPI 回传开始:', { entryOrderId: entryOrder.id, }); let apiResult; try { apiResult = await this._sendOpenApiCallback(entryOrder, { throwOnError: true, request: this.buildEntryOrderConfirmRequest(entryOrder, orderLines, { outBizCode, remark, isFin, }), }); } catch (err) { apiResult = { success: false, error: err.message }; } console.log('[qimenEntrySync] OpenAPI 回传结果:', apiResult); const isApiSuccess = apiResult && apiResult.success === true; if (!isApiSuccess) { const failMsg = apiResult?.error || 'API回传失败'; console.log(`[qimenEntrySync] 最终判定: failure (${failMsg})`); const txn = await ctx.model.transaction(); try { await entryOrder.update({ sync_status: 'FAILED', sync_message: JSON.stringify({ error: failMsg, errorCode: 'API_FAILED', errorTime: new Date().toISOString(), source: 'qimenEntrySync', }), updated_at: new Date(), }, { transaction: txn }); await ctx.service.systems.operationLog.createOperationLog({ businessType: 'entry_order', businessId: entryOrder.id, operationCode: 'QUICK_INBOUND_FAILED', operator: operator || {}, extras: { warehouseId: entryOrder.warehouse_id, message: failMsg }, transaction: txn, }); await txn.commit(); } catch (e) { await txn.rollback(); ctx.logger.error(`[qimenEntrySync] API失败日志写入异常: ${e.message}`); } return { success: false, message: failMsg }; } ctx.logger.info(`[qimenEntrySync] OpenAPI回传成功 entryOrderId=${entryOrder.id}`); console.log('[qimenEntrySync] 最终判定: success (API)'); if (onSuccess) { await onSuccess(entryOrder); } return { success: true, message: '同步成功' }; } } /** * 根据已提交(committed)的入库明细-收货明细绑定,回写收货单及收货明细的入库状态。 * 在事务内执行,读取 committed 绑定并按 receiving_detail_id 汇总。 * * @param {Object} params 参数 * @param {number[]} params.entryItemIds 当前入库单的所有明细 ID 列表 * @param {Object} params.transaction Sequelize 事务对象 * @param {number} [params.entryOrderId] 入库单 ID(用于同步数量台账) * @return {Promise} */ async _syncReceivingStorageStatus({ entryItemIds, transaction, entryOrderId = null }) { const { ctx, app } = this; // 查询所有 committed 状态的绑定记录(从 InboundDirectLog 中筛选有 receiving_detail_id 的记录) const committedBindings = await ctx.model.InboundDirectLog.findAll({ where: { entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, receiving_detail_id: { [app.Sequelize.Op.ne]: null }, status: 'committed', deleted_at: null, }, attributes: [ 'receiving_detail_id', 'quantity' ], raw: true, transaction, }); if (!committedBindings || committedBindings.length === 0) { return; } // 按 receiving_detail_id 汇总 quantity const detailQuantityMap = new Map(); for (const b of committedBindings) { const detailId = b.receiving_detail_id; const qty = Number(b.quantity) || 0; detailQuantityMap.set(detailId, (detailQuantityMap.get(detailId) || 0) + qty); } const detailIds = [ ...detailQuantityMap.keys() ]; // 查询收货明细(含 actual_quantity 和 receiving_id) const details = await ctx.model.ReceivingDetail.findAll({ where: { id: detailIds }, attributes: [ 'id', 'receiving_id', 'actual_quantity', 'stored_quantity', 'storage_status' ], raw: true, transaction, }); if (!details.length) { return; } // 逐条计算并更新收货明细 const receivingIdSet = new Set(); const ledgerQuantityMap = new Map(); for (const detail of details) { const storedQuantity = detailQuantityMap.get(detail.id) || 0; const actualQuantity = Number(detail.actual_quantity) || 0; const storageStatus = storedQuantity >= actualQuantity ? 'all' : (storedQuantity > 0 ? 'partial' : 'none'); receivingIdSet.add(detail.receiving_id); await ctx.model.ReceivingDetail.update( { stored_quantity: storedQuantity, storage_status: storageStatus, updated_at: new Date(), }, { where: { id: detail.id }, transaction, } ); // 台账覆盖条目:绑定模式对收货明细为直接覆写语义 ledgerQuantityMap.set(detail.id, { receivingId: Number(detail.receiving_id), quantity: storedQuantity, }); } // 按收货单汇总,更新 wms_receiving.storage_status const receivingIds = [ ...receivingIdSet ]; if (receivingIds.length === 0) { return; } // 重新查询该收货单下所有明细的 storage_status,汇总主表状态 const allDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: receivingIds }, attributes: [ 'receiving_id', 'storage_status' ], raw: true, transaction, group: [ 'receiving_id', 'storage_status' ], }); // 按 receiving_id 分组 const receivingDetailStatusMap = new Map(); for (const d of allDetails) { const rid = d.receiving_id; if (!receivingDetailStatusMap.has(rid)) { receivingDetailStatusMap.set(rid, new Set()); } receivingDetailStatusMap.get(rid).add(d.storage_status); } for (const [ rid, statusSet ] of receivingDetailStatusMap) { let receivingStorageStatus = 'none'; if (statusSet.has('all') && statusSet.has('partial')) { receivingStorageStatus = 'partial'; } else if (statusSet.has('all')) { if (statusSet.has('none') || statusSet.has('waiting')) { receivingStorageStatus = 'partial'; } else { receivingStorageStatus = 'all'; } } else if (statusSet.has('partial')) { receivingStorageStatus = 'partial'; } await ctx.model.Receiving.update( { storage_status: receivingStorageStatus, updated_at: new Date(), }, { where: { id: rid }, transaction, } ); } // 同步数量台账:绑定模式按 committed 汇总量覆写对应明细条目(保持台账与 stored_quantity 一致) if (entryOrderId && ledgerQuantityMap.size > 0) { await ctx.service.systems.receivingEntryMatch.setLedgerAllocation({ entryOrderId, detailQuantityMap: ledgerQuantityMap, transaction, }); } } /** * 非绑定模式收货单占用:导入记录未携带 receiving_detail_id 时, * 将剩余导入量按 stock_id(=收货明细 system_product_id)匹配到绑定收货单明细上, * 依次占用剩余可入数量(actual_quantity - stored_quantity), * 回写 stored_quantity/storage_status 并汇总收货单主表 storage_status。 * 携带 receiving_detail_id 的导入记录已由 _syncReceivingStorageStatus 优先处理, * 本方法只处理未携带 receiving_detail_id 的剩余部分(必须先调用前者)。 * * @param {Object} params 参数 * @param {Object} params.entryOrder 入库单实例 * @param {Array} params.directLogs 入库单下所有未删除的导入/PDA 入库记录 * @param {Object} params.transaction Sequelize 事务对象 * @return {Promise} */ async _applyReceivingStockOccupancy({ entryOrder, directLogs, transaction }) { const { ctx, app } = this; // 1. 入库单未绑定收货单 → 跳过 const bindings = await ctx.model.EntryOrderReceiving.findAll({ where: { entry_order_id: entryOrder.id, deleted_at: null }, attributes: [ 'receiving_id' ], raw: true, transaction, }); const receivingIds = [ ...new Set((bindings || []).map(b => Number(b.receiving_id)).filter(Boolean)) ]; if (receivingIds.length === 0) return; // 2. 汇总未携带 receiving_detail_id 的导入量(绑定模式已优先处理,这里只取剩余部分) const stockInboundQtyMap = new Map(); for (const log of directLogs) { if (log.receiving_detail_id) continue; const stockId = Number(log.stock_id); const qty = Number(log.quantity) || 0; if (!stockId || qty <= 0) continue; stockInboundQtyMap.set( stockId, { inboundQty: (stockInboundQtyMap.get(stockId)?.inboundQty || 0) + qty } ); } if (stockInboundQtyMap.size === 0) return; // 3. 查询绑定收货单明细(事务内读取,stored_quantity 已包含绑定模式扣减结果) const boundDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: { [app.Sequelize.Op.in]: receivingIds }, system_product_id: { [app.Sequelize.Op.ne]: null }, }, attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity' ], raw: true, transaction, }); if (!boundDetails || boundDetails.length === 0) return; // 4. 复用 storage.entry 的收货单占用逻辑(与 quickInbound 一致,事务内行锁防并发超分) await ctx.service.systems.storage.entry._applyReceivingInboundUsage({ receivingDetailRows: boundDetails, stockInboundQtyMap, transaction, entryOrderId: entryOrder.id, }); ctx.logger.info( `[InboundDirectLog] 非绑定模式导入已按 stock_id 占用收货单明细,entryOrderId=${entryOrder.id}` ); } } module.exports = InboundDirectLogService;