'use strict'; const Service = require('egg').Service; /** @type {number} 收货单缓存过期时间(秒) */ const RECEIVING_CACHE_TTL = 300; /** @type {number} 收货单查询天数范围 */ const RECEIVING_LOOKBACK_DAYS = 3; /** @type {string} 收货单列表缓存键前缀 */ const RECEIVING_CACHE_KEY_PREFIX = 'cache:receiving_orders:warehouse:'; /** * 入库单创建后异步匹配收货单并写入绑定关系服务。 * * 职责: * 1. 缓存仓库下近 3 天的收货单列表(Redis,TTL 300s) * 2. 根据入库单 remark 匹配收货单号 * 3. 对比入库单明细与收货单明细(SKU + 数量) * 4. 匹配成功后写入 wms_entry_order_receiving 绑定关系,CREATED 状态转 PENDING * 5. 覆盖场景标记收货单为"部分入库" */ class ReceivingEntryMatchService extends Service { /** * 入库单创建后的异步匹配入口:根据备注匹配收货单,写入绑定关系并在必要时转换状态。 * 匹配到收货单后写入 wms_entry_order_receiving 绑定关系; * 如果入库单当前状态为 CREATED,同步更新为 PENDING。 * 不阻塞主流程,所有错误仅记录日志。 * * @param {number} entryOrderId 入库单 ID * @return {Promise} */ async matchAfterEntryCompleted(entryOrderId) { const { ctx } = this; try { // 1. 加载入库单及其明细 const entryOrder = await ctx.model.EntryOrder.findOne({ where: { id: entryOrderId, is_enabled: 1, deleted_at: null }, include: [{ model: ctx.model.EntryItems, as: 'items', required: false, attributes: [ 'id', 'item_code', 'stock_id', 'count', 'received_quantity', 'inventory_type' ], }], }); if (!entryOrder) { ctx.logger.warn(`[ReceivingEntryMatch] 入库单不存在,跳过匹配 entryOrderId=${entryOrderId}`); return; } const remark = (entryOrder.remark || '').trim(); if (!remark) { ctx.logger.info(`[ReceivingEntryMatch] 入库单无备注,跳过匹配 entryOrderId=${entryOrderId}`); return; } const warehouseId = entryOrder.warehouse_id; // 2. 获取近 3 天的收货单列表(带缓存) const receivingOrders = await this._getRecentReceivingOrders(warehouseId); if (!receivingOrders || receivingOrders.length === 0) { ctx.logger.info(`[ReceivingEntryMatch] 仓库无近期收货单,跳过匹配 warehouseId=${warehouseId}`); return; } // 3. 从 remark 中提取可能匹配的收货单号 const matchedReceiving = await this._findReceivingByRemark(remark, receivingOrders, warehouseId); if (!matchedReceiving) { ctx.logger.info(`[ReceivingEntryMatch] remark 中未匹配到收货单号 entryOrderId=${entryOrderId} remark="${remark}"`); return; } ctx.logger.info( `[ReceivingEntryMatch] 匹配到收货单 entryOrderId=${entryOrderId} ` + `receivingId=${matchedReceiving.id} receivingNumber=${matchedReceiving.receiving_number}` ); // 4. 对比明细 const entryItems = (entryOrder.items || []).map(item => ({ stockId: item.stock_id, itemCode: item.item_code, count: item.count || 0, receivedQuantity: item.received_quantity || 0, inventoryType: item.inventory_type || 'ZP', })); const comparisonResult = this._compareDetails(entryItems, matchedReceiving.details || []); // 5. 根据对比结果写入绑定关系 if (comparisonResult.type === 'full_match' || comparisonResult.type === 'receiving_covers_entry') { // 匹配成功 → 写入 wms_entry_order_receiving 绑定关系 await this._bindEntryOrderReceiving(entryOrderId, matchedReceiving.id); // 若入库单当前状态是 CREATED,更新为 PENDING if (entryOrder.order_status === 'CREATED') { await ctx.model.EntryOrder.update( { order_status: 'PENDING', updated_at: new Date() }, { where: { id: entryOrderId, order_status: 'CREATED' } } ); ctx.logger.info( `[ReceivingEntryMatch] 入库单状态 CREATED → PENDING entryOrderId=${entryOrderId} ` + `receivingId=${matchedReceiving.id}` ); } // receipting_covers_entry 场景额外标记收货单为部分入库 if (comparisonResult.type === 'receiving_covers_entry') { await this._markReceivingPartialStorage(matchedReceiving.id, comparisonResult, warehouseId); } } else { // 其他情况(entry 有 receiving 没有的明细,或完全不匹配)→ 不做处理 ctx.logger.info( `[ReceivingEntryMatch] 明细对比结果为 ${comparisonResult.type},不触发绑定 ` + `entryOrderId=${entryOrderId} receivingId=${matchedReceiving.id}` ); } } catch (error) { ctx.logger.error( `[ReceivingEntryMatch] 异步匹配异常 entryOrderId=${entryOrderId}: ${error.message}`, error.stack ); } } /** * 写入入库单与收货单的主表级绑定关系。 * 使用 upsert 策略避免重复写入;绑定记录为软删除模型,已删除的历史记录会被恢复。 * * @param {number} entryOrderId 入库单 ID * @param {number} receivingId 收货单 ID * @return {Promise} */ async _bindEntryOrderReceiving(entryOrderId, receivingId) { const { ctx } = this; try { // 先检查是否已存在未删除的绑定记录 const existing = await ctx.model.EntryOrderReceiving.findOne({ where: { entry_order_id: entryOrderId, receiving_id: receivingId }, paranoid: false, }); if (existing) { if (existing.deleted_at) { // 已软删除的记录,恢复它 await existing.restore(); ctx.logger.info( `[ReceivingEntryMatch] 恢复已删除的绑定关系 entryOrderId=${entryOrderId} receivingId=${receivingId}` ); } else { ctx.logger.info( `[ReceivingEntryMatch] 绑定关系已存在,跳过 entryOrderId=${entryOrderId} receivingId=${receivingId}` ); } return; } await ctx.model.EntryOrderReceiving.create({ entry_order_id: entryOrderId, receiving_id: receivingId, }); ctx.logger.info( `[ReceivingEntryMatch] 写入绑定关系成功 entryOrderId=${entryOrderId} receivingId=${receivingId}` ); } catch (error) { // 唯一索引冲突时忽略(并发场景) if (error.name === 'SequelizeUniqueConstraintError') { ctx.logger.warn( `[ReceivingEntryMatch] 绑定关系已存在(并发写入) entryOrderId=${entryOrderId} receivingId=${receivingId}` ); return; } ctx.logger.error( `[ReceivingEntryMatch] 写入绑定关系失败 entryOrderId=${entryOrderId} receivingId=${receivingId}: ${error.message}`, error.stack ); } } /** * 写入入库单与收货单的主表级绑定关系(仅主表绑定,不做明细分配)。 * * 流程: * 1. 校验入库单状态 = CREATED * 2. 校验每个收货单:存在、同仓库、同货主、已审核、未取消 * 3. 逐条写入 EntryOrderReceiving.findOrCreate(主表绑定) * * @param {Object} data 请求参数 * @param {number} data.entry_order_id 入库单 ID * @param {number[]} data.receiving_ids 收货单 ID 列表 * @param {number} [data.creator_id] 操作人 ID(可选) * @return {Promise} 绑定结果,含 bound、skipped、summary */ async bindEntryOrderReceiving(data = {}) { const { ctx } = this; const { entry_order_id: entryOrderId, receiving_ids: receivingIds, creator_id: creatorId } = data || {}; // 参数校验 if (!entryOrderId) { throw new Error('entry_order_id 不能为空'); } if (!Array.isArray(receivingIds) || receivingIds.length === 0) { throw new Error('receiving_ids 不能为空且必须为数组'); } // ========== 第1步:查询入库单,校验状态 ========== const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId); if (!entryOrder) { throw new Error('入库单不存在'); } // 只允许 CREATED 状态 if (entryOrder.order_status !== 'CREATED') { throw new Error(`入库单状态不允许绑定,当前状态: ${entryOrder.order_status},仅 CREATED 状态可操作`); } const warehouseId = entryOrder.warehouse_id; // ========== 第2步:校验每个收货单的有效性 ========== const validatedReceivings = []; const failedValidations = []; for (const receivingId of receivingIds) { const receiving = await ctx.model.Receiving.findOne({ where: { id: receivingId, is_deleted: false }, attributes: [ 'id', 'receiving_number', 'warehouse_id', 'store_id', 'status', 'is_review' ], }); if (!receiving) { failedValidations.push({ receiving_id: receivingId, error_code: 'RECEIVING_NOT_FOUND', message: '收货单不存在或已删除', }); continue; } if (receiving.warehouse_id !== warehouseId) { failedValidations.push({ receiving_id: receivingId, receiving_number: receiving.receiving_number, error_code: 'WAREHOUSE_MISMATCH', message: `收货单 ${receiving.receiving_number} 与入库单不属于同一仓库`, }); continue; } if (receiving.store_id !== entryOrder.store_id) { failedValidations.push({ receiving_id: receivingId, receiving_number: receiving.receiving_number, error_code: 'OWNER_MISMATCH', message: `收货单 ${receiving.receiving_number} 与入库单货主不一致`, }); continue; } if (receiving.status === 'cancelled') { failedValidations.push({ receiving_id: receivingId, receiving_number: receiving.receiving_number, error_code: 'RECEIVING_CANCELLED', message: `收货单 ${receiving.receiving_number} 已取消`, }); continue; } if (!receiving.is_review) { failedValidations.push({ receiving_id: receivingId, receiving_number: receiving.receiving_number, error_code: 'RECEIVING_NOT_REVIEWED', message: `收货单 ${receiving.receiving_number} 未审核`, }); continue; } validatedReceivings.push(receiving); } // 有校验失败的收货单 → 直接返回失败 if (failedValidations.length > 0) { ctx.logger.info( `[ReceivingEntryMatch] bindEntryOrderReceiving 收货单校验失败 entryOrderId=${entryOrderId} failed=${failedValidations.length}` ); return { bound: [], skipped: [], summary: { bound_count: 0, skipped_count: failedValidations.length }, }; } // ========== 第3步:逐条写入主表绑定关系 ========== const boundResults = []; const skippedResults = []; for (const receiving of validatedReceivings) { try { const [ , created ] = await ctx.model.EntryOrderReceiving.findOrCreate({ where: { entry_order_id: entryOrderId, receiving_id: receiving.id }, defaults: { entry_order_id: entryOrderId, receiving_id: receiving.id }, }); if (created) { ctx.logger.info( `[ReceivingEntryMatch] 主表绑定成功 entryOrderId=${entryOrderId} receivingId=${receiving.id}` ); } else { ctx.logger.info( `[ReceivingEntryMatch] 主表绑定已存在,跳过 entryOrderId=${entryOrderId} receivingId=${receiving.id}` ); } boundResults.push({ receiving_id: receiving.id, receiving_number: receiving.receiving_number, created, }); } catch (error) { ctx.logger.error( `[ReceivingEntryMatch] 主表绑定写入失败 entryOrderId=${entryOrderId} receivingId=${receiving.id}: ${error.message}`, error.stack ); skippedResults.push({ receiving_id: receiving.id, receiving_number: receiving.receiving_number, error_code: 'BINDING_WRITE_FAILED', message: `写入绑定失败: ${error.message}`, }); } } ctx.logger.info( `[ReceivingEntryMatch] bindEntryOrderReceiving 主表绑定完成 entryOrderId=${entryOrderId} bound=${boundResults.length} skipped=${skippedResults.length} creatorId=${creatorId || 'N/A'}` ); return { bound: boundResults, skipped: skippedResults, summary: { bound_count: boundResults.length, skipped_count: skippedResults.length, }, }; } /** * 获取仓库近 3 天的收货单列表(优先从 Redis 缓存读取)。 * * @param {number} warehouseId 仓库 ID * @return {Promise>} 收货单列表(含明细) */ async _getRecentReceivingOrders(warehouseId) { const { ctx, app } = this; const cacheKey = `${RECEIVING_CACHE_KEY_PREFIX}${warehouseId}`; try { // 先尝试从缓存读取 const cached = await app.getCacheAsync(cacheKey); if (cached) { ctx.logger.info(`[ReceivingEntryMatch] 命中收货单缓存 warehouseId=${warehouseId}`); return cached; } } catch (cacheErr) { ctx.logger.warn(`[ReceivingEntryMatch] 读取缓存失败,回退到数据库查询: ${cacheErr.message}`); } // 缓存未命中,从数据库查询 const threeDaysAgo = new Date(Date.now() - RECEIVING_LOOKBACK_DAYS * 24 * 60 * 60 * 1000); const receivingOrders = await ctx.model.Receiving.findAll({ where: { warehouse_id: warehouseId, is_deleted: false, is_review: 1, status: [ 'receiving', 'completed' ], created_at: { [app.Sequelize.Op.gte]: threeDaysAgo }, }, attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ], include: [{ model: ctx.model.ReceivingDetail, as: 'details', required: false, attributes: [ 'id', 'system_product_id', 'product_name', 'actual_quantity', 'storage_status', 'stored_quantity', ], }], order: [[ 'created_at', 'DESC' ]], }); const result = receivingOrders.map(order => { const plain = typeof order.toJSON === 'function' ? order.toJSON() : order; return { id: plain.id, receiving_number: plain.receiving_number, status: plain.status, storage_status: plain.storage_status, details: (plain.details || []).map(d => ({ id: d.id, system_product_id: d.system_product_id, product_name: d.product_name, actual_quantity: d.actual_quantity, storage_status: d.storage_status, stored_quantity: d.stored_quantity || 0, })), }; }); // 写入缓存 try { await app.setCacheAsync(cacheKey, result, RECEIVING_CACHE_TTL); ctx.logger.info(`[ReceivingEntryMatch] 收货单缓存已写入 warehouseId=${warehouseId} count=${result.length}`); } catch (cacheErr) { ctx.logger.warn(`[ReceivingEntryMatch] 写入缓存失败: ${cacheErr.message}`); } return result; } /** * 从入库单备注中查找匹配的收货单号。 * 遍历缓存的收货单号列表,检查 remark 是否包含收货单号。 * 若匹配到多个,返回最近创建的那一个。 * * @param {string} remark 入库单备注 * @param {Array} receivingOrders 收货单列表 * @param {number} warehouseId 仓库 ID * @return {Promise} 匹配到的收货单(含明细),未匹配返回 null */ async _findReceivingByRemark(remark, receivingOrders, warehouseId) { const { ctx } = this; // 按字符串包含匹配 const matchedOrders = []; for (const order of receivingOrders) { if (remark.includes(order.receiving_number)) { matchedOrders.push(order); } } if (matchedOrders.length === 0) { return null; } // 多个匹配时取第一个(列表已按 created_at DESC 排序,即最新) const matched = matchedOrders[0]; // 如果缓存的收货单没有 details(可能为空),重新加载 if (!matched.details || matched.details.length === 0) { const fullOrder = await ctx.model.Receiving.findOne({ where: { id: matched.id, warehouse_id: warehouseId, is_deleted: false, is_review: 1 }, attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ], include: [{ model: ctx.model.ReceivingDetail, as: 'details', required: false, attributes: [ 'id', 'system_product_id', 'product_name', 'actual_quantity', 'storage_status', 'stored_quantity', ], }], }); if (!fullOrder) return null; const plain = typeof fullOrder.toJSON === 'function' ? fullOrder.toJSON() : fullOrder; return { id: plain.id, receiving_number: plain.receiving_number, status: plain.status, storage_status: plain.storage_status, details: (plain.details || []).map(d => ({ id: d.id, system_product_id: d.system_product_id, product_name: d.product_name, actual_quantity: d.actual_quantity, storage_status: d.storage_status, stored_quantity: d.stored_quantity || 0, })), }; } return matched; } /** * 对比入库单明细与收货单明细。 * * 判断规则: * - full_match:两者 SKU 与数量完全一致 * - receiving_covers_entry:收货单包含入库单所有明细(SKU 匹配), * 且收货单至少有一个 SKU 数量多于入库单 * - entry_exceeds_receiving:入库单有收货单没有的 SKU 或数量超出 * - no_match:SKU 完全没有交集 * * @param {Array} entryItems 入库单明细 [{ stockId, itemCode, count, receivedQuantity, inventoryType }] * @param {Array} receivingDetails 收货单明细 [{ id, system_product_id, actual_quantity, ... }] * @return {{ type: string, matchedDetails?: Array, uncoveredDetails?: Array, overageDetails?: Array }} 对比结果对象 */ _compareDetails(entryItems, receivingDetails) { // 构建收货单明细 Map:system_product_id → { actual_quantity, ... } const receivingMap = new Map(); for (const detail of receivingDetails) { const productId = detail.system_product_id; if (!productId) continue; const existing = receivingMap.get(productId); if (existing) { existing.actual_quantity += (detail.actual_quantity || 0); } else { receivingMap.set(productId, { detailId: detail.id, system_product_id: productId, actual_quantity: detail.actual_quantity || 0, stored_quantity: detail.stored_quantity || 0, }); } } // 构建入库单明细 Map:stock_id → { count, receivedQuantity } const entryMap = new Map(); for (const item of entryItems) { const stockId = item.stockId; if (!stockId) continue; const existing = entryMap.get(stockId); if (existing) { existing.count += (item.count || 0); existing.receivedQuantity += (item.receivedQuantity || 0); } else { entryMap.set(stockId, { stockId, itemCode: item.itemCode, count: item.count || 0, receivedQuantity: item.receivedQuantity || 0, inventoryType: item.inventoryType, }); } } if (entryMap.size === 0 || receivingMap.size === 0) { return { type: 'no_match' }; } // 检查入库单每个 SKU 是否在收货单中且数量 ≤ 收货单数量 let allEntryItemsCovered = true; let hasReceivingOverage = false; const matchedDetails = []; // 匹配到的收货单明细 const uncoveredDetails = []; // 入库单中有但收货单没有/不足的 for (const [ stockId, entryItem ] of entryMap) { const receivingItem = receivingMap.get(stockId); if (!receivingItem) { // 入库单有,收货单没有 → 入库单超出 allEntryItemsCovered = false; uncoveredDetails.push({ stockId, itemCode: entryItem.itemCode, entryCount: entryItem.count, receivingCount: 0, reason: 'missing_in_receiving', }); continue; } if (entryItem.count > receivingItem.actual_quantity) { // 入库单数量 > 收货单数量 → 入库单超出 allEntryItemsCovered = false; uncoveredDetails.push({ stockId, itemCode: entryItem.itemCode, entryCount: entryItem.count, receivingCount: receivingItem.actual_quantity, reason: 'entry_exceeds_receiving', }); } else if (entryItem.count < receivingItem.actual_quantity) { // 收货单数量 > 入库单数量 → 存在覆盖余量 hasReceivingOverage = true; matchedDetails.push({ ...receivingItem, entryCount: entryItem.count, overage: receivingItem.actual_quantity - entryItem.count, }); } else { // 数量完全相等 matchedDetails.push({ ...receivingItem, entryCount: entryItem.count, overage: 0, }); } } // 检查收货单是否有入库单没有的 SKU const receivingOnlyItems = []; for (const [ productId ] of receivingMap) { if (!entryMap.has(productId)) { receivingOnlyItems.push(productId); } } if (!allEntryItemsCovered) { return { type: 'entry_exceeds_receiving', uncoveredDetails, receivingOnlyItems, }; } if (hasReceivingOverage || receivingOnlyItems.length > 0) { return { type: 'receiving_covers_entry', matchedDetails, overageDetails: matchedDetails.filter(d => d.overage > 0), receivingOnlyItems, }; } // 所有入库单 SKU 都在收货单中,且数量完全相等,且收货单无额外 SKU return { type: 'full_match', matchedDetails, }; } /** * 根据入库单来源发送回传。 * - QM(奇门)→ 调用奇门入库单确认接口回传 * - API(OpenAPI)→ 查询 ApiApp 回调地址并 POST 回传 * * @param {Object} entryOrder 入库单实例 * @param {Object} receivingOrder 匹配到的收货单 * @param {string} [matchType='auto_match'] 匹配类型标识,手动匹配时传入 'manual_match' * @return {Promise<{success: boolean, sourceType: string, detail: Object}>} 回传结果 */ async _sendCallback(entryOrder, receivingOrder, matchType = 'auto_match') { const { ctx } = this; const sourceType = String(entryOrder.source_type || '').toUpperCase(); ctx.logger.info( `[ReceivingEntryMatch] 准备回传 entryOrderId=${entryOrder.id} ` + `sourceType=${sourceType} receivingNumber=${receivingOrder.receiving_number}` ); if (sourceType === 'QM') { const detail = await this._sendQimenCallback(entryOrder, receivingOrder); return { success: detail.success, sourceType, detail }; } else if (sourceType === 'API') { const detail = await this._sendOpenApiCallback(entryOrder, receivingOrder, matchType); return { success: detail.success, sourceType, detail }; } ctx.logger.info( `[ReceivingEntryMatch] 来源类型 ${sourceType} 不支持回传 entryOrderId=${entryOrder.id}` ); return { success: false, sourceType, detail: { success: false, error: `来源类型 ${sourceType} 不支持回传` } }; } /** * 奇门回传:复用现有奇门入库单确认接口。 * * @param {Object} entryOrder 入库单实例 * @param {Object} receivingOrder 匹配到的收货单 * @return {Promise<{success: boolean, error?: string}>} 回传结果 */ async _sendQimenCallback(entryOrder, receivingOrder) { const { ctx, app } = this; try { // 重新加载入库单明细 const items = await ctx.model.EntryItems.findAll({ where: { order_id: entryOrder.id }, attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code', 'received_quantity' ], raw: true, }); if (!items || items.length === 0) { ctx.logger.warn(`[ReceivingEntryMatch] 奇门回传:入库单无明细 entryOrderId=${entryOrder.id}`); return { success: false, error: '入库单无明细' }; } const orderLines = items.map((item, index) => ({ orderLineNo: index + 1, ownerCode: item.owner_code || '', itemCode: item.item_code || '', itemId: item.item_id || '', inventoryType: item.inventory_type || 'ZP', planQty: item.count || 0, actualQty: item.received_quantity || 0, })); const queryData = { request: { entryOrder: { entryOrderCode: entryOrder.entry_order_code, ownerCode: entryOrder.qimen_owner_code || '', warehouseCode: entryOrder.qimen_warehouse_code || '', entryOrderId: entryOrder.id, entryOrderType: entryOrder.order_type, outBizCode: `RECEIVING_MATCH_${Date.now()}`, confirmType: 0, // 0 = 最终确认 status: 'FULFILLED', freight: 0, operateTime: app.formatDate(new Date()), remark: `匹配收货单${receivingOrder.receiving_number}自动回传`, }, orderLines, }, }; const result = await app.qimenClient.send( 'taobao.qimen.entryorder.confirm', entryOrder.qimen_owner_code, queryData, { ctx } ); const qimenResult = result && result.xmlArray && result.xmlArray.response; if (qimenResult && String(qimenResult.flag) === 'success') { ctx.logger.info( `[ReceivingEntryMatch] 奇门回传成功 entryOrderId=${entryOrder.id} ` + `receivingNumber=${receivingOrder.receiving_number}` ); return { success: true }; } ctx.logger.warn( `[ReceivingEntryMatch] 奇门回传失败 entryOrderId=${entryOrder.id} ` + `message=${qimenResult?.message || '未知错误'}` ); return { success: false, error: qimenResult?.message || '未知错误' }; } catch (error) { ctx.logger.error( `[ReceivingEntryMatch] 奇门回传异常 entryOrderId=${entryOrder.id}: ${error.message}`, error.stack ); return { success: false, error: error.message }; } } /** * OpenAPI 回传:查询 ApiApp 回调地址,通过签名鉴权 POST 回传。 * * @param {Object} entryOrder 入库单实例 * @param {Object} receivingOrder 匹配到的收货单 * @param {string} [matchType='auto_match'] 匹配类型标识 * @return {Promise<{success: boolean, error?: string, retryCount?: number}>} 回传结果 */ async _sendOpenApiCallback(entryOrder, receivingOrder, matchType = 'auto_match') { const { ctx, app } = this; try { // 通过 store_warehouse 查找 ApiApp 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) { ctx.logger.warn( '[ReceivingEntryMatch] OpenAPI回传:未找到授权关系 ' + `entryOrderId=${entryOrder.id} storeId=${entryOrder.store_id} warehouseId=${entryOrder.warehouse_id}` ); return { success: false, error: '未找到授权关系' }; } 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) { ctx.logger.warn( '[ReceivingEntryMatch] OpenAPI回传:未找到有效ApiApp配置 ' + `entryOrderId=${entryOrder.id} contractId=${storeWarehouse.id}` ); return { success: false, error: '未找到有效ApiApp配置' }; } // 构建回传数据 const callbackData = { entryOrderId: entryOrder.id, entryOrderCode: entryOrder.entry_order_code, receivingNumber: receivingOrder.receiving_number, receivingId: receivingOrder.id, matchType, completedAt: new Date().toISOString(), }; // 使用 OpenAPI 回调服务发送 const result = await ctx.service.openapi.callback.sendWithRetry({ callbackUrl: apiApp.callback_url, appKey: apiApp.self_app_key, selfAppSecret: apiApp.self_app_secret || '', event: 'entry_order_receiving_matched', data: callbackData, metadata: { source: 'receiving_entry_match', entryOrderId: entryOrder.id, receivingId: receivingOrder.id, }, }); if (result.success) { ctx.logger.info( `[ReceivingEntryMatch] OpenAPI回传成功 entryOrderId=${entryOrder.id} ` + `callbackUrl=${apiApp.callback_url} retryCount=${result.retryCount}` ); return { success: true, retryCount: result.retryCount }; } ctx.logger.warn( `[ReceivingEntryMatch] OpenAPI回传失败 entryOrderId=${entryOrder.id} ` + `error=${result.error} retryCount=${result.retryCount}` ); return { success: false, error: result.error, retryCount: result.retryCount }; } catch (error) { ctx.logger.error( `[ReceivingEntryMatch] OpenAPI回传异常 entryOrderId=${entryOrder.id}: ${error.message}`, error.stack ); return { success: false, error: error.message }; } } /** * 标记收货单为"部分入库"。 * 更新收货单 storage_status 为 'partial',并更新明细的 storage_status 和 stored_quantity。 * * @param {number} receivingId 收货单 ID * @param {Object} comparisonResult 对比结果 * @param {number} warehouseId 仓库 ID * @return {Promise<{success: boolean, error?: string}>} 标记结果 */ async _markReceivingPartialStorage(receivingId, comparisonResult, warehouseId) { const { ctx } = this; try { const receiving = await ctx.model.Receiving.findOne({ where: { id: receivingId, warehouse_id: warehouseId, is_deleted: false }, }); if (!receiving) { ctx.logger.warn(`[ReceivingEntryMatch] 标记部分入库:收货单不存在 receivingId=${receivingId}`); return { success: false, error: '收货单不存在' }; } // 更新收货单主表的入库状态 await receiving.update({ storage_status: 'partial', updated_at: new Date(), }); // 更新匹配到的明细:标记为"全部入库",stored_quantity = entryCount if (comparisonResult.matchedDetails && comparisonResult.matchedDetails.length > 0) { for (const matched of comparisonResult.matchedDetails) { await ctx.model.ReceivingDetail.update( { storage_status: 'all', stored_quantity: matched.entryCount || matched.actual_quantity || 0, updated_at: new Date(), }, { where: { id: matched.detailId, receiving_id: receivingId } } ); } } // 更新超量明细:标记为"部分入库",stored_quantity = entryCount if (comparisonResult.overageDetails && comparisonResult.overageDetails.length > 0) { for (const overage of comparisonResult.overageDetails) { await ctx.model.ReceivingDetail.update( { storage_status: 'partial', stored_quantity: overage.entryCount || 0, updated_at: new Date(), }, { where: { id: overage.detailId, receiving_id: receivingId } } ); } } ctx.logger.info( `[ReceivingEntryMatch] 收货单已标记为部分入库 receivingId=${receivingId} ` + `receivingNumber=${receiving.receiving_number}` ); return { success: true }; } catch (error) { ctx.logger.error( `[ReceivingEntryMatch] 标记部分入库失败 receivingId=${receivingId}: ${error.message}`, error.stack ); return { success: false, error: error.message }; } } /** * 内部公共方法:在事务中提交单条入库明细-收货明细绑定。 * 包含 FOR UPDATE 行锁、可用量二次校验、绑定写入、主表绑定确保。 * 被 PDA 上架 addItem 流程调用,用于逐条写入明细绑定。 * * @param {Object} params 绑定参数 * @param {number} params.entryItemId 入库单明细 ID * @param {number} params.receivingDetailId 收货单明细 ID * @param {number} params.qty 分配数量 * @param {number} params.expectedSpId 期望的 system_product_id(用于匹配校验,可选) * @param {number} params.entryOrderId 入库单 ID(用于确保主表绑定存在) * @param {Object} params.transaction Sequelize 事务对象 * @throws {Object} 结构化错误对象,包含 error_code、message、detail * @return {Promise} */ async _commitBinding({ entryItemId, receivingDetailId, qty, expectedSpId, entryOrderId, transaction } = {}) { const { ctx } = this; // 1. FOR UPDATE 锁收货明细行 const lockedDetail = await ctx.model.query( `SELECT id, actual_quantity, receiving_id, system_product_id FROM wms_receiving_detail WHERE id = :rdId FOR UPDATE`, { replacements: { rdId: receivingDetailId }, type: ctx.model.QueryTypes.SELECT, transaction, } ); if (!lockedDetail || lockedDetail.length === 0) { throw { error_code: 'RECEIVING_DETAIL_NOT_FOUND', message: '收货明细不存在', detail: { receiving_detail_id: receivingDetailId }, }; } // 2. 校验收货明细与入库商品是否匹配(system_product_id) if (expectedSpId !== undefined && lockedDetail[0].system_product_id !== expectedSpId) { throw { error_code: 'RECEIVING_DETAIL_MISMATCH', message: '收货明细与入库商品不匹配', detail: { entry_item_id: entryItemId, receiving_detail_id: receivingDetailId, expected_sp_id: expectedSpId, actual_sp_id: lockedDetail[0].system_product_id, }, }; } // 3. 查已 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 = 'committed' AND deleted_at IS NULL`, { replacements: { rdId: receivingDetailId }, type: ctx.model.QueryTypes.SELECT, transaction, } ); const availableQty = lockedDetail[0].actual_quantity - Number(allocatedSum[0]?.total || 0); if (qty > availableQty) { throw { error_code: 'INSUFFICIENT_AVAILABLE_QUANTITY', message: '分配数量超出可用量', detail: { available_quantity: availableQty, requested_quantity: qty }, }; } // 4. 获取入库单信息以写入 InboundDirectLog const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId, { transaction }); if (!entryOrder) { throw { error_code: 'ENTRY_ORDER_NOT_FOUND', message: '入库单不存在', detail: { entry_order_id: entryOrderId }, }; } // 5. 写入明细绑定到 InboundDirectLog await ctx.model.InboundDirectLog.create({ warehouse_id: entryOrder.warehouse_id, store_id: entryOrder.store_id, stock_id: expectedSpId || 0, quantity: qty, inbound_type: 'import', entry_order_id: entryOrderId, entry_order_code: entryOrder.entry_order_code, entry_item_id: entryItemId, receiving_detail_id: receivingDetailId, status: 'committed', creator_id: ctx.currentUser?.id || 0, operator_id: ctx.currentUser?.employees_id || ctx.currentUser?.id || null, operator_name: ctx.currentUser?.employees_name || '', }, { transaction }); // 6. 确保主级绑定存在 await ctx.model.EntryOrderReceiving.findOrCreate({ where: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id }, defaults: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id }, transaction, }); } /** * 解除入库单与收货单的绑定关系。 * * 逻辑: * 1. 校验入库单存在,状态必须是 PENDING 或 CREATED(COMPLETED / CANCELLED 不允许解绑) * 2. 逐个收货单: * a. 查 wms_entry_order_receiving 主表绑定是否存在(只查 deleted_at IS NULL) * b. 查 wms_entry_receiving_binding 明细绑定是否存在(status='committed' 且 deleted_at IS NULL) * c. 无明细绑定 → 只软删除主表绑定 * d. 有明细绑定 → 事务中软删除明细绑定 + 软删除主表绑定 * 3. 不回退入库单状态(PENDING 解绑后仍是 PENDING) * * @param {Object} data 请求参数 * @param {number} data.entry_order_id 入库单 ID * @param {number[]} data.receiving_ids 要解除绑定的收货单 ID 列表 * @return {Promise} { success: Array, failed: Array, success_count: number, failed_count: number } */ async unbindEntryOrderReceiving(data = {}) { const { ctx } = this; const { entry_order_id: entryOrderId, receiving_ids: receivingIds } = data || {}; // 参数校验 if (!entryOrderId) { throw new Error('entry_order_id 不能为空'); } if (!Array.isArray(receivingIds) || receivingIds.length === 0) { throw new Error('receiving_ids 不能为空且必须为数组'); } // ---------- 第1步:校验入库单存在且状态允许解绑 ---------- const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId); if (!entryOrder) { return { success: [], failed: receivingIds.map(rid => ({ receiving_id: rid, error_code: 'ENTRY_ORDER_NOT_FOUND', message: '入库单不存在', })), success_count: 0, failed_count: receivingIds.length, }; } // 只允许 PENDING 或 CREATED 状态解绑(COMPLETED / CANCELLED 不允许) if (![ 'CREATED', 'PENDING' ].includes(entryOrder.order_status)) { return { success: [], failed: receivingIds.map(rid => ({ receiving_id: rid, error_code: 'ENTRY_ORDER_STATUS_INVALID', message: `入库单状态不允许解绑,当前状态: ${entryOrder.order_status}`, })), success_count: 0, failed_count: receivingIds.length, }; } // ---------- 第2步:逐个收货单处理解绑 ---------- const success = []; const failed = []; for (const receivingId of receivingIds) { try { // 2a. 查主表绑定是否存在 const mainBinding = await ctx.model.EntryOrderReceiving.findOne({ where: { entry_order_id: entryOrderId, receiving_id: receivingId, deleted_at: null, }, }); if (!mainBinding) { failed.push({ receiving_id: receivingId, error_code: 'BINDING_NOT_FOUND', message: '主表绑定不存在', }); continue; } // 2b. 查明细绑定是否存在(从 InboundDirectLog 查 receiving_detail_id 非空的记录) const detailBindings = await ctx.model.InboundDirectLog.findAll({ where: { entry_order_id: entryOrderId, receiving_detail_id: { [ctx.app.Sequelize.Op.ne]: null }, status: 'committed', deleted_at: null, }, include: [{ model: ctx.model.ReceivingDetail, as: 'receivingDetail', required: true, attributes: [], where: { receiving_id: receivingId }, }], attributes: [ 'id', 'receiving_detail_id', 'quantity' ], }); if (detailBindings.length === 0) { // 2c. 无明细绑定 → 只软删除主表绑定 await mainBinding.destroy(); ctx.logger.info( `[ReceivingEntryMatch] 解绑成功(仅主表) entryOrderId=${entryOrderId} receivingId=${receivingId}` ); success.push({ receiving_id: receivingId, released_detail_count: 0, message: '已解除主表绑定(无明细绑定)', }); } else { // 2d. 有明细绑定 → 事务:软删除明细绑定 + 软删除主表绑定 const detailIds = detailBindings.map(d => d.receiving_detail_id); await ctx.model.transaction(async t => { // 软删除所有明细绑定 for (const binding of detailBindings) { await binding.destroy({ transaction: t }); } // 软删除主表绑定 await mainBinding.destroy({ transaction: t }); }); ctx.logger.info( `[ReceivingEntryMatch] 解绑成功(含明细) entryOrderId=${entryOrderId} ` + `receivingId=${receivingId} detailCount=${detailBindings.length} ` + `detailIds=[${detailIds.join(',')}]` ); success.push({ receiving_id: receivingId, released_detail_ids: detailIds, released_detail_count: detailBindings.length, message: '已解除主表及明细绑定', }); } } catch (error) { ctx.logger.error( `[ReceivingEntryMatch] 解绑异常 entryOrderId=${entryOrderId} ` + `receivingId=${receivingId}: ${error.message}`, error.stack ); failed.push({ receiving_id: receivingId, error_code: 'UNBIND_ERROR', message: `解绑过程异常: ${error.message}`, }); } } return { success, failed, success_count: success.length, failed_count: failed.length }; } } module.exports = ReceivingEntryMatchService;