'use strict'; const Service = require('egg').Service; const { parseWhereConditions, buildSequelizeCondition: buildSequelizeConditionUtil, processConditionValue: processConditionValueUtil, isEmptyValue: isEmptyValueUtil, normalizeDate: normalizeDateUtil, } = require('../../lib/query_condition_parser'); class stockStoreService extends Service { async create(stockData) { const { app, service, } = this; const warehouseId = stockData.warehouse_id; // 设置创建时间 if (!stockData.create_time) { stockData.create_time = new Date(); } // 检查唯一约束 const existing = await app.model.StockStore.findOne({ where: { item_code: stockData.item_code, app_key: stockData.app_key, warehouse_id: warehouseId, store_id: stockData.store_id, }, }); let result; if (existing) { // 更新现有记录 await app.model.StockStore.update(stockData, { where: { id: existing.id, }, }); const updatedRow = await app.model.StockStore.findByPk(existing.id); result = updatedRow; } else { // 创建新记录 result = await app.model.StockStore.create(stockData); } try { // 创建/更新成功后,同步到库存表 // 注意:这里需要传入warehouseId作为第二个参数 const warehouseResult = await this.checkAndCreateWarehouseStock( stockData, warehouseId // 传入warehouse_id ); // 如果库存表操作成功,更新 stock_id if (warehouseResult.success) { await app.model.StockStore.update({ stock_id: warehouseResult.id, }, { where: { id: result.id, }, silent: true, // 不触发钩子,避免循环 }); await service.systems.operationLog.createOperationLog({ businessType: 'stock', businessId: warehouseResult.id, operationCode: 'BIND', operator: { id: null, name: '奇门', }, extras: { warehouseId, externalLogType: 'QIMEN', externalLogId: this.ctx.qimenLogId, }, beforeChanges: null, }); result.stock_id = warehouseResult.id; app.logger.debug(`[库存同步成功] StockStore ID: ${result.id}, StockWarehouse ID: ${warehouseResult.id}`); } else { app.logger.warn(`[库存同步失败] StockStore ID: ${result.id}, 原因: ${warehouseResult.message}`); } } catch (error) { // 库存同步失败不影响主流程,但记录日志 app.logger.error(`[库存同步异常] StockStore ID: ${result.id}`, { error: error.message, stack: error.stack, }); } return result; } async initQimenStockData(data, appKey, storeId, warehouseId) { const item_data = data.item ? data.item : {}; const result = { warehouse_code: data.warehouseCode || '', owner_code: data.ownerCode || '', is_area_sale: item_data.isAreaSale || 'N', item_code: item_data.itemCode || '', app_key: appKey || '', goods_code: item_data.goodsCode || '', item_name: item_data.itemName || '', sku_property: item_data.skuProperty || '', stock_unit: item_data.stockUnit || '', length: parseFloat(item_data.length) || 0, width: parseFloat(item_data.width) || 0, height: parseFloat(item_data.height) || 0, volume: parseFloat(item_data.volume) || 0, gross_weight: parseFloat(item_data.grossWeight) || 0, net_weight: parseFloat(item_data.netWeight) || 0, category_id: parseInt(item_data.categoryId) || 0, category_name: item_data.categoryName || '', item_type: item_data.itemType || '', tag_price: parseFloat(item_data.tagPrice) || 0, retail_price: parseFloat(item_data.retailPrice) || 0, brand_name: item_data.brandName || null, is_sn_mgmt: item_data.isSNMgmt || 'N', is_shelf_life_mgmt: item_data.isShelfLifeMgmt || 'N', is_batch_mgmt: item_data.isBatchMgmt || 'N', create_time: item_data.createTime || new Date(), update_time: new Date(), is_valid: item_data.isValid || 'Y', warehouse_id: warehouseId, barcode: item_data.barCode || '', store_id: storeId, create_from: 'qimen', }; return result; } async convertToQimenFormat(stockData) { const { app } = this; const result = { // 商品信息 item: { itemId: stockData.id, // 数据库主键作为奇门的itemId itemCode: stockData.item_code || '', goodsCode: stockData.goods_code || '', itemName: stockData.item_name || '', skuProperty: stockData.sku_property || '', stockUnit: stockData.stock_unit || '', // 尺寸重量信息 length: parseFloat(stockData.length) || 0, width: parseFloat(stockData.width) || 0, height: parseFloat(stockData.height) || 0, volume: parseFloat(stockData.volume) || 0, grossWeight: parseFloat(stockData.gross_weight) || 0, // 单位 g,Qimen 接口输出 netWeight: parseFloat(stockData.net_weight) || 0, // 单位 g,Qimen 接口输出 // 分类信息 categoryId: stockData.category_id || 0, categoryName: stockData.category_name || '', itemType: stockData.item_type || '', // 价格信息 tagPrice: parseFloat(stockData.tag_price) || 0, retailPrice: parseFloat(stockData.retail_price) || 0, // 管理标志 isAreaSale: stockData.is_area_sale === 'Y' ? 'Y' : 'N', isSNMgmt: stockData.is_sn_mgmt === 'Y' ? 'Y' : 'N', isShelfLifeMgmt: stockData.is_shelf_life_mgmt === 'Y' ? 'Y' : 'N', isBatchMgmt: stockData.is_batch_mgmt === 'Y' ? 'Y' : 'N', // 其他信息 barCode: stockData.barcode || '', isValid: stockData.is_valid === 'Y' ? 'Y' : 'N', createTime: stockData.create_time ? app.formatDate(stockData.create_time) : '', }, }; return result; } async getItemInfoWithCache(itemId) { const { app, ctx, } = this; const cacheKey = `item:info:${itemId}`; try { // 1. 尝试从缓存获取 const cached = await app.getCacheAsync(cacheKey); if (cached !== null && cached !== undefined) { app.logger.debug('[ItemCacheHit]', itemId); // 处理空值标记 if (cached.__isNull) { return null; // 明确返回 null 表示商品不存在 } // 返回缓存的对象 return cached; } // 2. 缓存未命中,查询数据库 app.logger.debug('[ItemCacheMiss]', itemId); // ⭐ 关键修复:使用 raw: true 获取纯对象 const itemInfo = await ctx.model.StockStore.findByPk(itemId, { attributes: [ 'id', 'stock_id', 'warehouse_code', 'item_code', 'item_name' ], // 按需增加字段 raw: true, // ⭐ 必须:转换为纯 JavaScript 对象 }); // 3. 处理查询结果并缓存 if (itemInfo) { // 缓存有效数据,设置合理过期时间(如5分钟) await app.setCacheAsync(cacheKey, itemInfo, 300); return itemInfo; } // ⭐ 关键:缓存空值,防止缓存穿透 // 使用特定标记,并设置较短过期时间(如1-2分钟) const nullMarker = { __isNull: true, }; await app.setCacheAsync(cacheKey, nullMarker, 120); return null; // 明确返回 null } catch (error) { app.logger.error('[getItemInfoWithCache] 查询失败', { itemId, error: error.message, stack: error.stack, }); // 根据错误类型处理 if (error.name && error.name.includes('Sequelize')) { // 数据库错误,抛出系统异常 throw new Error('商品信息查询服务暂时不可用'); } // Redis 等缓存错误,降级直接查数据库 // 这里简单重试一次数据库查询 app.logger.warn('缓存服务异常,降级直接查询数据库', itemId); try { const itemInfo = await ctx.model.StockStore.findByPk(itemId, { attributes: [ 'id', 'stock_id', 'warehouse_code', 'item_code' ], raw: true, }); return itemInfo || null; } catch (dbError) { // 数据库也失败,向上抛出 throw new Error(`查询商品信息失败: ${dbError.message}`); } } } /** * 查询商品对应的库存记录与可用量。 * * @param {number|string} itemId 商品 ID(StockStore.id)。 * @param {Object|null} transaction 数据库事务。 * @param {Object} [opts] 可选配置。 * @param {number} [opts.stockId] 当传入有效的 stockId 时,跳过 StockStore 映射层,直接使用该 stockId 查询 StockWarehouse。 * @return {Promise} 库存查询结果。 */ async getItemStorages(itemId, transaction, opts = {}) { const { ctx, app, } = this; const cacheKey = `storages:${itemId}`; try { const { stockId } = opts; // stockId 快速路径:跳过 StockStore 映射,直接用 stockId 查 StockWarehouse if (Number.isFinite(stockId) && stockId > 0) { const stockWarehouse = await ctx.model.StockWarehouse.findOne({ where: { id: stockId, is_valid: 'Y', deleted_at: null, }, attributes: [ 'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity', 'gross_weight', ], transaction, lock: transaction?.LOCK?.UPDATE, raw: true, }); if (stockWarehouse) { const quantity = parseInt(stockWarehouse.quantity) || 0; const lockedQuantity = parseInt(stockWarehouse.locked_quantity) || 0; const canUse = quantity - lockedQuantity; const grossWeight = parseInt(stockWarehouse.gross_weight) || 0; const storage = { id: stockWarehouse.id, storeId: Number(stockWarehouse.store_id) || 0, warehouseId: Number(stockWarehouse.warehouse_id) || 0, quantity, lockedQuantity, canUse, grossWeight, _updatedAt: Date.now(), exists: true, }; // 异步更新缓存 const cached = await app.getCacheAsync(cacheKey); if (!cached) { const ttl = this._calculateCacheTTL(storage); app.setCacheAsync(cacheKey, storage, ttl); } return { success: true, data: { stock: { id: itemId, stock_id: stockId, store_id: storage.storeId, warehouse_id: storage.warehouseId, }, storage, }, }; } // stockWarehouse 不存在 app.logger.warn(`[库存记录缺失-stockId快速路径] itemId=${itemId}, stockId=${stockId}`); return { success: false, error: '已更改未同步推送到仓库', data: null, }; } // 1. 获取商品信息 const itemInfo = await this.getItemInfoWithCache(itemId); // 情况A:商品不存在 if (!itemInfo || itemInfo.__isEmpty) { return { success: false, error: '已更改未同步推送到仓库', data: null, }; } // 情况B:商品存在但未绑定库存记录 if (!itemInfo.stock_id) { return { success: false, error: '仓库已解绑,请联系仓库关联绑定', data: null, }; } // 2. 检查缓存 let storage = null; let fromCache = false; const cached = await app.getCacheAsync(cacheKey); if (cached) { storage = cached; fromCache = true; if (storage && storage.canUse <= 0) { const policyConfig = await this.getStoreWarehousePolicyConfigByStockId(itemInfo.stock_id, transaction); if (!policyConfig.allowOversell) { app.logger.debug(`[缓存快速失败] 商品 ${itemId} 可用库存为0`); return { success: false, error: '库存不足', data: null, _fromCache: true, }; } } } // 3. 查询数据库(缓存未命中或事务场景) if (!storage || transaction) { const stockWarehouse = await ctx.model.StockWarehouse.findOne({ where: { id: itemInfo.stock_id, is_valid: 'Y', deleted_at: null, }, attributes: [ 'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity', 'gross_weight', ], transaction, lock: transaction?.LOCK?.UPDATE, raw: true, }); if (stockWarehouse) { const quantity = parseInt(stockWarehouse.quantity) || 0; const lockedQuantity = parseInt(stockWarehouse.locked_quantity) || 0; const canUse = quantity - lockedQuantity; const grossWeight = parseInt(stockWarehouse.gross_weight) || 0; storage = { id: stockWarehouse.id, storeId: Number(stockWarehouse.store_id) || 0, warehouseId: Number(stockWarehouse.warehouse_id) || 0, quantity, lockedQuantity, canUse, grossWeight, _updatedAt: Date.now(), exists: true, }; } else { // 库存记录不存在 app.logger.warn(`[库存记录缺失] 商品 ${itemId} 的 stock_id ${itemInfo.stock_id} 不存在`); storage = { id: null, quantity: 0, lockedQuantity: 0, canUse: 0, _updatedAt: Date.now(), exists: false, }; } // 4. 异步更新缓存(不加await,不阻塞主流程) const ttl = this._calculateCacheTTL(storage); if (!cached) { app.setCacheAsync(cacheKey, storage, ttl); } } // 5. 返回结果 return { success: true, data: { stock: { id: itemInfo.id, stock_id: itemInfo.stock_id, store_id: storage && storage.storeId ? storage.storeId : undefined, warehouse_id: storage && storage.warehouseId ? storage.warehouseId : undefined, warehouse_code: itemInfo.warehouse_code, item_code: itemInfo.item_code, }, storage, allow_oversell: storage && storage.canUse <= 0 ? (await this.getStoreWarehousePolicyConfigByStockId(itemInfo.stock_id, transaction)).allowOversell : undefined, }, error: null, _fromCache: fromCache, }; } catch (error) { app.logger.error(`[getItemStorages] 系统异常, itemId: ${itemId}`, { error: error.message, stack: error.stack, }); return { success: false, error: `库存查询系统错误: ${error.message}`, data: null, }; } } /** * 计算缓存时间 * @param {Object} storage - 库存对象 */ _calculateCacheTTL(storage) { if (!storage || !storage._exists || !storage._isValid) { return 5; // 无效库存缓存5秒 } if (storage.canUse <= 0) { return 10; // 无库存缓存10秒 } if (storage.canUse <= 10) { return 15; // 低库存缓存15秒 } return 60; // 正常库存缓存60秒 } /** * 清理缓存 * @param {number|string} itemId - 商品ID */ async clearItemStorageCache(itemId) { const { app, } = this; const cacheKey = `storages:${itemId}`; if (app && typeof app.delCacheAsync === 'function') { try { await app.delCacheAsync(cacheKey); app.logger.debug(`[缓存清理] 商品 ${itemId} 库存缓存已清理`); } catch (error) { app.logger.warn(`[缓存清理失败] 商品 ${itemId}`, error.message); } return; } if (app && typeof app.setCacheAsync === 'function') { try { await app.setCacheAsync(cacheKey, null, 0); app.logger.debug(`[缓存清理] 商品 ${itemId} 库存缓存已清理`); } catch (error) { app.logger.warn(`[缓存清理失败] 商品 ${itemId}`, error.message); } } } /** * 在给定事务中执行库存写操作,未传入事务时自动创建并提交回滚。 * * @param {Object} externalTransaction 外部传入的数据库事务 * @param {Function} handler 业务处理函数 * @return {Promise<*>} 业务处理结果 */ async _runWithTransaction(externalTransaction, handler) { const { ctx } = this; if (externalTransaction) { return handler(externalTransaction, true); } const internalTransaction = await ctx.model.transaction(); try { const result = await handler(internalTransaction, false); await internalTransaction.commit(); return result; } catch (error) { await internalTransaction.rollback(); throw error; } } /** * 按货主和仓库获取签约策略配置(带缓存,用于锁外预取)。 * * @param {number} storeId 货主ID。 * @param {number} warehouseId 仓库ID。 * @return {Promise} { allowOversell: boolean, relation: Object|null } */ async getStoreWarehousePolicyByStoreAndWarehouse(storeId, warehouseId) { const { ctx, app } = this; const normalizedStoreId = Number(storeId || 0); const normalizedWarehouseId = Number(warehouseId || 0); if (normalizedStoreId <= 0 || normalizedWarehouseId <= 0) { return { allowOversell: false, relation: null }; } const cacheKey = `sw_policy:${normalizedStoreId}:${normalizedWarehouseId}`; // 1. 先查缓存 const cached = await app.getCacheAsync(cacheKey); if (cached) { return cached; } // 2. 缓存未命中,查 DB(无事务) const relation = await ctx.model.StoreWarehouse.findOne({ where: { store_id: normalizedStoreId, warehouse_id: normalizedWarehouseId, auth_status: 2, warehouse_use_status: 1, }, attributes: [ 'id', 'policy_config', 'auth_status', 'warehouse_use_status', 'store_use_status' ], raw: true, }); if (!relation) { const fallback = { allowOversell: false, relation: null }; await app.setCacheAsync(cacheKey, fallback, 300); return fallback; } const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse; const policyConfig = storeWarehouseService && typeof storeWarehouseService.getEffectivePolicyConfigByContractId === 'function' ? await storeWarehouseService.getEffectivePolicyConfigByContractId(relation.id) : null; const result = { allowOversell: Number(policyConfig && policyConfig.allow_oversell) === 1, relation, }; await app.setCacheAsync(cacheKey, result, 300); return result; } /** * 获取库存对应的货主-仓库签约策略配置。 * * @param {number|Object} stockWarehouseId 库存 ID 或库存记录。 * @param {Object|null} [transaction=null] 事务对象。 * @return {Promise} 策略配置对象,包含 relation、policyConfig、allowOversell。 */ async getStoreWarehousePolicyConfigByStockId(stockWarehouseId, transaction = null) { const { ctx } = this; const stockRecord = stockWarehouseId && typeof stockWarehouseId === 'object' ? stockWarehouseId : await ctx.model.StockWarehouse.findOne({ where: { id: Number(stockWarehouseId || 0), is_valid: 'Y', deleted_at: null, }, attributes: [ 'id', 'store_id', 'warehouse_id' ], transaction, raw: true, }); const storeId = Number(stockRecord && stockRecord.store_id) || 0; const warehouseId = Number(stockRecord && stockRecord.warehouse_id) || 0; if (storeId <= 0 || warehouseId <= 0) { return { relation: null, policyConfig: null, allowOversell: false, }; } const relation = await ctx.model.StoreWarehouse.findOne({ where: { store_id: storeId, warehouse_id: warehouseId, auth_status: 2, warehouse_use_status: 1, }, attributes: [ 'id', 'policy_config', 'auth_status', 'warehouse_use_status', 'store_use_status' ], transaction, raw: true, }); if (!relation) { return { relation: null, policyConfig: null, allowOversell: false, }; } const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse; const policyConfig = storeWarehouseService && typeof storeWarehouseService.getEffectivePolicyConfigByContractId === 'function' ? await storeWarehouseService.getEffectivePolicyConfigByContractId(relation.id, transaction) : null; return { relation, policyConfig, allowOversell: Number(policyConfig && policyConfig.allow_oversell) === 1, }; } /** * 统一修改 wms_stock_warehouse.locked_quantity 并写入 stock_transaction 流水。 * 所有对 locked_quantity 的写操作必须通过此函数,禁止直接 increment/decrement/update。 * * @param {number} stockId StockWarehouse.id。 * @param {number} change 变更量,正数为加锁,负数为解锁。 * @param {Object} currentTransaction 数据库事务对象。 * @param {Object} [meta={}] 元信息。 * @param {boolean} [meta.allowOversell=false] 是否允许超卖,为 true 时跳过可用库存校验。 * @param {boolean} [meta.skipTransactionLog=false] 是否跳过流水写入。 * @param {string} [meta.orderType] 订单类型,用于流水。 * @param {string} [meta.orderNo] 订单号。 * @param {number} [meta.orderId] 订单ID。 * @param {string} [meta.remark] 备注。 * @param {string} [meta.operatorId] 操作人ID。 * @param {string} [meta.operatorName] 操作人姓名。 * @return {Promise<{success: boolean, error?: string, data?: Object}>} 修改结果,失败时携带错误信息。 */ async updateLockedQuantity(stockId, change, currentTransaction, meta = {}) { const { ctx, app } = this; const absQty = Math.abs(change); const isLocking = change > 0; if (!stockId || absQty <= 0) { return { success: false, error: `参数无效: stockId=${stockId}, change=${change}` }; } const stockRecord = await ctx.model.StockWarehouse.findOne({ where: { id: stockId, is_valid: 'Y', deleted_at: null }, transaction: currentTransaction, lock: currentTransaction.LOCK.UPDATE, attributes: [ 'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity' ], raw: false, }); if (!stockRecord) { return { success: false, error: `库存记录不存在或已失效 (ID: ${stockId})` }; } const beforeQuantity = Number(stockRecord.quantity) || 0; const beforeLocked = Number(stockRecord.locked_quantity) || 0; // 加锁校验:可用库存(允许超卖时跳过此校验) if (isLocking && meta.allowOversell !== true) { const availableQty = beforeQuantity - beforeLocked; if (availableQty < absQty) { return { success: false, error: `库存不足,可用 ${availableQty},需求 ${absQty}`, data: { available: availableQty, required: absQty }, }; } } // 解锁校验:锁定库存足够 if (!isLocking && beforeLocked < absQty) { return { success: false, error: `释放数量超过已锁定库存,已锁 ${beforeLocked},尝试释放 ${absQty}`, }; } // 执行写操作 await stockRecord.increment('locked_quantity', { by: change, transaction: currentTransaction, silent: true, }); const afterLocked = beforeLocked + change; const afterQuantity = beforeQuantity; // locked_quantity 变更不影响 quantity // 写入流水(除非显式跳过) const skipLog = meta.skipTransactionLog === true; if (!skipLog && ctx.service && ctx.service.systems && ctx.service.systems.stockTransaction) { // 锁定操作使用 LOCK 类型,释放操作(如取消订单)使用 UNLOCK await ctx.service.systems.stockTransaction.create({ transaction_type: isLocking ? 'LOCK' : 'UNLOCK', warehouse_id: stockRecord.warehouse_id, store_id: stockRecord.store_id, stock_id: stockId, quantity: absQty, order_type: meta.orderType || null, order_no: meta.orderNo || null, order_id: meta.orderId || null, operator_id: meta.operatorId || String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), operator_name: meta.operatorName || ctx.user?.employees_name || '', remark: meta.remark || `库存${isLocking ? '锁定' : '释放'}`, before_quantity: beforeQuantity, after_quantity: afterQuantity, before_locked_quantity: beforeLocked, after_locked_quantity: afterLocked, created_at: new Date(), }, { transaction: currentTransaction }); } app.logger.info( `[库存${isLocking ? '锁定' : '释放'}] ID: ${stockId}, ${isLocking ? '+' : '-'}${absQty}, 锁定后: ${afterLocked}` ); return { success: true, data: { id: stockId, action: isLocking ? 'lock' : 'unlock', quantity: absQty, beforeLocked, afterLocked, totalQuantity: afterQuantity, available: afterQuantity - afterLocked, }, }; } /** * 锁定或释放库存。 * * @param {number|string} stockWarehouseId 库存主键。 * @param {number} quantity 锁定数量,负数表示释放。 * @param {Object|null} transaction 数据库事务。 * @param {Object|null} [oversellConfig=null] 可选预取策略配置,用于避免锁内查DB。 * @param {Object} [meta={}] 可选元信息,透传给 updateLockedQuantity 用于流水记录。 * @return {Promise} 锁定结果。 */ async lockItemStorages(stockWarehouseId, quantity, transaction, oversellConfig = null, meta = {}) { const { app } = this; const lockQty = parseInt(quantity); if (!stockWarehouseId || isNaN(lockQty) || lockQty === 0) { return { success: false, error: '参数错误:库存ID无效或数量为0', data: null }; } const isLocking = lockQty > 0; const absQty = Math.abs(lockQty); try { return await this._runWithTransaction(transaction, async currentTransaction => { const allowOversell = oversellConfig ? oversellConfig.allowOversell : false; const result = await this.updateLockedQuantity(stockWarehouseId, lockQty, currentTransaction, { remark: meta.remark || (isLocking ? '出库单创建锁定' : '出库单创建解锁'), orderType: meta.orderType || null, orderNo: meta.orderNo || null, orderId: meta.orderId || null, allowOversell: isLocking ? allowOversell : undefined, }); if (!result.success) { return result; } const { beforeLocked, afterLocked, totalQuantity } = result.data; return { success: true, data: { id: stockWarehouseId, action: isLocking ? 'lock' : 'unlock', quantity: absQty, beforeLocked, afterLocked, totalQuantity, available: totalQuantity - afterLocked, }, error: null, }; }); } catch (error) { app.logger.error('[lockItemStorages] 系统异常', { stockWarehouseId, quantity, isLocking, error: error.message }); if (error.name && error.name.includes('Sequelize')) { return { success: false, error: `数据库操作失败: ${error.message}`, data: null }; } return { success: false, error: `系统错误: ${error.message}`, data: null }; } } /** * 商品入库服务 * @param {number} itemId 商品ID (StockStore.id) * @param {number} quantity 入库数量(正数) * @param {Object} transaction 数据库事务 * @param {Object} [opts] 可选配置,透传给 getItemStorages。 */ async inbound(itemId, quantity, transaction, opts = {}) { const { ctx, app, } = this; // 1. 参数验证 const inboundQty = parseInt(quantity); if (!itemId || inboundQty <= 0) { return { success: false, error: `入库参数无效: itemId=${itemId}, quantity=${quantity}`, data: null, }; } try { return await this._runWithTransaction(transaction, async (currentTransaction, hasExternalTransaction) => { // 2. 获取商品和库存信息(复用) const stockResult = await this.getItemStorages(itemId, currentTransaction, opts); if (!stockResult.success) { if (hasExternalTransaction) { throw new Error(stockResult.error); } return stockResult; } const { storage } = stockResult.data; // 3. 执行库存增加 if (!storage.exists) { const failureResult = { success: false, error: '库存记录不存在,首次入库需要完整参数', data: null, }; if (hasExternalTransaction) { throw new Error(failureResult.error); } return failureResult; } const beforeQuantity = Number(storage.quantity) || 0; const beforeLockedQuantity = Number(storage.lockedQuantity) || 0; // 非首次入库:更新现有记录(只增加quantity) const [ affectedRows ] = await ctx.model.StockWarehouse.increment('quantity', { by: inboundQty, where: { id: storage.id, is_valid: 'Y', deleted_at: null, }, transaction: currentTransaction, }); if (!affectedRows || affectedRows === 0) { const failureResult = { success: false, error: '商品库存记录不存在或已失效,入库失败', data: null, }; if (hasExternalTransaction) { throw new Error(failureResult.error); } return failureResult; } const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, { transaction: currentTransaction, raw: true, }); const afterQuantity = Number(updatedRecord.quantity) || 0; const afterLockedQuantity = Number(updatedRecord.locked_quantity) || 0; // 负库存回填:按 SW 非负增量冲销 GAP 补建行挂账(平账,拦截锁定回归真实数据) if (beforeQuantity <= 0) { const nonNegativeDelta = Math.max(0, afterQuantity) - Math.max(0, beforeQuantity); const offsetQty = await ctx.service.systems.storage.index.offsetGapOnInbound(storage.id, inboundQty, { transaction: currentTransaction, maxOffset: nonNegativeDelta, orderNo: 'STOCK_STORE_INBOUND', operatorId: String(ctx.user?.employees_id || ctx.user?.id || ''), operatorName: ctx.user?.employees_name || '', }); if (offsetQty > 0) { app.logger.info(`[入库] 负库存回填平账,冲销 GAP 挂账 ${offsetQty} 件 stockId=${storage.id}`); } } await ctx.service.systems.stockTransaction.create({ transaction_type: 'INBOUND', warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id, store_id: ctx.user.store_id, stock_id: storage.id, storage_id: null, space_id: null, quantity: inboundQty, batch_no: null, inventory_type: 'ZP', order_type: 'STOCK_STORE_INBOUND', order_no: null, order_id: null, receiving_id: null, entry_order_id: null, 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: currentTransaction, }); await ctx.model.StorageTransaction.create({ transaction_type: 'INBOUND', warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id, store_id: ctx.user.store_id, stock_id: storage.id, storage_id: null, space_id: null, quantity: inboundQty, before_quantity: beforeQuantity, after_quantity: afterQuantity, before_locked_quantity: beforeLockedQuantity, after_locked_quantity: afterLockedQuantity, batch_no: null, inventory_type: 'ZP', order_type: 'STOCK_STORE_INBOUND', order_no: null, order_id: null, source_order_codes: null, operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), operator_name: ctx.user?.employees_name || '', remark: '商品入库', created_at: new Date(), }, { transaction: currentTransaction, }); app.logger.info('[入库] 更新现有库存', { itemId, stockId: storage.id, quantity: inboundQty, before: beforeQuantity, after: afterQuantity, }); await this.clearItemStorageCache(itemId); return { success: true, data: { itemId, stockId: storage.id, action: 'inbound', quantity: inboundQty, beforeQuantity, afterQuantity, beforeLocked: beforeLockedQuantity, afterLocked: afterLockedQuantity, available: afterQuantity - afterLockedQuantity, updatedAt: updatedRecord.update_at, }, error: null, }; }); } catch (error) { if (transaction) { throw error; } app.logger.error('[inbound] 入库失败', { itemId, quantity, error: error.message, stack: error.stack, }); return { success: false, error: `入库系统错误: ${error.message}`, data: null, }; } } /** * 规范化出库元信息,兼容驼峰与下划线字段。 * * @param {Object} meta 出库元信息。 * @return {Object} 规范化后的订单上下文。 */ normalizeOutboundMeta(meta = {}) { const normalized = meta && typeof meta === 'object' ? meta : {}; const orderIdRaw = normalized.orderId ?? normalized.order_id ?? normalized.deliveryOrderId ?? normalized.delivery_order_id ?? normalized.id; const orderItemIdRaw = normalized.orderItemId ?? normalized.order_item_id; const sourceOrderCodesRaw = normalized.sourceOrderCodes ?? normalized.source_order_codes; const orderNoRaw = normalized.orderNo ?? sourceOrderCodesRaw ?? normalized.order_no ?? normalized.deliveryOrderCode ?? normalized.delivery_order_code; const orderId = Number(orderIdRaw); const orderItemId = Number(orderItemIdRaw); const orderNo = String(orderNoRaw || '').trim(); const sourceOrderCodes = String(sourceOrderCodesRaw || '').trim(); return { orderId: Number.isFinite(orderId) && orderId > 0 ? orderId : null, orderItemId: Number.isFinite(orderItemId) && orderItemId > 0 ? orderItemId : null, orderNo: orderNo || null, sourceOrderCodes: sourceOrderCodes || null, }; } /** * 查询订单明细对应的拣货分配记录。 * * @param {number|null} orderId 订单 ID。 * @param {number|null} orderItemId 订单明细 ID。 * @param {Object|null} transaction 事务对象。 * @param {number} warehouseId 仓库ID。 * @return {Promise>} 拣货分配列表。 */ async getPickingRowsForOutbound(orderId, orderItemId, transaction, warehouseId) { const { ctx } = this; const pickingModel = ctx.model && ctx.model.Picking; if (!pickingModel || typeof pickingModel.findAll !== 'function') { return []; } if (!orderId || !orderItemId) { return []; } const rows = await pickingModel.findAll({ where: { order_id: orderId, order_item_id: orderItemId, warehouse_id: warehouseId, }, attributes: [ 'storage_id', 'space_id', 'quantity' ], order: [[ 'id', 'ASC' ]], raw: true, transaction, }); return Array.isArray(rows) ? rows : []; } /** * 批量查询拣货行对应的库存批次号(wms_storage.batch_no)。 * * @param {Array} pickingRows 拣货分配记录列表 * @param {Object|null} transaction 事务对象 * @return {Promise>} storage_id → batch_no 映射表 */ async getPickingBatchMap(pickingRows, transaction) { const { ctx, app } = this; const map = new Map(); if (!Array.isArray(pickingRows) || pickingRows.length === 0) { return map; } const storageIds = [ ...new Set(pickingRows.map(r => Number(r.storage_id)).filter(id => id > 0)) ]; if (storageIds.length === 0) { return map; } try { const storageRows = await ctx.model.Storage.findAll({ where: { id: { [app.Sequelize.Op.in]: storageIds } }, attributes: [ 'id', 'batch_no' ], raw: true, transaction, }); for (const sr of storageRows) { if (sr && sr.batch_no) { map.set(Number(sr.id), String(sr.batch_no).trim()); } } } catch (error) { app.logger.warn(`[getPickingBatchMap] 查询 storage batch_no 失败,降级跳过: ${error.message}`); } return map; } /** * 生成出库流水写入明细,优先按拣货分配逐条记录。 * * @param {Object} options 参数集合。 * @param {number} options.outboundQty 本次出库总数量。 * @param {Array} options.pickingRows 拣货分配记录。 * @param {Object} options.basePayload 流水公共字段。 * @param {Map} options.pickingBatchMap storage_id → batch_no 映射表。 * @return {Array} 待写入的出库流水列表。 */ buildOutboundTransactionPayloads({ outboundQty, pickingRows, basePayload, pickingBatchMap = new Map() }) { const payloads = []; const normalizedRows = Array.isArray(pickingRows) ? pickingRows : []; let consumedQty = 0; for (const pickingRow of normalizedRows) { const remainingQty = outboundQty - consumedQty; if (remainingQty <= 0) { break; } const pickingQty = Number(pickingRow && pickingRow.quantity) || 0; if (pickingQty <= 0) { continue; } const transactionQty = Math.min(pickingQty, remainingQty); const storageId = pickingRow && pickingRow.storage_id ? Number(pickingRow.storage_id) : null; const batchNo = storageId ? (pickingBatchMap.get(storageId) || null) : null; payloads.push({ ...basePayload, storage_id: storageId, space_id: pickingRow && pickingRow.space_id ? Number(pickingRow.space_id) : null, quantity: transactionQty, batch_no: batchNo || basePayload.batch_no || null, }); consumedQty += transactionQty; } if (payloads.length === 0) { return [{ ...basePayload, storage_id: null, space_id: null, quantity: outboundQty, }]; } if (consumedQty < outboundQty) { payloads.push({ ...basePayload, storage_id: null, space_id: null, quantity: outboundQty - consumedQty, }); } return payloads; } /** * 商品出库服务 * @param {number} itemId 商品ID (StockStore.id) * @param {number} quantity 出库数量(正数) * @param {Object} transaction 数据库事务 * @param {Object} meta 出库元信息(订单、明细等) * @param {Object} [opts] 可选配置,透传给 getItemStorages。 */ async outbound(itemId, quantity, transaction, meta = {}, opts = {}) { const { ctx, app, } = this; const outboundMeta = this.normalizeOutboundMeta(meta); // 1. 参数验证 const outboundQty = parseInt(quantity); if (!itemId || outboundQty <= 0) { return { success: false, error: `出库参数无效: itemId=${itemId}, quantity=${quantity}`, data: null, }; } try { return await this._runWithTransaction(transaction, async (currentTransaction, hasExternalTransaction) => { // 2. 获取商品和库存信息(复用) const stockResult = await this.getItemStorages(itemId, currentTransaction, opts); if (!stockResult.success) { if (hasExternalTransaction) { throw new Error(stockResult.error); } return stockResult; } const { storage } = stockResult.data; // 3. 检查库存是否足够出库 if (!storage.exists) { const failureResult = { success: false, error: '库存记录不存在,无法出库', data: null, }; if (hasExternalTransaction) { throw new Error(failureResult.error); } return failureResult; } const beforeQuantity = Number(storage.quantity) || 0; const beforeLockedQuantity = Number(storage.lockedQuantity) || 0; const policyConfig = await this.getStoreWarehousePolicyConfigByStockId(storage.id, currentTransaction); const allowOversell = policyConfig.allowOversell === true; // 关键检查:总库存是否足够,启用超卖时放行负库存结果 if (beforeQuantity < outboundQty && !allowOversell) { const failureResult = { success: false, error: `总库存不足,当前 ${beforeQuantity},需求 ${outboundQty}`, data: null, }; if (hasExternalTransaction) { throw new Error(failureResult.error); } return failureResult; } // 关键检查:锁定库存是否足够扣减 if (beforeLockedQuantity < outboundQty) { const failureResult = { success: false, error: `锁定库存不足,已锁定 ${beforeLockedQuantity},需求 ${outboundQty}`, data: null, }; if (hasExternalTransaction) { throw new Error(failureResult.error); } return failureResult; } // 4. 执行出库扣减:先调用核心函数处理 locked_quantity,再单独扣减 quantity const lockResult = await this.updateLockedQuantity(storage.id, -outboundQty, currentTransaction, { skipTransactionLog: true, remark: '订单出库', orderType: 'STOCK_STORE_OUTBOUND', orderNo: outboundMeta.orderNo, orderId: outboundMeta.orderId, }); if (!lockResult.success) { if (hasExternalTransaction) { throw new Error(lockResult.error); } return lockResult; } // 同步扣减 quantity const qtyResult = await ctx.model.StockWarehouse.update({ quantity: app.Sequelize.literal(`quantity - ${outboundQty}`), update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), }, { where: { id: storage.id, is_valid: 'Y', deleted_at: null }, transaction: currentTransaction, }); if (qtyResult[0] === 0) { const failureResult = { success: false, error: '出库失败:库存已被其他操作修改', data: null }; if (hasExternalTransaction) throw new Error(failureResult.error); return failureResult; } // 5. 获取更新后的数据 const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, { transaction: currentTransaction, raw: true, }); const afterQuantity = Number(updatedRecord.quantity) || 0; const afterLockedQuantity = Number(updatedRecord.locked_quantity) || 0; let pickingRows = []; if (outboundMeta.orderId && outboundMeta.orderItemId) { try { const pickingWarehouseId = Number(storage.warehouse_id || updatedRecord.warehouse_id || ctx.user.store_id || 0); pickingRows = await this.getPickingRowsForOutbound(outboundMeta.orderId, outboundMeta.orderItemId, currentTransaction, pickingWarehouseId); } catch (error) { app.logger.warn(`[outbound] 读取拣货分配失败,降级为单条出库流水: ${error.message}`); } } // 获取拣货行对应的库存批次号(wms_storage.batch_no) const pickingBatchMap = await this.getPickingBatchMap(pickingRows, currentTransaction); const baseTransactionPayload = { transaction_type: 'OUTBOUND', warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id, store_id: storage.storeId || updatedRecord.store_id || ctx.user.store_id, stock_id: storage.id, batch_no: null, inventory_type: 'ZP', order_type: 'STOCK_STORE_OUTBOUND', order_no: outboundMeta.orderNo, order_id: outboundMeta.orderId, source_order_codes: outboundMeta.sourceOrderCodes, receiving_id: null, entry_order_id: null, 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(), }; const transactionPayloads = this.buildOutboundTransactionPayloads({ outboundQty, pickingRows, basePayload: baseTransactionPayload, pickingBatchMap, }); for (const payload of transactionPayloads) { await ctx.service.systems.stockTransaction.create(payload, { transaction: currentTransaction, }); } app.logger.info('[出库] 成功', { itemId, stockId: storage.id, quantity: outboundQty, beforeQuantity, afterQuantity, beforeLocked: beforeLockedQuantity, afterLocked: afterLockedQuantity, }); await this.clearItemStorageCache(itemId); return { success: true, data: { itemId, stockId: storage.id, action: 'outbound', quantity: outboundQty, beforeQuantity, afterQuantity, beforeLocked: beforeLockedQuantity, afterLocked: afterLockedQuantity, available: afterQuantity - afterLockedQuantity, updatedAt: updatedRecord.update_at, }, error: null, }; }); } catch (error) { if (transaction) { throw error; } app.logger.error('[outbound] 出库失败', { itemId, quantity, error: error.message, stack: error.stack, }); return { success: false, error: `出库系统错误: ${error.message}`, data: null, }; } } async checkAndCreateWarehouseStock(sourceData, warehouseId) { const { ctx, app, service, } = this; try { // 1. 参数验证 if (!sourceData || !sourceData.item_code) { return { success: false, id: null, message: '缺少必要参数: item_code', }; } if (!warehouseId) { return { success: false, id: null, message: '缺少必要参数: warehouseId', }; } // 2. 检查记录是否存在 const existingRecord = await ctx.model.StockWarehouse.findOne({ where: { item_code: sourceData.item_code, warehouse_id: warehouseId, store_id: sourceData.store_id, deleted_at: null, is_valid: 'Y', }, attributes: [ 'id' ], raw: true, }); // 3. 如果存在,直接返回ID if (existingRecord) { app.logger.debug( `[库存记录已存在] item_code: ${sourceData.item_code}, warehouse_id: ${warehouseId}` ); return { success: true, id: existingRecord.id, message: '库存记录已存在', exists: true, }; } // 4. 准备创建数据 const now = new Date(); const stockData = { // 唯一约束字段 item_code: sourceData.item_code, goods_code: sourceData.goods_code, warehouse_id: warehouseId, // 商品基本信息 store_id: sourceData.store_id || 0, item_name: sourceData.item_name || '', sku_property: sourceData.sku_property || '', stock_unit: sourceData.stock_unit || '个', // 提供默认值 item_type: sourceData.item_type || 'ZC', // 规格信息 length: parseFloat(sourceData.length) || 0, width: parseFloat(sourceData.width) || 0, height: parseFloat(sourceData.height) || 0, volume: parseFloat(sourceData.volume) || 0, gross_weight: parseFloat(sourceData.gross_weight) || 0, net_weight: parseFloat(sourceData.net_weight) || 0, // 价格信息 tag_price: parseFloat(sourceData.tag_price) || 0, retail_price: parseFloat(sourceData.retail_price) || 0, brand_name: sourceData.brand_name || null, // 管理属性 is_sn_mgmt: sourceData.is_sn_mgmt === 'Y' ? 'Y' : 'N', is_shelf_life_mgmt: sourceData.is_shelf_life_mgmt === 'Y' ? 'Y' : 'N', is_batch_mgmt: sourceData.is_batch_mgmt === 'Y' ? 'Y' : 'N', // 其他字段 packing_requirements: sourceData.packing_requirements || '', create_at: now, update_at: now, is_valid: 'Y', level: 'C', quantity: parseInt(sourceData.quantity) || 0, locked_quantity: parseInt(sourceData.locked_quantity) || 0, deleted_at: null, }; // 5. 创建记录(处理可能的重复插入) let createdRecord; try { createdRecord = await ctx.model.StockWarehouse.create(stockData); const barcodes = sourceData.barcode.split(';'); const existingFileIds = []; const toCreate = barcodes.filter(item => !existingFileIds.includes(item)); // 批量操作 const promises = []; if (toCreate.length > 0) { const refData = toCreate.map(item => ({ stock_id: createdRecord.id, barcode: item, warehouse_id: warehouseId, created_at: new Date(), })); promises.push(ctx.model.StockBarcode.bulkCreate(refData)); await Promise.all(promises); } await service.systems.operationLog.createOperationLog({ businessType: 'stock', businessId: createdRecord.id, operationCode: 'CREATE', operator: { id: null, name: '奇门', }, extras: { warehouseId, externalLogType: 'QIMEN', externalLogId: this.ctx.qimenLogId, }, beforeChanges: null, }); } catch (createError) { // 如果是唯一约束冲突,说明在创建过程中其他请求已经创建了 if (createError.name === 'SequelizeUniqueConstraintError') { app.logger.warn( `[库存记录并发创建] item_code: ${sourceData.item_code}, warehouse_id: ${warehouseId}` ); // 重新查询一次 const retryRecord = await ctx.model.StockWarehouse.findOne({ where: { item_code: sourceData.item_code, goods_code: sourceData.goods_code, warehouse_id: warehouseId, is_valid: 'Y', deleted_at: null, }, attributes: [ 'id' ], raw: true, }); if (retryRecord) { return { success: true, id: retryRecord.id, message: '库存记录并发创建成功', exists: true, }; } } throw createError; } app.logger.debug(`[库存记录创建成功] id: ${createdRecord.id}, item_code: ${sourceData.item_code}`); return { success: true, id: createdRecord.id, message: '库存记录创建成功', exists: false, }; } catch (error) { app.logger.error('[checkAndCreateStock] 系统异常', { sourceData, warehouseId, error: error.message, stack: error.stack, }); return { success: false, id: null, message: `库存记录操作失败: ${error.message}`, error, }; } } /** * 获取仓库库存列表(支持分页和动态查询条件) * @param {Object} where - 查询条件对象 * @param {Object} pageParams - 分页参数 * @param {number} pageParams.page - 当前页码,默认1 * @param {number} pageParams.pageSize - 每页条数,默认20 * @param {Object} sortParams - 排序参数 * @param {string} sortParams.sortField - 排序字段,默认'create_at' * @param {string} sortParams.sortOrder - 排序方式,默认'DESC' * @param {number} externalWarehouseId - 外部传入的仓库ID,缺省取当前用户仓库上下文 * @param {number} externalStoreId - 外部传入的货主ID,缺省不按货主过滤 * @return {Promise} 返回查询结果 */ async getWarehouseStock(where, pageParams = {}, sortParams = {}, externalWarehouseId = 0, externalStoreId = 0) { const { ctx, app, } = this; const { Sequelize, } = app; const { Op, } = Sequelize; // 仓库ID:优先使用外部传入,否则取当前用户上下文 const warehouseId = Number.isFinite(externalWarehouseId) && externalWarehouseId > 0 ? externalWarehouseId : ctx.user.store_id; // 货主ID:外部传入时按货主维度查询(不限定仓库) const storeId = Number.isFinite(externalStoreId) && externalStoreId > 0 ? externalStoreId : 0; try { // 设置默认参数 const { page = 1, pageSize = 20, } = pageParams; const { sortField = 'id', sortOrder = 'DESC', } = sortParams; // 构建基础查询条件 const queryOptions = { where: {}, order: [], attributes: { exclude: [ 'deleted_at' ], }, }; const barcodeQueryOptions = { where: {}, }; const prohibitedQueryOptions = { where: {}, }; const storeOutStockQueryOptions = { where: {}, }; // 添加默认条件 if (storeId > 0) { // 按货主维度查询(不限定仓库) queryOptions.where[Op.and] = [{ store_id: storeId, }, { is_valid: 'Y', }, { deleted_at: null, }, ]; } else { queryOptions.where[Op.and] = [{ warehouse_id: warehouseId, }, { is_valid: 'Y', }, { deleted_at: null, }, ]; } barcodeQueryOptions.where[Op.and] = []; prohibitedQueryOptions.where[Op.and] = []; storeOutStockQueryOptions.where[Op.and] = []; // 检测并处理条码查询条件 let hasBarcodeCondition = false; let hasProhibitedCondition = false; let hasBoundItemCondition = false; let boundItemValue = null; let barcodeCondition = null; let parsedBarcodeInput = null; const normalizedWhere = ctx.where && typeof ctx.where === 'object' ? ctx.where : (where && typeof where === 'object' ? where : {}); // 处理动态查询条件 if (normalizedWhere && Object.keys(normalizedWhere).length > 0) { let parsedResult = ctx.whereParsed; if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { const parsed = parseWhereConditions({ where: normalizedWhere, app, specialFieldMap: { barcode: { bucket: 'barcode', }, prohibited_type: { bucket: 'prohibited', field: 'id', }, has_bound_item: { bucket: 'storeOutStock', field: 'stock_id', }, keyword: { bucket: 'keyword', }, }, }); if (!parsed.ok) { return { code: 400, data: { list: [], pagination: { page: parseInt(page), pageSize: parseInt(pageSize), total: 0, totalPages: 0, hasPrevious: false, hasNext: false, }, }, message: `筛选条件解析失败: ${parsed.reason}`, }; } parsedResult = parsed.result; } const { dynamicConditions, bucketConditions, bucketFlags, rawConditionsByField, } = parsedResult; const barcodeDynamicConditions = bucketConditions.barcode || []; const prohibitedConditions = bucketConditions.prohibited || []; const storeOutStockConditions = bucketConditions.storeOutStock || []; hasBarcodeCondition = Boolean(bucketFlags.barcode); hasProhibitedCondition = Boolean(bucketFlags.prohibited); hasBoundItemCondition = Boolean(bucketFlags.storeOutStock); barcodeCondition = barcodeDynamicConditions[0] || null; parsedBarcodeInput = rawConditionsByField.barcode || null; if (hasBoundItemCondition && rawConditionsByField.has_bound_item) { boundItemValue = rawConditionsByField.has_bound_item.value; } // keyword 快捷搜索:模糊匹配商品编码/名称/货物编码 const keywordInput = rawConditionsByField.keyword || null; const keywordValue = keywordInput && typeof keywordInput === 'object' ? keywordInput.value : keywordInput; if (keywordValue !== undefined && keywordValue !== null && String(keywordValue).trim() !== '') { const kw = `%${String(keywordValue).trim()}%`; queryOptions.where[Op.and].push({ [Op.or]: [ { item_code: { [Op.like]: kw } }, { item_name: { [Op.like]: kw } }, { goods_code: { [Op.like]: kw } }, ], }); } if (dynamicConditions.length > 0) { queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions, }); } if (barcodeDynamicConditions.length > 0) { barcodeQueryOptions.where[Op.and].push({ [Op.and]: barcodeDynamicConditions, }); } if (prohibitedConditions.length > 0) { prohibitedQueryOptions.where[Op.and].push({ [Op.and]: prohibitedConditions, }); } if (storeOutStockConditions.length > 0) { storeOutStockQueryOptions.where[Op.and].push({ [Op.and]: storeOutStockConditions, }); } // has_bound_item 的「未绑定」场景:通过 NOT EXISTS 子查询在主表 where 上直接过滤 const isBoundFalse = boundItemValue === false || boundItemValue === 0 || String(boundItemValue || '').trim().toLowerCase() === 'false' || String(boundItemValue || '').trim() === '0' || String(boundItemValue || '').trim().toLowerCase() === 'n'; if (hasBoundItemCondition && isBoundFalse) { queryOptions.where[Op.and].push( Sequelize.literal( 'NOT EXISTS (SELECT 1 FROM wms_stock_store WHERE wms_stock_store.stock_id = stock_warehouse.id)' ) ); } } // 如果有条码查询条件,先查询匹配的库存ID let matchedStockIds = []; if (hasBarcodeCondition && barcodeCondition) { // 从条码条件中提取条码值,构建条码查询 let barcodeValues = []; // 根据不同的条件格式提取条码值 if (parsedBarcodeInput && parsedBarcodeInput.value) { if (Array.isArray(parsedBarcodeInput.value)) { barcodeValues = parsedBarcodeInput.value; } else if (typeof parsedBarcodeInput.value === 'string') { barcodeValues = [ parsedBarcodeInput.value ]; } } if (barcodeValues.length > 0) { // 构建条码查询条件 const barcodeWhere = {}; const barcodeOperator = String(parsedBarcodeInput.operator || 'like').toLowerCase(); if (barcodeOperator === 'eq') { // 精确查询 if (barcodeValues.length === 1) { barcodeWhere.barcode = barcodeValues[0]; } else { barcodeWhere.barcode = { [Op.in]: barcodeValues, }; } } else if (barcodeOperator === 'like') { // 模糊查询 if (barcodeValues.length === 1) { barcodeWhere.barcode = { [Op.like]: `%${barcodeValues[0]}%`, }; } else { const likeConditions = barcodeValues.map(value => ({ barcode: { [Op.like]: `%${value}%`, }, })); barcodeWhere[Op.or] = likeConditions; } } else { // 默认模糊查询 barcodeWhere.barcode = { [Op.like]: `%${barcodeValues[0]}%`, }; } // 查询匹配的条码,获取库存ID const matchedBarcodes = await ctx.model.StockBarcode.findAll({ ...barcodeQueryOptions, attributes: [ 'stock_id' ], group: [ 'stock_id' ], // 使用 GROUP BY 去重 raw: true, }); matchedStockIds = matchedBarcodes.map(b => b.stock_id); // 如果没有匹配的条码,直接返回空结果 if (matchedStockIds.length === 0) { return { code: 200, data: { list: [], pagination: { page: parseInt(page), pageSize: parseInt(pageSize), total: 0, totalPages: 0, hasPrevious: false, hasNext: false, }, }, message: '查询成功', }; } // 将库存ID条件合并到主查询条件中 queryOptions.where[Op.and].push({ id: { [Op.in]: matchedStockIds, }, }); } } // 处理排序 const validSortFields = [ 'id', 'item_code', 'item_name', 'quantity', 'locked_quantity', 'tag_price', 'retail_price', 'create_at', 'update_at', 'available_quantity', ]; const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at'; const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; if (actualSortField === 'available_quantity') { queryOptions.order.push([ Sequelize.literal('(quantity - locked_quantity)'), actualSortOrder ]); } else { queryOptions.order.push([ actualSortField, actualSortOrder ]); } // 计算分页偏移量 const offset = (page - 1) * pageSize; // 确定「外部商品绑定-已绑定」场景是否需要 INNER JOIN StockStore const isBoundTrue = hasBoundItemCondition && ( boundItemValue === true || boundItemValue === 1 || String(boundItemValue || '').trim().toLowerCase() === 'true' || String(boundItemValue || '').trim() === '1' || String(boundItemValue || '').trim().toLowerCase() === 'y' ); // 构建 include 数组 let storeStockInclude; if (storeId > 0) { // 按货主维度查询:确保 store_warehouse 关联同时匹配 store_id 和 warehouse_id,避免一对多导致行重复 storeStockInclude = { model: ctx.model.StoreWarehouse, as: 'store_stock', attributes: [ 'warehouse_remask' ], where: { store_id: storeId, warehouse_use_status: 1, [Op.and]: Sequelize.where( Sequelize.col('stock_warehouse.warehouse_id'), '=', Sequelize.col('store_stock.warehouse_id') ), }, required: false, include: [{ model: ctx.model.Store, as: 'warehouse', attributes: [ 'company_name' ], required: false, }], }; } else { storeStockInclude = ctx.model.StoreWarehouse.buildStoreStockInclude({ warehouseId, required: true, attributes: [ 'store_remask' ], }); } const includes = [ storeStockInclude, { ...prohibitedQueryOptions, model: ctx.model.ProhibitedType, as: 'prohibited', attributes: [ 'type_name' ], required: hasProhibitedCondition, }, ]; if (isBoundTrue) { includes.push({ model: ctx.model.StockStore, as: 'store_out_stock', attributes: [], required: true, }); } // 执行查询:获取总数和数据 const [ total, data ] = await Promise.all([ // 获取总数 ctx.model.StockWarehouse.count({ where: queryOptions.where, include: includes, distinct: true, }), // 获取分页数据 ctx.model.StockWarehouse.findAll({ ...queryOptions, include: includes, limit: parseInt(pageSize), offset: parseInt(offset), distinct: true, // 确保去重 raw: true, }), ]); // 计算分页信息 const totalPages = Math.ceil(total / pageSize); const hasPrevious = page > 1; const hasNext = page < totalPages; // 批量查询条码和图片信息(直接查 DB,不走 getStockDetails 缓存) const stockIds = data.map(item => item.id); const stockDetailsMap = new Map(); if (stockIds.length > 0) { // 并行查询条码和图片表(无缓存),避免影响其他接口对 getStockDetails 缓存的使用 const [ barcodeRows, imageRows ] = await Promise.all([ app.model.StockBarcode.findAll({ where: { stock_id: { [ Op.in ]: stockIds } }, attributes: [ 'id', 'barcode', 'stock_id' ], raw: true, }), app.model.FileReference.findAll({ where: { business_type: 'stock', business_id: { [ Op.in ]: stockIds.map(String) }, }, include: [{ model: app.model.File, as: 'file', attributes: [ 'file_url' ], required: false, }], raw: true, }), ]); // 按 stock_id 分组条码 const barcodeMap = new Map(); for (const row of barcodeRows) { const sid = row.stock_id; const bc = (row.barcode && String(row.barcode).trim()) || ''; if (!bc) continue; if (!barcodeMap.has(sid)) { barcodeMap.set(sid, []); } barcodeMap.get(sid).push(bc); } // 按 stock_id 分组图片 const imageMap = new Map(); for (const row of imageRows) { const sid = Number(row.business_id); const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || ''; if (!url) continue; if (!imageMap.has(sid)) { imageMap.set(sid, []); } imageMap.get(sid).push(url); } for (const item of data) { const sid = item.id; stockDetailsMap.set(sid, { barcodes: barcodeMap.get(sid) || [], images: imageMap.get(sid) || [], }); } } // 处理数据,添加一些计算字段 const processedData = data.map(item => { const availableQuantity = Math.max(0, item.quantity - item.locked_quantity); const lockRate = item.quantity > 0 ? (item.locked_quantity / item.quantity * 100).toFixed( 2) : 0; // 从直接的 DB 查询结果获取该商品的条码和图片 const stockDetail = stockDetailsMap.get(item.id); const itemBarcodes = stockDetail ? stockDetail.barcodes : []; const itemImages = stockDetail ? stockDetail.images : []; // 货主维度:仓库备注兜底仓库主体名 let warehouseRemask = ''; if (storeId > 0) { warehouseRemask = (item['store_stock.warehouse_remask'] || '') || (item['store_stock.warehouse.company_name'] || ''); delete item['store_stock.warehouse_remask']; delete item['store_stock.warehouse']; delete item['store_stock.warehouse.company_name']; } return { ...item, ...(storeId > 0 ? { warehouse_remask: warehouseRemask } : {}), barcodes: itemBarcodes, images: itemImages, available_quantity: availableQuantity, lock_rate: parseFloat(lockRate), lock_rate_display: `${lockRate}%`, create_at_display: item.create_at ? this.formatDate(item.create_at) : '', update_at_display: item.update_at ? this.formatDate(item.update_at) : '', // 标记是否通过条码查询匹配 is_barcode_matched: hasBarcodeCondition && matchedStockIds.includes(item.id), }; }); return { code: 200, data: { list: processedData, pagination: { page: parseInt(page), pageSize: parseInt(pageSize), total, totalPages, hasPrevious, hasNext, }, queryInfo: { conditions: normalizedWhere, sortField: actualSortField, sortOrder: actualSortOrder, hasBarcodeSearch: hasBarcodeCondition, }, }, message: '查询成功', }; } catch (error) { ctx.logger.error('[StockService.getWarehouseStock] 查询失败:', error); return { code: 500, data: { list: [], pagination: { page: parseInt(pageParams.page || 1), pageSize: parseInt(pageParams.pageSize || 20), total: 0, totalPages: 0, hasPrevious: false, hasNext: false, }, }, message: `查询失败: ${error.message}`, }; } } /** * 导出仓库商品列表。 * 说明:复用 getWarehouseStock 的筛选与排序语义,分页拉取全量数据后生成 Excel 并上传。 * @param {Object} where 筛选条件 * @param {Object} sortParams 排序参数 * @param {string} [sortParams.sortField] 排序字段 * @param {string} [sortParams.sortOrder] 排序方向(ASC|DESC) * @return {Promise} 导出上传结果(含 url/fileKey 等) */ async exportWarehouseStock(where = {}, sortParams = {}) { const { ctx } = this; const warehouseId = ctx.user && ctx.user.store_id ? ctx.user.store_id : 'common'; const pageSize = 500; let page = 1; let hasNext = true; const rows = []; while (hasNext) { const pageResult = await this.getWarehouseStock(where, { page, pageSize, }, sortParams); if (!pageResult || pageResult.code !== 200) { throw new Error(pageResult && pageResult.message ? pageResult.message : '导出仓库商品失败'); } const list = pageResult.data && Array.isArray(pageResult.data.list) ? pageResult.data.list : []; // 收集可能的 storeIds,用于回退查询 store_remask(优先取 item.store_id,其次 item['store_warehouse.store_id']) const storeIds = []; for (const item of list) { const sid = item.store_id || item['store_warehouse.store_id']; if (sid && !storeIds.includes(Number(sid))) { storeIds.push(Number(sid)); } } // 查询 StoreWarehouse 获取 store_remask(如果可用) const storeMap = new Map(); try { if (storeIds.length > 0 && ctx.model && ctx.model.StoreWarehouse) { const { Op } = ctx.app.Sequelize; const storeRows = await ctx.model.StoreWarehouse.findAll({ attributes: [ 'store_id', 'store_remask' ], where: { store_id: { [Op.in]: storeIds }, warehouse_id: warehouseId, }, raw: true, }); for (const r of storeRows || []) { storeMap.set(Number(r.store_id), r.store_remask); } } } catch (e) { // 查询失败不影响导出,记录日志并继续 ctx && ctx.logger && ctx.logger.warn && ctx.logger.warn('[exportWarehouseStock] 查询 StoreWarehouse 失败', e && e.message); } for (const item of list) { const storeId = Number(item.store_id || item['store_warehouse.store_id'] || 0); const store_remask = item.store_remask || item['store_warehouse.store_remask'] || storeMap.get(storeId) || ''; rows.push({ id: item.id, item_code: item.item_code, goods_code: item.goods_code || '', item_name: item.item_name, brand_name: item.brand_name || '', sku_property: item.sku_property || '', stock_unit: item.stock_unit || '', tag_price: item.tag_price || '', retail_price: item.retail_price || '', gross_weight: item.gross_weight || '', need_recheck: String(item.need_recheck || 'Y') === 'Y' ? '需要' : '不需要', store_remask, barcodes: Array.isArray(item.barcodes) ? item.barcodes.join(',') : '', quantity: item.quantity, locked_quantity: item.locked_quantity, available_quantity: item.available_quantity, lock_rate_display: item.lock_rate_display, create_at_display: item.create_at_display, update_at_display: item.update_at_display, }); } hasNext = Boolean(pageResult.data && pageResult.data.pagination && pageResult.data.pagination.hasNext); page += 1; } const now = new Date(); const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}${String(now.getMilliseconds()).padStart(3, '0')}`; return await ctx.service.systems.excel.generateAndUpload({ filename: `仓库商品导出_${dateToken}.xlsx`, dir: `exports/stock/warehouse/${warehouseId}`, category: 'document', sheets: [{ name: '仓库商品', columns: [ { header: 'SKU', key: 'id' }, { header: '商品编码', key: 'item_code' }, { header: '货物编码', key: 'goods_code' }, { header: '商品名称', key: 'item_name' }, { header: '品牌', key: 'brand_name' }, { header: '规格', key: 'sku_property' }, { header: '库存单位', key: 'stock_unit' }, { header: '标价', key: 'tag_price' }, { header: '零售价', key: 'retail_price' }, { header: '毛重', key: 'gross_weight' }, { header: '是否需要复核', key: 'need_recheck' }, { header: '货主', key: 'store_remask' }, { header: '条码', key: 'barcodes' }, { header: '库存', key: 'quantity' }, { header: '锁定库存', key: 'locked_quantity' }, { header: '可用库存', key: 'available_quantity' }, { header: '锁定率', key: 'lock_rate_display' }, { header: '创建时间', key: 'create_at_display' }, { header: '更新时间', key: 'update_at_display' }, ], rows, }], }); } /** * 导出外仓商品列表。 * 说明:复用 getWarehouseStock 的外部货主维度筛选语义,分页拉取全量数据后生成 Excel 并上传。 * @param {Object} where 筛选条件 * @param {Object} sortParams 排序参数 * @param {string} [sortParams.sortField] 排序字段 * @param {string} [sortParams.sortOrder] 排序方向(ASC|DESC) * @param {number} [externalWarehouseId=0] 外部仓库ID(0 表示按货主维度查) * @param {number} [externalStoreId=0] 外部货主ID * @return {Promise} 导出上传结果(含 url/fileKey 等) */ async exportExternalWarehouseStock(where = {}, sortParams = {}, externalWarehouseId = 0, externalStoreId = 0) { const { ctx } = this; const warehouseId = externalWarehouseId > 0 ? externalWarehouseId : (ctx.user && ctx.user.store_id ? ctx.user.store_id : 'common'); const pageSize = 500; let page = 1; let hasNext = true; const rows = []; while (hasNext) { const pageResult = await this.getWarehouseStock(where, { page, pageSize, }, sortParams, externalWarehouseId, externalStoreId); if (!pageResult || pageResult.code !== 200) { throw new Error(pageResult && pageResult.message ? pageResult.message : '导出外仓商品失败'); } const list = pageResult.data && Array.isArray(pageResult.data.list) ? pageResult.data.list : []; // 收集可能的 storeIds,用于回退查询 store_remask(优先取 item.store_id,其次 item['store_warehouse.store_id']) const storeIds = []; for (const item of list) { const sid = item.store_id || item['store_warehouse.store_id']; if (sid && !storeIds.includes(Number(sid))) { storeIds.push(Number(sid)); } } // 查询 StoreWarehouse 获取 store_remask(如果可用) const storeMap = new Map(); try { if (storeIds.length > 0 && ctx.model && ctx.model.StoreWarehouse) { const { Op } = ctx.app.Sequelize; const storeWhere = { store_id: { [Op.in]: storeIds } }; if (externalWarehouseId > 0) { storeWhere.warehouse_id = externalWarehouseId; } const storeRows = await ctx.model.StoreWarehouse.findAll({ attributes: [ 'store_id', 'store_remask' ], where: storeWhere, raw: true, }); for (const r of storeRows || []) { storeMap.set(Number(r.store_id), r.store_remask); } } } catch (e) { ctx && ctx.logger && ctx.logger.warn && ctx.logger.warn('[exportExternalWarehouseStock] 查询 StoreWarehouse 失败', e && e.message); } for (const item of list) { const storeId = Number(item.store_id || item['store_warehouse.store_id'] || 0); const storeRemask = item.store_remask || item['store_warehouse.store_remask'] || storeMap.get(storeId) || ''; rows.push({ id: item.id, item_code: item.item_code, goods_code: item.goods_code || '', item_name: item.item_name, brand_name: item.brand_name || '', sku_property: item.sku_property || '', stock_unit: item.stock_unit || '', tag_price: item.tag_price || '', retail_price: item.retail_price || '', gross_weight: item.gross_weight || '', need_recheck: String(item.need_recheck || 'Y') === 'Y' ? '需要' : '不需要', store_remask: storeRemask, barcodes: Array.isArray(item.barcodes) ? item.barcodes.join(',') : '', quantity: item.quantity, locked_quantity: item.locked_quantity, available_quantity: item.available_quantity, lock_rate_display: item.lock_rate_display, create_at_display: item.create_at_display, update_at_display: item.update_at_display, }); } hasNext = Boolean(pageResult.data && pageResult.data.pagination && pageResult.data.pagination.hasNext); page += 1; } const now = new Date(); const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}${String(now.getMilliseconds()).padStart(3, '0')}`; return await ctx.service.systems.excel.generateAndUpload({ filename: `外仓商品导出_${dateToken}.xlsx`, dir: `exports/stock/warehouse/${warehouseId}`, category: 'document', sheets: [{ name: '外仓商品', columns: [ { header: 'SKU', key: 'id' }, { header: '商品编码', key: 'item_code' }, { header: '货物编码', key: 'goods_code' }, { header: '商品名称', key: 'item_name' }, { header: '品牌', key: 'brand_name' }, { header: '规格', key: 'sku_property' }, { header: '库存单位', key: 'stock_unit' }, { header: '标价', key: 'tag_price' }, { header: '零售价', key: 'retail_price' }, { header: '毛重', key: 'gross_weight' }, { header: '是否需要复核', key: 'need_recheck' }, { header: '货主', key: 'store_remask' }, { header: '条码', key: 'barcodes' }, { header: '库存', key: 'quantity' }, { header: '锁定库存', key: 'locked_quantity' }, { header: '可用库存', key: 'available_quantity' }, { header: '锁定率', key: 'lock_rate_display' }, { header: '创建时间', key: 'create_at_display' }, { header: '更新时间', key: 'update_at_display' }, ], rows, }], }); } /** * 构建Sequelize查询条件 * @param {string} fieldKey - 字段键名 * @param {Object} condition - 条件对象 * @param {Object} app - Egg应用实例 * @return {Object|null} Sequelize条件对象 */ buildSequelizeCondition(fieldKey, condition, app) { const parsed = buildSequelizeConditionUtil(fieldKey, condition, app); if (!parsed.ok) { return null; } return parsed.condition; } /** * 处理条件值 * @param {any} value - 原始值 * @param {string} type - 字段类型 * @return {any} 处理后的值 */ processConditionValue(value, type) { return processConditionValueUtil(value, type); } normalizeDate(value) { return normalizeDateUtil(value); } /** * 格式化日期显示 * @param {string} dateString - 日期字符串 * @return {string} 格式化后的日期 */ formatDate(dateString) { if (!dateString) return ''; const date = new Date(dateString); if (isNaN(date.getTime())) return dateString; return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', }); } /** * 判断值是否为空 * @param {any} value - 要判断的值 * @return {boolean} 是否为空 */ isEmptyValue(value) { return isEmptyValueUtil(value); } async getProhibitedType() { const { ctx, app, } = this; const { Op, } = app.Sequelize; // 从用户信息获取仓库ID const warehouseId = ctx.user.store_id; // 查询系统预设分类和当前仓库专有分类 const types = await ctx.model.ProhibitedType.findAll({ where: { [Op.or]: [{ warehouse_id: null, }, // 系统预设 { warehouse_id: warehouseId, }, // 当前仓库专有 ], }, order: [ [ 'warehouse_id', 'ASC' ], // 系统预设在前(warehouse_id为null) [ 'sort_order', 'ASC' ], // 按排序字段 [ 'created_at', 'ASC' ], // 按创建时间 ], attributes: [ 'id', 'type_name', 'warehouse_id', 'is_system_preset', 'sort_order', ], }); // 转换为前端需要的格式 {value: id, label: type_name} const result = types.map(item => ({ value: item.id, label: item.type_name, warehouse_id: item.warehouse_id, is_system_preset: item.is_system_preset, sort_order: item.sort_order, })); return result; } async getBarcodes(data) { const { ctx, } = this; const { id, } = data; const warehouseId = ctx.user.store_id; const barcodes = await ctx.model.StockBarcode.findAll({ where: { stock_id: id, }, attributes: [ 'barcode', ], include: [{ model: ctx.model.StockWarehouse, as: 'stock', attributes: [ 'id' ], where: { warehouse_id: warehouseId, }, required: true, }], raw: true, }); return barcodes; } async handleBatchChange() { const { ctx, app } = this; const { Op } = app.Sequelize; const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'managementFlags', 'stock_unit', 'need_recheck' ]; const { ids, method, value } = ctx.request.body; try { // 1. 参数验证 if (!ids || !Array.isArray(ids) || ids.length === 0) { return { message: '请选择要修改的商品', code: 405 }; } if (!method || !canChangeFlide.includes(method)) { return { message: `不支持修改的字段: ${method}`, code: 405 }; } if (value === undefined || value === null) { return { message: '修改值不能为空', code: 405 }; } // 2. 获取仓库ID const warehouseId = ctx.user.store_id; if (!warehouseId) { return { message: '缺少仓库信息', code: 405 }; } // 3. 验证要修改的记录是否存在且属于当前仓库 const existingRefs = await ctx.model.StockWarehouse.findAll({ where: { id: { [Op.in]: ids }, warehouse_id: warehouseId, deleted_at: null, is_valid: 'Y', }, attributes: [ 'id' ], }); if (existingRefs.length !== ids.length) { const existingIds = existingRefs.map(item => item.id); const notExistIds = ids.filter(id => !existingIds.includes(id)); return { message: `部分商品不存在或无权修改: ${notExistIds.join(',')}`, code: 405, }; } // 4. 根据字段类型处理值 let updateData = {}; if (method === 'prohibited_id') { // 违禁品类型应该是数字 const updateValue = parseInt(value, 10); if (isNaN(updateValue)) { return { message: '违禁品类型必须是数字', code: 405 }; } updateData = { prohibited_id: updateValue, update_at: new Date(), update_by: ctx.user.id || ctx.user.username, }; } else if (method === 'gross_weight') { // 毛重必须为正整数(单位 g) const updateValue = parseInt(value, 10); if (isNaN(updateValue) || updateValue < 0 || !Number.isInteger(Number(value))) { return { message: '毛重必须是有效的正整数(单位 g)', code: 405 }; } updateData = { gross_weight: updateValue, update_at: new Date(), update_by: ctx.user.id || ctx.user.username, }; } else if (method === 'need_recheck') { // 是否需要复核:Y=需要复核,N=不需要复核 const updateValue = String(value).trim().toUpperCase(); if (![ 'Y', 'N' ].includes(updateValue)) { return { message: '是否需要复核必须是 Y(需要复核)或 N(不需要复核)', code: 405 }; } updateData = { need_recheck: updateValue, update_at: new Date(), update_by: ctx.user.id || ctx.user.username, }; } else if (method === 'managementFlags') { // 管理标识是对象格式,需要更新三个独立字段 if (typeof value !== 'object') { return { message: '管理标识必须是对象格式', code: 405 }; } // 验证三个管理标识字段 const managementFields = [ 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt' ]; updateData = { update_at: new Date(), update_by: ctx.user.id || ctx.user.username, }; for (const field of managementFields) { if (value[field] === undefined) { return { message: `管理标识缺少 ${field} 字段`, code: 405 }; } if (![ 'Y', 'N' ].includes(value[field])) { return { message: `管理标识 ${field} 的值必须是 Y 或 N`, code: 405 }; } updateData[field] = value[field]; } } else { // 品牌名称和打包要求验证 if (typeof value !== 'string') { return { message: `${method} 必须是字符串`, code: 405 }; } if (value.length > 255) { return { message: `${method} 不能超过255个字符`, code: 405 }; } updateData = { [method]: value, update_at: new Date(), update_by: ctx.user.id || ctx.user.username, }; } // 5. 执行批量更新 const [ affectedRows ] = await ctx.model.StockWarehouse.update(updateData, { where: { id: { [Op.in]: ids }, warehouse_id: warehouseId, delete_at: null, }, }); // 5.1 清除商品详情缓存(bulk update 不触发实例级 afterUpdate hook) if (affectedRows > 0) { const detailCacheSvc = ctx.service && ctx.service.systems && ctx.service.systems.stockWarehouse; if (detailCacheSvc && typeof detailCacheSvc.invalidateStockDetailCache === 'function') { await Promise.allSettled( ids.map(stockId => detailCacheSvc.invalidateStockDetailCache(Number(stockId), warehouseId)) ); } } return { message: `成功修改 ${affectedRows} 条记录`, code: 200, data: { affectedRows, ids, }, }; } catch (error) { ctx.logger.error('批量修改失败:', error); console.error('批量修改错误:', error); return { message: error.message || '批量修改失败', code: 500, }; } } async saveWarehouseStockBarcode(data) { const { ctx, service, } = this; const { id, barcodes, } = data; const warehouseId = ctx.user.store_id; // 获取现有的file_id const existingRefs = await ctx.model.StockBarcode.findAll({ where: { stock_id: id, warehouse_id: warehouseId, }, }); const existingFileIds = existingRefs.map(item => item.barcode); const newFileIds = barcodes.map(item => item); // 需要删除的ID const toDeleteIds = existingFileIds.filter(barcode => !newFileIds.includes(barcode)); // 需要创建的记录 const toCreate = barcodes.filter(item => !existingFileIds.includes(item)); // 批量操作 const promises = []; if (toDeleteIds.length > 0) { promises.push( ctx.model.StockBarcode.destroy({ where: { stock_id: id, barcode: toDeleteIds, warehouse_id: warehouseId, }, }) ); } if (toCreate.length > 0) { const refData = toCreate.map(item => ({ stock_id: id, barcode: item, warehouse_id: warehouseId, created_at: new Date(), })); promises.push(ctx.model.StockBarcode.bulkCreate(refData)); } await Promise.all(promises); await service.systems.operationLog.createOperationLog({ businessType: 'stock', businessId: id, operationCode: 'UPDATE_BARCODE', operator: { id: ctx.user.id, name: ctx.user.employees_name, }, beforeChanges: null, extras: { warehouseId, }, }); return { success: true, }; } async getStoreStocks(data) { const { app, } = this; const { Sequelize, } = app; const { Op, } = Sequelize; const { ctx, } = this; const { stock_id = null, store_id = null, page = 1, pageSize = 20, item_code = '', item_name = '', } = data || {}; // 优先使用 systemMethods 层校验后传入的 warehouse_id const warehouseId = Number(data._warehouseId || 0) || ctx.user.store_id; let barcodes = []; let warehouseStock = null; let total = 0; if (stock_id) { barcodes = await ctx.model.StockStore.findAll({ where: { stock_id, }, attributes: [ 'item_code', 'item_name', 'app_key', 'create_from', 'id', ], include: [{ model: ctx.model.StockWarehouse, as: 'warehouse_stock', attributes: [ 'id', 'store_id' ], where: { warehouse_id: warehouseId, }, required: true, }], raw: true, }); warehouseStock = await ctx.model.StockWarehouse.findOne({ where: { id: stock_id, }, attributes: [ 'store_id', ], }); } else { const StockWarehouseWhere = { warehouse_id: warehouseId, deleted_at: null, is_valid: 'Y', }; const StockStoreWhere = {}; if (store_id) { StockWarehouseWhere.store_id = store_id; } if (item_code) { const processedValue = item_code.split(','); const likeConditions = processedValue.map(value => ({ item_code: { [Op.like]: `%${value}%`, }, })); StockStoreWhere[Op.or] = likeConditions; } if (item_name) { const processedValue = item_name.split(','); const likeConditions = processedValue.map(value => ({ item_name: { [Op.like]: `%${value}%`, }, })); StockStoreWhere[Op.or] = likeConditions; } const offset = (page - 1) * pageSize; [ total, barcodes ] = await Promise.all([ ctx.model.StockStore.count({ where: StockStoreWhere, attributes: [ 'item_code', 'item_name', 'app_key', 'create_from', 'id', 'stock_id', ], include: [{ model: ctx.model.StockWarehouse, as: 'warehouse_stock', attributes: [ 'id' ], where: StockWarehouseWhere, required: false, }], limit: parseInt(pageSize), offset: parseInt(offset), raw: true, }), ctx.model.StockStore.findAll({ where: StockStoreWhere, attributes: [ 'item_code', 'item_name', 'app_key', 'create_from', 'id', 'stock_id', ], include: [{ model: ctx.model.StockWarehouse, as: 'warehouse_stock', attributes: [ 'id' ], where: StockWarehouseWhere, required: false, }], limit: parseInt(pageSize), offset: parseInt(offset), raw: true, }), ]); } // 批量查询奇门应用名称 const appKeys = [ ...new Set(barcodes.map(item => item.app_key).filter(Boolean)) ]; const qimenAppMap = new Map(); if (appKeys.length > 0) { const qimenApps = await ctx.model.QimenApp.findAll({ where: { app_key: appKeys }, attributes: [ 'app_key', 'name' ], raw: true, }); for (const app of qimenApps) { qimenAppMap.set(app.app_key, app.name || ''); } } const results = barcodes.map(item => { return { app_key: item.app_key, create_from: item.create_from === 'qimen' ? '奇门' : 'API', id: item.id, app_name: qimenAppMap.get(item.app_key) || item.app_key, item_code: item.item_code, stock_id: item['warehouse_stock.id'], hasBind: !!item.stock_id, item_name: item.item_name, }; }); const get_store_id = warehouseStock ? warehouseStock.store_id : barcodes[0]['warehouse_stock.store_id']; return { rows: results, store_id: get_store_id, total, }; } async bindItem(data) { const { ctx, app, } = this; const { id, warehouse_stock, } = data; const warehouseId = ctx.user.store_id; try { const storeStock = await ctx.model.StockStore.findOne({ where: { warehouse_id: warehouseId, delete_at: null, id, }, attributes: [ 'stock_id', 'store_id', ], }); if (!storeStock) { throw new Error('外部商品不存在'); } const warehouseStock = await ctx.model.StockWarehouse.findOne({ where: { warehouse_id: warehouseId, deleted_at: null, is_valid: 'Y', id: warehouse_stock, }, attributes: [ 'store_id', ], }); if (!warehouseStock) { throw new Error('仓库商品不存在'); } if (warehouseStock.store_id !== storeStock.store_id) { throw new Error('仓库商品和外部商品不是同一个货主,刷新再试'); } await app.model.StockStore.update({ stock_id: warehouse_stock, }, { where: { id, }, }); return 1; } catch (e) { throw e; } } async unbindItem(data) { const { ctx, app, } = this; const { id, } = data; const warehouseId = ctx.user.store_id; try { const storeStock = await ctx.model.StockStore.findOne({ where: { warehouse_id: warehouseId, delete_at: null, id, }, attributes: [ 'stock_id', 'store_id', ], }); if (!storeStock) { throw new Error('外部商品不存在'); } await app.model.StockStore.update({ stock_id: null, }, { where: { id, }, }); return 1; } catch (e) { throw e; } } /** * 查询库存商品详情。 * * @param {Object} data 请求参数。 * @param {number|string} data.id 库存商品 ID。 * @return {Promise} 库存商品详情。 */ async getInfo(data) { const { ctx, } = this; const { id, } = data; const warehouseId = ctx.user.store_id; const stock = await ctx.model.StockWarehouse.findOne({ where: { warehouse_id: warehouseId, deleted_at: null, is_valid: 'Y', id, }, attributes: [ 'gross_weight', 'height', 'id', 'is_batch_mgmt', 'is_shelf_life_mgmt', 'is_sn_mgmt', 'need_recheck', 'goods_code', 'item_code', 'item_name', 'length', 'net_weight', 'packing_requirements', 'prohibited_id', 'retail_price', 'sku_property', 'stock_unit', 'tag_price', 'brand_name', 'volume', 'width', 'enable_box_spec', 'quantity_per_box', 'box_gross_weight', 'box_net_weight', 'box_length', 'box_width', 'box_height', 'box_volume', 'inbound_min_days', 'outbound_min_days', 'remaining_threshold_days', 'shelf_life_days', 'store_id', ], raw: true, }); stock.enable_box_spec = !!stock.enable_box_spec; return stock; } /** * 更新仓库商品资料,并在启用保质期管理时校验保质期相关字段。 * * @param {Object} data 请求体,包含商品主键及待更新字段。 * @return {Promise} 返回更新后的商品详情。 */ async saveWarehouseStock(data) { const { ctx, service } = this; const warehouseId = ctx.user.store_id; const { item_code, item_name, goods_code, sku_property, stock_unit, packing_requirements, length, width, height, volume, volume_cm3, volumeCm3, gross_weight, net_weight, tag_price, retail_price, is_sn_mgmt, is_shelf_life_mgmt, is_batch_mgmt, prohibited_id, brand_name, managementFlags, enable_box_spec, box_unit, quantity_per_box, box_gross_weight, box_net_weight, box_length, box_width, box_height, box_volume, box_remark, id, box_volume_m3, boxVolumeM3, shelf_life_days, inbound_min_days, outbound_min_days, remaining_threshold_days, need_recheck, } = data; const normalizedVolume = volume ?? volume_cm3 ?? volumeCm3; const normalizedBoxVolume = box_volume ?? box_volume_m3 ?? boxVolumeM3; const prohibited_id_tmp = !prohibited_id ? null : parseInt(prohibited_id); // 1. 参数验证 this.validateSaveParams(data); if (is_shelf_life_mgmt === 'Y') { const shelfLifeFields = [ [ 'shelf_life_days', shelf_life_days ], [ 'inbound_min_days', inbound_min_days ], [ 'outbound_min_days', outbound_min_days ], [ 'remaining_threshold_days', remaining_threshold_days ], ]; const invalidShelfLifeFields = shelfLifeFields.filter(item => Number(item[1]) <= 0); if (invalidShelfLifeFields.length > 0) { throw new Error('启用保质期管理时,shelf_life_days、inbound_min_days、outbound_min_days、remaining_threshold_days 都必须存在且大于 0'); } } let transaction; try { // 2. 开启事务 transaction = await ctx.model.transaction(); // 3. 查询商品是否存在 const stock_info = await ctx.model.StockWarehouse.findOne({ where: { id, deleted_at: null, is_valid: 'Y', warehouse_id: ctx.user.store_id, }, transaction, }); if (!stock_info) { throw new Error('商品不存在'); } const hasInputItemCode = Object.prototype.hasOwnProperty.call(data, 'item_code'); if (hasInputItemCode) { const itemCodeUniqueResult = await this.checkItemCodeUnique( id, item_code, stock_info.store_id, stock_info.warehouse_id ); if (!itemCodeUniqueResult || !itemCodeUniqueResult.isUnique) { throw new Error('商品编码已存在,请检查后重试'); } } // 4. 准备更新数据 const updateData = { item_code, item_name, goods_code, sku_property, stock_unit, packing_requirements, length, width, height, volume: normalizedVolume, gross_weight, net_weight, tag_price, retail_price, enable_box_spec: enable_box_spec ? 1 : 0, is_sn_mgmt: is_sn_mgmt || false, is_shelf_life_mgmt: is_shelf_life_mgmt || false, is_batch_mgmt: is_batch_mgmt || false, need_recheck, prohibited_id: prohibited_id_tmp, brand_name, ...(managementFlags && { management_flags: managementFlags }), box_unit, quantity_per_box, box_gross_weight, box_net_weight, box_length, box_width, box_height, box_volume: normalizedBoxVolume, box_remark, shelf_life_days, inbound_min_days, outbound_min_days, remaining_threshold_days, updated_at: new Date(), }; // 5. 清除空值 Object.keys(updateData).forEach(key => { if (key !== 'prohibited_id' && (updateData[key] === undefined || updateData[key] === null)) { delete updateData[key]; } }); // 6. 执行更新 await ctx.model.StockWarehouse.update(updateData, { where: { id, warehouse_id: ctx.user.store_id, deleted_at: null, }, transaction, }); await service.systems.operationLog.createOperationLog({ businessType: 'stock', businessId: id, operationCode: 'UPDATE', operator: { id: ctx.user.id, name: ctx.user.employees_name, }, beforeChanges: stock_info, extras: { warehouseId, }, }); // 7. 提交事务 await transaction.commit(); // 7.1 清除商品详情缓存(getStockDetails 缓存,bulk update 不触发实例级 afterUpdate hook) try { await service.systems.stockWarehouse.invalidateStockDetailCache(id, warehouseId); } catch (cacheError) { ctx.logger.warn(`saveWarehouseStock 清除商品详情缓存失败: ${cacheError.message}`); } // 8. 返回更新后的数据 return await this.getInfo({ id }); } catch (error) { // 9. 回滚事务 if (transaction) { await transaction.rollback(); } ctx.logger.error('saveWarehouseStock error:', error); // 根据错误类型返回更友好的错误信息 if (error.name === 'SequelizeValidationError') { throw new Error(`数据验证失败: ${error.errors.map(e => e.message).join(', ')}`); } throw error; } } async createWarehouseStock(data) { const { ctx, service } = this; const warehouseId = ctx.user.store_id; const { item_code, store_id, item_name, goods_code, sku_property, stock_unit, packing_requirements, length, width, height, volume, gross_weight, net_weight, tag_price, retail_price, is_sn_mgmt, is_shelf_life_mgmt, is_batch_mgmt, prohibited_id, brand_name, managementFlags, enable_box_spec, box_unit, quantity_per_box, box_gross_weight, box_net_weight, box_length, box_width, box_height, box_volume, box_remark, need_recheck, } = data; // 1. 参数验证 this.validateSaveParams(data, false); let checkItemCodeUnique = {}; try { checkItemCodeUnique = await this.checkItemCodeUnique(null, item_code, store_id, warehouseId); } catch (e) { throw (e); } if (checkItemCodeUnique && !checkItemCodeUnique.isUnique) { throw (new Error('创建失败,商品编码已被使用')); } const insertData = { item_code, item_name, goods_code, sku_property, stock_unit, packing_requirements, length, width, height, volume, gross_weight, net_weight, tag_price, retail_price, warehouse_id: warehouseId, enable_box_spec: enable_box_spec ? 1 : 0, is_sn_mgmt: is_sn_mgmt || false, is_shelf_life_mgmt: is_shelf_life_mgmt || false, is_batch_mgmt: is_batch_mgmt || false, need_recheck: need_recheck || 'Y', prohibited_id, brand_name, ...(managementFlags && { management_flags: managementFlags }), box_unit, quantity_per_box, box_gross_weight, box_net_weight, item_type: 'ZC', level: 'C', store_id, box_length, create_at: new Date(), box_width, box_height, box_volume, box_remark, updated_at: new Date(), }; const transaction = await ctx.model.transaction(); try { // 2. 开启事务 const createdRecord = await ctx.model.StockWarehouse.create(insertData, transaction); await service.systems.operationLog.createOperationLog({ businessType: 'stock', businessId: createdRecord.id, operationCode: 'CREATE', operator: { id: ctx.user.id, name: ctx.user.employees_name, }, extras: { warehouseId, }, }); await transaction.commit(); return await this.getInfo({ id: createdRecord.id }); } catch (e) { if (transaction) { await transaction.rollback(); } throw (new Error(`创建失败,${e.message}`)); } } validateSaveParams(data, isEdit = true) { const requiredFields = [ 'item_code', 'item_name', 'stock_unit', 'gross_weight' ]; if (!data.id && isEdit) { throw new Error('缺失必要参数: id'); } for (const field of requiredFields) { if (!data[field]) { throw new Error(`缺失必要参数: ${field}`); } } if (data.enable_box_spec && (!data.quantity_per_box || data.quantity_per_box <= 0)) { throw new Error('启用箱规时,每箱数量必须大于0'); } // 是否需要复核:仅允许 Y(需要)/ N(不需要) if (data.need_recheck !== undefined && data.need_recheck !== null && ![ 'Y', 'N' ].includes(String(data.need_recheck).trim())) { throw new Error('need_recheck 必须是 Y(需要复核)或 N(不需要复核)'); } // 数值类型验证 const numericFields = [ 'length', 'width', 'height', 'volume', 'gross_weight', 'net_weight' ]; for (const field of numericFields) { if (data[field] && isNaN(Number(data[field]))) { throw new Error(`${field} 必须是有效的数字`); } } } async stockLog() { return undefined; } /** * 校验商品编码在指定仓库与货主维度下是否唯一。 * @param {number|null} item_id 商品ID(编辑场景用于排除自身) * @param {string} item_code 商品编码 * @param {number} owner_id 货主ID * @param {number} warehouse_id 仓库ID * @return {Promise<{unique:boolean,isUnique:boolean,message?:string}>} 唯一性校验结果 */ async checkItemCodeUnique(item_id, item_code, owner_id, warehouse_id) { const { ctx, app } = this; const { Op } = this.app.Sequelize || app.Sequelize; try { const normalizedItemCode = String(item_code || '').trim(); const where = { item_code: normalizedItemCode, store_id: owner_id, warehouse_id, deleted_at: null, is_valid: 'Y', }; if (item_id) { where.id = { [Op.ne]: item_id, }; } const space = await ctx.model.StockWarehouse.findOne({ where, attributes: [ 'id' ], }); if (!space) { return { unique: true, isUnique: true }; } return { unique: false, isUnique: false, message: '商品编码已存在' }; } catch (error) { ctx.logger.error('检查商品编码唯一性失败:', error); return { unique: false, isUnique: false, message: '商品编码检测失败' }; } } /** * 批量删除仓库商品资料(软删除)。 * 删除前会校验:1) 是否存在库存;2) 是否被待处理订单(step 1/2/3 且未取消)引用。 * 任一校验不通过的商品会被移入不可删除列表并返回原因。 * @param {Object} data 请求参数 * @param {Array} data.ids 待删除的商品ID列表 * @return {Promise} 删除结果,含 deletedProducts、undeletableProducts、failedIds 及 summary */ async handleBatchDelete(data) { const { ctx, app } = this; const { Op } = this.app.Sequelize || app.Sequelize; const { ids } = data; if (!ids || !Array.isArray(ids) || ids.length === 0) { return { code: 405, message: '请选择要删除的商品' }; } try { const where = { [Op.and]: [ { id: { [Op.in]: ids } }, { deleted_at: null }, { is_valid: 'Y' }, ], }; // 1. 查询商品资料及其库存情况 const products = await ctx.model.StockWarehouse.findAll({ where, include: [ { model: ctx.model.Storage, as: 'storage', attributes: [ 'id', 'quantity' ], required: false, // 使用left join,因为可能没有库存记录 }, ], attributes: [ 'id', 'item_name', 'quantity', 'return_quantity', 'warehouse_id' ], }); if (products.length === 0) { return { code: 200, message: '未找到对应的商品资料或已删除', data: [] }; } // 2. 分析哪些商品可以删除(没有库存或库存为0) const deletableProducts = []; const undeletableProducts = []; products.forEach(product => { const productInfo = { id: product.id, name: product.item_name, hasStock: false, stockQuantity: 0, }; // 检查库存情况 if (product.storage) { if (Array.isArray(product.storage)) { // 如果有多个库存记录 const totalStock = product.storage.reduce((sum, storage) => { return sum + (storage.quantity || 0); }, 0); productInfo.stockQuantity = totalStock; productInfo.hasStock = totalStock > 0; } else { // 如果只有一个库存记录 productInfo.stockQuantity = product.storage.quantity || 0; productInfo.hasStock = productInfo.stockQuantity > 0; } } if (product.quantity > 0 || product.return_quantity > 0) { productInfo.hasStock = true; } if (productInfo.hasStock) { undeletableProducts.push(productInfo); } else { deletableProducts.push(productInfo); } }); if (deletableProducts.length === 0) { return { code: 405, message: '所有选中的商品都有库存,无法删除', data: { undeletableProducts, message: `以下商品存在库存无法删除:${undeletableProducts.map(p => p.name).join('、')}`, }, }; } // 2.5 检查待处理订单引用:step in [1,2,3] 且 status != 'cancel' 的订单引用了该商品时不允许删除 const deletableIdSet = new Set(deletableProducts.map(p => p.id)); // 构建 stockId → warehouseId 映射 const stockWarehouseMap = new Map(); for (const product of products) { if (deletableIdSet.has(product.id)) { stockWarehouseMap.set(product.id, Number(product.warehouse_id) || 0); } } // 按仓库分组 const warehouseStockMap = new Map(); for (const [ stockId, warehouseId ] of stockWarehouseMap) { if (!warehouseStockMap.has(warehouseId)) { warehouseStockMap.set(warehouseId, []); } warehouseStockMap.get(warehouseId).push(stockId); } const orderReferencedMap = new Map(); // stockId → pendingOrderCount const orderItemsFactory = ctx.model && ctx.model.OrderItemsFactory; const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; if (orderItemsFactory && typeof orderItemsFactory.getCurrentModel === 'function' && orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') { for (const [ warehouseId, stockIds ] of warehouseStockMap) { if (!warehouseId || stockIds.length === 0) continue; try { const orderItemsModel = await orderItemsFactory.getCurrentModel(warehouseId); const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); // 查询该仓库下引用了待删除商品的订单明细 const orderItems = await orderItemsModel.findAll({ where: { stock_id: { [Op.in]: stockIds } }, attributes: [ 'stock_id', 'order_id' ], raw: true, }); if (orderItems.length === 0) continue; const orderIds = [ ...new Set(orderItems.map(oi => oi.order_id)) ]; // 查询这些订单中处于待处理状态(step 1/2/3 且未取消)的 const pendingOrders = await orderDeliveryModel.findAll({ where: { id: { [Op.in]: orderIds }, step: { [Op.in]: [ 1, 2, 3 ] }, status: { [Op.ne]: 'cancel' }, }, attributes: [ 'id' ], raw: true, }); if (pendingOrders.length === 0) continue; const pendingOrderIds = new Set(pendingOrders.map(po => po.id)); // 统计每个 stock_id 被待处理订单引用的数量 for (const oi of orderItems) { if (pendingOrderIds.has(oi.order_id)) { const sid = oi.stock_id; orderReferencedMap.set(sid, (orderReferencedMap.get(sid) || 0) + 1); } } } catch (err) { ctx.logger.warn(`[handleBatchDelete] 检查待处理订单引用失败(仓库${warehouseId}): ${err.message}`); // 检查失败时不阻塞删除,仅记录日志 } } } // 将存在待处理订单引用的商品从可删除列表移至不可删除列表 if (orderReferencedMap.size > 0) { const newDeletable = []; for (const product of deletableProducts) { const pendingCount = orderReferencedMap.get(product.id) || 0; if (pendingCount > 0) { undeletableProducts.push({ ...product, reason: `该商品已被 ${pendingCount} 个待处理订单引用,无法删除。请先处理相关订单后再删除。`, }); } else { newDeletable.push(product); } } // 用过滤后的列表替换原可删除列表 deletableProducts.length = 0; deletableProducts.push(...newDeletable); } if (deletableProducts.length === 0) { const blockedReasons = undeletableProducts .filter(p => p.reason) .map(p => `${p.name}: ${p.reason}`) .join(';'); return { code: 405, message: '所有选中的商品均无法删除', data: { undeletableProducts, message: blockedReasons || '所选商品均无法删除', }, }; } // 3. 执行删除(软删除) const deletableIds = deletableProducts.map(p => p.id); const result = await ctx.model.transaction(async t => { // 软删除商品资料 const [ affectedCount ] = await ctx.model.StockWarehouse.update( { deleted_at: new Date(), updated_at: new Date(), // 如果需要记录删除人 // deleted_by: ctx.user.user_id }, { where: { id: { [Op.in]: deletableIds }, }, transaction: t, // 如果要检查行锁 // lock: t.LOCK.UPDATE } ); return { deletedCount: affectedCount, deletedIds: deletableIds, }; }); // 4. 如果需要同时清理关联数据 if (deletableIds.length > 0) { // 例如:清理商品分类关联、商品标签关联等 // await this.cleanRelatedData(deletableIds); } return { code: 200, message: `删除成功,共删除 ${result.deletedCount} 个商品资料`, data: { deletedCount: result.deletedCount, deletedProducts: deletableProducts, undeletableProducts, failedIds: ids.filter(id => !deletableIds.includes(id)), summary: { totalSelected: ids.length, deleted: deletableProducts.length, failed: undeletableProducts.length, }, }, }; } catch (error) { console.error('批量删除商品资料失败:', error); ctx.logger.error('批量删除商品资料失败:', error); // 根据错误类型返回不同的提示 let errorMessage = '删除失败,请稍后重试'; if (error.name === 'SequelizeForeignKeyConstraintError') { errorMessage = '删除失败,存在关联数据,请先处理相关数据'; } else if (error.name === 'SequelizeDatabaseError') { errorMessage = '数据库操作失败'; } return { code: 500, message: errorMessage, error: process.env.NODE_ENV === 'development' ? { message: error.message, stack: error.stack, } : undefined, }; } } async deleteUnit(data) { const { id } = data; const { ctx } = this; const unitExit = await ctx.model.StockUnit.findOne({ where: { id, warehouse_id: ctx.user.store_id, }, }); if (!unitExit) { throw new Error('库存单位不存在'); } ctx.model.StockUnit.destroy({ where: { id, warehouse_id: ctx.user.store_id, }, }); return { message: '删除成功', code: 200 }; } async deleteProhibited(data) { const { id } = data; const { ctx } = this; const unitExit = await ctx.model.ProhibitedType.findOne({ where: { id, warehouse_id: ctx.user.store_id, }, }); if (!unitExit) { throw new Error('违禁品类型不存在'); } ctx.model.ProhibitedType.destroy({ where: { id, warehouse_id: ctx.user.store_id, }, }); return { message: '删除成功', code: 200 }; } /** * 快捷搜索仓库商品并补全库存管理标记。 * 支持多词 OR 搜索:使用中英文逗号 `,` `,`、换行 `\n`、回车 `\r` 分隔多个关键词, * 任意一个词在 item_code、item_name、goods_code 或条形码中命中即返回该商品。 * @param {Object} data 请求体 * @param {string} [data.keyword] 搜索关键字,支持多词以逗号/换行分隔进行 OR 匹配 * @param {number|string} [data.store_id] 货主ID * @param {boolean} [data.with_stock=false] 是否返回关联库存数据 * @param {boolean} [data.is_batch=false] with_stock=true 时是否按批次返回 * @return {Promise} 搜索结果,data 为商品数组 */ async search(data) { const { keyword, store_id = null, with_stock = false, is_batch = false } = data; const { ctx, app } = this; const { Op } = app.Sequelize; const warehouseId = ctx.user.store_id; try { const whereCondition = { warehouse_id: warehouseId, deleted_at: null, is_valid: 'Y', }; // 如果有传入store_id,则添加store_id条件 if (store_id) { whereCondition.store_id = store_id; } // 准备关联查询的条件 const includeConditions = []; // 如果有搜索关键词,按分隔符拆分为多个词进行 OR 匹配 if (keyword && keyword.trim()) { // 按分隔符拆词:中英文逗号、换行、回车、管道符、空格 const keywords = keyword .split(/[,\n\r,\|\s]+/) .map(k => k.trim()) .filter(k => k.length > 0); if (keywords.length === 1) { // 单个词,保持原逻辑 const searchKeyword = `%${keywords[0]}%`; const stockWarehouseConditions = { [Op.or]: [ { item_code: { [Op.like]: searchKeyword } }, { item_name: { [Op.like]: searchKeyword } }, { goods_code: { [Op.like]: searchKeyword } }, ], }; includeConditions.push({ model: app.model.StockBarcode, as: 'barcodes', attributes: [ 'barcode' ], required: false, where: { barcode: { [Op.like]: searchKeyword }, }, }); whereCondition[Op.or] = [ stockWarehouseConditions, { '$barcodes.barcode$': { [Op.like]: searchKeyword }, }, ]; } else if (keywords.length > 1) { // 多个词,OR 包装:每个词在 item_code/item_name/goods_code/barcode 任一命中即可 const stockWarehouseConditions = { [Op.or]: keywords.flatMap(kw => { const like = `%${kw}%`; return [ { item_code: { [Op.like]: like } }, { item_name: { [Op.like]: like } }, { goods_code: { [Op.like]: like } }, ]; }), }; includeConditions.push({ model: app.model.StockBarcode, as: 'barcodes', attributes: [ 'barcode' ], required: false, where: { [Op.or]: keywords.map(kw => ({ barcode: { [Op.like]: `%${kw}%` }, })), }, }); whereCondition[Op.or] = [ stockWarehouseConditions, ...keywords.map(kw => ({ '$barcodes.barcode$': { [Op.like]: `%${kw}%` }, })), ]; } // keywords.length === 0 时不加搜索条件,走 else 分支 } if (!includeConditions.some(c => c.as === 'barcodes')) { // 如果没有关键词或关键词全为空,也包含 barcodes 关联(但不需要 where 条件) includeConditions.push({ model: app.model.StockBarcode, as: 'barcodes', attributes: [ 'barcode' ], required: false, }); } includeConditions.push(app.model.StoreWarehouse.buildStoreStockInclude({ warehouseId, required: false, attributes: [ 'store_id', 'store_remask' ], })); // 执行查询 const results = await app.model.StockWarehouse.findAll({ where: whereCondition, attributes: [ 'id', 'item_code', 'goods_code', 'item_name', 'sku_property', 'stock_unit', 'quantity', 'locked_quantity', 'brand_name', 'item_type', 'inbound_min_days', 'outbound_min_days', 'shelf_life_days', 'remaining_threshold_days', 'is_batch_mgmt', 'is_shelf_life_mgmt', 'gross_weight', ], order: [[ 'create_at', 'DESC' ]], limit: 50, include: includeConditions, subQuery: false, // 避免子查询,提高性能 }); // 格式化返回数据 const formattedResults = results.map(item => { const result = item.toJSON(); // 提取所有条形码 result.barcodes = result.barcodes?.map(b => b.barcode) || []; const batchMgmtValue = result.is_batch_mgmt; result.is_batch_mgmt_enabled = typeof batchMgmtValue === 'boolean' ? batchMgmtValue : [ 'Y', '1', 'TRUE', 'T', 'YES' ].includes(String(batchMgmtValue).trim().toUpperCase()); delete result.is_batch_mgmt; const shelfLifeMgmtValue = result.is_shelf_life_mgmt; result.is_shelf_life_mgmt = typeof shelfLifeMgmtValue === 'boolean' ? shelfLifeMgmtValue : [ 'Y', '1', 'TRUE', 'T', 'YES' ].includes(String(shelfLifeMgmtValue).trim().toUpperCase()); return result; }); // 批查商品图片(与 stock.warehouse.list 一致:wms_file_reference + wms_file) if (formattedResults.length > 0) { const stockIds = formattedResults.map(r => r.id); const imageRows = await app.model.FileReference.findAll({ where: { business_type: 'stock', business_id: { [Op.in]: stockIds.map(String) }, }, include: [{ model: app.model.File, as: 'file', attributes: [ 'file_url' ], required: false, }], order: [[ 'display_order', 'ASC' ]], raw: true, }); const imageMap = new Map(); for (const row of imageRows) { const sid = Number(row.business_id); const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || ''; if (!url) continue; if (!imageMap.has(sid)) imageMap.set(sid, []); imageMap.get(sid).push(url); } for (const item of formattedResults) { item.images = imageMap.get(item.id) || []; } } // with_stock=true 时关联查询库存数据 if (with_stock && formattedResults.length > 0) { const stockIds = formattedResults.map(r => r.id); const storageWhere = { stock_id: { [Op.in]: stockIds }, warehouse_id: warehouseId, is_enabled: 1, delete_at: null, }; const storageRows = await app.model.Storage.findAll({ where: storageWhere, attributes: [ 'id', 'stock_id', 'space_id', 'batch_no', 'inventory_type', 'quantity', 'locked_quantity', 'intercept_locked_quantity', 'available_quantity', 'production_date', 'expiry_date', 'inbound_time', 'inbound_order_no', 'supplier_batch_no', 'created_at', ], include: [{ model: app.model.LocationSpace, as: 'space', attributes: [ 'id', 'space_code', 'custom_name' ], required: false, }], order: [[ 'created_at', 'DESC' ]], }); // 按 stock_id 分组 const storageMap = new Map(); for (const row of storageRows) { const plain = row.get({ plain: true }); const key = plain.stock_id; if (!storageMap.has(key)) { storageMap.set(key, []); } storageMap.get(key).push(plain); } for (const item of formattedResults) { const storageList = storageMap.get(item.id) || []; if (is_batch) { // is_batch=true:逐条批次明细返回,不分组 item.storage = storageList; } else { // is_batch=false(默认):按库位分组汇总 const mergedMap = new Map(); for (const s of storageList) { const spaceKey = s.space_id; if (mergedMap.has(spaceKey)) { const existing = mergedMap.get(spaceKey); existing.quantity += Number(s.quantity) || 0; existing.locked_quantity += Number(s.locked_quantity) || 0; existing.intercept_locked_quantity += Number(s.intercept_locked_quantity) || 0; existing.available_quantity = existing.quantity - existing.locked_quantity - existing.intercept_locked_quantity; } else { const quantity = Number(s.quantity) || 0; const lockedQuantity = Number(s.locked_quantity) || 0; const interceptLockedQuantity = Number(s.intercept_locked_quantity) || 0; mergedMap.set(spaceKey, { space_id: s.space_id, inventory_type: s.inventory_type, quantity, locked_quantity: lockedQuantity, intercept_locked_quantity: interceptLockedQuantity, available_quantity: quantity - lockedQuantity - interceptLockedQuantity, space: s.space, }); } } item.storage = Array.from(mergedMap.values()); } } } return { code: 200, data: formattedResults, total: formattedResults.length, }; } catch (error) { ctx.logger.error('搜索仓库商品失败:', error); return { code: 0, message: '搜索失败,请稍后重试', }; } } /** * 查询商品的库存明细(storage 表)。 * @param {Object} data 请求体 * @param {number} data.stock_id 商品库存ID(stock_warehouse.id) * @param {Object} [data.pagination] 分页参数 * @return {Promise} 库存明细分页结果 */ async getStockDetail(data) { const { ctx, app } = this; const warehouseId = ctx.user.store_id; const { stock_id, pagination = {}, group_by_batch = false } = data; if (!stock_id) { return { code: 0, message: '参数 stock_id 不能为空' }; } try { // 校验商品归属当前仓库 const stockItem = await app.model.StockWarehouse.findOne({ where: { id: stock_id, warehouse_id: warehouseId, deleted_at: null, is_valid: 'Y', }, attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit', 'quantity', 'locked_quantity' ], raw: true, }); if (!stockItem) { return { code: 0, message: '商品不存在或不属于当前仓库' }; } const { page = 1, pageSize = 20 } = pagination; const offset = (page - 1) * pageSize; const storageWhere = { stock_id, warehouse_id: warehouseId, is_enabled: 1, delete_at: null, }; if (group_by_batch) { // 区分批次:按原逻辑返回每一条库存明细 const { count, rows } = await app.model.Storage.findAndCountAll({ where: storageWhere, attributes: [ 'id', 'space_id', 'batch_no', 'inventory_type', 'quantity', 'locked_quantity', 'available_quantity', 'production_date', 'expiry_date', 'inbound_time', 'inbound_order_no', 'supplier_batch_no', 'created_at', ], include: [{ model: app.model.LocationSpace, as: 'space', attributes: [ 'id', 'space_code', 'custom_name' ], required: false, }], order: [[ 'created_at', 'DESC' ]], offset, limit: pageSize, }); return { code: 200, data: { stockItem, storageList: rows, pagination: { page, pageSize, total: count, }, }, }; } // 不区分批次:按 space_id 合并库存数据 const allRows = await app.model.Storage.findAll({ where: storageWhere, attributes: [ 'id', 'space_id', 'inventory_type', 'quantity', 'locked_quantity', 'intercept_locked_quantity', 'created_at', ], include: [{ model: app.model.LocationSpace, as: 'space', attributes: [ 'id', 'space_code', 'custom_name', ], required: false, }], order: [ [ 'created_at', 'DESC', ], ], }); // 按 space_id 合并 const mergedMap = new Map(); for (const row of allRows) { const plain = row.get({ plain: true }); const key = plain.space_id; if (mergedMap.has(key)) { const existing = mergedMap.get(key); existing.quantity += Number(plain.quantity) || 0; existing.locked_quantity += Number(plain.locked_quantity) || 0; existing.intercept_locked_quantity += Number(plain.intercept_locked_quantity) || 0; existing.available_quantity = existing.quantity - existing.locked_quantity - existing.intercept_locked_quantity; } else { const quantity = Number(plain.quantity) || 0; const lockedQuantity = Number(plain.locked_quantity) || 0; const interceptLockedQuantity = Number(plain.intercept_locked_quantity) || 0; mergedMap.set(key, { id: plain.id, space_id: plain.space_id, batch_no: null, inventory_type: plain.inventory_type, quantity, locked_quantity: lockedQuantity, intercept_locked_quantity: interceptLockedQuantity, available_quantity: quantity - lockedQuantity - interceptLockedQuantity, production_date: null, expiry_date: null, inbound_time: null, inbound_order_no: null, supplier_batch_no: null, created_at: plain.created_at, space: plain.space, }); } } const mergedList = Array.from(mergedMap.values()); const total = mergedList.length; const storageList = mergedList.slice(offset, offset + pageSize); return { code: 200, data: { stockItem, storageList, pagination: { page, pageSize, total, }, }, }; } catch (error) { ctx.logger.error(`查询商品库存明细失败, stock_id: ${stock_id}`, error); return { code: 0, message: '查询库存明细失败,请稍后重试' }; } } } module.exports = stockStoreService;