'use strict'; const Service = require('egg').Service; const DAY_MS = 24 * 60 * 60 * 1000; /** * 计算库存批次的保质期预警状态。 * * @param {Object} stock 商品库存资料 * @param {string|Date|null} expiryDate 批次到期日期 * @param {number} [nowMs=Date.now()] 当前时间戳 * @return {{remainingDays: (number|null), isTriggered: boolean}} 预警信息 */ function getShelfLifeWarningState(stock = {}, expiryDate = null, nowMs = Date.now()) { const expiryTime = expiryDate ? new Date(expiryDate).getTime() : null; const remainingDays = expiryTime === null || Number.isNaN(expiryTime) ? null : Math.max(0, Math.ceil((expiryTime - nowMs) / DAY_MS)); const isShelfLifeMgmt = stock.is_shelf_life_mgmt === 'Y' || stock.is_shelf_life_mgmt === true; const thresholdDays = Number(stock.remaining_threshold_days) || 0; return { remainingDays, isTriggered: Boolean(isShelfLifeMgmt && thresholdDays > 0 && remainingDays !== null && remainingDays <= thresholdDays), }; } /** * 将库存预警规则转换为按到期天数递增的区间配置。 * * @param {Array} warningRules 库存预警规则 * @return {Array<{name: string, key: string, tip_text: string, min_days: number, max_days: number}>} 规则区间列表 */ function buildInventoryWarningRanges(warningRules = []) { if (!Array.isArray(warningRules) || !warningRules.length) { return []; } const sortedRules = warningRules .filter(rule => rule && typeof rule === 'object') .map(rule => ({ name: rule.name, key: rule.key, tip_text: rule.tip_text === undefined || rule.tip_text === null ? '' : String(rule.tip_text), expire_days: Number(rule.expire_days), })) .filter(rule => Number.isInteger(rule.expire_days) && rule.expire_days >= 0) .sort((a, b) => a.expire_days - b.expire_days); let previousMax = null; return sortedRules.map(rule => { const minDays = previousMax === null ? 0 : previousMax + 1; const maxDays = rule.expire_days; previousMax = maxDays; return { name: rule.name, key: rule.key, tip_text: rule.tip_text, min_days: minDays, max_days: maxDays, }; }); } /** * 根据剩余天数命中库存预警规则并返回响应字段。 * * @param {number|null} remainingDays 到期剩余天数 * @param {Array} warningRanges 预警规则区间 * @return {{expiry_remaining_days: (number|null), inventory_warning_level: (string|null), inventory_warning_color: (string|null), inventory_warning_range: ({min_days: number, max_days: number}|null), inventory_warning_tip_text: (string|null)}} 预警输出字段 */ function getInventoryWarningPayload(remainingDays, warningRanges = []) { if (!Number.isInteger(remainingDays) || !Array.isArray(warningRanges) || !warningRanges.length) { return { expiry_remaining_days: null, inventory_warning_level: null, inventory_warning_color: null, inventory_warning_range: null, inventory_warning_tip_text: null, }; } const matchedRange = warningRanges.find(rule => ( remainingDays >= rule.min_days && remainingDays <= rule.max_days )); if (!matchedRange) { return { expiry_remaining_days: remainingDays, inventory_warning_level: null, inventory_warning_color: null, inventory_warning_range: null, inventory_warning_tip_text: null, }; } return { expiry_remaining_days: remainingDays, inventory_warning_level: matchedRange.name || null, inventory_warning_color: matchedRange.key || null, inventory_warning_range: { min_days: matchedRange.min_days, max_days: matchedRange.max_days, }, inventory_warning_tip_text: matchedRange.tip_text, }; } /** * 将库存商品上的标记值规范化为布尔值。 * * @param {unknown} value 待转换的标记值 * @return {boolean} 是否为真值 */ function toBooleanFlag(value) { if (typeof value === 'boolean') { return value; } if (typeof value === 'number') { return value === 1; } if (typeof value === 'string') { return [ 'Y', '1', 'TRUE', 'T', 'YES' ].includes(value.trim().toUpperCase()); } return false; } /** * 将模型查询结果转换为普通对象。 * * @param {unknown} record 模型记录或普通对象 * @return {Object|null} 普通对象 */ function toPlainRecord(record) { if (!record) { return null; } if (typeof record.get === 'function') { return record.get({ plain: true }); } return record; } /** * 批量加载库存商品的条码与图片附属信息。 * * @param {Object} ctx 当前请求上下文 * @param {number[]} stockIds 商品ID列表 * @return {Promise<{barcodesByStockId: Map, imagesByStockId: Map}>} 附属信息映射 */ async function loadStockAttachments(ctx, stockIds = []) { const uniqueStockIds = [ ...new Set( Array.isArray(stockIds) ? stockIds.map(item => Number(item)).filter(Boolean) : [] ) ]; const barcodesByStockId = new Map(); const imagesByStockId = new Map(); if (!uniqueStockIds.length) { return { barcodesByStockId, imagesByStockId }; } const hasStockBarcodeModel = ctx.model && ctx.model.StockBarcode && typeof ctx.model.StockBarcode.findAll === 'function'; if (hasStockBarcodeModel) { try { const barcodeRows = await ctx.model.StockBarcode.findAll({ where: { stock_id: { [ctx.app.Sequelize.Op.in]: uniqueStockIds, }, }, attributes: [ 'stock_id', 'barcode' ], raw: true, }); for (const item of barcodeRows || []) { const row = toPlainRecord(item); if (!row) { continue; } const stockId = Number(row.stock_id); const barcode = row.barcode ? String(row.barcode) : ''; if (!stockId || !barcode) { continue; } if (!barcodesByStockId.has(stockId)) { barcodesByStockId.set(stockId, []); } barcodesByStockId.get(stockId).push(barcode); } } catch (error) { ctx.logger?.warn?.('[storage.inventory] 查询商品条码失败,已降级为空数组', { error: error.message, }); } } const hasFileReferenceModel = ctx.model && ctx.model.FileReference && typeof ctx.model.FileReference.findAll === 'function'; const hasFileModel = Boolean(ctx.model && ctx.model.File); if (hasFileReferenceModel && hasFileModel) { try { const imageRows = await ctx.model.FileReference.findAll({ where: { business_type: 'stock', business_id: { [ctx.app.Sequelize.Op.in]: uniqueStockIds, }, }, include: [{ model: ctx.model.File, as: 'file', attributes: [ 'file_url' ], required: false, }], }); for (const item of imageRows || []) { const row = toPlainRecord(item); if (!row) { continue; } const stockId = Number(row.business_id); const imageUrl = (row.file && row.file.file_url) || row.file_url || row.url || row.file_path || ''; if (!stockId || !imageUrl) { continue; } if (!imagesByStockId.has(stockId)) { imagesByStockId.set(stockId, []); } imagesByStockId.get(stockId).push(String(imageUrl)); } } catch (error) { ctx.logger?.warn?.('[storage.inventory] 查询商品图片失败,已降级为空数组', { error: error.message, }); } } return { barcodesByStockId, imagesByStockId, }; } /** * 为库存列表补充商品附属信息。 * * @param {Object} ctx 当前请求上下文 * @param {Object[]} list 库存列表 * @return {Promise} */ async function enrichInventoryStockAttachments(ctx, list = []) { const stockIds = list.map(item => Number(item?.stock?.id || item?.stock_id || 0)).filter(Boolean); const { barcodesByStockId, imagesByStockId } = await loadStockAttachments(ctx, stockIds); for (const item of list) { const stockId = Number(item?.stock?.id || item?.stock_id || 0); if (!stockId) { continue; } if (!item.stock) { item.stock = {}; } item.stock.barcodes = barcodesByStockId.get(stockId) || []; item.stock.images = imagesByStockId.get(stockId) || []; } } class InventoryService extends Service { /** * 收货单快捷入库上架。 * 从收货单直接生成入库单并写入库存。 * * 流程: * 1. 校验收货单状态(必须 completed) * 2. 校验收货单已审核(is_review = 1) * 3. 校验所有明细已匹配系统商品(system_product_id 不为空) * 4. 校验未全部入库(storage_status !== 'all') * 4. 事务内: * a. 创建入库单(EntryOrder)和入库明细(EntryItems) * b. 逐条锁定 StockWarehouse 行,增加 quantity * c. 写入/更新 wms_storage 库存记录 * d. 更新 receiving_detail 的 storage_status 和 stored_quantity * e. 更新 receiving 的 storage_status * * @param {Object} data 请求体 * @param {number} data.receiving_id 收货单ID(必填) * @return {Promise} code/data/message 结构 */ async quickPutaway(data = {}) { const { ctx, app } = this; const warehouseId = ctx.user.store_id; const receivingId = Number(data.receiving_id || data.id || 0); if (!receivingId) { return { code: 400, message: 'receiving_id 必填', data: null }; } const transaction = await ctx.model.transaction(); try { // ────────── 1. 查询并锁定收货单 ────────── const receiving = await ctx.model.Receiving.findOne({ where: { id: receivingId, warehouse_id: warehouseId, is_deleted: false, }, lock: transaction.LOCK.UPDATE, transaction, include: [{ model: ctx.model.ReceivingDetail, as: 'details', required: false, }], }); if (!receiving) { await transaction.rollback(); return { code: 404, message: '收货单不存在或无权访问', data: null }; } if (receiving.status !== 'completed') { await transaction.rollback(); return { code: 400, message: `收货单状态为 ${receiving.status},须完成收货后才能入库`, data: null }; } if (Number(receiving.is_review) !== 1) { await transaction.rollback(); return { code: 400, message: '收货单未审核,审核通过后才能入库', data: null }; } const storeRelation = await ctx.model.StoreWarehouse.findOne({ where: { warehouse_id: warehouseId, store_id: Number(receiving.store_id || 0), use_status: 1, }, attributes: [ 'id', 'policy_config', 'store_remask' ], lock: transaction.LOCK.UPDATE, transaction, }); if (!storeRelation) { await transaction.rollback(); return { code: 404, message: '收货单绑定的货主与当前仓库不存在有效签约关系', data: null }; } const policyConfig = storeRelation.policy_config && typeof storeRelation.policy_config === 'object' ? storeRelation.policy_config : {}; if (Number(policyConfig.allow_receiving_quick_putaway) !== 1) { const storeName = String(storeRelation.store_remask || receiving.store_name || receiving.store_id || '当前货主'); await transaction.rollback(); return { code: 400, message: `货主${storeName}不允许快速上架,如需开启请到:货主->策略配置调整`, data: null }; } if (receiving.storage_status === 'all') { await transaction.rollback(); return { code: 400, message: '该收货单已全部入库,无需重复操作', data: null }; } const details = receiving.details || []; if (!details.length) { await transaction.rollback(); return { code: 400, message: '收货单没有明细,无法入库', data: null }; } // ────────── 3. 校验所有明细已匹配系统商品 ────────── const unmatchedDetails = details.filter(d => !d.system_product_id); if (unmatchedDetails.length > 0) { await transaction.rollback(); const names = unmatchedDetails.map(d => d.product_name).join('、'); return { code: 400, message: `以下商品未匹配系统商品,请先绑定:${names}`, data: { unmatched_count: unmatchedDetails.length, unmatched_names: names }, }; } // 过滤出需要入库的明细(排除已全部入库的) const pendingDetails = details.filter(d => d.storage_status !== 'all'); if (!pendingDetails.length) { await transaction.rollback(); return { code: 400, message: '所有明细已入库完成', data: null }; } // ────────── 4. 创建入库单 ────────── // 获取仓库名称快照 let warehouseName = ''; const warehouseData = await ctx.service.systems.store.getStoreName(warehouseId); if (warehouseData.code === 200 && warehouseData.data) { warehouseName = warehouseData.data.company_name || ''; } // 获取合约表备注名称(优先使用) const contract_data = await ctx.service.systems.store.getStoreRemaskName(receiving.store_id, warehouseId); let contract = null; if (contract_data.code === 200) { contract = contract_data.data; } const entryOrderCode = `SCRK${Date.now()}${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`; const entryOrder = await ctx.model.EntryOrder.create({ entry_order_code: entryOrderCode, order_type: 'SCRK', purchase_order_code: receiving.receiving_number || '', total_order_lines: pendingDetails.length, order_create_time: new Date(), source_type: 'WMS', order_status: 'CREATED', sync_status: 'SUCCESS', sync_message: `快捷入库-来自收货单 ${receiving.receiving_number}`, is_enabled: 1, warehouse_id: warehouseId, store_id: receiving.store_id || warehouseId, store_name: contract?.store_remask || receiving.store_name || '', warehouse_name: contract?.warehouse_remask || warehouseName, remark: `快捷入库,关联收货单 ${receiving.receiving_number}`, created_at: new Date(), updated_at: new Date(), }, { transaction }); // ────────── 5. 逐条处理明细:创建入库明细 + 更新库存 ────────── const results = []; const errors = []; for (let i = 0; i < pendingDetails.length; i++) { const detail = pendingDetails[i]; const stockWarehouseId = detail.system_product_id; const inboundQty = (detail.actual_quantity || 0) - (detail.stored_quantity || 0); if (inboundQty <= 0) { continue; // 已入库完的跳过 } // 5a. 锁定 StockWarehouse 行 const stockRecord = await ctx.model.StockWarehouse.findOne({ where: { id: stockWarehouseId, is_valid: 'Y', deleted_at: null, }, lock: transaction.LOCK.UPDATE, transaction, }); if (!stockRecord) { errors.push(`商品 ${detail.product_name} 的库存记录不存在 (stock_id: ${stockWarehouseId})`); continue; } // 5b. 增加 StockWarehouse 库存数量 const beforeQuantity = Number(stockRecord.quantity) || 0; const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true, }); await stockRecord.reload({ transaction }); const afterQuantity = Number(stockRecord.quantity) || 0; const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; // 5c. 写入/更新 wms_storage 库存位置表 const spaceId = detail.space_id || 1; // 明细有库位则用,否则默认库位 const batchNo = String(detail.batch_number || '').trim() || String(receiving.receiving_number || '').trim() || entryOrderCode; const productionDate = detail.production_date || null; const expiryDate = detail.expiry_date || null; const inventoryType = 'ZP'; // 默认正品 // 查找是否已有相同 库位+SKU+批次+类型 的库存记录 let storageRecord = await ctx.model.Storage.findOne({ where: { space_id: spaceId, stock_id: stockWarehouseId, batch_no: batchNo, inventory_type: inventoryType, is_enabled: 1, delete_at: null, }, lock: transaction.LOCK.UPDATE, transaction, }); if (storageRecord) { // 已有记录:累加数量 await ctx.model.Storage.update({ quantity: app.Sequelize.literal(`quantity + ${inboundQty}`), available_quantity: app.Sequelize.literal(`available_quantity + ${inboundQty}`), entry_order_id: entryOrder.id, batch_no: batchNo, production_date: productionDate, expiry_date: expiryDate, updated_at: new Date(), }, { where: { id: storageRecord.id }, transaction, }); } else { // 新建库存记录 storageRecord = await ctx.model.Storage.create({ warehouse_id: warehouseId, store_id: receiving.store_id || warehouseId, space_id: spaceId, stock_id: stockWarehouseId, batch_no: batchNo, inventory_type: inventoryType, quantity: inboundQty, locked_quantity: 0, available_quantity: inboundQty, production_date: productionDate, expiry_date: expiryDate, inbound_time: new Date(), inbound_order_no: entryOrderCode, receiving_id: receivingId, entry_order_id: entryOrder.id, supplier_id: null, supplier_batch_no: null, is_enabled: 1, created_at: new Date(), updated_at: new Date(), }, { transaction }); } // 5d. 创建入库明细 await ctx.model.EntryItems.create({ order_id: entryOrder.id, order_line_no: i + 1, item_code: stockRecord.item_code || '', item_id: stockWarehouseId, count: inboundQty, inventory_type: inventoryType, stock_id: stockWarehouseId, received_quantity: inboundQty, confirm_quantity: inboundQty, }, { transaction }); // 5d+. 写入出入库记录 await ctx.service.systems.stockTransaction.create({ transaction_type: 'INBOUND', warehouse_id: warehouseId, store_id: receiving.store_id || warehouseId, stock_id: stockWarehouseId, storage_id: storageRecord.id, space_id: spaceId, quantity: inboundQty, batch_no: batchNo, inventory_type: inventoryType, order_type: 'SCRK', order_no: entryOrderCode, order_id: null, receiving_id: receivingId, entry_order_id: entryOrder.id, operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), operator_name: ctx.user?.employees_name || '', remark: `快捷入库-收货单 ${receiving.receiving_number}`, before_quantity: beforeQuantity, after_quantity: afterQuantity, before_locked_quantity: beforeLockedQuantity, after_locked_quantity: afterLockedQuantity, created_at: new Date(), }, { transaction }); // 5e. 更新收货明细的入库状态 const newStoredQty = (detail.stored_quantity || 0) + inboundQty; const detailStorageStatus = newStoredQty >= detail.actual_quantity ? 'all' : 'partial'; await ctx.model.ReceivingDetail.update({ storage_status: detailStorageStatus, stored_quantity: newStoredQty, }, { where: { id: detail.id }, transaction, }); results.push({ detail_id: detail.id, product_name: detail.product_name, stock_warehouse_id: stockWarehouseId, inbound_quantity: inboundQty, space_id: spaceId, storage_status: detailStorageStatus, }); } // 如果全部明细都失败 if (results.length === 0 && errors.length > 0) { await transaction.rollback(); return { code: 400, message: `入库失败:${errors.join(';')}`, data: null, }; } // ────────── 6. 更新入库单状态 ────────── await entryOrder.update({ order_status: 'COMPLETED', total_order_lines: results.length, updated_at: new Date(), }, { transaction }); // ────────── 7. 更新收货单入库状态 ────────── const allDetailsStored = details.every(d => { if (d.storage_status === 'all') return true; // 检查本次入库后是否全部完成 const pending = pendingDetails.find(p => p.id === d.id); if (!pending) return true; const newStored = (pending.stored_quantity || 0) + ((pending.actual_quantity || 0) - (pending.stored_quantity || 0)); return newStored >= pending.actual_quantity; }); const receivingStorageStatus = allDetailsStored ? 'all' : 'partial'; await ctx.model.Receiving.update({ storage_status: receivingStorageStatus, }, { where: { id: receivingId }, transaction, }); // ────────── 8. 提交事务 ────────── await transaction.commit(); // 记录操作日志 try { await ctx.service.systems.operationLog.createOperationLog({ businessType: 'entry', businessId: entryOrder.id, operationCode: 'QUICK_PUTAWAY', operator: { id: ctx.user?.employees_id || ctx.user?.id, name: ctx.user?.employees_name || '', }, extras: { warehouseId, }, beforeChanges: null, }); } catch (logErr) { ctx.logger.warn('[quickPutaway] 写入操作日志失败,不影响业务', logErr); } ctx.logger.info('[quickPutaway] 快捷入库完成', { receiving_id: receivingId, receiving_number: receiving.receiving_number, entry_order_code: entryOrderCode, entry_order_id: entryOrder.id, total_items: results.length, errors: errors.length, }); return { code: 200, message: errors.length ? `入库部分完成,${results.length} 条成功,${errors.length} 条失败` : '快捷入库完成', data: { receiving_id: receivingId, receiving_number: receiving.receiving_number, receiving_storage_status: receivingStorageStatus, entry_order: { id: entryOrder.id, entry_order_code: entryOrderCode, order_status: 'COMPLETED', }, items: results, errors: errors.length ? errors : undefined, }, }; } catch (error) { await transaction.rollback(); ctx.logger.error('[quickPutaway] 快捷入库异常', { receiving_id: receivingId, error: error.message, stack: error.stack, }); if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { return { code: 409, message: '库存记录被锁定,请稍后重试', data: null, }; } throw error; } } /** * 匹配入库:将已完成收货的收货单与已有入库单按 stock_warehouse_id 做数量匹配入库。 * * @param {Object} data 请求体 * @param {number[]} data.receiving_ids 收货单ID列表 * @param {number[]} data.entry_order_ids 入库单ID列表 * @return {Promise} code/data/message 结构 */ async matchPutaway(data = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; const warehouseId = ctx.user.store_id; // ────────── 1. 参数校验 ────────── const receivingIds = Array.isArray(data.receiving_ids) ? data.receiving_ids.map(Number).filter(Boolean) : []; const entryOrderIds = Array.isArray(data.entry_order_ids) ? data.entry_order_ids.map(Number).filter(Boolean) : []; if (!receivingIds.length) { return { code: 400, message: 'receiving_ids 不能为空', data: null }; } if (!entryOrderIds.length) { return { code: 400, message: 'entry_order_ids 不能为空', data: null }; } // ────────── 2. 开事务 ────────── const transaction = await ctx.model.transaction(); try { // ────────── 3. 查询并锁定收货单 ────────── const receivings = await ctx.model.Receiving.findAll({ where: { id: { [Op.in]: receivingIds }, warehouse_id: warehouseId, status: 'completed', is_deleted: false, }, lock: transaction.LOCK.UPDATE, transaction, include: [{ model: ctx.model.ReceivingDetail, as: 'details', required: false, }], }); if (!receivings.length) { await transaction.rollback(); return { code: 404, message: '未找到符合条件的收货单', data: null }; } const unreviewedReceiving = receivings.find(item => Number(item.is_review) !== 1); if (unreviewedReceiving) { await transaction.rollback(); return { code: 400, message: `收货单 ${unreviewedReceiving.receiving_number || unreviewedReceiving.id} 未审核,审核通过后才能入库`, data: null, }; } // ────────── 4. 查询并锁定入库单 ────────── const entryOrders = await ctx.model.EntryOrder.findAll({ where: { id: { [Op.in]: entryOrderIds }, warehouse_id: warehouseId, is_enabled: 1, deleted_at: null, order_status: { [Op.in]: [ 'PENDING', 'CONFIRMED', 'PARTIAL_RECEIVED', 'CREATED' ] }, }, lock: transaction.LOCK.UPDATE, transaction, include: [{ model: ctx.model.EntryItems, as: 'items', required: false, }], }); if (!entryOrders.length) { await transaction.rollback(); return { code: 404, message: '未找到符合条件的入库单', data: null }; } // ────────── 5. 按 stock_warehouse_id 汇总 ────────── // 收货侧:可入库明细(排除已全部入库的) const rcvDetailsBySWId = {}; // stock_warehouse_id -> [ detail, ... ] for (const rcv of receivings) { for (const d of (rcv.details || [])) { if (d.storage_status === 'all') continue; if (!d.system_product_id) continue; const available = (d.actual_quantity || 0) - (d.stored_quantity || 0); if (available <= 0) continue; const key = d.system_product_id; if (!rcvDetailsBySWId[key]) rcvDetailsBySWId[key] = []; rcvDetailsBySWId[key].push({ detail: d, available, receiving: rcv }); } } // 入库侧:待入库明细 const entryItemsBySWId = {}; // stock_warehouse_id -> [ item, ... ] for (const eo of entryOrders) { for (const item of (eo.items || [])) { if (!item.stock_id) continue; const remaining = (item.count || 0) - (item.received_quantity || 0); if (remaining <= 0) continue; const key = item.stock_id; if (!entryItemsBySWId[key]) entryItemsBySWId[key] = []; entryItemsBySWId[key].push({ item, remaining, entryOrder: eo }); } } // ────────── 6. 逐个 stock_warehouse_id 执行匹配 ────────── const matchedItems = []; const unmatchedProducts = []; const warnings = []; // 跟踪各明细的累计分配量 const rcvDetailAllocated = {}; // detail.id -> allocated qty const entryItemAllocated = {}; // item.id -> allocated qty // 取交集 key const allSWIds = new Set([ ...Object.keys(rcvDetailsBySWId), ...Object.keys(entryItemsBySWId), ]); for (const swIdStr of allSWIds) { const swId = Number(swIdStr); const rcvGroup = rcvDetailsBySWId[swId]; const entryGroup = entryItemsBySWId[swId]; if (!rcvGroup || !entryGroup) { if (rcvGroup && !entryGroup) { unmatchedProducts.push({ stock_warehouse_id: swId, reason: '收货侧有库存但无对应入库计划' }); } if (!rcvGroup && entryGroup) { unmatchedProducts.push({ stock_warehouse_id: swId, reason: '入库计划存在但无对应收货明细' }); } continue; } // 计算总量 const totalRcvAvailable = rcvGroup.reduce((s, r) => s + r.available, 0); const totalEntryRemaining = entryGroup.reduce((s, e) => s + e.remaining, 0); const actualInbound = Math.min(totalRcvAvailable, totalEntryRemaining); if (actualInbound <= 0) continue; if (totalRcvAvailable < totalEntryRemaining) { warnings.push( `stock_warehouse_id=${swId}: 收货可入库量(${totalRcvAvailable}) < 入库计划量(${totalEntryRemaining}),按收货量入库` ); } // 6a. 锁定 stock_warehouse 行并增加 quantity const stockRecord = await ctx.model.StockWarehouse.findOne({ where: { id: swId, is_valid: 'Y', deleted_at: null }, lock: transaction.LOCK.UPDATE, transaction, }); if (!stockRecord) { warnings.push(`stock_warehouse_id=${swId}: 库存记录不存在,跳过`); continue; } const beforeQuantity = Number(stockRecord.quantity) || 0; const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; await stockRecord.increment('quantity', { by: actualInbound, transaction, silent: true, }); await stockRecord.reload({ transaction }); const afterQuantity = Number(stockRecord.quantity) || 0; const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; // 6b. 写入/更新 wms_storage(取第一个收货明细的信息) const firstRcvDetail = rcvGroup[0].detail; const firstRcv = rcvGroup[0].receiving; const firstEntryOrder = entryGroup[0].entryOrder; const spaceId = firstRcvDetail.space_id || 1; const batchNo = firstRcvDetail.batch_number || firstRcv.receiving_number || ''; const inventoryType = 'ZP'; let storageRecord = await ctx.model.Storage.findOne({ where: { space_id: spaceId, stock_id: swId, batch_no: batchNo, inventory_type: inventoryType, is_enabled: 1, delete_at: null, }, lock: transaction.LOCK.UPDATE, transaction, }); if (storageRecord) { await ctx.model.Storage.update({ quantity: app.Sequelize.literal(`quantity + ${actualInbound}`), available_quantity: app.Sequelize.literal(`available_quantity + ${actualInbound}`), entry_order_id: firstEntryOrder.id, }, { where: { id: storageRecord.id }, transaction, }); } else { storageRecord = await ctx.model.Storage.create({ warehouse_id: warehouseId, store_id: firstRcv.store_id || warehouseId, space_id: spaceId, stock_id: swId, batch_no: batchNo, inventory_type: inventoryType, quantity: actualInbound, locked_quantity: 0, available_quantity: actualInbound, production_date: firstRcvDetail.production_date || null, expiry_date: firstRcvDetail.expiry_date || null, inbound_time: new Date(), inbound_order_no: firstEntryOrder.entry_order_code, receiving_id: firstRcv.id, entry_order_id: firstEntryOrder.id, supplier_id: null, supplier_batch_no: null, is_enabled: 1, created_at: new Date(), updated_at: new Date(), }, { transaction }); } // 6b+. 写入出入库记录 await ctx.service.systems.stockTransaction.create({ transaction_type: 'INBOUND', warehouse_id: warehouseId, store_id: firstRcv.store_id || warehouseId, stock_id: swId, storage_id: storageRecord.id, space_id: spaceId, quantity: actualInbound, batch_no: batchNo, inventory_type: inventoryType, order_type: 'MATCH', order_no: firstEntryOrder.entry_order_code, order_id: null, receiving_id: firstRcv.id, entry_order_id: firstEntryOrder.id, operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), operator_name: ctx.user?.employees_name || '', remark: '匹配入库', before_quantity: beforeQuantity, after_quantity: afterQuantity, before_locked_quantity: beforeLockedQuantity, after_locked_quantity: afterLockedQuantity, created_at: new Date(), }, { transaction }); // 6c. 分配到各个收货明细(按顺序依次扣减) let rcvRemain = actualInbound; for (const rcvItem of rcvGroup) { if (rcvRemain <= 0) break; const allocate = Math.min(rcvRemain, rcvItem.available); rcvDetailAllocated[rcvItem.detail.id] = (rcvDetailAllocated[rcvItem.detail.id] || 0) + allocate; rcvRemain -= allocate; } // 6d. 分配到各个入库明细(按顺序依次填充) let entryRemain = actualInbound; for (const entryItem of entryGroup) { if (entryRemain <= 0) break; const allocate = Math.min(entryRemain, entryItem.remaining); entryItemAllocated[entryItem.item.id] = (entryItemAllocated[entryItem.item.id] || 0) + allocate; entryRemain -= allocate; } matchedItems.push({ stock_warehouse_id: swId, item_code: stockRecord.item_code || '', inbound_quantity: actualInbound, rcv_available: totalRcvAvailable, entry_planned: totalEntryRemaining, }); } if (!matchedItems.length) { await transaction.rollback(); return { code: 400, message: '没有可匹配入库的商品', data: { unmatched_products: unmatchedProducts }, }; } // ────────── 7. 更新收货明细 stored_quantity 和 storage_status ────────── for (const rcv of receivings) { for (const d of (rcv.details || [])) { const allocated = rcvDetailAllocated[d.id]; if (!allocated) continue; const newStoredQty = (d.stored_quantity || 0) + allocated; const detailStorageStatus = newStoredQty >= d.actual_quantity ? 'all' : 'partial'; await ctx.model.ReceivingDetail.update({ stored_quantity: newStoredQty, storage_status: detailStorageStatus, }, { where: { id: d.id }, transaction, }); } } // ────────── 8. 更新入库明细 received_quantity ────────── for (const eo of entryOrders) { for (const item of (eo.items || [])) { const allocated = entryItemAllocated[item.id]; if (!allocated) continue; const newReceivedQty = (item.received_quantity || 0) + allocated; await ctx.model.EntryItems.update({ received_quantity: newReceivedQty, }, { where: { id: item.id }, transaction, }); } } // ────────── 9. 更新收货单 storage_status ────────── const receivingResults = []; for (const rcv of receivings) { const details = rcv.details || []; const allStored = details.every(d => { const allocated = rcvDetailAllocated[d.id] || 0; const newStored = (d.stored_quantity || 0) + allocated; return d.storage_status === 'all' || newStored >= d.actual_quantity; }); const hasAny = details.some(d => { const allocated = rcvDetailAllocated[d.id] || 0; return d.storage_status !== 'none' || allocated > 0; }); const newStatus = allStored ? 'all' : (hasAny ? 'partial' : rcv.storage_status); if (newStatus !== rcv.storage_status) { await ctx.model.Receiving.update({ storage_status: newStatus }, { where: { id: rcv.id }, transaction, }); } receivingResults.push({ receiving_id: rcv.id, receiving_number: rcv.receiving_number, storage_status: newStatus, }); } // ────────── 10. 更新入库单 order_status ────────── const entryOrderResults = []; const completedEntryOrders = []; // 事务外回传用 for (const eo of entryOrders) { const items = eo.items || []; const allFulfilled = items.every(item => { const allocated = entryItemAllocated[item.id] || 0; const newReceived = (item.received_quantity || 0) + allocated; return newReceived >= (item.count || 0); }); const hasAnyReceived = items.some(item => { const allocated = entryItemAllocated[item.id] || 0; return (item.received_quantity || 0) + allocated > 0; }); let newStatus = eo.order_status; if (allFulfilled) { newStatus = 'COMPLETED'; } else if (hasAnyReceived) { newStatus = 'PARTIAL_RECEIVED'; } if (newStatus !== eo.order_status) { await ctx.model.EntryOrder.update({ order_status: newStatus, updated_at: new Date(), }, { where: { id: eo.id }, transaction, }); } const result = { entry_order_id: eo.id, entry_order_code: eo.entry_order_code, order_status: newStatus, source_type: eo.source_type, callback_status: null, }; entryOrderResults.push(result); if (allFulfilled) { completedEntryOrders.push({ entryOrder: eo, result }); } else { warnings.push( `入库单 ${eo.entry_order_code}: 未全部入库完成(${newStatus}),不触发回传,需手工操作或等待其他收货入库` ); } } // ────────── 12. 提交事务 ────────── await transaction.commit(); // ────────── 13. 事务外:对已完成的入库单触发回传 ────────── for (const { entryOrder, result } of completedEntryOrders) { try { if (entryOrder.source_type === 'QM') { const confirmResult = await ctx.service.systems.entryOrder.entryorderConfirm(entryOrder.id, true); result.callback_status = confirmResult.success ? 'SUCCESS' : 'FAILED'; result.callback_detail = confirmResult; } else if (entryOrder.source_type === 'API') { const callbackResult = await this.apiCallback(entryOrder); result.callback_status = callbackResult.success ? 'SUCCESS' : (callbackResult.skipped ? 'SKIPPED' : 'FAILED'); result.callback_detail = callbackResult; } else { result.callback_status = 'NOT_REQUIRED'; } } catch (cbErr) { ctx.logger.error(`[matchPutaway] 入库单 ${entryOrder.entry_order_code} 回传异常`, cbErr); result.callback_status = 'ERROR'; result.callback_detail = { error: cbErr.message }; } } // ────────── 14. 记录操作日志 ────────── try { await ctx.service.systems.operationLog.createOperationLog({ businessType: 'entry', businessId: entryOrderIds.join(','), operationCode: 'MATCH_PUTAWAY', operator: { id: ctx.user?.employees_id || ctx.user?.id, name: ctx.user?.employees_name || '', }, extras: { warehouseId, receivingIds, entryOrderIds }, beforeChanges: null, }); } catch (logErr) { ctx.logger.warn('[matchPutaway] 写入操作日志失败,不影响业务', logErr); } ctx.logger.info('[matchPutaway] 匹配入库完成', { receiving_ids: receivingIds, entry_order_ids: entryOrderIds, matched_count: matchedItems.length, unmatched_count: unmatchedProducts.length, warnings_count: warnings.length, }); // ────────── 15. 返回结果 ────────── return { code: 200, message: '匹配入库完成', data: { matched_items: matchedItems, receiving_results: receivingResults, entry_order_results: entryOrderResults, unmatched_products: unmatchedProducts, warnings: warnings.length ? warnings : undefined, }, }; } catch (error) { await transaction.rollback(); ctx.logger.error('[matchPutaway] 匹配入库异常', { receiving_ids: receivingIds, entry_order_ids: entryOrderIds, error: error.message, stack: error.stack, }); if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { return { code: 409, message: '库存记录被锁定,请稍后重试', data: null }; } throw error; } } /** * 写入移库双向库位流水(移库出/移库入)。 * * 说明: * 1) before/after 与锁定字段均写同值快照,避免被识别为普通出入库数量变化; * 2) 仅记录移库行为本身,不绑定订单字段。 * * @param {Object} data 入参 * @param {Object} data.transaction 数据库事务 * @param {Object} data.srcRecord 源库存记录 * @param {number} data.transferQuantity 移库数量 * @param {number} data.sourceSpaceId 源库位ID * @param {number} data.targetSpaceId 目标库位ID * @param {number|null} data.targetStorageId 目标库存记录ID * @param {number} data.totalSnapshotQuantity stock_id 总库存快照数量 * @param {number} data.totalSnapshotLockedQuantity stock_id 总锁定快照数量 * @return {Promise} 无返回值 */ async createTransferStockTransactions(data = {}) { const { ctx } = this; const operatorId = ctx.user?.employees_id || ctx.user?.id || null; const operatorName = ctx.user?.employees_name || ''; const totalSnapshotQuantity = Number(data.totalSnapshotQuantity) || 0; const totalSnapshotLockedQuantity = Number(data.totalSnapshotLockedQuantity) || 0; await ctx.model.StorageTransaction.create({ transaction_type: 'TRANSFER_OUT', warehouse_id: data.srcRecord.warehouse_id, store_id: data.srcRecord.store_id, stock_id: data.srcRecord.stock_id, storage_id: data.srcRecord.id, space_id: data.sourceSpaceId, quantity: data.transferQuantity, batch_no: data.srcRecord.batch_no, inventory_type: data.srcRecord.inventory_type, order_type: null, order_no: null, order_id: null, operator_id: operatorId, operator_name: operatorName, remark: '移库出', before_quantity: totalSnapshotQuantity, after_quantity: totalSnapshotQuantity, before_locked_quantity: totalSnapshotLockedQuantity, after_locked_quantity: totalSnapshotLockedQuantity, source_order_codes: null, created_at: new Date(), }, { transaction: data.transaction, }); await ctx.model.StorageTransaction.create({ transaction_type: 'TRANSFER_IN', warehouse_id: data.srcRecord.warehouse_id, store_id: data.srcRecord.store_id, stock_id: data.srcRecord.stock_id, storage_id: data.targetStorageId, space_id: data.targetSpaceId, quantity: data.transferQuantity, batch_no: data.srcRecord.batch_no, inventory_type: data.srcRecord.inventory_type, order_type: null, order_no: null, order_id: null, operator_id: operatorId, operator_name: operatorName, remark: '移库入', before_quantity: totalSnapshotQuantity, after_quantity: totalSnapshotQuantity, before_locked_quantity: totalSnapshotLockedQuantity, after_locked_quantity: totalSnapshotLockedQuantity, source_order_codes: null, created_at: new Date(), }, { transaction: data.transaction, }); } /** * 移库(库位转移):将单条库存从一个库位移动到另一个库位。 * 支持部分/全量移库、目标库位合并。 * * @param {Object} data 请求体 * @param {number} data.storage_id 库存记录ID(必填) * @param {number} data.target_space_id 目标库位ID(必填) * @param {number} [data.quantity] 移库数量(可选,默认全部移动) * @return {Promise} code/data/message 结构 */ async transferLocation(data = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; // ────────── 1. 参数校验 ────────── const storageId = Number(data.storage_id || 0); if (!storageId) { return { code: 400, message: 'storage_id 必填', data: null }; } const targetSpaceId = Number(data.target_space_id || 0); if (!targetSpaceId) { return { code: 400, message: 'target_space_id 必填', data: null }; } if (data.quantity !== undefined && data.quantity !== null) { const qty = Number(data.quantity); if (!Number.isFinite(qty) || qty <= 0) { return { code: 400, message: 'quantity 必须为正数', data: null }; } } // ────────── 2. 开事务 ────────── const transaction = await ctx.model.transaction(); try { // ────────── 3. 锁定并校验原库存记录 ────────── const srcRecord = await ctx.model.Storage.findOne({ where: { id: storageId, is_enabled: 1, delete_at: null, }, lock: transaction.LOCK.UPDATE, transaction, }); if (!srcRecord) { await transaction.rollback(); return { code: 404, message: `库存记录不存在: storage_id=${storageId}`, data: null }; } const warehouseId = srcRecord.warehouse_id; const stockWarehouseSnapshot = await ctx.model.StockWarehouse.findOne({ where: { id: srcRecord.stock_id }, attributes: [ 'id', 'quantity', 'locked_quantity' ], lock: transaction.LOCK.UPDATE, transaction, }); if (!stockWarehouseSnapshot) { await transaction.rollback(); return { code: 404, message: `商品SKU不存在: stock_id=${srcRecord.stock_id}`, data: null }; } // ────────── 4. 校验目标库位 ────────── const targetSpace = await ctx.model.LocationSpace.findOne({ where: { id: targetSpaceId, is_enabled: true, }, lock: transaction.LOCK.UPDATE, transaction, }); if (!targetSpace) { await transaction.rollback(); return { code: 404, message: `目标库位不存在或未启用: space_id=${targetSpaceId}`, data: null }; } if (targetSpace.warehouse_id !== warehouseId) { await transaction.rollback(); return { code: 400, message: `目标库位 ${targetSpaceId} 不属于仓库 ${warehouseId}`, data: null }; } if (![ 'AVAILABLE', 'OCCUPIED' ].includes(targetSpace.space_status)) { await transaction.rollback(); return { code: 400, message: `目标库位 ${targetSpace.space_code} 状态为 ${targetSpace.space_status},不可移入`, data: null, }; } // ────────── 5. 处理移库 ────────── const availableQty = srcRecord.quantity - srcRecord.locked_quantity; const transferQty = (data.quantity !== undefined && data.quantity !== null) ? Number(data.quantity) : availableQty; // 校验移库数量 if (transferQty > availableQty) { await transaction.rollback(); return { code: 400, message: `库存记录 ${storageId} 可用数量不足:可用 ${availableQty},请求移库 ${transferQty}`, data: null, }; } // 原库位与目标库位相同则直接返回 if (srcRecord.space_id === targetSpaceId) { await transaction.rollback(); return { code: 200, message: '原库位与目标库位相同,无需移库', data: { storage_id: storageId, target_space_id: targetSpaceId, transfer_quantity: 0, status: 'skipped', }, }; } const beforeSnapshot = { storage_id: storageId, space_id: srcRecord.space_id, quantity: srcRecord.quantity, available_quantity: srcRecord.available_quantity, }; const isFullTransfer = (transferQty === srcRecord.quantity); // 查找目标库位是否已有相同 stock_id + batch_no + inventory_type 的记录 const existingTarget = await ctx.model.Storage.findOne({ where: { space_id: targetSpaceId, stock_id: srcRecord.stock_id, batch_no: srcRecord.batch_no, inventory_type: srcRecord.inventory_type, is_enabled: 1, delete_at: null, id: { [Op.ne]: storageId }, // 排除自身(全量移库时直接改 space_id 的情况) }, lock: transaction.LOCK.UPDATE, transaction, }); let afterSnapshot; let targetStorageId = null; // 原库位统计变化 const srcSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; // 目标库位统计变化 const tgtSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; if (existingTarget) { // ── 目标库位已有同规格记录:合并数量 ── await ctx.model.Storage.update({ quantity: app.Sequelize.literal(`quantity + ${transferQty}`), available_quantity: app.Sequelize.literal(`available_quantity + ${transferQty}`), updated_at: new Date(), }, { where: { id: existingTarget.id }, transaction, }); if (isFullTransfer) { // 全量移库且合并:删除原记录 await ctx.model.Storage.update({ is_enabled: 0, delete_at: new Date(), updated_at: new Date(), }, { where: { id: storageId }, transaction, }); srcSpaceDelta.qtyDelta -= srcRecord.quantity; // 检查原库位该 SKU 是否还有其他记录 const remainingSku = await ctx.model.Storage.count({ where: { space_id: srcRecord.space_id, stock_id: srcRecord.stock_id, is_enabled: 1, delete_at: null, id: { [Op.ne]: storageId }, }, transaction, }); if (remainingSku === 0) { srcSpaceDelta.skuDelta -= 1; } } else { // 部分移库:减少原记录数量 await ctx.model.Storage.update({ quantity: app.Sequelize.literal(`quantity - ${transferQty}`), available_quantity: app.Sequelize.literal(`available_quantity - ${transferQty}`), updated_at: new Date(), }, { where: { id: storageId }, transaction, }); srcSpaceDelta.qtyDelta -= transferQty; } // 目标库位数量增加 tgtSpaceDelta.qtyDelta += transferQty; // 目标库位该 SKU 之前已有记录,skuDelta 不变 targetStorageId = existingTarget.id; afterSnapshot = { merged_into: existingTarget.id, target_space_id: targetSpaceId, transfer_quantity: transferQty, source_deleted: isFullTransfer, }; } else if (isFullTransfer) { // ── 全量移库 & 目标无同规格记录:直接修改 space_id ── await ctx.model.Storage.update({ space_id: targetSpaceId, updated_at: new Date(), }, { where: { id: storageId }, transaction, }); srcSpaceDelta.qtyDelta -= srcRecord.quantity; // 检查原库位该 SKU 是否还有其他记录 const remainingSku = await ctx.model.Storage.count({ where: { space_id: srcRecord.space_id, stock_id: srcRecord.stock_id, is_enabled: 1, delete_at: null, id: { [Op.ne]: storageId }, }, transaction, }); if (remainingSku === 0) { srcSpaceDelta.skuDelta -= 1; } // 目标库位新增一个 SKU const existingSkuInTarget = await ctx.model.Storage.count({ where: { space_id: targetSpaceId, stock_id: srcRecord.stock_id, is_enabled: 1, delete_at: null, id: { [Op.ne]: storageId }, // 排掉自身(此时 space_id 已更新,但事务内逻辑用旧值) }, transaction, }); if (existingSkuInTarget === 0) { tgtSpaceDelta.skuDelta += 1; } tgtSpaceDelta.qtyDelta += srcRecord.quantity; targetStorageId = storageId; afterSnapshot = { storage_id: storageId, target_space_id: targetSpaceId, transfer_quantity: transferQty, source_deleted: false, }; } else { // ── 部分移库 & 目标无同规格记录:减少原记录数量,新建目标记录 ── await ctx.model.Storage.update({ quantity: app.Sequelize.literal(`quantity - ${transferQty}`), available_quantity: app.Sequelize.literal(`available_quantity - ${transferQty}`), updated_at: new Date(), }, { where: { id: storageId }, transaction, }); const newRecord = await ctx.model.Storage.create({ warehouse_id: srcRecord.warehouse_id, store_id: srcRecord.store_id, space_id: targetSpaceId, stock_id: srcRecord.stock_id, batch_no: srcRecord.batch_no, inventory_type: srcRecord.inventory_type, quantity: transferQty, locked_quantity: 0, available_quantity: transferQty, production_date: srcRecord.production_date, expiry_date: srcRecord.expiry_date, inbound_time: srcRecord.inbound_time, inbound_order_no: srcRecord.inbound_order_no, receiving_id: srcRecord.receiving_id, entry_order_id: srcRecord.entry_order_id, supplier_id: srcRecord.supplier_id, supplier_batch_no: srcRecord.supplier_batch_no, is_enabled: 1, created_at: new Date(), updated_at: new Date(), }, { transaction }); srcSpaceDelta.qtyDelta -= transferQty; // 原库位 SKU 数不变(原记录仍在) // 目标库位:新增 SKU const existingSkuInTarget = await ctx.model.Storage.count({ where: { space_id: targetSpaceId, stock_id: srcRecord.stock_id, is_enabled: 1, delete_at: null, }, transaction, }); // count 包含刚 create 的记录,如果只有 1 条说明之前没有 if (existingSkuInTarget <= 1) { tgtSpaceDelta.skuDelta += 1; } tgtSpaceDelta.qtyDelta += transferQty; targetStorageId = newRecord.id; afterSnapshot = { new_storage_id: newRecord.id, target_space_id: targetSpaceId, transfer_quantity: transferQty, source_deleted: false, }; } await this.createTransferStockTransactions({ transaction, srcRecord, transferQuantity: transferQty, sourceSpaceId: srcRecord.space_id, targetSpaceId, targetStorageId, totalSnapshotQuantity: Number(stockWarehouseSnapshot.quantity) || 0, totalSnapshotLockedQuantity: Number(stockWarehouseSnapshot.locked_quantity) || 0, }); // ────────── 记录操作日志(事务内) ────────── try { await ctx.service.systems.operationLog.createOperationLog({ businessType: 'storage', businessId: storageId, operationCode: 'STORAGE_TRANSFER_LOCATION', operator: { id: ctx.user?.employees_id || ctx.user?.id, name: ctx.user?.employees_name || '', }, extras: { warehouseId, target_space_id: targetSpaceId, transfer_quantity: transferQty, }, beforeChanges: beforeSnapshot, afterChanges: afterSnapshot, }); } catch (logErr) { ctx.logger.warn('[inventory.transferLocation] 写入操作日志失败,不影响业务', logErr); } // ────────── 6. 更新库位统计 ────────── const updateSpaceStats = async (spaceId, delta) => { if (delta.qtyDelta === 0 && delta.skuDelta === 0) return; const updateFields = {}; if (delta.qtyDelta !== 0) { updateFields.current_quantity = app.Sequelize.literal( `GREATEST(COALESCE(current_quantity, 0) + (${delta.qtyDelta}), 0)` ); } if (delta.skuDelta !== 0) { updateFields.current_sku_count = app.Sequelize.literal( `GREATEST(COALESCE(current_sku_count, 0) + (${delta.skuDelta}), 0)` ); } await ctx.model.LocationSpace.update(updateFields, { where: { id: spaceId }, transaction, }); }; await updateSpaceStats(srcRecord.space_id, srcSpaceDelta); await updateSpaceStats(targetSpaceId, tgtSpaceDelta); // ────────── 7. 提交事务 ────────── await transaction.commit(); // ────────── 8. 发送通知(事务外) ────────── try { await ctx.service.systems.notice.send({ event: 'storage_transfer_completed', businessName: 'storage', warehouseId, subjectId: warehouseId, title: '移库操作完成', content: `移库完成:库存${storageId} -> 库位${targetSpaceId}(数量:${transferQty})`, data: { warehouse_id: warehouseId, storage_id: storageId, target_space_id: targetSpaceId, transfer_quantity: transferQty }, sender: { id: ctx.user?.employees_id || ctx.user?.id, name: ctx.user?.employees_name || '', }, }); } catch (noticeErr) { ctx.logger.warn('[inventory.transferLocation] 发送通知失败,不影响业务', noticeErr); } ctx.logger.info('[inventory.transferLocation] 移库完成', { warehouse_id: warehouseId, storage_id: storageId, target_space_id: targetSpaceId, transfer_quantity: transferQty, }); return { code: 200, message: '移库完成', data: { storage_id: storageId, stock_id: srcRecord.stock_id, target_space_id: targetSpaceId, transfer_quantity: transferQty, status: 'success', }, }; } catch (error) { await transaction.rollback(); ctx.logger.error('[inventory.transferLocation] 移库异常', { storage_id: storageId, target_space_id: targetSpaceId, error: error.message, stack: error.stack, }); if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { return { code: 409, message: '库存记录被锁定,请稍后重试', data: null }; } throw error; } } /** * 按库位+商品维度移库。 * 自动查找该库位下该商品的所有 storage 记录,按 quantity ASC 逐条扣减并合并移动到目标库位。 * * @param {Object} data 请求体 * @param {number} data.space_id 原库位ID(必填) * @param {number} data.stock_id 商品SKU ID(必填,对应 wms_stock_warehouse.id) * @param {number} data.target_space_id 目标库位ID(必填) * @param {number} data.quantity 移库数量(必填) * @return {Promise} code/data/message 结构 */ async transferByProduct(data = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; // ────────── 1. 参数校验 ────────── const spaceId = Number(data.space_id || 0); const stockId = Number(data.stock_id || 0); const targetSpaceId = Number(data.target_space_id || 0); const quantity = Number(data.quantity || 0); if (!spaceId) { return { code: 400, message: 'space_id 必填', data: null }; } if (!stockId) { return { code: 400, message: 'stock_id 必填', data: null }; } if (!targetSpaceId) { return { code: 400, message: 'target_space_id 必填', data: null }; } if (!Number.isFinite(quantity) || quantity <= 0) { return { code: 400, message: 'quantity 必须为正数', data: null }; } // ────────── 2. 批次管理校验 ────────── const stockWarehouse = await ctx.model.StockWarehouse.findOne({ where: { id: stockId }, attributes: [ 'id', 'is_batch_mgmt' ], }); if (!stockWarehouse) { return { code: 404, message: `商品SKU不存在: stock_id=${stockId}`, data: null }; } if (stockWarehouse.is_batch_mgmt === 'Y') { return { code: 400, message: '该商品已开启批次管理,请使用按库存记录移库(transferLocation)', data: null, }; } // ────────── 3. 原库位与目标库位相同 ────────── if (spaceId === targetSpaceId) { return { code: 200, message: '原库位与目标库位相同,无需移库', data: { space_id: spaceId, stock_id: stockId, target_space_id: targetSpaceId, transfer_quantity: 0, affected_storage_count: 0, status: 'skipped', }, }; } // ────────── 4. 开事务 ────────── const transaction = await ctx.model.transaction(); try { // ────────── 5. 查找并锁定原库存记录 ────────── const srcRecords = await ctx.model.Storage.findAll({ where: { space_id: spaceId, stock_id: stockId, is_enabled: 1, delete_at: null, }, order: [[ 'quantity', 'ASC' ]], lock: transaction.LOCK.UPDATE, transaction, }); if (!srcRecords.length) { await transaction.rollback(); return { code: 404, message: `原库位 ${spaceId} 下未找到商品 ${stockId} 的库存记录`, data: null }; } const totalAvailable = srcRecords.reduce((sum, r) => sum + (r.quantity - r.locked_quantity), 0); if (quantity > totalAvailable) { await transaction.rollback(); return { code: 400, message: `可用数量不足:可用 ${totalAvailable},请求移库 ${quantity}`, data: null, }; } const warehouseId = srcRecords[0].warehouse_id; const stockWarehouseSnapshot = await ctx.model.StockWarehouse.findOne({ where: { id: stockId }, attributes: [ 'id', 'quantity', 'locked_quantity' ], lock: transaction.LOCK.UPDATE, transaction, }); if (!stockWarehouseSnapshot) { await transaction.rollback(); return { code: 404, message: `商品SKU不存在: stock_id=${stockId}`, data: null }; } // ────────── 6. 校验目标库位 ────────── const targetSpace = await ctx.model.LocationSpace.findOne({ where: { id: targetSpaceId, is_enabled: true, }, lock: transaction.LOCK.UPDATE, transaction, }); if (!targetSpace) { await transaction.rollback(); return { code: 404, message: `目标库位不存在或未启用: space_id=${targetSpaceId}`, data: null }; } if (targetSpace.warehouse_id !== warehouseId) { await transaction.rollback(); return { code: 400, message: `目标库位 ${targetSpaceId} 不属于仓库 ${warehouseId}`, data: null }; } if (![ 'AVAILABLE', 'OCCUPIED' ].includes(targetSpace.space_status)) { await transaction.rollback(); return { code: 400, message: `目标库位 ${targetSpace.space_code} 状态为 ${targetSpace.space_status},不可移入`, data: null, }; } // ────────── 7. 逐条扣减并移库 ────────── let remainingQty = quantity; let affectedCount = 0; const srcSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; const tgtSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; // 预先记录目标库位是否已有该 SKU(用于事后计算 skuDelta) const tgtSkuCountBefore = await ctx.model.Storage.count({ where: { space_id: targetSpaceId, stock_id: stockId, is_enabled: 1, delete_at: null, }, transaction, }); for (const srcRecord of srcRecords) { if (remainingQty <= 0) break; const available = srcRecord.quantity - srcRecord.locked_quantity; const toTransfer = Math.min(available, remainingQty); if (toTransfer <= 0) continue; affectedCount++; const isFullTransfer = (toTransfer === srcRecord.quantity); let targetStorageId = null; // ── 在目标库位查找同 stock_id + batch_no + inventory_type 的记录 ── const existingTarget = await ctx.model.Storage.findOne({ where: { space_id: targetSpaceId, stock_id: srcRecord.stock_id, batch_no: srcRecord.batch_no, inventory_type: srcRecord.inventory_type, is_enabled: 1, delete_at: null, id: { [Op.ne]: srcRecord.id }, }, lock: transaction.LOCK.UPDATE, transaction, }); if (existingTarget) { // 目标已有同规格记录:合并数量 await ctx.model.Storage.update({ quantity: app.Sequelize.literal(`quantity + ${toTransfer}`), available_quantity: app.Sequelize.literal(`available_quantity + ${toTransfer}`), updated_at: new Date(), }, { where: { id: existingTarget.id }, transaction, }); if (isFullTransfer) { // 全量:软删除原记录 await ctx.model.Storage.update({ is_enabled: 0, delete_at: new Date(), updated_at: new Date(), }, { where: { id: srcRecord.id }, transaction, }); } else { // 部分:减少原记录 await ctx.model.Storage.update({ quantity: app.Sequelize.literal(`quantity - ${toTransfer}`), available_quantity: app.Sequelize.literal(`available_quantity - ${toTransfer}`), updated_at: new Date(), }, { where: { id: srcRecord.id }, transaction, }); } targetStorageId = existingTarget.id; } else if (isFullTransfer) { // 全量移库 & 目标无同规格记录:直接改 space_id await ctx.model.Storage.update({ space_id: targetSpaceId, updated_at: new Date(), }, { where: { id: srcRecord.id }, transaction, }); targetStorageId = srcRecord.id; } else { // 部分移库 & 目标无同规格记录:减少原记录,新建目标记录 await ctx.model.Storage.update({ quantity: app.Sequelize.literal(`quantity - ${toTransfer}`), available_quantity: app.Sequelize.literal(`available_quantity - ${toTransfer}`), updated_at: new Date(), }, { where: { id: srcRecord.id }, transaction, }); const newRecord = await ctx.model.Storage.create({ warehouse_id: srcRecord.warehouse_id, store_id: srcRecord.store_id, space_id: targetSpaceId, stock_id: srcRecord.stock_id, batch_no: srcRecord.batch_no, inventory_type: srcRecord.inventory_type, quantity: toTransfer, locked_quantity: 0, available_quantity: toTransfer, production_date: srcRecord.production_date, expiry_date: srcRecord.expiry_date, inbound_time: srcRecord.inbound_time, inbound_order_no: srcRecord.inbound_order_no, receiving_id: srcRecord.receiving_id, entry_order_id: srcRecord.entry_order_id, supplier_id: srcRecord.supplier_id, supplier_batch_no: srcRecord.supplier_batch_no, is_enabled: 1, created_at: new Date(), updated_at: new Date(), }, { transaction }); targetStorageId = newRecord.id; } await this.createTransferStockTransactions({ transaction, srcRecord, transferQuantity: toTransfer, sourceSpaceId: srcRecord.space_id, targetSpaceId, targetStorageId, totalSnapshotQuantity: Number(stockWarehouseSnapshot.quantity) || 0, totalSnapshotLockedQuantity: Number(stockWarehouseSnapshot.locked_quantity) || 0, }); srcSpaceDelta.qtyDelta -= toTransfer; tgtSpaceDelta.qtyDelta += toTransfer; remainingQty -= toTransfer; } // ── 计算 SKU 维度统计变化 ── const remainingSrcSku = await ctx.model.Storage.count({ where: { space_id: spaceId, stock_id: stockId, is_enabled: 1, delete_at: null, }, transaction, }); if (remainingSrcSku === 0) { srcSpaceDelta.skuDelta -= 1; } if (tgtSkuCountBefore === 0) { // 操作前目标库位没有该 SKU,现在有了 tgtSpaceDelta.skuDelta += 1; } // ────────── 8. 操作日志 ────────── try { await ctx.service.systems.operationLog.createOperationLog({ businessType: 'storage', businessId: spaceId, operationCode: 'STORAGE_TRANSFER_BY_PRODUCT', operator: { id: ctx.user?.employees_id || ctx.user?.id, name: ctx.user?.employees_name || '', }, extras: { warehouseId, space_id: spaceId, stock_id: stockId, target_space_id: targetSpaceId, transfer_quantity: quantity, affected_storage_count: affectedCount, }, beforeChanges: { space_id: spaceId, stock_id: stockId, total_available: totalAvailable, source_record_count: srcRecords.length, }, afterChanges: { target_space_id: targetSpaceId, transfer_quantity: quantity, affected_storage_count: affectedCount, }, }); } catch (logErr) { ctx.logger.warn('[inventory.transferByProduct] 写入操作日志失败,不影响业务', logErr); } // ────────── 9. 更新库位统计 ────────── const updateSpaceStats = async (updateSpaceId, delta) => { if (delta.qtyDelta === 0 && delta.skuDelta === 0) return; const updateFields = {}; if (delta.qtyDelta !== 0) { updateFields.current_quantity = app.Sequelize.literal( `GREATEST(COALESCE(current_quantity, 0) + (${delta.qtyDelta}), 0)` ); } if (delta.skuDelta !== 0) { updateFields.current_sku_count = app.Sequelize.literal( `GREATEST(COALESCE(current_sku_count, 0) + (${delta.skuDelta}), 0)` ); } await ctx.model.LocationSpace.update(updateFields, { where: { id: updateSpaceId }, transaction, }); }; await updateSpaceStats(spaceId, srcSpaceDelta); await updateSpaceStats(targetSpaceId, tgtSpaceDelta); // ────────── 10. 提交事务 ────────── await transaction.commit(); // ────────── 11. 发送通知(事务外) ────────── try { await ctx.service.systems.notice.send({ event: 'storage_transfer_completed', businessName: 'storage', warehouseId, subjectId: warehouseId, title: '按商品移库操作完成', content: `按商品移库完成:库位${spaceId} 商品${stockId} -> 库位${targetSpaceId}(数量:${quantity},涉及${affectedCount}条记录)`, data: { warehouse_id: warehouseId, space_id: spaceId, stock_id: stockId, target_space_id: targetSpaceId, transfer_quantity: quantity, affected_storage_count: affectedCount, }, sender: { id: ctx.user?.employees_id || ctx.user?.id, name: ctx.user?.employees_name || '', }, }); } catch (noticeErr) { ctx.logger.warn('[inventory.transferByProduct] 发送通知失败,不影响业务', noticeErr); } ctx.logger.info('[inventory.transferByProduct] 按商品移库完成', { warehouse_id: warehouseId, space_id: spaceId, stock_id: stockId, target_space_id: targetSpaceId, transfer_quantity: quantity, affected_storage_count: affectedCount, }); return { code: 200, message: '按商品移库完成', data: { space_id: spaceId, stock_id: stockId, target_space_id: targetSpaceId, transfer_quantity: quantity, affected_storage_count: affectedCount, warehouse_id: warehouseId, }, }; } catch (error) { await transaction.rollback(); ctx.logger.error('[inventory.transferByProduct] 按商品移库异常', { space_id: spaceId, stock_id: stockId, target_space_id: targetSpaceId, quantity, error: error.message, stack: error.stack, }); if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { return { code: 409, message: '库存记录被锁定,请稍后重试', data: null }; } throw error; } } /** * API 入库单回调:向 api_app 配置的 callback_url 发送入库确认通知。 * * @param {Object} entryOrder 入库单实例 * @return {Promise} { success, skipped?, status?, error? } */ async apiCallback(entryOrder) { const { ctx, app } = this; try { const apiApp = await app.model.ApiApp.findOne({ where: { warehouse_id: entryOrder.warehouse_id, is_enabled: 1, }, }); if (!apiApp || !apiApp.callback_url) { ctx.logger.info('[matchPutaway] 未找到API回调配置或无回调地址,跳过回调'); return { success: true, skipped: true }; } const items = await app.model.EntryItems.findAll({ where: { order_id: entryOrder.id }, }); const payload = { entry_order_code: entryOrder.entry_order_code, order_type: entryOrder.order_type, order_status: 'COMPLETED', warehouse_id: entryOrder.warehouse_id, store_id: entryOrder.store_id, items: items.map(item => ({ item_code: item.item_code, item_id: item.item_id, plan_quantity: item.count, received_quantity: item.received_quantity, confirm_quantity: item.received_quantity, })), confirm_time: new Date().toISOString(), }; const response = await ctx.curl(apiApp.callback_url, { method: 'POST', contentType: 'json', data: payload, timeout: 10000, dataType: 'json', }); ctx.logger.info('[matchPutaway] API回调结果', { entry_order_id: entryOrder.id, callback_url: apiApp.callback_url, status: response.status, }); return { success: response.status === 200, status: response.status }; } catch (err) { ctx.logger.error('[matchPutaway] API回调失败', err); return { success: false, error: err.message }; } } /** * 查询库存列表。 * * 支持按批次明细或合并模式返回库存,并补充商品条码、图片附件、保质期预警和货主名称。 * 货主名称来源于货主签约表的 store_remask 字段,最终以 stock.store_name 输出。 * * @param {Object} [pageParams={}] 分页参数 * @param {number} [pageParams.page=1] 页码 * @param {number} [pageParams.pageSize=20] 每页数量 * @param {Object} [sortParams={}] 排序参数 * @param {string} [sortParams.sortField='created_at'] 排序字段 * @param {string} [sortParams.sortOrder='DESC'] 排序方向 * @param {boolean} [groupByBatch=false] 是否按批次明细返回 * @return {Promise<{list: Object[], pagination: {page: number, pageSize: number, total: number, totalPages: number}}>} 库存列表结果 */ async getInventoryList(pageParams = {}, sortParams = {}, groupByBatch = false) { const { ctx, app } = this; const { Op, fn, col, literal } = app.Sequelize; const nowMs = Date.now(); const warehouseId = ctx.user.store_id; const { page = 1, pageSize = 20 } = pageParams; const { sortField = 'created_at', sortOrder = 'DESC' } = sortParams; // 基础条件 const baseWhere = { [Op.and]: [ { warehouse_id: warehouseId }, { is_enabled: 1 }, { delete_at: null }, ], }; // 动态 where 条件 const parsed = ctx.whereParsed; if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) { baseWhere[Op.and].push(...parsed.dynamicConditions); } const offset = (page - 1) * pageSize; const limit = pageSize; if (groupByBatch) { let inventoryWarningRanges = []; try { const store = await ctx.model.Store.findByPk(warehouseId, { attributes: [ 'id', 'subject_config' ], }); const normalizedSubjectConfig = ctx.model.Store.normalizeSubjectConfig( store ? store.subject_config : null ); inventoryWarningRanges = buildInventoryWarningRanges( normalizedSubjectConfig && Array.isArray(normalizedSubjectConfig.inventory_warning_rules) ? normalizedSubjectConfig.inventory_warning_rules : [] ); } catch (error) { ctx.logger.warn(`[getInventoryList] 库存预警规则读取失败: ${error.message}`); } // 按批次明细:逐条返回 const { count: total, rows } = await ctx.model.Storage.findAndCountAll({ where: baseWhere, order: [[ sortField, sortOrder ]], offset, limit, include: [ { model: ctx.model.StockWarehouse, as: 'stock', attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit', 'is_batch_mgmt', 'is_shelf_life_mgmt', 'remaining_threshold_days', ], include: [ { model: ctx.model.StoreWarehouse, as: 'store_stock', attributes: [ 'store_id', 'store_remask' ], required: false, }, ], required: false, }, { model: ctx.model.LocationSpace, as: 'space', attributes: [ 'id', 'space_code', 'custom_name' ], required: false, }, ], }); const list = rows.map(item => { const row = item.get({ plain: true }); const shelfLifeWarningState = getShelfLifeWarningState(row.stock || {}, row.expiry_date, nowMs); const inventoryWarningPayload = getInventoryWarningPayload( shelfLifeWarningState.remainingDays, inventoryWarningRanges ); if (row.stock) { row.stock.is_batch_mgmt_enabled = toBooleanFlag(row.stock.is_batch_mgmt); row.stock.store_name = row.stock.store_stock?.store_remask || null; delete row.stock.store_stock; delete row.stock.is_batch_mgmt; } row.created_at = row.created_at ? app.formatDate(row.created_at) : ''; row.updated_at = row.updated_at ? app.formatDate(row.updated_at) : ''; row.inbound_time = row.inbound_time ? app.formatDate(row.inbound_time) : ''; row.production_date = row.production_date ? app.formatDate(row.production_date) : ''; row.expiry_date = row.expiry_date ? app.formatDate(row.expiry_date) : ''; row.is_shelf_life_warning_triggered = shelfLifeWarningState.isTriggered; row.expiry_remaining_days = inventoryWarningPayload.expiry_remaining_days; row.inventory_warning_level = inventoryWarningPayload.inventory_warning_level; row.inventory_warning_color = inventoryWarningPayload.inventory_warning_color; row.inventory_warning_range = inventoryWarningPayload.inventory_warning_range; row.inventory_warning_tip_text = inventoryWarningPayload.inventory_warning_tip_text; return row; }); await enrichInventoryStockAttachments(ctx, list); return { list, pagination: { page, pageSize, total, totalPages: Math.ceil(total / pageSize), }, }; } // 不按批次:按 stock_id + space_id + inventory_type 合并 const groupFields = [ 'stock_id', 'space_id', 'inventory_type', 'warehouse_id', 'store_id' ]; const countResult = await ctx.model.Storage.count({ where: baseWhere, group: groupFields, }); const total = Array.isArray(countResult) ? countResult.length : countResult; const rows = await ctx.model.Storage.findAll({ where: baseWhere, attributes: [ 'stock_id', 'space_id', 'inventory_type', 'warehouse_id', 'store_id', [ fn('MIN', col('wms_storage.production_date')), 'production_date' ], [ fn('MIN', col('wms_storage.expiry_date')), 'expiry_date' ], [ fn('SUM', col('wms_storage.quantity')), 'quantity' ], [ fn('SUM', col('wms_storage.locked_quantity')), 'locked_quantity' ], [ fn('SUM', col('wms_storage.available_quantity')), 'available_quantity' ], [ fn('MIN', col('wms_storage.inbound_time')), 'first_inbound_time' ], [ fn('MAX', col('wms_storage.inbound_time')), 'last_inbound_time' ], [ fn('COUNT', col('wms_storage.id')), 'batch_count' ], ], group: groupFields, order: [[ literal('last_inbound_time'), sortOrder ]], offset, limit, include: [ { model: ctx.model.StockWarehouse, as: 'stock', attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit', 'is_batch_mgmt', 'is_shelf_life_mgmt', 'remaining_threshold_days', ], include: [ { model: ctx.model.StoreWarehouse, as: 'store_stock', attributes: [ 'store_id', 'store_remask' ], required: false, }, ], required: false, }, { model: ctx.model.LocationSpace, as: 'space', attributes: [ 'id', 'space_code', 'custom_name' ], required: false, }, ], raw: true, nest: true, }); const list = rows.map(row => { const shelfLifeWarningState = getShelfLifeWarningState(row.stock || {}, row.expiry_date, nowMs); if (row.stock) { row.stock.is_batch_mgmt_enabled = toBooleanFlag(row.stock.is_batch_mgmt); row.stock.store_name = row.stock.store_stock?.store_remask || null; delete row.stock.store_stock; delete row.stock.is_batch_mgmt; } row.first_inbound_time = row.first_inbound_time ? app.formatDate(row.first_inbound_time) : ''; row.last_inbound_time = row.last_inbound_time ? app.formatDate(row.last_inbound_time) : ''; row.production_date = row.production_date ? app.formatDate(row.production_date) : ''; row.expiry_date = row.expiry_date ? app.formatDate(row.expiry_date) : ''; row.is_shelf_life_warning_triggered = shelfLifeWarningState.isTriggered; return row; }); await enrichInventoryStockAttachments(ctx, list); return { list, pagination: { page, pageSize, total, totalPages: Math.ceil(total / pageSize), }, }; } } module.exports = InventoryService;