'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. 覆盖场景标记收货单为"部分入库" * 6. 新建绑定时按来源回传外部系统(奇门 confirm / OpenAPI entryorder.match) */ class ReceivingEntryMatchService extends Service { /** * 入库单创建后的异步匹配入口:根据备注匹配收货单,写入绑定关系并在必要时转换状态。 * 匹配到收货单后写入 wms_entry_order_receiving 绑定关系; * 如果入库单当前状态为 CREATED,同步更新为 PENDING; * 仅在本次确实新建绑定时按来源回传外部系统(奇门 / OpenAPI), * 回传失败仅记录日志,不影响绑定与状态更新结果。 * 不阻塞主流程,所有错误仅记录日志。 * * @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 绑定关系,返回本次是否新建绑定 const bindResult = 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); } // 6. 按来源回传外部系统(奇门 / OpenAPI)。 // 仅当本次确实新建了绑定关系才回传:重复触发时绑定已存在(created=false), // 不会重复通知外部;回传失败仅记录 warn 日志,不影响绑定与状态更新结果。 if (bindResult && bindResult.created) { try { const callbackResult = await this._sendCallback(entryOrder, matchedReceiving, 'auto_match'); if (!callbackResult || !callbackResult.success) { ctx.logger.warn( `[ReceivingEntryMatch] 回传失败(不影响绑定结果) entryOrderId=${entryOrderId} ` + `receivingId=${matchedReceiving.id} ` + `sourceType=${callbackResult ? callbackResult.sourceType : 'N/A'}` ); } } catch (callbackError) { ctx.logger.warn( `[ReceivingEntryMatch] 回传异常(不影响绑定结果) entryOrderId=${entryOrderId} ` + `receivingId=${matchedReceiving.id}: ${callbackError.message}` ); } } } 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 ); } } /** * 写入入库单与收货单的主表级绑定关系。 * 幂等策略:先查(含软删除)——已存在未删除 → 跳过;已软删除 → 恢复;不存在 → 新建(唯一索引兜底并发)。 * 仅当本次确实新建绑定行时返回 created=true,调用方据此判断是否需要回传外部系统。 * * @param {number} entryOrderId 入库单 ID * @param {number} receivingId 收货单 ID * @return {Promise<{created: boolean}>} 本次是否新建了绑定行;已存在/恢复/并发冲突/写入失败时均为 false */ 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 { created: false }; } await ctx.model.EntryOrderReceiving.create({ entry_order_id: entryOrderId, receiving_id: receivingId, // 新链路绑定行台账初始化为空对象(区别于旧数据 NULL),恢复/分配时从 0 起步 allocated_quantity: {}, }); ctx.logger.info( `[ReceivingEntryMatch] 写入绑定关系成功 entryOrderId=${entryOrderId} receivingId=${receivingId}` ); return { created: true }; } catch (error) { // 唯一索引冲突时忽略(并发场景) if (error.name === 'SequelizeUniqueConstraintError') { ctx.logger.warn( `[ReceivingEntryMatch] 绑定关系已存在(并发写入) entryOrderId=${entryOrderId} receivingId=${receivingId}` ); return { created: false }; } ctx.logger.error( `[ReceivingEntryMatch] 写入绑定关系失败 entryOrderId=${entryOrderId} receivingId=${receivingId}: ${error.message}`, error.stack ); return { created: false }; } } /** * 绑定入库单与收货单(主表绑定)。 * * 流程: * 1. 校验入库单状态,仅 CREATED / COMPLETED 允许绑定,其他状态抛错 * 2. 校验每个收货单:存在、同仓库、同货主、已审核、未取消 * 3. CREATED:保持原有逻辑,仅逐条写入 EntryOrderReceiving 主表绑定 * 4. COMPLETED:事务内完成主表绑定 + 收货明细入库进度同步 + 收货单入库状态重算, * 任一异常整体回滚 * * @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 / COMPLETED 状态绑定;COMPLETED 绑定后同步收货单入库进度 const ALLOWED_BIND_STATUSES = [ 'CREATED', 'COMPLETED' ]; if (!ALLOWED_BIND_STATUSES.includes(entryOrder.order_status)) { throw new Error( `入库单状态不允许绑定,当前状态: ${entryOrder.order_status},仅 ${ALLOWED_BIND_STATUSES.join('、')} 状态可操作` ); } 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 = []; if (entryOrder.order_status === 'COMPLETED') { // COMPLETED:事务内完成 主表绑定 + 明细入库进度同步 + 主表入库状态重算,失败整体回滚 try { const txResult = await this._bindReceivingsWithStorageSync({ entryOrderId, entryOrder, validatedReceivings, }); boundResults.push(...txResult.bound); skippedResults.push(...txResult.skipped); } catch (error) { ctx.logger.error( `[ReceivingEntryMatch] COMPLETED 绑定入库进度同步失败,事务已回滚 entryOrderId=${entryOrderId}: ${error.message}`, error.stack ); throw new Error(`入库单绑定收货单失败,已回滚: ${error.message}`); } } else { // CREATED:保持原有逻辑,仅逐条写入主表绑定关系 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, // 新链路绑定行台账初始化为空对象(区别于旧数据 NULL) allocated_quantity: {}, }, }); 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, }, }; } /** * 事务内为 COMPLETED 入库单批量绑定收货单并同步入库进度。 * 逐个收货单完成主表绑定(幂等)与明细入库数量同步; * 任一非预期异常抛出,整个事务回滚。 * * 锁序约定(防死锁):事务内第一步先 FOR UPDATE 锁定入库单主行, * 再创建绑定行、锁定绑定行与收货明细行(主行 → 绑定行 → 收货明细行)。 * 同一入库单的并发绑定事务在主行锁上串行排队;排队事务不产生插入/间隙锁, * 从根因上消除「主行锁 ↔ 未提交插入行间隙锁」的环等待死锁。 * * @param {Object} params 参数 * @param {number} params.entryOrderId 入库单 ID * @param {Object} params.entryOrder 入库单实例 * @param {Array} params.validatedReceivings 已通过校验的收货单列表 * @return {Promise<{bound: Array, skipped: Array}>} 绑定结果,skipped 项含 error_code */ async _bindReceivingsWithStorageSync({ entryOrderId, entryOrder, validatedReceivings } = {}) { const { ctx } = this; return await ctx.model.transaction(async transaction => { // ---------- 0. 统一锁序:先 FOR UPDATE 锁定入库单主行,串行化同一入库单的并发绑定事务 ---------- await ctx.model.EntryOrder.findByPk(entryOrder.id, { attributes: [ 'id' ], lock: transaction.LOCK.UPDATE, transaction, }); const bound = []; const skipped = []; for (const receiving of validatedReceivings) { const itemResult = await this._bindOneReceivingAndSyncStorage({ entryOrderId, entryOrder, receiving, transaction, }); if (itemResult.error_code) { skipped.push(itemResult); } else { bound.push(itemResult); } } return { bound, skipped }; }); } /** * 事务内绑定单个收货单并同步入库进度(COMPLETED 场景)。 * * 幂等设计: * 1. 先查绑定关系(含软删除记录): * - 已存在且未删除 → 跳过,不重复累加 stored_quantity * - 已存在但已软删除 → 恢复绑定并同步进度(COMPLETED 状态不允许解绑, * 软删除记录必然产生于 CREATED/PENDING 阶段,该阶段未做过进度同步) * - 不存在 → 新建绑定(唯一索引冲突视为并发已建立,跳过同步) * 2. 仅在本次新建立/恢复绑定时,按入库单明细同步收货单入库进度 * * @param {Object} params 参数 * @param {number} params.entryOrderId 入库单 ID * @param {Object} params.entryOrder 入库单实例 * @param {Object} params.receiving 收货单实例 * @param {Object} params.transaction Sequelize 事务对象 * @return {Promise} 单条绑定结果;绑定已存在时含 error_code: 'ALREADY_BOUND' */ async _bindOneReceivingAndSyncStorage({ entryOrderId, entryOrder, receiving, transaction } = {}) { const { ctx } = this; // ---------- 1. 主表绑定(幂等) ---------- const existing = await ctx.model.EntryOrderReceiving.findOne({ where: { entry_order_id: entryOrderId, receiving_id: receiving.id }, paranoid: false, transaction, }); let restored = false; if (existing) { const deletedAt = existing.deletedAt || existing.deleted_at || null; if (deletedAt) { await existing.restore({ transaction }); restored = true; ctx.logger.info( `[ReceivingEntryMatch] 恢复已删除的绑定关系并同步入库进度 entryOrderId=${entryOrderId} ` + `receivingId=${receiving.id}` ); } else { ctx.logger.info( `[ReceivingEntryMatch] 绑定关系已存在,跳过入库进度同步(幂等) entryOrderId=${entryOrderId} ` + `receivingId=${receiving.id}` ); return { receiving_id: receiving.id, receiving_number: receiving.receiving_number, created: false, error_code: 'ALREADY_BOUND', message: '绑定关系已存在,跳过入库进度同步', }; } } else { try { await ctx.model.EntryOrderReceiving.create({ entry_order_id: entryOrderId, receiving_id: receiving.id, // 新链路绑定行台账初始化为空对象(区别于旧数据 NULL) allocated_quantity: {}, }, { transaction }); ctx.logger.info( `[ReceivingEntryMatch] 主表绑定成功 entryOrderId=${entryOrderId} receivingId=${receiving.id}` ); } catch (error) { if (error.name === 'SequelizeUniqueConstraintError') { ctx.logger.warn( `[ReceivingEntryMatch] 绑定关系已存在(并发写入),跳过入库进度同步 entryOrderId=${entryOrderId} ` + `receivingId=${receiving.id}` ); return { receiving_id: receiving.id, receiving_number: receiving.receiving_number, created: false, error_code: 'ALREADY_BOUND', message: '绑定关系已存在(并发写入),跳过入库进度同步', }; } throw error; } } // ---------- 2. 同步入库进度 ---------- const storageSync = await this._syncReceivingStorageByEntryItems({ entryOrder, receiving, transaction, }); return { receiving_id: receiving.id, receiving_number: receiving.receiving_number, created: true, restored, storage_sync: storageSync, }; } /** * 按入库单明细同步单个收货单的入库进度(事务内,COMPLETED 场景,方案A台账版)。 * * 分配算法(修复同 SKU 多绑定超分漏洞): * 1. 入库单主行 FOR UPDATE 锁由事务入口 _bindReceivingsWithStorageSync 统一前置获取 * (全局锁序:主行 → 绑定行 → 收货明细行),本方法承接后续锁定步骤 * 2. FOR UPDATE 行锁该入库单全部未删除绑定行 + 全部绑定收货单明细行 * 3. 每 SKU 可分配上限 = max(0, 入库单计划数量 − 已向其他未删除绑定分配量), * 再与当前收货单该 SKU 剩余可入量(actual_quantity − stored_quantity)取小 * 4. 当前绑定按目标值归一化:多退少补(旧数据超分时回收、亏分时补分配), * 明细级分配结果回写绑定行台账(allocated_quantity,明细 ID → 数量) * 5. 重算收货单主表 storage_status,并同步 entry_items.received_quantity 台账口径 * 6. SKU 不匹配的入库明细:记录日志并跳过,汇总进 unmatched_items * * @param {Object} params 参数 * @param {Object} params.entryOrder 入库单实例 * @param {Object} params.receiving 收货单实例 * @param {Object} params.transaction Sequelize 事务对象 * @return {Promise} 同步结果 { stored_total, matched_item_count, unmatched_items } */ async _syncReceivingStorageByEntryItems({ entryOrder, receiving, transaction } = {}) { const { ctx, app } = this; // ---------- 1. 行锁入库单主行:已由事务入口 _bindReceivingsWithStorageSync 前置获取, // 本方法内不再重复加锁(锁序:主行 → 绑定行 → 收货明细行) ---------- // ---------- 2. 行锁该入库单全部未删除绑定行(台账唯一事实来源) ---------- const bindingRows = await ctx.model.EntryOrderReceiving.findAll({ where: { entry_order_id: entryOrder.id, deleted_at: null }, order: [[ 'id', 'ASC' ]], lock: transaction.LOCK.UPDATE, transaction, }); // ---------- 3. 行锁全部绑定收货单的明细行 ---------- const receivingIds = [ ...new Set(bindingRows.map(b => Number(b.receiving_id)).filter(Boolean)) ]; const lockedDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: { [app.Sequelize.Op.in]: receivingIds } }, attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity', 'storage_status' ], order: [[ 'id', 'ASC' ]], lock: transaction.LOCK.UPDATE, transaction, raw: true, }); const detailById = new Map(lockedDetails.map(d => [ Number(d.id), d ])); // ---------- 4. 加载入库单明细并按 stock_id 汇总(计划数量) ---------- const entryItems = await ctx.model.EntryItems.findAll({ where: { order_id: entryOrder.id }, attributes: [ 'item_code', 'stock_id', 'count' ], raw: true, transaction, }); const entryQtyMap = new Map(); const entryCountByStock = new Map(); for (const item of entryItems) { const stockId = Number(item.stock_id); if (!stockId) continue; const count = Number(item.count) || 0; if (count <= 0) continue; entryCountByStock.set(stockId, (entryCountByStock.get(stockId) || 0) + count); const current = entryQtyMap.get(stockId); if (current) { current.count += count; } else { entryQtyMap.set(stockId, { stockId, itemCode: item.item_code || '', count }); } } // ---------- 5. 计算其他绑定(非当前收货单)按 SKU 已占用量 ---------- const otherAllocatedByStock = new Map(); for (const binding of bindingRows) { if (Number(binding.receiving_id) === Number(receiving.id)) continue; const allocByStock = this._bindingAllocationByStock({ binding, detailById, entryCountByStock }); for (const [ stockId, qty ] of allocByStock) { otherAllocatedByStock.set(stockId, (otherAllocatedByStock.get(stockId) || 0) + qty); } } // ---------- 6. 当前绑定:归一化分配(多退少补),并重建明细级台账 ---------- const currentBinding = bindingRows.find(b => Number(b.receiving_id) === Number(receiving.id)); if (!currentBinding) { ctx.logger.warn( `[ReceivingEntryMatch] 事务内未找到当前绑定行,跳过入库进度同步 entryOrderId=${entryOrder.id} ` + `receivingId=${receiving.id}` ); return { stored_total: 0, matched_item_count: 0, unmatched_items: [] }; } // 当前绑定已有台账:新链路台账直接解析;旧数据(NULL)按收货侧累计量兜底重建 const currentLedgerMap = currentBinding.allocated_quantity !== null && currentBinding.allocated_quantity !== undefined ? this._parseLedgerMap(currentBinding.allocated_quantity) : this._buildLegacyBaselineLedger({ detailById, entryCountByStock, receivingId: Number(receiving.id), }); const currentAllocatedByStock = new Map(); for (const [ detailId, qty ] of currentLedgerMap) { const detail = detailById.get(detailId); if (!detail) continue; const stockId = Number(detail.system_product_id); if (!stockId) continue; currentAllocatedByStock.set(stockId, (currentAllocatedByStock.get(stockId) || 0) + qty); } // 当前收货单明细(按 SKU 分组,id 升序) const currentDetailsByStock = new Map(); for (const detail of lockedDetails) { if (Number(detail.receiving_id) !== Number(receiving.id)) continue; const stockId = Number(detail.system_product_id); if (!stockId) continue; if (!currentDetailsByStock.has(stockId)) currentDetailsByStock.set(stockId, []); currentDetailsByStock.get(stockId).push(detail); } const newLedgerMap = new Map(currentLedgerMap); const unmatchedItems = []; let storedTotal = 0; let matchedItemCount = 0; let changed = false; for (const [ stockId, entryItem ] of entryQtyMap) { const details = currentDetailsByStock.get(stockId) || []; if (details.length === 0) { // SKU 不匹配:记录日志并跳过(保持原行为,不影响其他 SKU 与绑定本身) unmatchedItems.push({ stock_id: stockId, item_code: entryItem.itemCode, count: entryItem.count, }); ctx.logger.warn( `[ReceivingEntryMatch] SKU 不匹配,跳过入库进度同步 entryOrderId=${entryOrder.id} ` + `receivingId=${receiving.id} stockId=${stockId} itemCode=${entryItem.itemCode} ` + `count=${entryItem.count}` ); continue; } const otherAllocated = otherAllocatedByStock.get(stockId) || 0; const entryRemaining = Math.max(0, entryItem.count - otherAllocated); const currentAllocated = currentAllocatedByStock.get(stockId) || 0; const receivingRemaining = details.reduce( (sum, d) => sum + Math.max(0, (Number(d.actual_quantity) || 0) - (Number(d.stored_quantity) || 0)), 0 ); // 归一化目标:既不能超过入库单剩余计划,也不能超过收货单剩余可入量 const target = Math.min(entryRemaining, currentAllocated + receivingRemaining); const delta = target - currentAllocated; if (delta === 0) continue; if (delta > 0) { // 补分配:明细 id 升序,逐行补足剩余可入量,台账同步累加 let left = delta; let allocated = 0; for (const detail of details) { if (left <= 0) break; const actual = Number(detail.actual_quantity) || 0; const stored = Number(detail.stored_quantity) || 0; const remain = Math.max(0, actual - stored); if (remain <= 0) continue; const add = Math.min(left, remain); const newStored = stored + add; const storageStatus = newStored >= actual ? 'all' : 'partial'; await ctx.model.ReceivingDetail.update({ stored_quantity: newStored, storage_status: storageStatus, updated_at: new Date(), }, { where: { id: detail.id }, transaction, }); detail.stored_quantity = newStored; detail.storage_status = storageStatus; newLedgerMap.set(Number(detail.id), (newLedgerMap.get(Number(detail.id)) || 0) + add); changed = true; allocated += add; left -= add; } storedTotal += allocated; if (allocated > 0) { matchedItemCount += 1; } if (left > 0) { ctx.logger.warn( `[ReceivingEntryMatch] 入库数量未完全分配(收货明细剩余可入数量不足) entryOrderId=${entryOrder.id} ` + `receivingId=${receiving.id} stockId=${stockId} left=${left}` ); } } else { // 归一化回收:按台账已有分配(明细 id 升序)回收超分部分,避免继续占用其他入库单的可入量 let left = -delta; const sortedEntries = [ ...newLedgerMap.entries() ].sort((a, b) => a[0] - b[0]); for (const [ detailId, ledgerQty ] of sortedEntries) { if (left <= 0) break; const detail = detailById.get(detailId); if (!detail || Number(detail.system_product_id) !== stockId) continue; const remove = Math.min(left, ledgerQty); if (remove <= 0) continue; const stored = Number(detail.stored_quantity) || 0; const actualRemove = Math.min(remove, stored); const newStored = Math.max(0, stored - actualRemove); const actual = Number(detail.actual_quantity) || 0; const storageStatus = newStored >= actual ? 'all' : (newStored > 0 ? 'partial' : 'none'); await ctx.model.ReceivingDetail.update({ stored_quantity: newStored, storage_status: storageStatus, updated_at: new Date(), }, { where: { id: detail.id }, transaction, }); detail.stored_quantity = newStored; detail.storage_status = storageStatus; const remainingLedger = ledgerQty - remove; if (remainingLedger > 0) { newLedgerMap.set(detailId, remainingLedger); } else { newLedgerMap.delete(detailId); } changed = true; left -= remove; } if (left > 0) { ctx.logger.warn( `[ReceivingEntryMatch] 归一化回收未完成(台账不足) entryOrderId=${entryOrder.id} ` + `receivingId=${receiving.id} stockId=${stockId} left=${left}` ); } } } // ---------- 7. 回写当前绑定台账(空台账也写 {},标记新链路已初始化) ---------- await currentBinding.update({ allocated_quantity: this._serializeLedgerMap(newLedgerMap), updated_at: new Date(), }, { transaction }); // ---------- 8. 汇总重算收货单主表 storage_status(基于本收货单全部明细) ---------- let masterStatus = null; if (changed) { const currentRows = lockedDetails.filter(d => Number(d.receiving_id) === Number(receiving.id)); masterStatus = await this._recalcReceivingStorageStatus(receiving.id, transaction, currentRows); } // ---------- 9. 同步 entry_items.received_quantity(入库单侧台账口径,F3) ---------- await this._reconcileEntryReceivedQuantity({ entryOrder, transaction, bindingRows, detailById, entryCountByStock, }); if (changed) { ctx.logger.info( `[ReceivingEntryMatch] 收货单入库进度已同步 receivingId=${receiving.id} ` + `storageStatus=${masterStatus} storedTotal=${storedTotal} matchedItemCount=${matchedItemCount} ` + `unmatchedCount=${unmatchedItems.length}` ); } else { ctx.logger.info( `[ReceivingEntryMatch] 无匹配 SKU 或无可分配数量,收货单入库状态保持不变 receivingId=${receiving.id} ` + `unmatchedCount=${unmatchedItems.length}` ); } return { stored_total: storedTotal, matched_item_count: matchedItemCount, unmatched_items: unmatchedItems, }; } /** * 解析绑定行数量台账(收货明细ID → 已分配数量)。 * 兼容对象 / JSON 字符串 / 空值;空值或解析失败返回空 Map。 * * @param {Object|string|null} ledgerValue 台账字段原始值 * @return {Map} detailId → 分配数量 */ _parseLedgerMap(ledgerValue) { const { ctx } = this; const ledgerMap = new Map(); if (!ledgerValue) return ledgerMap; let parsed = ledgerValue; if (typeof ledgerValue === 'string') { try { parsed = JSON.parse(ledgerValue); } catch (error) { ctx.logger.warn(`[ReceivingEntryMatch] 台账 JSON 解析失败,按空台账处理: ${error.message}`); return ledgerMap; } } if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return ledgerMap; for (const [ detailIdKey, qty ] of Object.entries(parsed)) { const detailId = Number(detailIdKey); const quantity = Number(qty) || 0; if (!Number.isFinite(detailId) || detailId <= 0 || quantity <= 0) continue; ledgerMap.set(detailId, quantity); } return ledgerMap; } /** * 将明细级分配数量 Map 序列化为台账 JSON(空 Map → 空对象,保持"新链路已初始化"语义)。 * * @param {Map} ledgerMap detailId → 分配数量 * @return {Object} 台账 JSON 对象(空对象而非 null) */ _serializeLedgerMap(ledgerMap) { const json = {}; for (const [ detailId, qty ] of ledgerMap) { if (!Number.isFinite(detailId) || detailId <= 0) continue; const quantity = Number(qty) || 0; if (quantity <= 0) continue; json[String(detailId)] = quantity; } return json; } /** * 旧数据兜底:为无台账(allocated_quantity 为 null)的绑定行重建明细级分配台账。 * 以"收货单侧已累计量"为依据:每 SKU 取 min(入库单计划数量, 该收货单该 SKU 明细 stored_quantity 之和), * 再按明细 id 升序分摊到各收货明细(每行封顶 actual_quantity)。 * 新链路创建的绑定行台账为 {}(非 null),不会进入该兜底。 * * @param {Object} params 参数 * @param {Map} params.detailById 收货明细快照(id → detail) * @param {Map} params.entryCountByStock stockId → 入库单计划数量 * @param {number} params.receivingId 收货单 ID * @return {Map} detailId → 分配数量 */ _buildLegacyBaselineLedger({ detailById, entryCountByStock, receivingId } = {}) { const receivingDetails = []; for (const detail of detailById.values()) { if (Number(detail.receiving_id) === Number(receivingId)) receivingDetails.push(detail); } receivingDetails.sort((a, b) => Number(a.id) - Number(b.id)); const storedByStock = new Map(); const detailsByStock = new Map(); for (const detail of receivingDetails) { const stockId = Number(detail.system_product_id); if (!stockId) continue; storedByStock.set(stockId, (storedByStock.get(stockId) || 0) + (Number(detail.stored_quantity) || 0)); if (!detailsByStock.has(stockId)) detailsByStock.set(stockId, []); detailsByStock.get(stockId).push(detail); } const ledgerMap = new Map(); for (const [ stockId, storedTotal ] of storedByStock) { const entryCount = entryCountByStock.get(stockId) || 0; let left = Math.min(entryCount, storedTotal); if (left <= 0) continue; for (const detail of detailsByStock.get(stockId)) { if (left <= 0) break; const actual = Number(detail.actual_quantity) || 0; const assign = Math.min(left, actual); if (assign <= 0) continue; ledgerMap.set(Number(detail.id), assign); left -= assign; } } return ledgerMap; } /** * 计算绑定行在 SKU 维度的已分配数量: * - 台账非 null → 台账按收货明细的 system_product_id 汇总; * - 台账为 null(旧数据)→ 按收货单侧累计量兜底重建(封顶入库单计划数量)。 * * @param {Object} params 参数 * @param {Object} params.binding 绑定行实例或快照 * @param {Map} params.detailById 收货明细快照(id → detail) * @param {Map} params.entryCountByStock stockId → 入库单计划数量 * @return {Map} stockId → 已分配数量 */ _bindingAllocationByStock({ binding, detailById, entryCountByStock } = {}) { const { ctx } = this; if (binding.allocated_quantity !== null && binding.allocated_quantity !== undefined) { const ledgerMap = this._parseLedgerMap(binding.allocated_quantity); const byStock = new Map(); for (const [ detailId, qty ] of ledgerMap) { const detail = detailById.get(detailId); if (!detail) { ctx.logger.warn(`[ReceivingEntryMatch] 台账存在失效收货明细,忽略 detailId=${detailId}`); continue; } const stockId = Number(detail.system_product_id); if (!stockId) continue; byStock.set(stockId, (byStock.get(stockId) || 0) + qty); } return byStock; } // 旧数据兜底 const baseline = this._buildLegacyBaselineLedger({ detailById, entryCountByStock, receivingId: Number(binding.receiving_id), }); const byStock = new Map(); for (const [ detailId, qty ] of baseline) { const detail = detailById.get(detailId); if (!detail) continue; const stockId = Number(detail.system_product_id); if (!stockId) continue; byStock.set(stockId, (byStock.get(stockId) || 0) + qty); } return byStock; } /** * 按收货单全部明细重算收货单主表 storage_status。 * 规则:全部明细 stored >= actual → 'all';存在部分入库 → 'partial';全部未入库 → 'none'。 * * @param {number} receivingId 收货单 ID * @param {Object} transaction Sequelize 事务对象 * @param {Array|null} [detailRows] 已锁定的明细快照(可选,缺省时重新查询) * @return {Promise} 重算后的 storage_status */ async _recalcReceivingStorageStatus(receivingId, transaction, detailRows = null) { const { ctx } = this; const rows = detailRows || await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: receivingId }, attributes: [ 'actual_quantity', 'stored_quantity' ], raw: true, transaction, }); let masterStatus = 'none'; const fullyStored = rows.length > 0 && rows.every(d => (Number(d.stored_quantity) || 0) >= (Number(d.actual_quantity) || 0)); if (fullyStored) { masterStatus = 'all'; } else if (rows.some(d => (Number(d.stored_quantity) || 0) > 0)) { masterStatus = 'partial'; } await ctx.model.Receiving.update({ storage_status: masterStatus, updated_at: new Date(), }, { where: { id: receivingId }, transaction, }); return masterStatus; } /** * 重算入库单明细 received_quantity(F3 口径对齐)。 * 按 stock_id 汇总该入库单全部未删除绑定的台账占用(旧数据按收货侧累计量兜底), * 再按明细 id 升序分摊到各明细行(每行封顶计划数量), * 使入库单侧已入库量与各绑定收货单 stored_quantity 之和可对账。 * * @param {Object} params 参数 * @param {Object} params.entryOrder 入库单实例(至少含 id) * @param {Object} params.transaction Sequelize 事务对象 * @param {Array|null} [params.bindingRows] 已锁定的绑定行(可选,缺省重新查询) * @param {Map|null} [params.detailById] 已锁定的收货明细快照(可选) * @param {Map|null} [params.entryCountByStock] stockId → 计划数量(可选) * @return {Promise} */ async _reconcileEntryReceivedQuantity({ entryOrder, transaction, bindingRows = null, detailById = null, entryCountByStock = null, } = {}) { const { ctx, app } = this; const bindings = bindingRows || await ctx.model.EntryOrderReceiving.findAll({ where: { entry_order_id: entryOrder.id, deleted_at: null }, raw: true, transaction, }); let detailsMap = detailById; if (!detailsMap) { const receivingIds = [ ...new Set(bindings.map(b => Number(b.receiving_id)).filter(Boolean)) ]; if (receivingIds.length > 0) { const rows = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: { [app.Sequelize.Op.in]: receivingIds } }, attributes: [ 'id', 'receiving_id', 'system_product_id', 'stored_quantity' ], raw: true, transaction, }); detailsMap = new Map(rows.map(d => [ Number(d.id), d ])); } else { detailsMap = new Map(); } } let countByStock = entryCountByStock; if (!countByStock) { countByStock = new Map(); const items = await ctx.model.EntryItems.findAll({ where: { order_id: entryOrder.id }, attributes: [ 'stock_id', 'count' ], raw: true, transaction, }); for (const item of items) { const stockId = Number(item.stock_id); if (!stockId) continue; countByStock.set(stockId, (countByStock.get(stockId) || 0) + (Number(item.count) || 0)); } } // 汇总每 SKU 的台账占用 const allocatedByStock = new Map(); for (const binding of bindings) { const allocByStock = this._bindingAllocationByStock({ binding, detailById: detailsMap, entryCountByStock: countByStock }); for (const [ stockId, qty ] of allocByStock) { allocatedByStock.set(stockId, (allocatedByStock.get(stockId) || 0) + qty); } } // 按明细 id 升序分摊到各明细行(封顶计划数量),保持同 SKU 多明细顺序语义 const items = await ctx.model.EntryItems.findAll({ where: { order_id: entryOrder.id }, attributes: [ 'id', 'stock_id', 'count', 'received_quantity' ], order: [[ 'id', 'ASC' ]], raw: true, transaction, }); const itemsByStock = new Map(); for (const item of items) { const stockId = Number(item.stock_id); if (!stockId) continue; if (!itemsByStock.has(stockId)) itemsByStock.set(stockId, []); itemsByStock.get(stockId).push(item); } for (const [ stockId, total ] of allocatedByStock) { const stockItems = itemsByStock.get(stockId) || []; let left = Math.min(total, countByStock.get(stockId) || 0); for (const item of stockItems) { if (left <= 0) break; const itemCount = Number(item.count) || 0; const share = Math.min(left, itemCount); if (share !== (Number(item.received_quantity) || 0)) { await ctx.model.EntryItems.update({ received_quantity: share, }, { where: { id: item.id }, transaction, }); } left -= share; } } } /** * 累计台账:把本次已实际落到收货明细的分配量累加到对应绑定行台账。 * 供完成链路(quickInbound / commit 非绑定占用 / PDA 明细绑定)在写 stored_quantity 后调用, * 保证台账与收货单侧进度一致。旧绑定行(台账为 null)先按收货侧累计量兜底初始化。 * * @param {Object} params 参数 * @param {number} params.entryOrderId 入库单 ID * @param {Map} params.detailDeltaMap 收货明细ID → 本次分配增量 * @param {Object} params.transaction Sequelize 事务对象 * @return {Promise} */ async recordLedgerAllocation({ entryOrderId, detailDeltaMap, transaction } = {}) { const { ctx, app } = this; if (!entryOrderId || !detailDeltaMap || detailDeltaMap.size === 0) return; const receivingIds = []; for (const info of detailDeltaMap.values()) { if (info && Number(info.receivingId)) receivingIds.push(Number(info.receivingId)); } const uniqueReceivingIds = [ ...new Set(receivingIds) ]; if (uniqueReceivingIds.length === 0) return; // 1. 行锁涉及收货单的绑定行 const bindingRows = await ctx.model.EntryOrderReceiving.findAll({ where: { entry_order_id: entryOrderId, receiving_id: { [app.Sequelize.Op.in]: uniqueReceivingIds }, deleted_at: null, }, lock: transaction.LOCK.UPDATE, transaction, }); const bindingByReceiving = new Map(bindingRows.map(b => [ Number(b.receiving_id), b ])); // 2. 读取涉及收货单的全部明细与入库单计划数量(供旧台账兜底初始化) const detailRows = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: { [app.Sequelize.Op.in]: uniqueReceivingIds } }, attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity' ], raw: true, transaction, }); const detailById = new Map(detailRows.map(d => [ Number(d.id), d ])); const entryItemRows = await ctx.model.EntryItems.findAll({ where: { order_id: entryOrderId }, attributes: [ 'stock_id', 'count' ], raw: true, transaction, }); const entryCountByStock = new Map(); for (const item of entryItemRows) { const stockId = Number(item.stock_id); if (!stockId) continue; entryCountByStock.set(stockId, (entryCountByStock.get(stockId) || 0) + (Number(item.count) || 0)); } // 3. 逐绑定行回写台账 for (const [ receivingId, binding ] of bindingByReceiving) { const ledgerMap = binding.allocated_quantity !== null && binding.allocated_quantity !== undefined ? this._parseLedgerMap(binding.allocated_quantity) : this._buildLegacyBaselineLedger({ detailById, entryCountByStock, receivingId }); let changed = false; for (const [ detailId, info ] of detailDeltaMap) { if (Number(info.receivingId) !== receivingId) continue; const qty = Number(info.quantity) || 0; if (qty <= 0) continue; ledgerMap.set(detailId, (ledgerMap.get(detailId) || 0) + qty); changed = true; } if (!changed) continue; await binding.update({ allocated_quantity: this._serializeLedgerMap(ledgerMap), updated_at: new Date(), }, { transaction }); } } /** * 覆盖台账:绑定模式完成链路(commit)对收货明细 stored_quantity 为直接覆写语义, * 台账同步覆写对应明细条目(其余明细条目保持不动)。旧绑定行先按收货侧累计量兜底初始化。 * * @param {Object} params 参数 * @param {number} params.entryOrderId 入库单 ID * @param {Map} params.detailQuantityMap 收货明细ID → 覆写数量 * @param {Object} params.transaction Sequelize 事务对象 * @return {Promise} */ async setLedgerAllocation({ entryOrderId, detailQuantityMap, transaction } = {}) { const { ctx, app } = this; if (!entryOrderId || !detailQuantityMap || detailQuantityMap.size === 0) return; const receivingIds = []; for (const info of detailQuantityMap.values()) { if (info && Number(info.receivingId)) receivingIds.push(Number(info.receivingId)); } const uniqueReceivingIds = [ ...new Set(receivingIds) ]; if (uniqueReceivingIds.length === 0) return; // 1. 行锁涉及收货单的绑定行 const bindingRows = await ctx.model.EntryOrderReceiving.findAll({ where: { entry_order_id: entryOrderId, receiving_id: { [app.Sequelize.Op.in]: uniqueReceivingIds }, deleted_at: null, }, lock: transaction.LOCK.UPDATE, transaction, }); const bindingByReceiving = new Map(bindingRows.map(b => [ Number(b.receiving_id), b ])); // 2. 读取涉及收货单的全部明细与入库单计划数量(供旧台账兜底初始化) const detailRows = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: { [app.Sequelize.Op.in]: uniqueReceivingIds } }, attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity' ], raw: true, transaction, }); const detailById = new Map(detailRows.map(d => [ Number(d.id), d ])); const entryItemRows = await ctx.model.EntryItems.findAll({ where: { order_id: entryOrderId }, attributes: [ 'stock_id', 'count' ], raw: true, transaction, }); const entryCountByStock = new Map(); for (const item of entryItemRows) { const stockId = Number(item.stock_id); if (!stockId) continue; entryCountByStock.set(stockId, (entryCountByStock.get(stockId) || 0) + (Number(item.count) || 0)); } // 3. 逐绑定行覆写台账条目 for (const [ receivingId, binding ] of bindingByReceiving) { const ledgerMap = binding.allocated_quantity !== null && binding.allocated_quantity !== undefined ? this._parseLedgerMap(binding.allocated_quantity) : this._buildLegacyBaselineLedger({ detailById, entryCountByStock, receivingId }); let changed = false; for (const [ detailId, info ] of detailQuantityMap) { if (Number(info.receivingId) !== receivingId) continue; const qty = Number(info.quantity) || 0; if (qty <= 0) { if (ledgerMap.delete(detailId)) changed = true; } else { ledgerMap.set(detailId, qty); changed = true; } } if (!changed) continue; await binding.update({ allocated_quantity: this._serializeLedgerMap(ledgerMap), updated_at: new Date(), }, { transaction }); } } /** * 回滚入库单绑定的台账占用(作废/解绑共用入口)。 * 对每个未删除绑定:按台账(旧数据按收货侧累计量兜底)回收该绑定在收货单上的 * stored_quantity,重算 storage_status,并把台账重置为空对象。 * 事务内行锁入库单主行与相关收货明细,避免误清其他入库单的占用。 * * @param {Object} params 参数 * @param {number} params.entryOrderId 入库单 ID * @param {number|null} [params.receivingId] 仅回滚该收货单(解绑场景),null 回滚全部(作废场景) * @param {boolean} [params.softDeleteBinding=true] 是否软删除绑定行 * @return {Promise} { rolled_back: Array<{receiving_id, detail_count, rolled_back_quantity}> } */ async rollbackEntryOrderBindings({ entryOrderId, receivingId = null, softDeleteBinding = true } = {}) { const { ctx } = this; return await ctx.model.transaction(async transaction => { // 串行化同一入库单的分配/回滚事务 await ctx.model.EntryOrder.findByPk(entryOrderId, { attributes: [ 'id' ], lock: transaction.LOCK.UPDATE, transaction, }); const where = { entry_order_id: entryOrderId, deleted_at: null }; if (receivingId !== null && receivingId !== undefined) { where.receiving_id = receivingId; } const bindingRows = await ctx.model.EntryOrderReceiving.findAll({ where, order: [[ 'id', 'ASC' ]], lock: transaction.LOCK.UPDATE, transaction, }); const rolledBack = []; for (const binding of bindingRows) { const result = await this._rollbackOneBindingStorage({ binding, entryOrderId, transaction, softDelete: softDeleteBinding, }); if (result) rolledBack.push(result); } // 回滚后重算入库单侧 received_quantity(与台账对齐) await this._reconcileEntryReceivedQuantity({ entryOrder: { id: entryOrderId }, transaction }); return { rolled_back: rolledBack }; }); } /** * 回滚单条绑定的台账占用:按台账明细条目(旧数据兜底)扣减收货明细 stored_quantity, * 重算收货单 storage_status,并把绑定台账重置为空对象。 * * @param {Object} params 参数 * @param {Object} params.binding 已行锁的绑定行实例 * @param {number} params.entryOrderId 入库单 ID * @param {Object} params.transaction Sequelize 事务对象 * @param {boolean} [params.softDelete=false] 是否软删除绑定行 * @return {Promise} 回滚汇总,无可回滚量时返回 null */ async _rollbackOneBindingStorage({ binding, entryOrderId, transaction, softDelete = false } = {}) { const { ctx } = this; const receivingId = Number(binding.receiving_id); const lockedDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: receivingId }, attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity', 'storage_status' ], order: [[ 'id', 'ASC' ]], lock: transaction.LOCK.UPDATE, transaction, raw: true, }); const detailById = new Map(lockedDetails.map(d => [ Number(d.id), d ])); const entryItemRows = await ctx.model.EntryItems.findAll({ where: { order_id: entryOrderId }, attributes: [ 'stock_id', 'count' ], raw: true, transaction, }); const entryCountByStock = new Map(); for (const item of entryItemRows) { const stockId = Number(item.stock_id); if (!stockId) continue; entryCountByStock.set(stockId, (entryCountByStock.get(stockId) || 0) + (Number(item.count) || 0)); } // 回滚条目:优先台账;旧数据按收货侧累计量兜底 const ledgerMap = binding.allocated_quantity !== null && binding.allocated_quantity !== undefined ? this._parseLedgerMap(binding.allocated_quantity) : this._buildLegacyBaselineLedger({ detailById, entryCountByStock, receivingId }); let rolledBackQty = 0; let touchedCount = 0; const sortedEntries = [ ...ledgerMap.entries() ].sort((a, b) => a[0] - b[0]); for (const [ detailId, ledgerQty ] of sortedEntries) { const detail = detailById.get(detailId); if (!detail) { ctx.logger.warn(`[ReceivingEntryMatch] 回滚时台账明细不存在,跳过 detailId=${detailId}`); continue; } const stored = Number(detail.stored_quantity) || 0; const remove = Math.min(ledgerQty, stored); if (remove <= 0) continue; const newStored = stored - remove; const actual = Number(detail.actual_quantity) || 0; const storageStatus = newStored >= actual ? 'all' : (newStored > 0 ? 'partial' : 'none'); await ctx.model.ReceivingDetail.update({ stored_quantity: newStored, storage_status: storageStatus, updated_at: new Date(), }, { where: { id: detail.id }, transaction, }); detail.stored_quantity = newStored; detail.storage_status = storageStatus; rolledBackQty += remove; touchedCount += 1; } // 重算收货单主表状态(基于本收货单全部明细,不影响其他入库单占用) await this._recalcReceivingStorageStatus(receivingId, transaction, lockedDetails); // 台账重置为空对象(保留"已初始化"语义,恢复绑定时从 0 重新分配) await binding.update({ allocated_quantity: {}, updated_at: new Date(), }, { transaction }); if (softDelete) { await binding.destroy({ transaction }); } if (touchedCount === 0) return null; return { receiving_id: receivingId, detail_count: touchedCount, rolled_back_quantity: rolledBackQty, }; } /** * 获取仓库近 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, }; } /** * 加载入库单明细并组装为奇门 orderLines 数组(行号从 1 递增)。 * ownerCode / itemCode / itemId 缺省为空字符串,inventoryType 缺省为 ZP, * planQty 取计划数量、actualQty 取已入库数量,缺省为 0。 * @param {Object} entryOrder 入库单实例 * @return {Promise|null>} 明细行数组;无明细时返回 null */ async _queryEntryOrderLines(entryOrder) { const { ctx } = this; // 重新加载入库单明细 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) { return null; } return 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, })); } /** * 组装 entryorder.confirm 业务报文(与奇门 taobao.qimen.entryorder.confirm 同层级)。 * 返回 { entryOrder, orderLines },不包含外层 request 包装, * 字段与取值逻辑以奇门分支为唯一基准,奇门与 OpenAPI 回传共用。 * @param {Object} entryOrder 入库单实例 * @param {Array} orderLines 入库明细行数组 * @param {Object} [options] 可选配置 * @param {string} [options.outBizCode] 外部业务编码,缺省时自动生成 RECEIVING_MATCH_时间戳 * @param {string} [options.remark] 备注 * @return {{ entryOrder: Object, orderLines: Array }} 组装后的业务报文 */ buildEntryOrderConfirmRequest(entryOrder, orderLines, options = {}) { const { app } = this; const { outBizCode, 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 || `RECEIVING_MATCH_${Date.now()}`, confirmType: 0, // 0 = 最终确认 status: 'FULFILLED', freight: 0, operateTime: app.formatDate(new Date()), remark: remark || '', }, orderLines, }; } /** * 根据入库单来源发送回传。 * - 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 { // 重新加载入库单明细并组装为奇门 orderLines const orderLines = await this._queryEntryOrderLines(entryOrder); if (!orderLines) { ctx.logger.warn(`[ReceivingEntryMatch] 奇门回传:入库单无明细 entryOrderId=${entryOrder.id}`); return { success: false, error: '入库单无明细' }; } const request = this.buildEntryOrderConfirmRequest(entryOrder, orderLines, { outBizCode: `RECEIVING_MATCH_${Date.now()}`, remark: `匹配收货单${receivingOrder.receiving_number}自动回传`, }); const result = await app.qimenClient.send( 'taobao.qimen.entryorder.confirm', entryOrder.qimen_owner_code, { request }, { 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 回传。 * 报文体与奇门同层级({ request: { entryOrder, orderLines } },外层 request 由发送端自动包裹), * 与 _sendQimenCallback 共用同一份报文组装。 * * @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配置' }; } // 组装与奇门同层级的业务报文(entryorder.match 与奇门 entryorder.confirm 共用同一份组装) const orderLines = await this._queryEntryOrderLines(entryOrder); if (!orderLines) { ctx.logger.warn( '[ReceivingEntryMatch] OpenAPI回传:入库单无明细 ' + `entryOrderId=${entryOrder.id} receivingNumber=${receivingOrder.receiving_number}` ); return { success: false, error: '入库单无明细' }; } const request = this.buildEntryOrderConfirmRequest(entryOrder, orderLines, { remark: `匹配收货单${receivingOrder.receiving_number}自动回传`, }); // 使用 OpenAPI 回调服务发送(matchType 仅保留在日志中,不塞入奇门报文) const result = await ctx.service.openapi.callback.sendWithRetry({ callbackUrl: apiApp.callback_url, appKey: apiApp.self_app_key, selfAppSecret: apiApp.self_app_secret || '', event: 'entryorder.match', request, }); if (result.success) { ctx.logger.info( `[ReceivingEntryMatch] OpenAPI回传成功 entryOrderId=${entryOrder.id} ` + `callbackUrl=${apiApp.callback_url} matchType=${matchType} retryCount=${result.retryCount}` ); return { success: true, retryCount: result.retryCount }; } ctx.logger.warn( `[ReceivingEntryMatch] OpenAPI回传失败 entryOrderId=${entryOrder.id} ` + `matchType=${matchType} 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, allocated_quantity: {}, }, transaction, }); // 7. 回写数量台账:本批次对该收货明细的分配量累加到绑定行 const ledgerDeltaMap = new Map(); ledgerDeltaMap.set(Number(receivingDetailId), { receivingId: Number(lockedDetail[0].receiving_id), quantity: Number(qty), }); await this.recordLedgerAllocation({ entryOrderId, detailDeltaMap: ledgerDeltaMap, 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' ], }); // 2c/2d. 事务内:回滚收货侧占用(台账)+ 重算 storage_status + 软删除绑定(含明细绑定) const rollbackResult = await ctx.model.transaction(async t => { // 行锁入库单主行,串行化与绑定分配/其他解绑的并发 await ctx.model.EntryOrder.findByPk(entryOrderId, { attributes: [ 'id' ], lock: t.LOCK.UPDATE, transaction: t, }); // 事务内重查绑定行并加锁,防止并发绑定/解绑 const lockedBinding = await ctx.model.EntryOrderReceiving.findOne({ where: { entry_order_id: entryOrderId, receiving_id: receivingId, deleted_at: null }, lock: t.LOCK.UPDATE, transaction: t, }); if (!lockedBinding) { const bindErr = new Error('主表绑定不存在或已被解绑'); bindErr.error_code = 'BINDING_NOT_FOUND'; throw bindErr; } const rollback = await this._rollbackOneBindingStorage({ binding: lockedBinding, entryOrderId, transaction: t, softDelete: true, }); // 软删除所有明细绑定(InboundDirectLog) for (const binding of detailBindings) { await binding.destroy({ transaction: t }); } return rollback; }); const detailIds = detailBindings.map(d => d.receiving_detail_id); const rolledBackQty = rollbackResult ? rollbackResult.rolled_back_quantity : 0; ctx.logger.info( `[ReceivingEntryMatch] 解绑成功 entryOrderId=${entryOrderId} receivingId=${receivingId} ` + `releasedDetailCount=${detailBindings.length} rolledBackQty=${rolledBackQty} ` + `detailIds=[${detailIds.join(',')}]` ); success.push({ receiving_id: receivingId, released_detail_ids: detailIds, released_detail_count: detailBindings.length, rolled_back_quantity: rolledBackQty, message: '已解除绑定并回滚收货单入库进度', }); } catch (error) { ctx.logger.error( `[ReceivingEntryMatch] 解绑异常 entryOrderId=${entryOrderId} ` + `receivingId=${receivingId}: ${error.message}`, error.stack ); failed.push({ receiving_id: receivingId, error_code: error && error.error_code ? error.error_code : 'UNBIND_ERROR', message: `解绑过程异常: ${error.message}`, }); } } return { success, failed, success_count: success.length, failed_count: failed.length }; } } module.exports = ReceivingEntryMatchService;