From 86222a24eb32bcb7707cabac0745b48a2a47ed03 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 7 Sep 2026 22:16:54 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20COMPLETED=20=E5=85=A5=E5=BA=93=E5=8D=95?= =?UTF-8?q?=E7=BB=91=E5=AE=9A=E6=94=B6=E8=B4=A7=E5=8D=95=E4=B8=8E=E9=98=B2?= =?UTF-8?q?=E8=B6=85=E6=89=A3=E5=8F=B0=E8=B4=A6=E9=93=BE=E8=B7=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 入库单 COMPLETED 状态放开绑定收货单,事务内按 SKU 同步收货单明细入库进度(stored_quantity/storage_status) - wms_entry_order_receiving 新增 allocated_quantity 台账列(迁移已在生产执行),多收货单绑定按剩余可分配量封顶防超扣 - 统一锁序(入库单主行→绑定行→收货明细行)修复并发绑定死锁;解绑/作废按台账回滚,不再整体清零共享收货单 - 同步 entry_items.received_quantity 口径,与绑定收货单 stored_quantity 可对账 - 同步 methods 文档与变更记录、AI_METHOD_ROUTING 方法清单 --- AI_METHOD_ROUTING.md | 20 +- app/model/entry_order_receiving.js | 8 +- app/service/systems/inbound_direct_log.js | 22 +- app/service/systems/receiving_entry_match.js | 1223 ++++++++++++++++- app/service/systems/storage/entry.js | 50 +- ...d-quantity-to-wms-entry-order-receiving.js | 72 + methods/changes/system.json | 64 + methods/system.json | 323 ++++- 8 files changed, 1631 insertions(+), 151 deletions(-) create mode 100644 database/migrations/20260907160000-add-allocated-quantity-to-wms-entry-order-receiving.js diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md index 9feca77..3d980b4 100644 --- a/AI_METHOD_ROUTING.md +++ b/AI_METHOD_ROUTING.md @@ -208,10 +208,10 @@ rg "class .*Service|module.exports" app/service/qimenMethods - 临时清单输出:temp/tmp-service-method-inventory.md -自动生成时间: 2026-09-06T08:24:13.502Z +自动生成时间: 2026-09-07T13:11:46.995Z 扫描范围: app/service/**/*.js -文件数: 203 +文件数: 204 - app/service/api.js (1) - callMethod @@ -457,8 +457,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - addOrder, getLineCount, received, success, fail, findByOrderCode, findByStatus, getStatsByWarehouse, updateSyncStatus, updateOrderStatus, calculateReceivedQuantities, batchUpdateReceived, getOrderProgress, tryCreateEntryOrder, addItems, reviewEntry - app/service/systems/excel.js (26) - getContentType, sanitizeSheetName, normalizeHeaders, normalizeColumns, prepareSheetData, hasEmbeddedImages, buildWorksheet, buildWorkbook, buildExcelJsWorkbook, inferImageExtension, resolveImageSource, mergeCellStyle, applyStyledRows, applyTextColumnsToSheetJs, applyTextColumnsToExcelJs, addEmbeddedImages, generateBuffer, writeFile, writeAtomicBufferFile, sanitizeFilename, buildUploadKey, generateAndUpload, sendFile, parseBuffer, parseFile, workbookToJSON -- app/service/systems/express_platform.js (16) - - getOrderLogOperator, buildOrderExpressVerPatch, buildExpressPlatformTraceId, OrderExpress, cleanupFailedWaybillOrders, buildFailedOrderCleanupList, polyapi, cainiao, parsePlatformPrintData, stringifyPlatformPrintData, buildWaybillOrderMetaMap, buildWaybillSettlementRelationMap, lockAndDeductWaybillSettlement, persistWaybillSuccessUpdates, normalizePddExtData, pdd +- app/service/systems/express_platform.js (17) + - getOrderLogOperator, buildOrderExpressVerPatch, buildExpressPlatformTraceId, OrderExpress, cleanupFailedWaybillOrders, warnExpressCodeMismatch, buildFailedOrderCleanupList, polyapi, cainiao, parsePlatformPrintData, stringifyPlatformPrintData, buildWaybillOrderMetaMap, buildWaybillSettlementRelationMap, lockAndDeductWaybillSettlement, persistWaybillSuccessUpdates, normalizePddExtData, pdd - app/service/systems/express_policy.js (10) - getWarehousePolicyCacheKey, getWarehousePolicyCacheTTL, clearWarehousePolicyCache, fetchWarehousePoliciesFromDB, getWarehousePolicies, _matchAnyToken, _matchAnyIntersect, _matchValueInArray, _isStoreOnlyPolicy, matchPolicy - app/service/systems/express.js (72) @@ -471,6 +471,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - getItems, _addSingleItem, _bindReceivingDetail, addItem, removeItem, commit, notifyEntryOrderCompleted, _queryCompletedEntryItems, _buildCompletedItemLines, _sendOpenApiCallback, operationLog, qimenEntrySync, _syncReceivingStorageStatus, _applyReceivingStockOccupancy - app/service/systems/inbox/group.js (10) - list, quickList, members, disable, update, reset, validateExpressInterfaces, validateSystemExpressCode, findGroupsByExpress, findStoreAfterSalesGroups +- app/service/systems/intercept_auto_confirm.js (10) + - withPatchedCtxUser, listCurrentWarehouseIds, NOW, buildCandidateWhereSql, Date, matchesAutoConfirmCriteria, resolveCurrentTableName, scanCandidateOrderIds, confirmInterceptForOrderIds, runAutoConfirm - app/service/systems/license_plate.js (7) - getTencentCloudConfig, getTencentCloudRegion, normalizeBase64Image, buildTencentCloudRequest, sendTencentCloudRequest, recognizeLicensePlate, formatLicensePlateResult - app/service/systems/location_space.js (16) @@ -529,8 +531,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - notifyRefreshInfo, list, update, setRecording, cancelRecording, delete - app/service/systems/qimen_query.js (3) - qimenClient, send, sendRequest -- app/service/systems/receiving_entry_match.js (12) - - matchAfterEntryCompleted, _bindEntryOrderReceiving, bindEntryOrderReceiving, _getRecentReceivingOrders, _findReceivingByRemark, _compareDetails, _sendCallback, _sendQimenCallback, _sendOpenApiCallback, _markReceivingPartialStorage, _commitBinding, unbindEntryOrderReceiving +- app/service/systems/receiving_entry_match.js (27) + - matchAfterEntryCompleted, _bindEntryOrderReceiving, bindEntryOrderReceiving, _bindReceivingsWithStorageSync, _bindOneReceivingAndSyncStorage, max, _syncReceivingStorageByEntryItems, _parseLedgerMap, _serializeLedgerMap, min, _buildLegacyBaselineLedger, _bindingAllocationByStock, _recalcReceivingStorageStatus, _reconcileEntryReceivedQuantity, recordLedgerAllocation, setLedgerAllocation, rollbackEntryOrderBindings, _rollbackOneBindingStorage, _getRecentReceivingOrders, _findReceivingByRemark, _compareDetails, _sendCallback, _sendQimenCallback, _sendOpenApiCallback, _markReceivingPartialStorage, _commitBinding, unbindEntryOrderReceiving - app/service/systems/report.js (16) - getDefinition, parseFieldsField, definitionToView, resolveTypeEntry, resolveQuerier, listRegisteredTypes, validateTypeFields, resolveOrderedFields, buildFilename, buildWorkbookSheets, generate, generateBuffer, saveDefinition, findDefinitionById, listDefinitions, deleteDefinition - app/service/systems/report/queries/index.js (0) @@ -609,8 +611,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - closeFinishedWaves - app/service/systems/waybill.js (5) - toOrder, list, detail, export, buildWaybillExportFile -- app/service/systems/workbench.js (52) - - list, detail, create, update, delete, bindCamera, business, _countWaveOrders, _countWaveOrdersCached, _getWaveOrderIds, Set, _buildPackChangeSummary, _writePackOperationLog, _updateOrderPackStatus, _packOrder, resolvePackTaskEndTime, _finishPack, _sendWeight, _writeWeighOpLog, _queryOrder, getWorkbenchBindClientCacheKey, getWorkbenchBindCodeCacheKey, getWorkbenchTokenCacheKey, generateRandomChars, generateWorkbenchToken, generateWorkbenchLoginCode, normalizeWorkbenchBindCode, generateUniqueWorkbenchLoginCode, createUniqueWorkbenchClientCode, createUniqueWorkbenchBindCode, buildWorkbenchBindState, getWorkbenchBindRemainingSeconds, setWorkbenchBindState, createWorkbenchBindSession, refreshWorkbenchBindCode, formatWorkbenchBindData, waitForWorkbenchBindComplete, getWorkbenchBindCode, formatWorkbenchTokenInfo, bindWorkbench, getWorkbenchInfoByToken, loginWorkbenchByCode, resetLoginCode, resolveWorkbenchContext, resolveWorkbenchByToken, normalizeWorkbenchMemberIds, removeWorkbenchMember, bindWorkbenchMember, packOrderByToken, finishPackByToken, sendWeightByToken, queryOrderByToken +- app/service/systems/workbench.js (61) + - list, detail, create, update, delete, bindCamera, business, _countWaveOrders, _countWaveOrdersCached, SUM, _sumWaveItemsTotal, _sumWaveItemsTotalCached, _getWaveOrderIds, Set, _buildPackChangeSummary, _writePackOperationLog, _updateOrderPackStatus, _packOrder, resolvePackTaskEndTime, _finishPack, _sendWeight, _writeWeighOpLog, _queryOrder, getWorkbenchBindClientCacheKey, getWorkbenchBindCodeCacheKey, getWorkbenchTokenCacheKey, generateRandomChars, generateWorkbenchToken, generateWorkbenchLoginCode, normalizeWorkbenchBindCode, generateUniqueWorkbenchLoginCode, createUniqueWorkbenchClientCode, createUniqueWorkbenchBindCode, buildWorkbenchBindState, getWorkbenchBindRemainingSeconds, setWorkbenchBindState, createWorkbenchBindSession, refreshWorkbenchBindCode, formatWorkbenchBindData, waitForWorkbenchBindComplete, getWorkbenchBindCode, formatWorkbenchTokenInfo, listWorkbenchMembers, listCurrentPackTasks, buildCurrentPackingInfo, invalidateWorkbenchTokenCacheByWorkbenchId, buildWorkbenchTokenInfo, bindWorkbench, getWorkbenchInfoByToken, loginWorkbenchByCode, resetLoginCode, clearExpiredWorkbenchTokens, resolveWorkbenchContext, resolveWorkbenchByToken, packOrderByToken, finishPackByToken, sendWeightByToken, queryOrderByToken, normalizeWorkbenchMemberIds, removeWorkbenchMember, bindWorkbenchMember - app/service/warehouse.js (7) - resolveWarehouseMethod, getWarehouseMethodService, dispatchWarehouseMethod, validateWarehouseParams, parseJsonBody, normalizeSignFields, processRequest - app/service/warehouseMethods/inbox.js (2) @@ -634,3 +636,5 @@ rg "class .*Service|module.exports" app/service/qimenMethods + + diff --git a/app/model/entry_order_receiving.js b/app/model/entry_order_receiving.js index 2100143..4fbdd46 100644 --- a/app/model/entry_order_receiving.js +++ b/app/model/entry_order_receiving.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { BIGINT, DATE } = app.Sequelize; + const { BIGINT, DATE, JSON: JSON_TYPE } = app.Sequelize; const EntryOrderReceiving = app.model.define('wms_entry_order_receiving', { id: { @@ -20,6 +20,12 @@ module.exports = app => { allowNull: false, comment: '收货单ID,关联 wms_receiving.id', }, + allocated_quantity: { + type: JSON_TYPE, + allowNull: true, + defaultValue: null, + comment: '数量台账:收货明细ID→已分配数量(JSON对象,如 {"123":8});null 表示旧数据未初始化', + }, created_at: { type: DATE, allowNull: false, diff --git a/app/service/systems/inbound_direct_log.js b/app/service/systems/inbound_direct_log.js index 801979d..cd69f89 100644 --- a/app/service/systems/inbound_direct_log.js +++ b/app/service/systems/inbound_direct_log.js @@ -1177,7 +1177,7 @@ class InboundDirectLogService extends Service { } // 回写收货单和收货明细的入库状态(绑定模式:按 receiving_detail_id 优先扣减) - await this._syncReceivingStorageStatus({ entryItemIds, transaction }); + await this._syncReceivingStorageStatus({ entryItemIds, transaction, entryOrderId: eo.id }); // 非绑定模式剩余导入量:按 stock_id 匹配绑定收货单明细占用(绑定模式优先,剩余兜底) await this._applyReceivingStockOccupancy({ entryOrder: eo, directLogs, transaction }); @@ -1729,9 +1729,10 @@ class InboundDirectLogService extends Service { * @param {Object} params 参数 * @param {number[]} params.entryItemIds 当前入库单的所有明细 ID 列表 * @param {Object} params.transaction Sequelize 事务对象 + * @param {number} [params.entryOrderId] 入库单 ID(用于同步数量台账) * @return {Promise} */ - async _syncReceivingStorageStatus({ entryItemIds, transaction }) { + async _syncReceivingStorageStatus({ entryItemIds, transaction, entryOrderId = null }) { const { ctx, app } = this; // 查询所有 committed 状态的绑定记录(从 InboundDirectLog 中筛选有 receiving_detail_id 的记录) @@ -1775,6 +1776,7 @@ class InboundDirectLogService extends Service { // 逐条计算并更新收货明细 const receivingIdSet = new Set(); + const ledgerQuantityMap = new Map(); for (const detail of details) { const storedQuantity = detailQuantityMap.get(detail.id) || 0; const actualQuantity = Number(detail.actual_quantity) || 0; @@ -1795,6 +1797,12 @@ class InboundDirectLogService extends Service { transaction, } ); + + // 台账覆盖条目:绑定模式对收货明细为直接覆写语义 + ledgerQuantityMap.set(detail.id, { + receivingId: Number(detail.receiving_id), + quantity: storedQuantity, + }); } // 按收货单汇总,更新 wms_receiving.storage_status @@ -1847,6 +1855,15 @@ class InboundDirectLogService extends Service { } ); } + + // 同步数量台账:绑定模式按 committed 汇总量覆写对应明细条目(保持台账与 stored_quantity 一致) + if (entryOrderId && ledgerQuantityMap.size > 0) { + await ctx.service.systems.receivingEntryMatch.setLedgerAllocation({ + entryOrderId, + detailQuantityMap: ledgerQuantityMap, + transaction, + }); + } } /** @@ -1907,6 +1924,7 @@ class InboundDirectLogService extends Service { receivingDetailRows: boundDetails, stockInboundQtyMap, transaction, + entryOrderId: entryOrder.id, }); ctx.logger.info( diff --git a/app/service/systems/receiving_entry_match.js b/app/service/systems/receiving_entry_match.js index 0bc101e..2819b6e 100644 --- a/app/service/systems/receiving_entry_match.js +++ b/app/service/systems/receiving_entry_match.js @@ -164,6 +164,8 @@ class ReceivingEntryMatchService extends Service { await ctx.model.EntryOrderReceiving.create({ entry_order_id: entryOrderId, receiving_id: receivingId, + // 新链路绑定行台账初始化为空对象(区别于旧数据 NULL),恢复/分配时从 0 起步 + allocated_quantity: {}, }); ctx.logger.info( @@ -185,12 +187,14 @@ class ReceivingEntryMatchService extends Service { } /** - * 写入入库单与收货单的主表级绑定关系(仅主表绑定,不做明细分配)。 + * 绑定入库单与收货单(主表绑定)。 * * 流程: - * 1. 校验入库单状态 = CREATED + * 1. 校验入库单状态,仅 CREATED / COMPLETED 允许绑定,其他状态抛错 * 2. 校验每个收货单:存在、同仓库、同货主、已审核、未取消 - * 3. 逐条写入 EntryOrderReceiving.findOrCreate(主表绑定) + * 3. CREATED:保持原有逻辑,仅逐条写入 EntryOrderReceiving 主表绑定 + * 4. COMPLETED:事务内完成主表绑定 + 收货明细入库进度同步 + 收货单入库状态重算, + * 任一异常整体回滚 * * @param {Object} data 请求参数 * @param {number} data.entry_order_id 入库单 ID @@ -215,9 +219,12 @@ class ReceivingEntryMatchService extends Service { if (!entryOrder) { throw new Error('入库单不存在'); } - // 只允许 CREATED 状态 - if (entryOrder.order_status !== 'CREATED') { - throw new Error(`入库单状态不允许绑定,当前状态: ${entryOrder.order_status},仅 CREATED 状态可操作`); + // 仅允许 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; @@ -296,43 +303,68 @@ class ReceivingEntryMatchService extends Service { }; } - // ========== 第3步:逐条写入主表绑定关系 ========== + // ========== 第3步:写入主表绑定关系 ========== const boundResults = []; const skippedResults = []; - for (const receiving of validatedReceivings) { + if (entryOrder.order_status === 'COMPLETED') { + // COMPLETED:事务内完成 主表绑定 + 明细入库进度同步 + 主表入库状态重算,失败整体回滚 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, + const txResult = await this._bindReceivingsWithStorageSync({ + entryOrderId, + entryOrder, + validatedReceivings, }); + boundResults.push(...txResult.bound); + skippedResults.push(...txResult.skipped); } catch (error) { ctx.logger.error( - `[ReceivingEntryMatch] 主表绑定写入失败 entryOrderId=${entryOrderId} receivingId=${receiving.id}: ${error.message}`, + `[ReceivingEntryMatch] COMPLETED 绑定入库进度同步失败,事务已回滚 entryOrderId=${entryOrderId}: ${error.message}`, error.stack ); - skippedResults.push({ - receiving_id: receiving.id, - receiving_number: receiving.receiving_number, - error_code: 'BINDING_WRITE_FAILED', - message: `写入绑定失败: ${error.message}`, - }); + 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}`, + }); + } } } @@ -350,6 +382,1023 @@ class ReceivingEntryMatchService extends Service { }; } + /** + * 事务内为 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 缓存读取)。 * @@ -1010,10 +2059,26 @@ class ReceivingEntryMatchService extends Service { operator_name: ctx.currentUser?.employees_name || '', }, { transaction }); - // 6. 确保主级绑定存在 + // 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 }, + 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, }); } @@ -1118,44 +2183,58 @@ class ReceivingEntryMatchService extends Service { 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 }); + // 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, }); - 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: '已解除主表及明细绑定', + // 事务内重查绑定行并加锁,防止并发绑定/解绑 + 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} ` + @@ -1164,7 +2243,7 @@ class ReceivingEntryMatchService extends Service { ); failed.push({ receiving_id: receivingId, - error_code: 'UNBIND_ERROR', + error_code: error && error.error_code ? error.error_code : 'UNBIND_ERROR', message: `解绑过程异常: ${error.message}`, }); } diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 5c49134..8546d85 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -1119,39 +1119,23 @@ class EntryService extends Service { /** * 回退入库单关联收货单的入库状态(入库单作废时调用)。 - * 失败不阻塞主流程,仅打印日志。 + * 按绑定行数量台账逐单回收本入库单在收货单上的占用(不影响其他入库单的占用), + * 并清空台账;失败不阻塞主流程,仅打印日志。 * @param {number} entryOrderId 入库单ID * @return {Promise} */ async _rollbackReceivingStorageStatus(entryOrderId) { const { ctx } = this; try { - // 1. 查询关联的收货单ID列表 - const bindings = await ctx.model.EntryOrderReceiving.findAll({ - where: { entry_order_id: entryOrderId, deleted_at: null }, - attributes: [ 'receiving_id' ], - raw: true, + const result = await ctx.service.systems.receivingEntryMatch.rollbackEntryOrderBindings({ + entryOrderId, + receivingId: null, + softDeleteBinding: false, }); - const receivingIds = (bindings || [ ]).map(b => b.receiving_id).filter(Boolean); - if (receivingIds.length === 0) { - return; - } - - // 2. 回退收货单主表 storage_status → 'none' - await ctx.model.Receiving.update( - { storage_status: 'none', updated_at: new Date() }, - { where: { id: { [ctx.app.Sequelize.Op.in]: receivingIds } } } - ); - - // 3. 回退收货单明细 storage_status → 'none', stored_quantity → 0 - await ctx.model.ReceivingDetail.update( - { storage_status: 'none', stored_quantity: 0, updated_at: new Date() }, - { where: { receiving_id: { [ctx.app.Sequelize.Op.in]: receivingIds } } } - ); - ctx.logger.info( - `[storage.entry.cancel] 入库单 ${entryOrderId} 作废,已回退收货单入库状态,receivingIds=[${receivingIds.join(',')}]` + `[storage.entry.cancel] 入库单 ${entryOrderId} 作废,已按台账回退收货单入库状态,` + + `rolledBack=${JSON.stringify((result && result.rolled_back) || [])}` ); } catch (err) { ctx.logger.error( @@ -1426,9 +1410,10 @@ class EntryService extends Service { * @param {Array} params.receivingDetailRows 收货明细快照 [{ id, receiving_id, system_product_id, actual_quantity, stored_quantity }] * @param {Map} params.stockInboundQtyMap stock_id -> 本次入库量 * @param {Object} params.transaction Sequelize 事务对象 + * @param {number} [params.entryOrderId] 入库单 ID(传入时同步累加数量台账) * @return {Promise} */ - async _applyReceivingInboundUsage({ receivingDetailRows, stockInboundQtyMap, transaction }) { + async _applyReceivingInboundUsage({ receivingDetailRows, stockInboundQtyMap, transaction, entryOrderId = null }) { const { ctx, app } = this; if (!receivingDetailRows || receivingDetailRows.length === 0) return; @@ -1453,6 +1438,7 @@ class EntryService extends Service { } const touchedReceivingIds = new Set(); + const detailDeltaMap = new Map(); // 3. 逐商品分配本次入库量:使用了多少就写多少 for (const [ stockId, plan ] of stockInboundQtyMap) { @@ -1476,6 +1462,10 @@ class EntryService extends Service { transaction, }); touchedReceivingIds.add(Number(detail.receiving_id)); + detailDeltaMap.set(Number(detail.id), { + receivingId: Number(detail.receiving_id), + quantity: delta, + }); left -= delta; } } @@ -1511,6 +1501,15 @@ class EntryService extends Service { ctx.logger.info( `[storage.entry] 已回写收货单入库状态,receivingIds=[${[ ...touchedReceivingIds ].join(',')}]` ); + + // 5. 同步数量台账:本次落到各收货明细的分配量累加到对应绑定行 + if (entryOrderId && detailDeltaMap.size > 0) { + await ctx.service.systems.receivingEntryMatch.recordLedgerAllocation({ + entryOrderId, + detailDeltaMap, + transaction, + }); + } } /** @@ -1859,6 +1858,7 @@ class EntryService extends Service { receivingDetailRows: receivingDetailsSnapshot, stockInboundQtyMap: stockPlanMap, transaction, + entryOrderId: eo.id, }); } diff --git a/database/migrations/20260907160000-add-allocated-quantity-to-wms-entry-order-receiving.js b/database/migrations/20260907160000-add-allocated-quantity-to-wms-entry-order-receiving.js new file mode 100644 index 0000000..b75d5f8 --- /dev/null +++ b/database/migrations/20260907160000-add-allocated-quantity-to-wms-entry-order-receiving.js @@ -0,0 +1,72 @@ +'use strict'; + +/** + * wms_entry_order_receiving 绑定表增加 allocated_quantity(数量台账)字段。 + * + * 背景:入库单-收货单绑定后按入库单计划数量向收货单明细累加 stored_quantity, + * 同一入库单绑定多个收货单时会重复全额分配(合计超出计划数量)。 + * 修复方案 A:在绑定行上维护数量台账(收货明细ID → 已分配数量), + * 分配时按 SKU 封顶 min(入库单计划数 − 其他绑定已分配量, 收货明细剩余可入量)。 + * + * 取值约定:JSON,可空。 + * - NULL:迁移前的历史绑定行(未初始化台账,业务代码按“收货单侧已累计量”兜底重建); + * - {}:新链路创建/解绑清零后的空台账; + * - {"": }:明细级分配数量台账。 + * + * 幂等:列已存在则跳过。仅基表(无分表)。 + */ + +const TABLE_NAME = 'wms_entry_order_receiving'; + +const COLUMN_NAME = 'allocated_quantity'; + +/** + * 判断列是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const described = await queryInterface.describeTable(tableName); + return Boolean(described && described[columnName]); +} + +module.exports = { + /** + * 执行迁移:为绑定表增加 allocated_quantity 台账列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造器。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + if (await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { + console.log(`[20260907160000-add-allocated-quantity-to-wms-entry-order-receiving] up skip: ${TABLE_NAME}.${COLUMN_NAME} exists`); + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.JSON, + allowNull: true, + defaultValue: null, + comment: '数量台账:收货明细ID→已分配数量(JSON对象);null 表示旧数据未初始化', + }); + + console.log(`[20260907160000-add-allocated-quantity-to-wms-entry-order-receiving] up added: ${TABLE_NAME}.${COLUMN_NAME}`); + }, + + /** + * 回滚迁移:移除台账列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + if (!await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { + console.log(`[20260907160000-add-allocated-quantity-to-wms-entry-order-receiving] down skip: ${TABLE_NAME}.${COLUMN_NAME} missing`); + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + console.log(`[20260907160000-add-allocated-quantity-to-wms-entry-order-receiving] down removed: ${TABLE_NAME}.${COLUMN_NAME}`); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index a80bed6..fabd4de 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,68 @@ [ + { + "version": "2026.09.07-ai-method-routing-service-inventory-refresh", + "date": "2026-09-07", + "type": "changed", + "summary": "AI_METHOD_ROUTING.md 第 6 节「全量 Service Method 能力清单」按项目维护脚本重新扫描刷新:receiving_entry_match.js 由 12 个函数更新为 27 个(补齐台账/防超扣链路的 _bindReceivingsWithStorageSync、_bindOneReceivingAndSyncStorage、_syncReceivingStorageByEntryItems、_parseLedgerMap、_serializeLedgerMap、_buildLegacyBaselineLedger、_bindingAllocationByStock、_recalcReceivingStorageStatus、_reconcileEntryReceivedQuantity、recordLedgerAllocation、setLedgerAllocation、rollbackEntryOrderBindings、_rollbackOneBindingStorage 等),并同步刷新 workbench.js(52→61)、express_platform.js(16→17)、intercept_auto_confirm.js(新增)等存量漂移条目;本节内容由自动扫描脚本生成,仅函数清单、无接口行为描述。", + "methods": [ + "storage.entry.bindReceiving", + "storage.entry.unbindReceiving", + "storage.entry.cancel", + "storage.entry.commit", + "storage.entry.quickInbound" + ], + "notes": [ + "本记录是对 2026.09.07-entry-receiving-binding-allocated-quantity-ledger 同任务的补充记录:该记录撰写时判定 AI_METHOD_ROUTING.md 无需同步,随后按文件内维护说明执行刷新脚本同步了第 6 节自动扫描清单(本任务涉及 receiving_entry_match.js 新增 13 个台账/防超扣相关方法)", + "刷新方式:node .\\script\\tmp-gen-service-method-inventory.cjs(扫描 app/service/**/*.js 输出 temp/tmp-service-method-inventory.md)→ node .\\script\\tmp-update-ai-method-routing.cjs(注入 AI_METHOD_ROUTING.md 第 6 节 BEGIN/END 标记内),自动生成时间 2026-09-06 → 2026-09-07、文件数 203 → 204", + "生成器按类方法扫描,个别内置标识符(如 max、min、Set、Date、NOW)会被一并列出为方法名,属于既有生成器口径,非手工修改", + "methods/system.json 无实质变化:本次 spec 复用 storage.entry.unbindReceiving 现有条目内容,upsert 为无差异重写;接口行为、参数、响应、错误码均不变", + "本次仅同步文档,未修改任何业务代码,未执行数据库/Redis 写操作" + ], + "module": "storage.entry" + }, + { + "version": "2026.09.07-entry-receiving-binding-allocated-quantity-ledger", + "date": "2026-09-07", + "type": "changed", + "summary": "入库单绑定收货单链路防超扣修复文档同步:wms_entry_order_receiving 新增 allocated_quantity 数量台账列(JSON,收货明细ID→分配数量,迁移 20260907160000 仅基表);storage.entry.bindReceiving COMPLETED 绑定改为台账制归一化分配(每 SKU 分配目标 = min(入库单计划数 − 其他绑定已占用, 收货单剩余可入量),多退少补、旧超分数据回收、重复绑定幂等跳过、软删恢复仅分配剩余量),并同步 entry_items.received_quantity 口径;新增 storage.entry.unbindReceiving 接口文档(解绑按台账回滚 stored_quantity、重算 storage_status、清空台账,响应新增 rolled_back_quantity);storage.entry.cancel 作废回滚改台账制逐绑定回收(不再整体清零共享收货单);storage.entry.commit / storage.entry.quickInbound 分别按覆写/累计语义同步台账。", + "methods": [ + "storage.entry.bindReceiving", + "storage.entry.unbindReceiving", + "storage.entry.cancel", + "storage.entry.commit", + "storage.entry.quickInbound" + ], + "notes": [ + "app/model/entry_order_receiving.js 新增 allocated_quantity 列(JSON 可空,comment 数量台账:收货明细ID→已分配数量(JSON对象,如 {\"123\":8});null 表示旧数据未初始化);数据库迁移 database/migrations/20260907160000-add-allocated-quantity-to-wms-entry-order-receiving.js 仅基表(describeTable 幂等检测)", + "app/service/systems/receiving_entry_match.js _syncReceivingStorageByEntryItems(方案A台账版):FOR UPDATE 行锁入库单主行 + 该入库单全部未删除绑定行 + 绑定收货单明细行,串行化同一入库单的分配事务;每 SKU 分配目标 target = min(max(0, 入库单计划数 − 其他绑定已分配), 当前绑定已分配 + 收货单剩余可入量),多退少补(旧数据超分回收、亏分补分配);明细级结果回写绑定行台账 allocated_quantity,重算收货单主表 storage_status,并经 _reconcileEntryReceivedQuantity 同步 entry_items.received_quantity;返回的 storage_sync.stored_total 仅计补分配量(归一化回收不计入)", + "幂等/恢复语义:绑定已存在且未删除 → skipped(error_code=ALREADY_BOUND,不重复分配);已软删除 → restore 后按归一化目标仅分配剩余量(restored=true);并发唯一索引冲突按已绑定跳过。旧绑定行(台账 null)由 _buildLegacyBaselineLedger 按收货侧累计量兜底重建明细级台账,新链路绑定行台账初始化为 {}(非 null)", + "新增 unbindEntryOrderReceiving(对应 storage.entry.unbindReceiving):仅 CREATED / PENDING 可解绑(COMPLETED / CANCELLED 拒绝),解绑不回退入库单状态;事务内行锁后按台账逐明细回收该收货单 stored_quantity、重算明细与主表 storage_status、台账重置为 {},软删除主表绑定与关联明细绑定(InboundDirectLog status=committed 且 receiving_detail_id 非空的记录);返回 success/failed/success_count/failed_count,success 项含 released_detail_ids / released_detail_count / rolled_back_quantity(本次回滚的 stored_quantity 总量,无可回滚量为 0);不影响同一收货单上其他入库单的占用", + "app/service/systems/storage/entry.js cancel → _rollbackReceivingStorageStatus → rollbackEntryOrderBindings(receivingId=null、softDeleteBinding=false):按台账逐绑定回收、清空台账(绑定行保留)、重算 received_quantity;回滚失败仅日志不阻塞作废主流程;QM 来源入库单作废前先发送奇门取消同步,sync_status=SUCCESS 不可取消", + "app/service/systems/inbound_direct_log.js commit 绑定模式 _syncReceivingStorageStatus → receivingEntryMatch.setLedgerAllocation(按 committed 汇总量覆写台账条目);app/service/systems/storage/entry.js quickInbound _applyReceivingInboundUsage → receivingEntryMatch.recordLedgerAllocation(按本次落到收货明细的分配量累计台账)。说明:receiving_entry_match._commitBinding(PDA 明细绑定)内部调用 recordLedgerAllocation,但当前无调用方(实际 addItem 绑定走 inboundDirectLog._bindReceivingDetail),本次按实际生效链路记录,addItem 文档不改动", + "methods/system.json:storage.entry.bindReceiving 条目 description/storage_sync.stored_total 说明按台账归一化语义更新;新增 storage.entry.unbindReceiving 条目(按脚本规则追加到 storage.entry 组列表末尾);storage.entry.cancel / commit / quickInbound 描述补充台账行为;cancel errors 补充「入库单已完成回传,不可取消」;版本 0.3.96 -> 0.3.97(docMeta.version),updatedAt 保持 2026-09-07", + "README.md / AI_TOOLBOX.md / AI_METHOD_ROUTING.md 检索确认:无本链路行为描述(AI_METHOD_ROUTING.md 仅函数清单,无行为描述),无需同步", + "本次仅同步文档,未修改任何业务代码,未执行数据库/Redis 写操作" + ], + "module": "storage.entry" + }, + { + "version": "2026.09.07-entry-bindReceiving-completed-storage-sync", + "date": "2026-09-07", + "type": "changed", + "summary": "storage.entry.bindReceiving 契约变更:可绑定状态由 CREATED/PENDING 调整为 CREATED/COMPLETED;COMPLETED 绑定在事务内联动同步收货单入库进度(SKU 级累加 stored_quantity、重算明细与主表 storage_status);绑定已存在时幂等跳过不重复累加、软删除恢复后执行同步;返回结构由 success/failed/success_count/failed_count 修正为实际返回的 bound/skipped/summary,并在 COMPLETED 结果中新增 restored 与 storage_sync(含 unmatched_items)。", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "app/service/systems/receiving_entry_match.js bindEntryOrderReceiving:ALLOWED_BIND_STATUSES = [CREATED, COMPLETED],其他状态抛错「入库单状态不允许绑定,当前状态: {status},仅 CREATED、COMPLETED 状态可操作」;收货单校验含 存在未删除、同仓库、同货主、未取消、已审核(is_review)", + "COMPLETED 路径新增 _bindReceivingsWithStorageSync / _bindOneReceivingAndSyncStorage / _syncReceivingStorageByEntryItems:事务内逐收货单主表绑定 + 入库明细按 stock_id(≡ wms_receiving_detail.system_product_id)汇总,FOR UPDATE 行锁后逐明细累加 stored_quantity(上限 actual_quantity),按 stored vs actual 重算明细 storage_status(none/partial/all)并汇总更新收货单主表 storage_status;SKU 未匹配明细汇总进 unmatched_items;任一异常整体回滚", + "幂等语义:绑定已存在且未删除 → skipped(error_code=ALREADY_BOUND,不重复累加);已软删除 → restore 并执行进度同步(restored=true);并发唯一索引冲突 → 按已绑定跳过", + "methods/system.json:storage.entry.bindReceiving 条目 description/errors 按代码更新;response 由 success/failed/success_count/failed_count 修正为实际返回的 flag/code/message/bound/skipped/summary/timestamp(bound 项 CREATED 含 receiving_id/receiving_number/created,COMPLETED 新增 restored 与 storage_sync.stored_total/matched_item_count/unmatched_items;skipped 项 error_code 枚举 ALREADY_BOUND/BINDING_WRITE_FAILED;收货单校验失败不返回明细、仅 summary.skipped_count 计数);错误码同步为实际文案(抛错经 /system 全局异常处理返回 500「接口错误: ...」);版本 0.3.95 -> 0.3.96(docMeta.version),updatedAt 保持 2026-09-07", + "README.md / AI_TOOLBOX.md / AI_METHOD_ROUTING.md 检索确认:无本接口状态规则描述(AI_METHOD_ROUTING.md 仅函数清单,无行为描述),无需同步", + "本次仅同步文档,未修改任何业务代码" + ], + "module": "storage.entry" + }, { "version": "2026.09.07-store-openAccount-remove-logo-url-domain", "date": "2026-09-07", diff --git a/methods/system.json b/methods/system.json index 268a446..d5113c8 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,7 +1,7 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.95", + "version": "0.3.97", "updatedAt": "2026-09-07", "headers": [ { @@ -22722,7 +22722,7 @@ }, { "method": "storage.entry.cancel", - "description": "作废入库单(支持单条或批量作废)。CREATED(已创建待审核)和 PENDING(已审核)状态的入库单可以直接作废;已完成(COMPLETED)入库单不允许作废。", + "description": "作废入库单(支持单条或批量作废)。CREATED(已创建待审核)和 PENDING(已审核)状态的入库单可以直接作废;已完成(COMPLETED)入库单不允许作废,sync_status=SUCCESS(已完成回传)的入库单也不允许作废;QM 来源入库单作废前先发送奇门取消同步。作废成功后按绑定行数量台账(wms_entry_order_receiving.allocated_quantity,旧数据按收货侧累计量兜底)逐绑定回收本入库单在收货单上的 stored_quantity 占用、重算各收货单 storage_status、清空台账(绑定行保留不软删),并同步重算入库单明细 received_quantity;同一收货单上其他入库单的占用不受影响(不再整体清零共享收货单);回滚失败不阻塞作废主流程(仅记录日志)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -22765,11 +22765,15 @@ ], "errors": [ { - "code": "400", + "code": 400, "message": "参数错误/参数不合法:需传入非空的 id 或 ids;ids 必须为数字数组且不得包含非法或重复值;已完成(COMPLETED)入库单不允许作废" }, { - "code": "404", + "code": 400, + "message": "入库单已完成回传,不可取消" + }, + { + "code": 404, "message": "入库单不存在或无权访问" } ] @@ -22973,7 +22977,7 @@ }, { "method": "storage.entry.commit", - "description": "提交确认完成导入/PDA 入库。先同步奇门/API 回传,成功后在 onSuccess 回调内开启事务写入库存(wms_stock_warehouse.quantity 增量、wms_stock_transaction 流水),将 pending 状态的 InboundDirectLog 更新为 committed,更新入库单状态为 COMPLETED,同步 sync_status=SUCCESS。不足量提交时未入库商品跳过。noNeedNotice=1 时跳过入库完成通知(默认 0 通知)。", + "description": "提交确认完成导入/PDA 入库。先同步奇门/API 回传,成功后在 onSuccess 回调内开启事务写入库存(wms_stock_warehouse.quantity 增量、wms_stock_transaction 流水),将 pending 状态的 InboundDirectLog 更新为 committed,更新入库单状态为 COMPLETED,同步 sync_status=SUCCESS。绑定收货明细的入库(InboundDirectLog.receiving_detail_id 非空)在事务内按 committed 汇总量覆写收货明细 stored_quantity/storage_status 并重算收货单主表 storage_status,同时覆写绑定行数量台账 allocated_quantity(与 stored_quantity 保持一致,setLedgerAllocation 覆写语义)。不足量提交时未入库商品跳过。noNeedNotice=1 时跳过入库完成通知(默认 0 通知)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -23118,7 +23122,7 @@ }, { "method": "storage.entry.quickInbound", - "description": "快捷直入(虚拟入库):将入库单商品直入到虚拟库位(space_id=2),跳过收货/质检流程。有绑定收货单时,只取收货单中与入库单明细有交集(按 stock_id 判断)且剩余可入数量(actual_quantity - stored_quantity)的商品直入,实际入库量 = min(明细计划数量, 收货单剩余可入数量),并在事务内回写收货单明细已入库数量与收货单入库状态;未绑定收货单时按明细计划数量全量直入。仅支持 CREATED 状态的入库单;CANCELLED(已作废)、COMPLETED(已完成)、PENDING 等其他状态均拒绝操作。事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、回写收货单明细、变更入库单状态为 COMPLETED,并在同一事务内回写入库单 is_virtual_inbound(是否虚拟入库):有绑定收货单 → 0(非虚拟入库),无绑定收货单 → 1(虚拟入库)。事务外异步回传奇门/API。noNeedNotice=1 时跳过入库完成通知(默认 0 通知)。", + "description": "快捷直入(虚拟入库):将入库单商品直入到虚拟库位(space_id=2),跳过收货/质检流程。有绑定收货单时,只取收货单中与入库单明细有交集(按 stock_id 判断)且剩余可入数量(actual_quantity - stored_quantity)的商品直入,实际入库量 = min(明细计划数量, 收货单剩余可入数量),并在事务内回写收货单明细已入库数量与收货单入库状态、同步累加绑定行数量台账 allocated_quantity(recordLedgerAllocation 累计语义,旧台账为 null 的绑定行先按收货侧累计量兜底初始化);未绑定收货单时按明细计划数量全量直入。仅支持 CREATED 状态的入库单;CANCELLED(已作废)、COMPLETED(已完成)、PENDING 等其他状态均拒绝操作。事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、回写收货单明细、变更入库单状态为 COMPLETED,并在同一事务内回写入库单 is_virtual_inbound(是否虚拟入库):有绑定收货单 → 0(非虚拟入库),无绑定收货单 → 1(虚拟入库)。事务外异步回传奇门/API。noNeedNotice=1 时跳过入库完成通知(默认 0 通知)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [], @@ -23398,7 +23402,7 @@ }, { "method": "storage.entry.bindReceiving", - "description": "将收货单绑定到入库单(仅建立主表级关联,不做明细数量分配)。校验入库单状态(需为 CREATED 或 PENDING)、收货单有效性(存在、同仓库、未取消)后,逐个建立 wms_entry_order_receiving 绑定记录。支持部分成功:校验通过的写入绑定,不通过的在 failed 列表中返回原因。", + "description": "将收货单绑定到入库单(主表级关联 wms_entry_order_receiving)。入库单仅 CREATED、COMPLETED 状态允许绑定,其他状态抛错;收货单须存在且未删除、与入库单同仓库、同货主、未取消(status≠cancelled)、已审核(is_review)。CREATED 绑定:逐条写入主表绑定(幂等,已存在跳过),绑定行数量台账 allocated_quantity 初始化为空对象 {}(区别于旧数据 null),仅建立关联、不做入库进度同步。COMPLETED 绑定:事务内完成主表绑定 + 收货单入库进度同步(数量台账版防超扣)——FOR UPDATE 行锁入库单主行、该入库单全部未删除绑定行及相关收货单明细行,串行化同一入库单的分配事务;入库单明细按 SKU 汇总(entry_items.stock_id ≡ wms_receiving_detail.system_product_id),每 SKU 分配目标 = min(入库单计划数量 − 其他未删除绑定已分配量, 当前收货单该 SKU 剩余可入量),按明细 id 升序逐行补分配或回收(多退少补:旧数据超分回收、亏分补分配),同步更新收货明细 stored_quantity/storage_status(none/partial/all)、回写绑定行台账 allocated_quantity(收货明细ID→分配数量)、重算收货单主表 storage_status,并同步重算 entry_items.received_quantity(入库单侧已入库量,与各绑定收货单 stored_quantity 之和可对账);绑定已存在且未删除时跳过进度同步(幂等不重复分配),软删除绑定恢复后按归一化目标仅分配剩余量(旧超分数据归一化回收);SKU 未匹配的入库明细仅记录 unmatched_items 不阻塞;任一异常事务整体回滚。creator_id 由服务端从登录态自动注入,无需前端传值。支持部分成功:逐个收货单处理,跳过项计入 skipped。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -23427,67 +23431,162 @@ ], "response": [ { - "name": "success", - "type": "array", + "name": "flag", + "type": "string", "required": true, - "description": "绑定成功列表,每项包含 receiving_id、receiving_number" + "description": "success" }, { - "name": "failed", + "name": "code", + "type": "number", + "required": true, + "description": "1" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息(绑定完成)" + }, + { + "name": "bound", "type": "array", "required": true, - "description": "绑定失败列表,每项包含 receiving_id、error_code、message", - "items": { - "type": "object", - "properties": { - "receiving_id": { - "type": "number", - "description": "收货单ID" - }, - "receiving_number": { - "type": "string", - "description": "收货单号(部分失败项可能不返回)" - }, - "error_code": { - "type": "string", - "description": "错误码,可能值:RECEIVING_NOT_FOUND(收货单不存在或已删除)、RECEIVING_NOT_REVIEWED(收货单未审核)、WAREHOUSE_MISMATCH(收货单与入库单仓库不一致)、RECEIVING_CANCELLED(收货单已取消)、OWNER_MISMATCH(收货单与入库单货主不一致)、BIND_ERROR(绑定过程异常)" - }, - "message": { - "type": "string", - "description": "中文错误描述" - } + "description": "绑定/进度同步成功列表。CREATED 每项含 receiving_id、receiving_number、created;COMPLETED 每项额外含 restored(软删除恢复为 true)与 storage_sync(入库进度同步结果,含 stored_total、matched_item_count、unmatched_items)", + "children": [ + { + "name": "receiving_id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "receiving_number", + "type": "string", + "required": true, + "description": "收货单号" + }, + { + "name": "created", + "type": "boolean", + "required": true, + "description": "本次是否新建绑定(CREATED 为 findOrCreate 结果;COMPLETED 新建或恢复均为 true)" + }, + { + "name": "restored", + "type": "boolean", + "required": false, + "description": "仅 COMPLETED:是否由已软删除的绑定关系恢复(恢复后按归一化目标执行进度同步)" + }, + { + "name": "storage_sync", + "type": "object", + "required": false, + "description": "仅 COMPLETED 新建/恢复绑定时返回的入库进度同步结果", + "children": [ + { + "name": "stored_total", + "type": "number", + "required": true, + "description": "本次补分配到收货单明细 stored_quantity 的总数量(归一化回收的超分数量不计入;无分配变化时可为 0)" + }, + { + "name": "matched_item_count", + "type": "number", + "required": true, + "description": "成功补分配数量(allocated>0)的 SKU 数量" + }, + { + "name": "unmatched_items", + "type": "array", + "required": true, + "description": "未匹配到收货明细的入库明细 SKU 列表(仅记录跳过,不影响绑定),每项含 stock_id、item_code、count" + } + ] } - } + ] }, { - "name": "success_count", - "type": "number", + "name": "skipped", + "type": "array", "required": true, - "description": "成功数量" + "description": "跳过列表,每项含 receiving_id、receiving_number、error_code、message。error_code 可能值:ALREADY_BOUND(绑定已存在,COMPLETED 幂等跳过进度同步,不重复分配)、BINDING_WRITE_FAILED(CREATED 写入绑定失败)。收货单校验失败(不存在/跨仓/跨货主/已取消/未审核)时 skipped 为空数组、仅 summary.skipped_count 计数(失败明细仅服务端日志)" }, { - "name": "failed_count", + "name": "summary", + "type": "object", + "required": true, + "description": "汇总统计", + "children": [ + { + "name": "bound_count", + "type": "number", + "required": true, + "description": "成功数量" + }, + { + "name": "skipped_count", + "type": "number", + "required": true, + "description": "跳过/失败数量(含收货单校验失败数)" + } + ] + }, + { + "name": "timestamp", "type": "number", "required": true, - "description": "失败数量" + "description": "响应时间戳(秒)" } ], "errors": [ { - "code": 400, - "message": "参数校验失败:entry_order_id 必填 / receiving_ids 必填且为非空数组 / 入库单状态不允许绑定(当前状态非 CREATED/PENDING)" + "code": 500, + "message": "接口错误: entry_order_id 不能为空" }, { - "code": 404, - "message": "入库单不存在" + "code": 500, + "message": "接口错误: receiving_ids 不能为空且必须为数组" + }, + { + "code": 500, + "message": "接口错误: 入库单不存在" + }, + { + "code": 500, + "message": "接口错误: 入库单状态不允许绑定,当前状态: {当前状态},仅 CREATED、COMPLETED 状态可操作" + }, + { + "code": 500, + "message": "接口错误: 入库单绑定收货单失败,已回滚: {原因}(COMPLETED 事务内主表绑定+进度同步任一异常整体回滚)" + }, + { + "code": "RECEIVING_NOT_FOUND", + "message": "收货单不存在或已删除(业务校验失败不抛错:skipped 为空数组,计入 summary.skipped_count,失败明细仅服务端日志)" + }, + { + "code": "WAREHOUSE_MISMATCH", + "message": "收货单与入库单不属于同一仓库(处理同上)" }, { "code": "OWNER_MISMATCH", - "message": "收货单与入库单货主不一致" + "message": "收货单与入库单货主不一致(处理同上)" + }, + { + "code": "RECEIVING_CANCELLED", + "message": "收货单已取消(处理同上)" }, { "code": "RECEIVING_NOT_REVIEWED", - "message": "收货单未审核" + "message": "收货单未审核(处理同上)" + }, + { + "code": "ALREADY_BOUND", + "message": "绑定关系已存在,跳过入库进度同步(COMPLETED 幂等,计入 skipped,不重复分配 stored_quantity)" + }, + { + "code": "BINDING_WRITE_FAILED", + "message": "写入绑定失败: {原因}(CREATED 逐条写入异常,计入 skipped)" } ] }, @@ -23727,6 +23826,144 @@ "message": "查询失败" } ] + }, + { + "method": "storage.entry.unbindReceiving", + "description": "解除入库单与收货单的主表绑定关系,并按数量台账回滚该收货单的入库进度。仅 CREATED / PENDING 状态的入库单可解绑(COMPLETED / CANCELLED 不允许),解绑不回退入库单状态。逐个收货单处理:主表绑定不存在计入 failed(BINDING_NOT_FOUND);存在则在事务内 FOR UPDATE 行锁入库单主行与绑定行,按绑定行台账(wms_entry_order_receiving.allocated_quantity,旧数据按收货侧累计量兜底)逐明细回收该收货单 stored_quantity、重算明细与主表 storage_status、台账重置为空对象 {},软删除主表绑定与关联明细绑定(InboundDirectLog 中 status=committed 且 receiving_detail_id 非空、属于该收货单的记录);同一收货单上其他入库单的占用不受影响。返回 success/failed/success_count/failed_count,success 项含 rolled_back_quantity(本次回滚的 stored_quantity 总量)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + }, + { + "name": "receiving_ids", + "type": "array", + "required": true, + "source": "body", + "description": "要解除绑定的收货单ID列表,每项为 integer" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "1" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息(解绑完成)" + }, + { + "name": "success", + "type": "array", + "required": true, + "description": "解绑成功列表,每项含 receiving_id、released_detail_ids、released_detail_count、rolled_back_quantity、message", + "children": [ + { + "name": "receiving_id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "released_detail_ids", + "type": "array", + "required": true, + "description": "已软删除的关联明细绑定对应的收货明细ID列表(wms_receiving_detail.id)" + }, + { + "name": "released_detail_count", + "type": "number", + "required": true, + "description": "已软删除的关联明细绑定数(InboundDirectLog 中 status=committed 且 receiving_detail_id 非空的记录数)" + }, + { + "name": "rolled_back_quantity", + "type": "number", + "required": true, + "description": "本次按台账回滚的该收货单 stored_quantity 总量(无可回滚量时为 0)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "处理结果说明(已解除绑定并回滚收货单入库进度)" + } + ] + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "解绑失败列表,每项含 receiving_id、error_code、message。error_code 可能值:BINDING_NOT_FOUND(主表绑定不存在)、ENTRY_ORDER_NOT_FOUND(入库单不存在)、ENTRY_ORDER_STATUS_INVALID(入库单状态不允许解绑)、UNBIND_ERROR(解绑过程异常)" + }, + { + "name": "success_count", + "type": "number", + "required": true, + "description": "解绑成功数量" + }, + { + "name": "failed_count", + "type": "number", + "required": true, + "description": "解绑失败数量" + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "响应时间戳(秒)" + } + ], + "errors": [ + { + "code": 500, + "message": "接口错误: entry_order_id 不能为空" + }, + { + "code": 500, + "message": "接口错误: receiving_ids 不能为空且必须为数组" + }, + { + "code": "ENTRY_ORDER_NOT_FOUND", + "message": "入库单不存在(业务校验失败不抛错:success 为空数组,全部收货单计入 failed,failed_count=请求收货单数)" + }, + { + "code": "ENTRY_ORDER_STATUS_INVALID", + "message": "入库单状态不允许解绑,当前状态: {状态}(仅 CREATED、PENDING 可解绑;处理同上不抛错)" + }, + { + "code": "BINDING_NOT_FOUND", + "message": "主表绑定不存在(计入 failed)" + }, + { + "code": "UNBIND_ERROR", + "message": "解绑过程异常: {原因}(计入 failed,已执行的回滚在事务内回退)" + } + ] } ] },