'use strict'; const Service = require('egg').Service; class IndexService extends Service { async findByStockAndBatch(stockId, batchNo, inventoryType = 'ZP') { const { ctx } = this; return await ctx.model.Storage.findOne({ where: { stock_id: stockId, batch_no: batchNo, inventory_type: inventoryType, is_enabled: 1, delete_at: null, }, include: [ { model: ctx.model.LocationSpace, as: 'space', attributes: [ 'space_code', 'custom_name' ], }, { model: ctx.model.Store, as: 'warehouse', attributes: [[ 'company_name', 'store_name' ]], }, ], }); } async findBySpace(spaceId) { const { ctx } = this; return await ctx.model.Storage.findAll({ where: { space_id: spaceId, is_enabled: 1, delete_at: null, }, include: [ { model: ctx.model.StockWarehouse, as: 'stock', attributes: [ 'product_code', 'product_name' ], }, ], order: [[ 'inbound_time', 'ASC' ]], }); } async findAvailableByWarehouse(warehouseId, stockId = null) { const { ctx, app } = this; const where = { warehouse_id: warehouseId, is_enabled: 1, delete_at: null, available_quantity: { [app.Sequelize.Op.gt]: 0 }, }; if (stockId) { where.stock_id = stockId; } return await ctx.model.Storage.findAll({ where, include: [ { model: ctx.model.LocationSpace, as: 'space', attributes: [ 'space_code', 'custom_name' ], }, { model: ctx.model.StockWarehouse, as: 'stock', attributes: [ 'product_code', 'product_name' ], }, ], order: [ [ 'expiry_date', 'ASC' ], [ 'inbound_time', 'ASC' ], ], }); } async findExpiringSoon(days = 30) { const { ctx, app } = this; const expiryDate = new Date(); expiryDate.setDate(expiryDate.getDate() + days); return await ctx.model.Storage.findAll({ where: { expiry_date: { [app.Sequelize.Op.between]: [ new Date(), expiryDate ], }, is_enabled: 1, delete_at: null, quantity: { [app.Sequelize.Op.gt]: 0 }, }, include: [ { model: ctx.model.Store, as: 'warehouse', attributes: [[ 'company_name', 'store_name' ]], }, { model: ctx.model.StockWarehouse, as: 'stock', attributes: [ 'product_code', 'product_name' ], }, ], order: [[ 'expiry_date', 'ASC' ]], }); } /** * 更新库存数量、锁定数量与拦截锁定数量,并按统一口径重算可用数量。 * * 可用数量统一口径: * `available_quantity = quantity - locked_quantity - intercept_locked_quantity`。 * * @param {number} id 库存记录 ID。 * @param {number} quantityChange 库存数量变化量(正数为增加,负数为减少)。 * @param {number} [lockedChange=0] 锁定数量变化量。 * @param {Object} [options={}] 执行上下文与事务参数。 * @param {Object} [options.transaction] Sequelize 事务对象。 * @param {number} [options.interceptLockedChange=0] 拦截锁定数量变化量(正数为拦截锁定,负数为释放; * 允许结果为负值:差异对账场景下 storage 比 stock 少的差异以负拦截锁定入账,可用数量等量回补)。 * @return {Promise} 更新后的库存记录。 */ async updateQuantity(id, quantityChange, lockedChange = 0, options = {}) { const { ctx } = this; const interceptLockedChange = Number((options && options.interceptLockedChange) || 0); const applyUpdate = async transaction => { const storage = await ctx.model.Storage.findByPk(id, { transaction, lock: transaction ? transaction.LOCK.UPDATE : undefined, }); if (!storage) { throw new Error('库存记录不存在'); } const newQuantity = storage.quantity + quantityChange; const newLocked = storage.locked_quantity + lockedChange; const newInterceptLocked = Number(storage.intercept_locked_quantity || 0) + interceptLockedChange; if (newQuantity < 0) { throw new Error('库存数量不能为负数'); } if (newLocked < 0) { throw new Error('锁定数量无效'); } // 拦截锁定允许为负(差异对账:storage 比 stock 少的差异以负值入账,可用数量回补); // 上界仍禁止超过库存数量;锁定数量仍禁止为负 if (newInterceptLocked > newQuantity) { throw new Error('拦截锁定数量无效'); } // 总和上界:锁定与拦截锁定之和不能超过库存数量; // 等价于锁定后可用不为负(available ≥ 0)。 // 负拦截锁(差异对账补回)时锁定量可超过 quantity,但总和上限口径不变, // 保证补回的可用数量可真实被锁定使用。 if (newLocked + newInterceptLocked > newQuantity) { throw new Error('锁定数量与拦截锁定数量之和不能超过库存数量'); } const updateData = { quantity: newQuantity, locked_quantity: newLocked, intercept_locked_quantity: newInterceptLocked, available_quantity: newQuantity - newLocked - newInterceptLocked, updated_at: new Date(), }; await storage.update(updateData, { transaction, }); return storage; }; if (options.transaction) { return await applyUpdate(options.transaction); } return await ctx.model.transaction(async transaction => { return await applyUpdate(transaction); }); } /** * 锁定指定库存记录的可用数量。 * * @param {number} id 库存记录 ID。 * @param {number} quantity 需要锁定的数量。 * @param {Object} [options={}] 执行上下文与事务参数。 * @param {Object} [options.transaction] Sequelize 事务对象。 * @param {string} [options.source] 调用来源标识。 * @param {string} [options.caller] 调用方标识。 * @param {string} [options.from] 来源模块标识。 * @param {string} [options.action] 操作标识。 * @return {Promise} 更新后的库存记录。 */ async lockQuantity(id, quantity, options = {}) { return await this.updateQuantity(id, 0, quantity, options); } /** * 解除指定库存记录的锁定数量(锁定数量减少,可用数量等量增加)。 * * @param {number} id 库存记录 ID。 * @param {number} quantity 需要解除锁定的数量。 * @param {Object} [options={}] 执行上下文与事务参数。 * @param {Object} [options.transaction] Sequelize 事务对象。 * @return {Promise} 更新后的库存记录。 */ async unlockQuantity(id, quantity, options = {}) { return await this.updateQuantity(id, 0, -quantity, options); } /** * 从可用数量中分配锁定指定数量(锁定数量增加,可用数量等量减少)。 * * @param {number} id 库存记录 ID。 * @param {number} quantity 需要分配锁定的数量。 * @param {Object} [options={}] 执行上下文与事务参数。 * @param {Object} [options.transaction] Sequelize 事务对象。 * @return {Promise} 更新后的库存记录。 */ async allocateQuantity(id, quantity, options = {}) { const { ctx } = this; const storage = await ctx.model.Storage.findByPk(id, { transaction: options.transaction, }); if (!storage) { throw new Error('库存记录不存在'); } if (storage.available_quantity < quantity) { throw new Error('可用数量不足'); } return await this.updateQuantity(id, 0, quantity, options); } /** * 将作业锁定数量迁移为拦截锁定数量(拦截确认专用,pending 拣货行)。 * * 库存总量与可用数量均不变,仅将锁定类型从 `locked_quantity` 迁移到 `intercept_locked_quantity`: * `locked_quantity -q`、`intercept_locked_quantity +q`、`quantity` 与 `available_quantity` 不变。 * * @param {number} id 库存记录 ID。 * @param {number} quantity 需要迁移为拦截锁定的数量。 * @param {Object} [options={}] 执行上下文与事务参数。 * @param {Object} [options.transaction] Sequelize 事务对象。 * @return {Promise} 更新后的库存记录。 */ async interceptLockQuantity(id, quantity, options = {}) { return await this.updateQuantity(id, 0, -quantity, { ...options, interceptLockedChange: quantity, }); } /** * 实物返还并拦截锁定(拦截确认专用,fin 已拣货行)。 * * 库存总量与拦截锁定数量等量增加,可用数量不变: * `quantity +q`、`intercept_locked_quantity +q`、`locked_quantity` 与 `available_quantity` 不变。 * * @param {number} id 库存记录 ID。 * @param {number} quantity 需要返还并拦截锁定的数量。 * @param {Object} [options={}] 执行上下文与事务参数。 * @param {Object} [options.transaction] Sequelize 事务对象。 * @return {Promise} 更新后的库存记录。 */ async interceptReceiveQuantity(id, quantity, options = {}) { return await this.updateQuantity(id, quantity, 0, { ...options, interceptLockedChange: quantity, }); } /** * 释放拦截锁定数量,使其回落到可用数量(解除拦截/退货登记专用)。 * * 库存总量与作业锁定数量不变,拦截锁定数量减少、可用数量等量增加: * `intercept_locked_quantity -q`、`available_quantity +q`、`quantity` 与 `locked_quantity` 不变。 * * @param {number} id 库存记录 ID。 * @param {number} quantity 需要释放的拦截锁定数量。 * @param {Object} [options={}] 执行上下文与事务参数。 * @param {Object} [options.transaction] Sequelize 事务对象。 * @return {Promise} 更新后的库存记录。 */ async interceptUnlockQuantity(id, quantity, options = {}) { return await this.updateQuantity(id, 0, 0, { ...options, interceptLockedChange: -quantity, }); } /** * 入库回填平账:负库存入库时,按入库量冲销该商品的 GAP 补建行挂账。 * * 背景:差异对账(INTERCEPT_GAP)对无行/截断差异会补建 GAP- 前缀库存行承载拦截锁定; * 当负库存商品真实入库回填时,将补建行挂账按入库量冲销(quantity/intercept 同减), * 账归真实入库数据,避免补建挂账与真实入库叠加造成虚账。 * * 冲销口径:每行冲销量 m = min(入库量, 行 quantity, 行 intercept_locked_quantity); * available 按统一口径重算(quantity 与 intercept 同减,available 不变); * 写 INTERCEPT_GAP(UNLOCK 方向)冲销流水,保留快照可追溯。 * * 冲销上限:差异基准为 max(SW.quantity, 0),只有 SW 在非负区间的增量才会收窄差异; * SW 在负数区间回填(如 -10→0)不改变基准,不冲销。因此调用方应传入 * options.maxOffset = max(0, 入库后SW) - max(0, 入库前SW),缺省时按入库量冲销(兼容)。 * * @param {number} stockId 商品SKU ID(wms_stock_warehouse.id)。 * @param {number} qty 本次入库数量。 * @param {Object} [options={}] 执行上下文与事务参数。 * @param {Object} [options.transaction] Sequelize 事务对象。 * @param {number} [options.maxOffset] 冲销上限(推荐传 SW 非负区间增量,缺省=入库量)。 * @param {string} [options.orderNo] 入库单号/来源标识(流水追溯)。 * @param {number} [options.orderId] 关联订单/入库单 ID。 * @param {string} [options.operatorId] 操作人 ID。 * @param {string} [options.operatorName] 操作人名。 * @return {Promise} 实际冲销量。 */ async offsetGapOnInbound(stockId, qty, options = {}) { const { ctx, app } = this; const inboundQty = Number(qty) || 0; if (!stockId || inboundQty <= 0) return 0; const maxOffset = options.maxOffset !== undefined && options.maxOffset !== null ? Math.max(0, Number(options.maxOffset) || 0) : inboundQty; if (maxOffset <= 0) return 0; const apply = async transaction => { const gapRows = await ctx.model.Storage.findAll({ where: { stock_id: stockId, is_enabled: 1, delete_at: null, [app.Sequelize.Op.or]: [ { batch_no: { [app.Sequelize.Op.like]: 'GAP-%' } }, { inbound_order_no: { [app.Sequelize.Op.like]: 'GAP-%' } }, ], }, order: [[ 'id', 'ASC' ]], lock: transaction ? transaction.LOCK.UPDATE : undefined, transaction, }); let remain = inboundQty; let offsetTotal = 0; let offsetBudget = maxOffset; for (const row of gapRows) { if (remain <= 0 || offsetBudget <= 0) break; const gapQty = Number(row.quantity) || 0; const gapIntercept = Number(row.intercept_locked_quantity) || 0; const offsetQty = Math.min(remain, offsetBudget, Math.min(gapQty, gapIntercept)); if (offsetQty <= 0) continue; const newQty = gapQty - offsetQty; const newIntercept = gapIntercept - offsetQty; const lockedQty = Number(row.locked_quantity) || 0; await row.update({ quantity: newQty, intercept_locked_quantity: newIntercept, available_quantity: newQty - lockedQty - newIntercept, updated_at: new Date(), }, { transaction }); // 冲销流水(UNLOCK 方向,快照守恒:after = before - offsetQty) await ctx.model.StorageTransaction.create({ transaction_type: 'UNLOCK', warehouse_id: row.warehouse_id, store_id: row.store_id, stock_id: stockId, storage_id: row.id, space_id: row.space_id, quantity: offsetQty, before_quantity: gapQty, after_quantity: newQty, before_locked_quantity: lockedQty, after_locked_quantity: lockedQty, before_intercept_locked_quantity: gapIntercept, after_intercept_locked_quantity: newIntercept, batch_no: row.batch_no, inventory_type: row.inventory_type, order_type: 'INTERCEPT_GAP', order_no: String(options.orderNo || 'INBOUND_GAP_OFFSET').slice(0, 255), order_id: Number(options.orderId || 0) || null, operator_id: options.operatorId || null, operator_name: options.operatorName || '', remark: '入库回填平账(冲销差异挂账)', created_at: new Date(), }, { transaction }); remain -= offsetQty; offsetBudget -= offsetQty; offsetTotal += offsetQty; } return offsetTotal; }; if (options.transaction) { return await apply(options.transaction); } return await ctx.model.transaction(async transaction => { return await apply(transaction); }); } async getStockSummary(warehouseId) { const { ctx, app } = this; return await ctx.model.Storage.findAll({ attributes: [ 'stock_id', 'inventory_type', [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ], [ app.Sequelize.fn('SUM', app.Sequelize.col('locked_quantity')), 'total_locked' ], [ app.Sequelize.fn('SUM', app.Sequelize.col('available_quantity')), 'total_available' ], ], where: { warehouse_id: warehouseId, is_enabled: 1, delete_at: null, }, group: [ 'stock_id', 'inventory_type' ], raw: true, }); } async getSpaceUsage(spaceId) { const { ctx, app } = this; const result = await ctx.model.Storage.findAll({ attributes: [ 'inventory_type', [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'record_count' ], [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ], ], where: { space_id: spaceId, is_enabled: 1, delete_at: null, }, group: [ 'inventory_type' ], raw: true, }); const usage = { normal: 0, defective: 0, damaged: 0, frozen: 0, total: 0, }; result.forEach(item => { let type; switch (item.inventory_type) { case 'ZP': type = 'normal'; break; case 'CC': type = 'defective'; break; case 'JS': case 'XS': type = 'damaged'; break; case 'DJ': type = 'frozen'; break; default: return; } usage[type] = parseInt(item.total_quantity, 10) || 0; usage.total += usage[type]; }); return usage; } } module.exports = IndexService;