From 59eb736740b94eb2fac62c15cf5e88ad14b3808a Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 27 Aug 2026 23:41:47 +0800 Subject: [PATCH] =?UTF-8?q?feat(storage):=20=E8=A1=A5=E8=B4=A7=E9=9C=80?= =?UTF-8?q?=E6=B1=82=E6=94=AF=E6=8C=81=E8=B4=A7=E4=B8=BB=E7=AD=9B=E9=80=89?= =?UTF-8?q?=E5=B9=B6=E8=A1=A5=E5=85=85=E8=B4=A7=E4=B8=BB=E5=90=8D=E7=A7=B0?= =?UTF-8?q?=E4=B8=8ESKU=E6=9D=A1=E7=A0=81=EF=BC=8C=E5=BF=AB=E6=8D=B7?= =?UTF-8?q?=E7=9B=B4=E5=85=A5=E6=8C=89=E7=BB=91=E5=AE=9A=E6=94=B6=E8=B4=A7?= =?UTF-8?q?=E5=8D=95=E6=88=AA=E6=96=AD=E5=B9=B6=E5=9B=9E=E5=86=99=E5=85=A5?= =?UTF-8?q?=E5=BA=93=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../systemMethods/storage/management.js | 25 ++ app/service/systems/storage/entry.js | 232 ++++++++++++++++-- app/service/systems/storage/management.js | 80 +++++- 3 files changed, 310 insertions(+), 27 deletions(-) diff --git a/app/service/systemMethods/storage/management.js b/app/service/systemMethods/storage/management.js index 53e0d15..765c77a 100644 --- a/app/service/systemMethods/storage/management.js +++ b/app/service/systemMethods/storage/management.js @@ -27,6 +27,7 @@ class StorageManagementMethodService extends MainService { * @param {Object} [data={}] 请求参数。 * @param {Object} [data.pagination] 分页参数。 * @param {Object} [data.sort] 排序参数。 + * @param {number|number[]} [data.store_id] 货主筛选:单值或数组(正整数),也可通过 data.where.store_id 传入;不传时返回全部货主。 * @return {Promise} 统一 success 包装的补货需求明细、汇总与分页信息。 */ async replenishmentDemand(data = {}) { @@ -34,9 +35,33 @@ class StorageManagementMethodService extends MainService { const requestData = this.isPlainObject(data) ? data : {}; const pagination = requestData.pagination || {}; const sort = requestData.sort || requestData.order || {}; + const where = this.isPlainObject(requestData.where) ? requestData.where : {}; + + // 货主筛选:支持顶层 store_id / store_ids,或 where.store_id(单值/数组) + const rawStoreIdValue = requestData.store_id !== undefined && requestData.store_id !== null + ? requestData.store_id + : (requestData.store_ids !== undefined && requestData.store_ids !== null + ? requestData.store_ids + : where.store_id); + + let storeIds = []; + if (rawStoreIdValue !== undefined && rawStoreIdValue !== null && rawStoreIdValue !== '') { + const rawList = Array.isArray(rawStoreIdValue) ? rawStoreIdValue : [ rawStoreIdValue ]; + const normalizedStoreIds = new Set(); + for (const item of rawList) { + const value = Number(item); + if (!Number.isFinite(value) || value <= 0 || !Number.isInteger(value)) { + throw new Error(`store_id 必须是正整数,非法值: ${item}`); + } + normalizedStoreIds.add(value); + } + storeIds = Array.from(normalizedStoreIds); + } + const result = await service.systems.storage.management.replenishmentDemand({ pagination, sort, + storeIds, }); return this.success('补货需求计算完成', result); } diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 644a9d3..8a2278f 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -1416,7 +1416,107 @@ class EntryService extends Service { } /** - * 快捷直入/虚拟入库:将入库单的所有商品按明细数量全部直入到虚拟库位(space_id=2),跳过收货、质检等正常流程。 + * 快捷直入后回写绑定收货单的明细已入库数量与入库状态(事务内)。 + * 按 stock_id(=收货明细 system_product_id)把本次入库量依次分配到收货明细上, + * 每个明细最多分配其剩余可入数量(actual_quantity - stored_quantity), + * 分配后更新明细 stored_quantity/storage_status,并按各明细实际入库量 + * (stored_quantity 与 actual_quantity 比较)汇总更新收货单主表 storage_status: + * 全部明细均已足量入库才置 all,否则有部分入库置 partial,全部未入库置 none。 + * @param {Object} params 参数 + * @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 事务对象 + * @return {Promise} + */ + async _applyReceivingInboundUsage({ receivingDetailRows, stockInboundQtyMap, transaction }) { + const { ctx, app } = this; + + if (!receivingDetailRows || receivingDetailRows.length === 0) return; + + // 1. 事务内行锁重新读取收货明细,避免并发超额分配 + const detailIds = receivingDetailRows.map(d => d.id); + const lockedDetails = await ctx.model.ReceivingDetail.findAll({ + where: { id: { [app.Sequelize.Op.in]: detailIds } }, + lock: transaction.LOCK.UPDATE, + order: [[ 'id', 'ASC' ]], + transaction, + raw: true, + }); + + // 2. 按 system_product_id(=stock_id)分组,同一商品多条明细按 id 升序依次分配 + const detailsByStock = new Map(); + for (const d of lockedDetails) { + const spid = Number(d.system_product_id); + if (!spid) continue; + if (!detailsByStock.has(spid)) detailsByStock.set(spid, []); + detailsByStock.get(spid).push(d); + } + + const touchedReceivingIds = new Set(); + + // 3. 逐商品分配本次入库量:使用了多少就写多少 + for (const [ stockId, plan ] of stockInboundQtyMap) { + let left = Number(plan.inboundQty) || 0; + const details = detailsByStock.get(Number(stockId)) || []; + 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 delta = Math.min(left, remain); + const newStored = stored + delta; + 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, + }); + touchedReceivingIds.add(Number(detail.receiving_id)); + left -= delta; + } + } + + // 4. 按实际入库量汇总更新收货单主表 storage_status: + // 全部明细均已足量入库(stored >= actual)→ all;存在部分入库 → partial;全部未入库 → none + for (const receivingId of touchedReceivingIds) { + const allDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingId }, + attributes: [ 'actual_quantity', 'stored_quantity' ], + raw: true, + transaction, + }); + + let masterStatus = 'none'; + const fullyStored = allDetails.length > 0 + && allDetails.every(d => (Number(d.stored_quantity) || 0) >= (Number(d.actual_quantity) || 0)); + if (fullyStored) { + masterStatus = 'all'; + } else if (allDetails.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, + }); + } + + ctx.logger.info( + `[storage.entry] 已回写收货单入库状态,receivingIds=[${[ ...touchedReceivingIds ].join(',')}]` + ); + } + + /** + * 快捷直入/虚拟入库:将入库单明细直入到虚拟库位(space_id=2),跳过收货、质检等正常流程。 + * 有绑定收货单时,只取收货单中与入库单明细有交集(按 stock_id 判断)且剩余可入数量的部分直入, + * 并回写收货单明细已入库数量;未绑定收货单时按明细计划数量全量直入。 * 采用"先同步后写库"两段式:① 先发奇门/OpenAPI 回传,② 回传成功后再开启事务写库存。 * @param {Object} data 请求体 * @param {number} data.id 入库单ID @@ -1479,18 +1579,79 @@ class EntryService extends Service { }; } + // 2.1 查询绑定收货单("已绑定"状态),按 stock_id 聚合收货明细剩余可入数量 + const bindings = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: entryOrder.id, deleted_at: null }, + attributes: [ 'receiving_id' ], + raw: true, + }); + const receivingIds = [ ...new Set((bindings || []).map(b => Number(b.receiving_id)).filter(Boolean)) ]; + + // 收货明细快照(用于事务内行锁回写),stockRemainingMap: null=未绑定(全量直入) + let receivingDetailsSnapshot = []; + let stockRemainingMap = null; + if (receivingIds.length > 0) { + const boundDetails = await ctx.model.ReceivingDetail.findAll({ + where: { + receiving_id: { [app.Sequelize.Op.in]: receivingIds }, + system_product_id: { [app.Sequelize.Op.ne]: null }, + }, + attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity' ], + raw: true, + }); + receivingDetailsSnapshot = boundDetails; + stockRemainingMap = new Map(); + for (const d of boundDetails) { + const spid = Number(d.system_product_id); + const remaining = Math.max(0, (Number(d.actual_quantity) || 0) - (Number(d.stored_quantity) || 0)); + stockRemainingMap.set(spid, (stockRemainingMap.get(spid) || 0) + remaining); + } + } + + // 2.2 按入库单明细计算实际直入数量:有绑定时只取收货单中有交集(stock_id)且剩余可入的数量 + const inboundPlans = entryItems.map(item => { + const planQty = Number(item.count) || 0; + let inboundQty = planQty; + if (stockRemainingMap) { + const stockId = Number(item.stock_id) || 0; + if (!stockId || !stockRemainingMap.has(stockId)) { + inboundQty = 0; // 收货单无交集商品,跳过 + } else { + const remaining = stockRemainingMap.get(stockId) || 0; + inboundQty = Math.min(planQty, remaining); + stockRemainingMap.set(stockId, remaining - inboundQty); + } + } + return { item, planQty, inboundQty }; + }); + + const effectivePlans = inboundPlans.filter(p => p.inboundQty > 0); + if (effectivePlans.length === 0) { + return { + code: 400, + message: stockRemainingMap + ? '收货单中无交集商品或剩余可入数量不足,无法快捷直入' + : '入库明细数量均为0,无法快捷直入', + data: { id: entryOrder.id, entry_order_code: entryOrder.entry_order_code }, + }; + } + + // 存在被截断/跳过的明细时按部分入库回传(confirmType=1, PARTFULFILLED) + const isPartialInbound = inboundPlans.some(p => p.inboundQty < p.planQty); + // ===== 阶段一 + 阶段二合并为统一调用 ===== const syncResult = await ctx.service.systems.inboundDirectLog.qimenEntrySync({ entryOrder, - orderLines: entryItems.map((item, idx) => ({ + orderLines: effectivePlans.map((plan, idx) => ({ orderLineNo: idx + 1, - ownerCode: item.owner_code || '', - itemCode: item.item_code || '', - itemId: item.item_id || '', - inventoryType: item.inventory_type || 'ZP', - planQty: Number(item.count) || 0, - actualQty: Number(item.count) || 0, + ownerCode: plan.item.owner_code || '', + itemCode: plan.item.item_code || '', + itemId: plan.item.item_id || '', + inventoryType: plan.item.inventory_type || 'ZP', + planQty: plan.planQty, + actualQty: plan.inboundQty, })), + isFin: !isPartialInbound, outBizCode: `DIRECT_INBOUND_${Date.now()}`, remark: '导入/PDA直接入库提交', operator: { @@ -1506,27 +1667,39 @@ class EntryService extends Service { const processedStockIds = new Set(); let totalInboundQty = 0; + let totalPlanQty = 0; + + // 按 stock_id 汇总本次实际入库量与库存类型(有绑定收货单时实际入库量 ≤ 计划量) + const stockPlanMap = new Map(); + for (const plan of inboundPlans) { + totalPlanQty += plan.planQty; + if (plan.inboundQty <= 0) continue; + const stockId = Number(plan.item.stock_id); + if (!stockId) continue; + const cur = stockPlanMap.get(stockId) || { inboundQty: 0, inventoryType: plan.item.inventory_type || 'ZP' }; + cur.inboundQty += plan.inboundQty; + stockPlanMap.set(stockId, cur); + totalInboundQty += plan.inboundQty; + } + + if (totalInboundQty <= 0) { + throw new Error('无有效可入明细,快捷直入失败'); + } try { - for (const item of entryItems) { - const stockId = item.stock_id; - if (!stockId) continue; - - const planQty = Number(item.count) || 0; - if (planQty <= 0) continue; - - const inventoryType = item.inventory_type || 'ZP'; - + // 回写入库单明细:本次实际入库多少写多少(跳过明细写 0) + for (const plan of inboundPlans) { await ctx.model.EntryItems.update({ - received_quantity: planQty, + received_quantity: plan.inboundQty, }, { - where: { id: item.id }, + where: { id: plan.item.id }, transaction, }); + } - if (processedStockIds.has(String(stockId))) continue; - processedStockIds.add(String(stockId)); - totalInboundQty += planQty; + for (const [ stockId, plan ] of stockPlanMap) { + const planQty = plan.inboundQty; + const inventoryType = plan.inventoryType; const stockRecord = await ctx.model.StockWarehouse.findOne({ where: { id: stockId, is_valid: 'Y', deleted_at: null }, @@ -1658,12 +1831,22 @@ class EntryService extends Service { }, { transaction }); } + // 回写绑定收货单明细已入库数量与入库状态(有绑定收货单时) + if (receivingDetailsSnapshot.length > 0) { + await this._applyReceivingInboundUsage({ + receivingDetailRows: receivingDetailsSnapshot, + stockInboundQtyMap: stockPlanMap, + transaction, + }); + } + await eo.update({ order_status: 'COMPLETED', sync_status: 'SUCCESS', sync_message: JSON.stringify({ completedAt: new Date(), totalQuantity: totalInboundQty, + planQuantity: totalPlanQty, itemCount: processedStockIds.size, source: 'quick_inbound', }), @@ -1715,8 +1898,9 @@ class EntryService extends Service { entry_order_code: entryOrder.entry_order_code, order_status: 'COMPLETED', sync_status: 'SUCCESS', - items_count: entryItems.length, - total_quantity: entryItems.reduce((s, item) => s + (Number(item.count) || 0), 0), + items_count: effectivePlans.length, + total_quantity: effectivePlans.reduce((s, p) => s + p.inboundQty, 0), + plan_quantity: entryItems.reduce((s, item) => s + (Number(item.count) || 0), 0), }, }; } diff --git a/app/service/systems/storage/management.js b/app/service/systems/storage/management.js index f57d34d..09a0a68 100644 --- a/app/service/systems/storage/management.js +++ b/app/service/systems/storage/management.js @@ -54,12 +54,17 @@ class StorageManagementService extends Service { * @param {Object} [options.sort] 排序参数。 * @param {string} [options.sort.sortField='shortage'] 排序字段,默认 shortage。 * @param {string} [options.sort.sortOrder='DESC'] 排序方向,ASC/DESC。 + * @param {number[]} [options.storeIds] 货主筛选:仅返回指定货主的 SKU,空数组表示不筛选。 * @return {Promise} 补货需求明细、汇总与分页信息。 */ async replenishmentDemand(options = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; + // 货主筛选集合(空数组 = 不筛选) + const storeIds = Array.isArray(options.storeIds) ? options.storeIds : []; + const storeFilterSet = storeIds.length > 0 ? new Set(storeIds) : null; + // 仓库上下文:从用户上下文获取 const warehouseId = toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0); @@ -127,7 +132,7 @@ class StorageManagementService extends Service { is_valid: 'Y', deleted_at: null, }, - attributes: [ 'id', 'item_code', 'item_name' ], + attributes: [ 'id', 'item_code', 'item_name', 'store_id' ], raw: true, }) : []; @@ -139,6 +144,7 @@ class StorageManagementService extends Service { const stockId = toNumber(row.id, 0); if (stockId <= 0) continue; stockInfoMap.set(stockId, { + store_id: toNumber(row.store_id, 0), stock_code: String(row.item_code || ''), stock_name: String(row.item_name || ''), }); @@ -153,7 +159,7 @@ class StorageManagementService extends Service { id: { [Op.in]: missedStockIds }, deleted_at: null, }, - attributes: [ 'id', 'item_code', 'item_name' ], + attributes: [ 'id', 'item_code', 'item_name', 'store_id' ], raw: true, }); @@ -161,6 +167,7 @@ class StorageManagementService extends Service { const stockId = toNumber(row.id, 0); if (stockId <= 0 || stockInfoMap.has(stockId)) continue; stockInfoMap.set(stockId, { + store_id: toNumber(row.store_id, 0), stock_code: String(row.item_code || ''), stock_name: String(row.item_name || ''), }); @@ -174,7 +181,7 @@ class StorageManagementService extends Service { where: { id: { [Op.in]: stillMissedStockIds }, }, - attributes: [ 'id', 'item_code', 'item_name' ], + attributes: [ 'id', 'item_code', 'item_name', 'store_id' ], raw: true, }); @@ -182,12 +189,72 @@ class StorageManagementService extends Service { const stockId = toNumber(row.id, 0); if (stockId <= 0 || stockInfoMap.has(stockId)) continue; stockInfoMap.set(stockId, { + store_id: toNumber(row.store_id, 0), stock_code: String(row.item_code || ''), stock_name: String(row.item_name || ''), }); } } + // 4.5) 查询货主名称与 SKU 条码 + const ownerStoreIds = Array.from( + new Set( + Array.from(stockInfoMap.values()) + .map(info => toNumber(info.store_id, 0)) + .filter(id => id > 0) + ) + ); + + const [ storeWarehouseRows, storeRows, barcodeRows ] = await Promise.all([ + ownerStoreIds.length > 0 + ? ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [Op.in]: ownerStoreIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }) + : [], + ownerStoreIds.length > 0 + ? ctx.model.Store.findAll({ + where: { id: { [Op.in]: ownerStoreIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }) + : [], + ctx.model.StockBarcode.findAll({ + where: { stock_id: { [Op.in]: allStockIds } }, + attributes: [ 'id', 'stock_id', 'barcode' ], + raw: true, + }), + ]); + + // 货主名称:签约表备注名 store_remask 优先,商家表 company_name 兜底 + const storeNameMap = new Map(); + for (const row of Array.isArray(storeRows) ? storeRows : []) { + const storeId = toNumber(row.id, 0); + if (storeId > 0) storeNameMap.set(storeId, String(row.company_name || '')); + } + for (const row of Array.isArray(storeWarehouseRows) ? storeWarehouseRows : []) { + const storeId = toNumber(row.store_id, 0); + const remask = String(row.store_remask || '').trim(); + if (storeId > 0 && remask) storeNameMap.set(storeId, remask); + } + + // SKU 条码按 stock_id 分组 + const barcodeMap = new Map(); + for (const row of Array.isArray(barcodeRows) ? barcodeRows : []) { + const stockId = toNumber(row.stock_id, 0); + if (stockId <= 0) continue; + const barcodeList = barcodeMap.get(stockId) || []; + barcodeList.push({ + id: toNumber(row.id, 0), + barcode: String(row.barcode || ''), + }); + barcodeMap.set(stockId, barcodeList); + } + // 5) 查询所有可用库存(不区分分拣/存货区),再按库位类型分类汇总 const storageRows = allStockIds.length > 0 ? await ctx.model.Storage.findAll({ @@ -263,6 +330,10 @@ class StorageManagementService extends Service { for (const stockId of allStockIds) { const info = stockInfoMap.get(stockId) || { stock_code: `SKU#${stockId}`, stock_name: `商品#${stockId}` }; + + // 货主筛选:仅返回指定货主的 SKU + if (storeFilterSet && !storeFilterSet.has(info.store_id || 0)) continue; + const totalDemand = demandByStockId.get(stockId) || 0; const pickZoneQty = pickZoneQtyByStockId.get(stockId) || 0; const storageZoneQty = storageZoneQtyByStockId.get(stockId) || 0; @@ -280,6 +351,9 @@ class StorageManagementService extends Service { stock_id: stockId, stock_code: info.stock_code, stock_name: info.stock_name, + store_id: info.store_id || 0, + store_name: storeNameMap.get(info.store_id) || '', + barcodes: barcodeMap.get(stockId) || [], pick_zone_quantity: pickZoneQty, storage_zone_quantity: storageZoneQty, total_demand: totalDemand,