'use strict'; const assert = require('node:assert/strict'); const Sequelize = require('sequelize'); const { getAuthToken, invokeSystemMethod, } = require('../../support/system_method_client'); const EXTRA_HEADERS = { platform: 'web', project: 'all' }; const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; const TEST_STORE_ID = 1000000; const TEST_WAREHOUSE_ID = 100000; // ──── 数据库连接(用于锁冲突测试) ──── const dbConfig = require('../../../database/config'); const env = process.env.NODE_ENV || 'development'; const config = dbConfig[env] || dbConfig.development || Object.values(dbConfig)[0]; let sequelize; // ──── switchToWarehouseRole ──── async function switchToWarehouseRole(token) { let currentToken = token; const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); assert.equal(infoRes.status, 200); assert.equal(infoRes.body.flag, 'success'); const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id) && Number(item.store_id) === TEST_WAREHOUSE_ID ); const candidateRoleIds = [ ...new Set([ ...warehouseRoles.map(item => Number(item.id)), ...FALLBACK_ROLE_IDS, ].filter(Boolean)) ]; assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); for (const roleId of candidateRoleIds) { const changeRes = await invokeSystemMethod('user.changeRole', { roleId }, currentToken, EXTRA_HEADERS); if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) continue; currentToken = changeRes.body?.data?.token || currentToken; const listRes = await invokeSystemMethod('storage.receiving.getReceivingList', { pagination: { page: 1, pageSize: 1 }, where: {}, }, currentToken, EXTRA_HEADERS); if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) { return { token: currentToken, roleId }; } } throw new Error(`未找到 warehouse_id=${TEST_WAREHOUSE_ID} 的仓库角色`); } // ──── 获取系统商品(至少 minCount 个) ──── async function getSystemProducts(token, minCount = 2) { const res = await invokeSystemMethod('stock.warehouse.list', { pagination: { page: 1, pageSize: 20 }, where: {}, }, token, EXTRA_HEADERS); assert.equal(res.status, 200); assert.equal(res.body.flag, 'success'); let list = []; if (res.body?.data?.data?.list) list = res.body.data.data.list; else if (res.body?.data?.list) list = res.body.data.list; const products = list .filter(item => Number(item?.id || 0) > 0) .slice(0, minCount) .map(item => ({ id: Number(item.id), item_name: String(item.item_name || item.name || ''), item_code: String(item.item_code || ''), })); assert.ok(products.length >= minCount, `需至少 ${minCount} 个系统商品,实际只有 ${products.length} 个`); return products; } // ──── 创建收货单 ──── async function createReceiving(token) { const res = await invokeSystemMethod('storage.receiving.create', { delivery_method: 'truck', license_plate: `ITEST-QP-${Date.now().toString().slice(-6)}`, loading_method: 'without_pallet', remark: `quickPutaway集成测试 ${new Date().toISOString()}`, total_boxes: 1, total_pallets: 0, }, token, EXTRA_HEADERS); assert.equal(res.status, 200, `创建收货单HTTP失败: ${JSON.stringify(res.body)}`); assert.equal(res.body.flag, 'success', `创建收货单失败: ${res.body.message}`); const receivingId = Number(res.body.id || res.body?.data?.id || 0); assert.ok(receivingId > 0, '创建收货单无返回ID'); return receivingId; } // ──── 绑定货主 ──── async function bindStore(token, receivingId) { const res = await invokeSystemMethod('storage.receiving.bindStore', { id: receivingId, store_id: TEST_STORE_ID, }, token, EXTRA_HEADERS); assert.equal(res.status, 200); assert.equal(res.body.flag, 'success', `绑定货主失败: ${res.body.message}`); } // ──── 添加明细 + 修改明细 + 绑定商品 ──── async function addAndFillDetail(token, receivingId, product, qty) { // addDetail const addRes = await invokeSystemMethod('storage.receiving.addDetail', { receiving_id: receivingId, }, token, EXTRA_HEADERS); assert.equal(addRes.status, 200, `添加明细HTTP失败: ${JSON.stringify(addRes.body)}`); assert.equal(addRes.body.flag, 'success', `添加明细失败: ${addRes.body.message}`); const detailId = Number(addRes.body?.data?.selectId || 0); assert.ok(detailId > 0, `添加明细无返回selectId: ${JSON.stringify(addRes.body)}`); // detailChange const changeRes = await invokeSystemMethod('storage.receiving.detailChange', { id: detailId, receiving_id: receivingId, product_name: product.item_name || '测试商品', barcode: product.item_code || `TEST-BC-${Date.now()}`, actual_quantity: qty, box_quantity: 1, pallet_quantity: 0, }, token, EXTRA_HEADERS); assert.equal(changeRes.status, 200, `修改明细失败: ${JSON.stringify(changeRes.body)}`); assert.equal(changeRes.body.flag, 'success', `修改明细失败: ${changeRes.body.message}`); return detailId; } async function bindDetailProduct(token, detailId, productId) { const res = await invokeSystemMethod('storage.receiving.bindDetailProduct', { detail_id: detailId, system_product_id: productId, }, token, EXTRA_HEADERS); assert.equal(res.status, 200, `绑定商品失败: ${JSON.stringify(res.body)}`); assert.equal(res.body.flag, 'success', `绑定商品失败: ${res.body.message}`); } // ──── 完成收货 ──── async function completeReceiving(token, receivingId) { const res = await invokeSystemMethod('storage.receiving.completeReceiving', { id: receivingId, }, token, EXTRA_HEADERS); assert.equal(res.status, 200, `完成收货HTTP失败: ${JSON.stringify(res.body)}`); assert.equal(res.body.flag, 'success', `完成收货失败: ${res.body.message}`); if (sequelize) { await sequelize.query( 'UPDATE wms_receiving SET status = :status, storage_status = :storageStatus, updated_at = NOW() WHERE id = :receivingId', { replacements: { status: 'completed', storageStatus: 'partial', receivingId, }, } ); } } // ──── 快捷入库 ──── async function quickPutaway(token, receivingId) { return invokeSystemMethod('storage.inventory.quickPutaway', { receiving_id: receivingId, }, token, EXTRA_HEADERS); } describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', () => { let authToken; let products; // 至少 3 个 before(async function() { this.timeout(30000); sequelize = new Sequelize(config.database, config.username, config.password, { host: config.host, port: config.port, dialect: 'mysql', logging: false, }); const { token } = await getAuthToken(); const switched = await switchToWarehouseRole(token); authToken = switched.token; products = await getSystemProducts(authToken, 3); console.log(`[SETUP] 测试商品: ${products.map(p => `${p.item_name}(${p.id})`).join(', ')}`); }); after(async function() { if (sequelize) { await sequelize.close(); sequelize = null; } }); // ────────────────────────────────────────────────────── // 1. 部分匹配拒绝 // ────────────────────────────────────────────────────── it('should reject quickPutaway for partially matched receiving', async function() { this.timeout(60000); const receivingId = await createReceiving(authToken); await bindStore(authToken, receivingId); console.log(`[PARTIAL] 收货单 ID: ${receivingId}`); // 添加 3 条明细 const detailIds = []; const quantities = [ 5, 3, 2 ]; for (let i = 0; i < 3; i++) { const detailId = await addAndFillDetail(authToken, receivingId, products[i], quantities[i]); detailIds.push(detailId); console.log(`[PARTIAL] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}`); } // 只绑定前 2 条,第 3 条不绑定 await bindDetailProduct(authToken, detailIds[0], products[0].id); await bindDetailProduct(authToken, detailIds[1], products[1].id); console.log('[PARTIAL] 只绑定了 2/3 条明细的商品'); // 完成收货 await completeReceiving(authToken, receivingId); // 快捷入库 → 应被拒绝 const res = await quickPutaway(authToken, receivingId); console.log('[PARTIAL] quickPutaway 响应:', JSON.stringify(res.body, null, 2)); const resCode = Number(res.body?.data?.code || res.body?.code || 0); assert.equal(resCode, 400, `部分匹配应返回 400, 实际: ${resCode}`); const message = String(res.body?.data?.message || res.body?.message || ''); assert.ok(message.includes('未匹配'), `message 应包含"未匹配", 实际: ${message}`); }); // ────────────────────────────────────────────────────── // 2. 全匹配成功 // ────────────────────────────────────────────────────── it('should complete quickPutaway for fully matched receiving', async function() { this.timeout(60000); const receivingId = await createReceiving(authToken); await bindStore(authToken, receivingId); console.log(`[FULL] 收货单 ID: ${receivingId}`); // 添加 2 条明细,全部绑定商品 const detailIds = []; const quantities = [ 10, 5 ]; for (let i = 0; i < 2; i++) { const detailId = await addAndFillDetail(authToken, receivingId, products[i], quantities[i]); detailIds.push(detailId); await bindDetailProduct(authToken, detailId, products[i].id); console.log(`[FULL] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, qty=${quantities[i]}`); } // 完成收货 await completeReceiving(authToken, receivingId); // 快捷入库 const res = await quickPutaway(authToken, receivingId); console.log('[FULL] quickPutaway 响应:', JSON.stringify(res.body, null, 2)); assert.equal(res.status, 200, `快捷入库HTTP失败: ${JSON.stringify(res.body)}`); assert.equal(res.body.flag, 'success', `快捷入库flag失败: ${res.body.message}`); const putawayData = res.body?.data?.data || res.body?.data || {}; assert.ok(putawayData.entry_order, '返回中缺少 entry_order'); assert.ok(putawayData.entry_order.id, '返回中缺少 entry_order.id'); assert.ok(putawayData.entry_order.entry_order_code, '返回中缺少 entry_order_code'); assert.ok(Array.isArray(putawayData.items), '返回中缺少 items 数组'); assert.ok(putawayData.items.length > 0, 'items 数组为空'); // 验证 storage_status for (const item of putawayData.items) { assert.ok(item.storage_status, 'item 缺少 storage_status'); } console.log(`[FULL] 入库单号: ${putawayData.entry_order.entry_order_code}, 明细数: ${putawayData.items.length}`); // 验证收货单明细入库状态 const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', { id: receivingId, pagination: { page: 1, pageSize: 100 }, }, authToken, EXTRA_HEADERS); assert.equal(detailRes.status, 200); const detailPayload = detailRes.body?.data?.data || detailRes.body?.data || {}; const receivingAfter = detailPayload.receiving || {}; const detailsAfter = Array.isArray(receivingAfter.details) ? receivingAfter.details : []; for (const d of detailsAfter) { assert.equal(d.storage_status, 'all', `明细 ${d.id} 应全部入库, 实际: ${d.storage_status}`); assert.equal(Number(d.stored_quantity), Number(d.actual_quantity), `明细 ${d.id} stored_quantity(${d.stored_quantity}) 应等于 actual_quantity(${d.actual_quantity})`); console.log(`[FULL] 明细 ${d.id}: stored=${d.stored_quantity}, actual=${d.actual_quantity}, status=${d.storage_status}`); } // 重复入库应被拒绝 const repeatRes = await quickPutaway(authToken, receivingId); console.log('[FULL] 重复入库响应:', JSON.stringify(repeatRes.body, null, 2)); const repeatCode = Number(repeatRes.body?.data?.code || repeatRes.body?.code || 0); assert.equal(repeatCode, 400, `重复入库应返回 400, 实际: ${repeatCode}`); }); // ────────────────────────────────────────────────────── // 3. 数据库行锁冲突 → 409 // ────────────────────────────────────────────────────── it('should return 409 when stock row is locked by concurrent transaction', async function() { this.timeout(120000); const productId = products[0].id; console.log(`[LOCK] 测试商品 ID: ${productId}`); console.log('[LOCK] 注意:本测试需等待服务端锁超时(约50秒),请耐心等待'); let lockTx; try { // 先准备好收货单数据 const receivingId = await createReceiving(authToken); await bindStore(authToken, receivingId); const detailId = await addAndFillDetail(authToken, receivingId, products[0], 1); await bindDetailProduct(authToken, detailId, products[0].id); await completeReceiving(authToken, receivingId); // 开事务锁行 lockTx = await sequelize.transaction(); await sequelize.query( 'SELECT * FROM wms_stock_warehouse WHERE id = :productId FOR UPDATE', { replacements: { productId }, transaction: lockTx } ); console.log(`[LOCK] 已锁定 wms_stock_warehouse.id = ${productId}`); // 安全网:70秒后自动释放(确保超过服务端默认50秒锁等待) const releaseTimer = setTimeout(async () => { try { await lockTx.rollback(); } catch (_) { console.log('错误中断'); } }, 70000); // 调 quickPutaway —— 服务端会等50秒左右才超时返回409 const startTime = Date.now(); const res = await quickPutaway(authToken, receivingId); const elapsed = Math.round((Date.now() - startTime) / 1000); console.log(`[LOCK] quickPutaway 响应 (耗时 ${elapsed}s):`, JSON.stringify(res.body, null, 2)); const resCode = Number(res.body?.data?.code || res.body?.code || 0); assert.equal(resCode, 409, `锁冲突应返回 409, 实际: ${resCode}`); const message = String(res.body?.data?.message || res.body?.message || ''); assert.ok(message.includes('锁定'), `message 应包含"锁定", 实际: ${message}`); clearTimeout(releaseTimer); } finally { try { if (lockTx) await lockTx.rollback(); } catch (_) { console.log('错误中断'); } console.log('[LOCK] 数据库连接已关闭'); } }); // ────────────────────────────────────────────────────── // 4. 无锁冲突正常入库 // ────────────────────────────────────────────────────── it('should complete quickPutaway without lock contention', async function() { this.timeout(60000); const receivingId = await createReceiving(authToken); await bindStore(authToken, receivingId); console.log(`[NOLOCK] 收货单 ID: ${receivingId}`); // 添加 2 条明细,全部绑定 const detailIds = []; const quantities = [ 8, 4 ]; for (let i = 0; i < 2; i++) { const detailId = await addAndFillDetail(authToken, receivingId, products[i], quantities[i]); detailIds.push(detailId); await bindDetailProduct(authToken, detailId, products[i].id); console.log(`[NOLOCK] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, qty=${quantities[i]}`); } // 完成收货 → 快捷入库 await completeReceiving(authToken, receivingId); const res = await quickPutaway(authToken, receivingId); console.log('[NOLOCK] quickPutaway 响应:', JSON.stringify(res.body, null, 2)); assert.equal(res.status, 200, `快捷入库HTTP失败: ${JSON.stringify(res.body)}`); assert.equal(res.body.flag, 'success', `快捷入库flag失败: ${res.body.message}`); const putawayData = res.body?.data?.data || res.body?.data || {}; assert.ok(putawayData.entry_order, '返回中缺少 entry_order'); assert.ok(putawayData.entry_order.id, '返回中缺少 entry_order.id'); assert.ok(Array.isArray(putawayData.items), '返回中缺少 items 数组'); assert.ok(putawayData.items.length === 2, `items 数量应为 2, 实际: ${putawayData.items.length}`); console.log(`[NOLOCK] 入库单号: ${putawayData.entry_order.entry_order_code}`); console.log(`[NOLOCK] 入库明细数: ${putawayData.items.length}`); // 验证入库结果 for (const item of putawayData.items) { assert.ok(item.detail_id, 'item 缺少 detail_id'); assert.ok(item.stock_warehouse_id, 'item 缺少 stock_warehouse_id'); assert.ok(item.inbound_quantity > 0, 'inbound_quantity 应大于 0'); console.log(`[NOLOCK] 明细 ${item.detail_id}: 入库 ${item.inbound_quantity}, 状态 ${item.storage_status}`); } }); // ────────────────────────────────────────────────────── // 5. 空批次回退 + 批次日期落库存 // ────────────────────────────────────────────────────── it('should fallback to receiving number when batch is empty and persist batch dates into storage', async function() { this.timeout(60000); const receivingId = await createReceiving(authToken); await bindStore(authToken, receivingId); console.log(`[BATCH] 收货单 ID: ${receivingId}`); const firstDetailId = await addAndFillDetail(authToken, receivingId, products[0], 2); console.log(`[BATCH] 明细 1: detailId=${firstDetailId}, product=${products[0].item_name}, qty=2`); const secondDetailId = await addAndFillDetail(authToken, receivingId, products[0], 3); await invokeSystemMethod('storage.receiving.detailChange', { id: secondDetailId, receiving_id: receivingId, actual_quantity: 3, production_date: '2026-04-01', expiry_date: '2026-12-31', }, authToken, EXTRA_HEADERS); console.log(`[BATCH] 明细 2: detailId=${secondDetailId}, product=${products[0].item_name}, qty=3, production_date=2026-04-01, expiry_date=2026-12-31`); await bindDetailProduct(authToken, firstDetailId, products[0].id); await bindDetailProduct(authToken, secondDetailId, products[0].id); await completeReceiving(authToken, receivingId); const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', { id: receivingId, pagination: { page: 1, pageSize: 100 }, }, authToken, EXTRA_HEADERS); assert.equal(detailRes.status, 200); const detailPayload = detailRes.body?.data?.data || detailRes.body?.data || {}; const receivingAfter = detailPayload.receiving || {}; const receivingNumber = String(receivingAfter.receiving_number || '').trim(); assert.ok(receivingNumber, '收货单号应存在'); const res = await quickPutaway(authToken, receivingId); console.log('[BATCH] quickPutaway 响应:', JSON.stringify(res.body, null, 2)); assert.equal(res.status, 200, `快捷入库HTTP失败: ${JSON.stringify(res.body)}`); assert.equal(res.body.flag, 'success', `快捷入库flag失败: ${res.body.message}`); try { const [ storageRows ] = await sequelize.query( ` SELECT batch_no, DATE_FORMAT(production_date, '%Y-%m-%d') AS production_date, DATE_FORMAT(expiry_date, '%Y-%m-%d') AS expiry_date, quantity, available_quantity FROM wms_storage WHERE receiving_id = :receivingId AND stock_id = :stockId ORDER BY id DESC LIMIT 1 `, { replacements: { receivingId, stockId: products[0].id } } ); assert.equal(storageRows.length, 1, '应找到对应库存记录'); assert.equal(storageRows[0].batch_no, receivingNumber, '空批次应回退为收货单号'); assert.equal(storageRows[0].production_date, '2026-04-01', '生产日期应写入库存'); assert.equal(storageRows[0].expiry_date, '2026-12-31', '过期日期应写入库存'); assert.equal(Number(storageRows[0].quantity), 5, '两条明细的入库数量应合并为 5'); assert.equal(Number(storageRows[0].available_quantity), 5, '可用数量应与库存数量一致'); } finally { await sequelize.close(); } }); });