'use strict'; const assert = require('node:assert/strict'); const Sequelize = require('sequelize'); const InventoryService = require('../../../../app/service/systems/storage/inventory'); const OrderStorageAllocationService = require('../../../../app/service/systems/order_storage_allocation'); /** * 构造锁定冲突桩(模拟 stock_check.getStaticLockConflict)。 * * @param {boolean} locked 是否锁定。 * @return {Object} 桩服务。 */ function createStockCheckStub(locked) { const calls = []; return { calls, async getStaticLockConflict(params = {}) { calls.push(params); if (!locked) { return { locked: false, rows: [], message: '' }; } return { locked: true, rows: [{ stock_id: 301, item_code: 'LOCKED-ITEM', check_nos: [ 'PD20261028000001' ], check_ids: [ 1 ] }], message: '商品正在静态盘点中,禁止移库:LOCKED-ITEM(301) 盘点单 PD20261028000001', }; }, }; } /** * 创建移库(transferLocation)测试上下文。 * * @param {boolean} locked 静态盘点是否锁定。 * @return {Object} { service, captures, stockCheck }。 */ function createTransferLocationHarness(locked) { const captures = { rollbacks: 0, commits: 0, storageUpdates: 0, storageTransactions: 0 }; const stockCheck = createStockCheckStub(locked); const srcRecord = { id: 11, warehouse_id: 100000, store_id: 100001, space_id: 21, stock_id: 301, batch_no: 'B1', inventory_type: 'ZP', quantity: 10, locked_quantity: 0, intercept_locked_quantity: 0, available_quantity: 10, is_enabled: 1, delete_at: null, }; const ctx = { app: { Sequelize }, logger: { info() {}, warn() {}, error() {} }, user: { employees_id: 'E1', employees_name: '测试员' }, model: { async transaction() { return { LOCK: { UPDATE: 'UPDATE' }, async commit() { captures.commits += 1; }, async rollback() { captures.rollbacks += 1; }, }; }, Storage: { async findOne() { return srcRecord; }, async update() { captures.storageUpdates += 1; }, async count() { return 0; }, async findAll() { return [ srcRecord ]; }, async create() { return srcRecord; }, }, StockWarehouse: { async findOne() { return { id: 301, quantity: 10, locked_quantity: 0, warehouse_id: 100000, is_batch_mgmt: 'N' }; }, }, LocationSpace: { async findOne() { return { id: 22, warehouse_id: 100000, is_enabled: true, space_status: 'AVAILABLE', space_code: 'A-22' }; }, async update() { return null; }, }, StorageTransaction: { async create() { captures.storageTransactions += 1; return { id: 1 }; }, }, }, service: { systems: { stockCheck, operationLog: { async createOperationLog() { return null; } }, notice: { async send() { return null; } }, }, }, }; return { service: new InventoryService(ctx), captures, stockCheck }; } describe('静态盘点锁定拦截:分配储位 / 移库', () => { it('transferLocation:商品静态盘点中 → 400、事务回滚、不写库存', async () => { const { service, captures, stockCheck } = createTransferLocationHarness(true); const result = await service.transferLocation({ storage_id: 11, target_space_id: 22, quantity: 1 }); assert.equal(result.code, 400); assert.match(result.message, /静态盘点/); assert.match(result.message, /PD20261028000001/); assert.equal(captures.rollbacks, 1, '命中锁定应回滚事务'); assert.equal(captures.storageUpdates, 0, '不应更新库存'); assert.equal(captures.storageTransactions, 0, '不应写库存流水'); assert.equal(stockCheck.calls.length, 1, '应调用一次锁定校验'); assert.deepEqual(stockCheck.calls[0].stockIds, [ 301 ]); assert.equal(stockCheck.calls[0].actionLabel, '移库'); }); it('transferByProduct:商品静态盘点中 → 400、事务回滚、不写库存', async () => { const { service, captures } = createTransferLocationHarness(true); const result = await service.transferByProduct({ space_id: 21, stock_id: 301, target_space_id: 22, quantity: 2 }); assert.equal(result.code, 400); assert.match(result.message, /静态盘点/); assert.equal(captures.rollbacks, 1); assert.equal(captures.storageUpdates, 0); assert.equal(captures.storageTransactions, 0); }); it('未锁定时移库不拦截(保持原有可用量校验路径)', async () => { const { service, stockCheck } = createTransferLocationHarness(false); const result = await service.transferByProduct({ space_id: 21, stock_id: 301, target_space_id: 22, quantity: 99 }); assert.equal(result.code, 400); assert.match(result.message, /可用数量不足/, '未锁定时进入原有校验分支'); assert.equal(stockCheck.calls.length, 1); }); /** * 创建储位分配测试上下文(可含多个订单,模拟批量分配)。 * * @param {Object} options 配置。 * @param {boolean} options.locked 静态盘点是否锁定。 * @param {Array} options.orders 订单行。 * @param {Array} options.orderItems 订单明细行。 * @param {Array} options.storageRows 库存行(仅未锁定商品)。 * @return {Object} { service, captures, stockCheck }。 */ function createAllocateHarness(options = {}) { const captures = { commits: 0, rollbacks: 0, orderUpdates: [], lockCalls: [], pickingRows: [], storageQueries: 0, }; const stockCheck = createStockCheckStub(options.locked === true); const storageRows = (options.storageRows || []).map(row => ({ ...row })); const ctx = { user: { store_id: 100000, id: 1, employees_id: 'E1', employees_name: '测试员' }, logger: { debug() {}, info() {}, warn() {}, error() {} }, app: { Sequelize, config: {} }, model: { async transaction() { return { LOCK: { UPDATE: 'UPDATE' }, async commit() { captures.commits += 1; }, async rollback() { captures.rollbacks += 1; }, }; }, OrderDeliveryFactory: { async getCurrentModel() { return { async findAll() { return (options.orders || []).map(row => ({ ...row })); }, async update(values, opts = {}) { captures.orderUpdates.push({ values, where: opts.where }); return [ 1 ]; }, }; }, }, OrderItemsFactory: { async getCurrentModel() { return { async findAll() { return (options.orderItems || []).map(row => ({ ...row })); }, }; }, }, Picking: { async bulkCreate(rows) { captures.pickingRows.push(...rows.map(row => ({ ...row }))); return rows; }, async findAll() { return []; }, }, StockWarehouse: { async findAll() { return [ ...new Set((options.orderItems || []).map(row => Number(row.stock_id))) ].map(id => ({ id })); }, }, Storage: { async findAll() { captures.storageQueries += 1; return storageRows.map(row => ({ ...row })); }, async update() { return [ 1 ]; }, }, StorageTransaction: { async create(payload) { return { id: 1, ...payload }; }, }, }, service: { systems: { stockCheck, storage: { index: { async lockQuantity(storageId, quantity) { captures.lockCalls.push({ storageId, quantity }); const row = storageRows.find(item => Number(item.id) === Number(storageId)); if (row) { row.available_quantity = Number(row.available_quantity) - quantity; row.locked_quantity = Number(row.locked_quantity) + quantity; } return [ 1 ]; }, async unlockQuantity(storageId, quantity) { const row = storageRows.find(item => Number(item.id) === Number(storageId)); if (row) { row.available_quantity = Number(row.available_quantity) + quantity; row.locked_quantity = Number(row.locked_quantity) - quantity; } return [ 1 ]; }, }, }, stockStore: { async getStoreWarehousePolicyConfigByStockId() { return { policyConfig: { storage_separation: false, allow_storage_location: true } }; }, }, orderPendingException: { async reversePendingException() { return null; }, }, }, }, }; return { service: new OrderStorageAllocationService(ctx), captures, stockCheck }; } it('allocatePicking 批量分配:锁定商品订单标记失败(同库存不足流程),其余订单照常分配', async () => { const { service, captures, stockCheck } = createAllocateHarness({ locked: true, orders: [ { id: 1, warehouse_id: 100000, status: 'padding', storage_status: 'none', intercept_status: null, lock_status: null }, { id: 2, warehouse_id: 100000, status: 'padding', storage_status: 'none', intercept_status: null, lock_status: null }, ], orderItems: [ { id: 11, order_id: 1, stock_id: 301, plan_qty: 2, order_line_no: 1 }, { id: 12, order_id: 2, stock_id: 302, plan_qty: 3, order_line_no: 1 }, ], storageRows: [ // 仅未锁定商品 302 有可用库存(锁定商品 301 即便有库存也不应被分配) { id: 501, stock_id: 302, space_id: 601, store_id: 100001, batch_no: 'B302', inventory_type: 'ZP', quantity: 10, available_quantity: 10, locked_quantity: 0, intercept_locked_quantity: 0, production_date: null, inbound_time: null, }, { id: 502, stock_id: 301, space_id: 602, store_id: 100001, batch_no: 'B301', inventory_type: 'ZP', quantity: 10, available_quantity: 10, locked_quantity: 0, intercept_locked_quantity: 0, production_date: null, inbound_time: null, }, ], }); const result = await service.allocatePicking({ order_ids: [ 1, 2 ], allow_storage_location: true }); assert.equal(result.code, 200, '批量分配不因单个订单命中锁定而整体失败'); assert.deepEqual(result.data.shortage_order_ids, [ 1 ], '锁定商品所在订单计入失败列表'); assert.deepEqual(result.data.allocated_order_ids, [ 2 ], '其余订单正常分配'); assert.ok(result.data.shortage_messages.some(message => /静态盘点锁定/.test(message)), '失败原因应含静态盘点锁定'); assert.ok(result.data.shortage_messages.some(message => /PD20261028000001/.test(message)), '失败原因应含来源盘点单号'); const lockedOrderResult = result.data.orders.find(item => Number(item.order_id) === 1); assert.equal(lockedOrderResult.status, 'error', '锁定订单状态应为 error'); assert.match(lockedOrderResult.shortage_message, /静态盘点锁定/); // 订单状态写库:锁定订单 storage_status=error 且 order_flag 带原因 const lockedUpdate = captures.orderUpdates.find(item => Number(item.where.id) === 1); assert.equal(lockedUpdate.values.storage_status, 'error'); assert.match(String(lockedUpdate.values.order_flag), /静态盘点锁定/); const normalUpdate = captures.orderUpdates.find(item => Number(item.where.id) === 2); assert.equal(normalUpdate.values.storage_status, 'fin', '未锁定订单应正常完成分配'); // 库存锁定只发生在未锁定商品 302 上,锁定商品 301 一行都不加锁 assert.deepEqual(captures.lockCalls, [{ storageId: 501, quantity: 3 }]); assert.equal(captures.pickingRows.length, 1, '仅未锁定订单写拣货行'); assert.equal(Number(captures.pickingRows[0].order_id), 2); assert.deepEqual(stockCheck.calls[0].stockIds.slice().sort((left, right) => left - right), [ 301, 302 ]); assert.equal(stockCheck.calls[0].actionLabel, '分配储位'); }); it('allocatePicking 全部订单命中锁定:返回 200 且全部计入失败列表(不中断批量)', async () => { const { service, captures } = createAllocateHarness({ locked: true, orders: [ { id: 1, warehouse_id: 100000, status: 'padding', storage_status: 'none', intercept_status: null, lock_status: null }, ], orderItems: [{ id: 11, order_id: 1, stock_id: 301, plan_qty: 2, order_line_no: 1 }], storageRows: [], }); const result = await service.allocatePicking({ order_ids: [ 1 ], allow_storage_location: true }); assert.equal(result.code, 200, '全部命中锁定时仍按批量口径返回 200(与库存不足一致)'); assert.deepEqual(result.data.shortage_order_ids, [ 1 ]); assert.deepEqual(result.data.allocated_order_ids, []); assert.equal(result.data.picking_count, 0); assert.equal(captures.lockCalls.length, 0, '不应锁定任何库存'); assert.equal(captures.commits, 1, '事务正常提交(订单标记失败但流程完成)'); }); });