323 lines
14 KiB
JavaScript
323 lines
14 KiB
JavaScript
'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];
|
||
|
||
// ──── 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} 的仓库角色`);
|
||
}
|
||
|
||
// ──── 获取系统商品 ────
|
||
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-TX-${Date.now().toString().slice(-6)}`,
|
||
loading_method: 'without_pallet',
|
||
remark: `transaction集成测试 ${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) {
|
||
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)}`);
|
||
|
||
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}`);
|
||
}
|
||
|
||
// ──── 快捷入库 ────
|
||
async function quickPutaway(token, receivingId) {
|
||
return invokeSystemMethod('storage.inventory.quickPutaway', {
|
||
receiving_id: receivingId,
|
||
}, token, EXTRA_HEADERS);
|
||
}
|
||
|
||
describe('test/app/controller/system.storage.transaction.test.js', () => {
|
||
let authToken;
|
||
let products;
|
||
let sequelize;
|
||
|
||
before(async function() {
|
||
this.timeout(30000);
|
||
const { token } = await getAuthToken();
|
||
const switched = await switchToWarehouseRole(token);
|
||
authToken = switched.token;
|
||
products = await getSystemProducts(authToken, 2);
|
||
|
||
sequelize = new Sequelize(config.database, config.username, config.password, {
|
||
host: config.host,
|
||
port: config.port,
|
||
dialect: 'mysql',
|
||
logging: false,
|
||
});
|
||
|
||
console.log(`[SETUP] 测试商品: ${products.map(p => `${p.item_name}(${p.id})`).join(', ')}`);
|
||
});
|
||
|
||
after(async function() {
|
||
if (sequelize) {
|
||
await sequelize.close();
|
||
console.log('[TEARDOWN] 数据库连接已关闭');
|
||
}
|
||
});
|
||
|
||
// ──────────────────────────────────────────────────────
|
||
// 用例 1:快捷入库后 wms_stock_transaction 记录验证
|
||
// ──────────────────────────────────────────────────────
|
||
it('should write INBOUND/SCRK records to wms_stock_transaction after quickPutaway', async function() {
|
||
this.timeout(60000);
|
||
|
||
// === 准备阶段 ===
|
||
const receivingId = await createReceiving(authToken);
|
||
await bindStore(authToken, receivingId);
|
||
console.log(`[TX] 收货单 ID: ${receivingId}`);
|
||
|
||
const quantities = [ 7, 3 ];
|
||
const detailIds = [];
|
||
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(`[TX] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}(${products[i].id}), qty=${quantities[i]}`);
|
||
}
|
||
|
||
await completeReceiving(authToken, receivingId);
|
||
|
||
// 记录入库前的 transaction 最大 ID,用于过滤
|
||
const [ beforeRows ] = await sequelize.query(
|
||
'SELECT COALESCE(MAX(id), 0) AS max_id FROM wms_stock_transaction'
|
||
);
|
||
const beforeMaxId = Number(beforeRows[0].max_id);
|
||
console.log(`[TX] 入库前 wms_stock_transaction max_id: ${beforeMaxId}`);
|
||
|
||
// === 执行入库 ===
|
||
const res = await quickPutaway(authToken, receivingId);
|
||
console.log('[TX] 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');
|
||
const entryOrderId = putawayData.entry_order.id;
|
||
const entryOrderCode = putawayData.entry_order.entry_order_code;
|
||
console.log(`[TX] 入库单: id=${entryOrderId}, code=${entryOrderCode}`);
|
||
|
||
// === 断言:查询 wms_stock_transaction 新增记录 ===
|
||
const [ txRows ] = await sequelize.query(
|
||
'SELECT * FROM wms_stock_transaction WHERE id > :beforeMaxId AND receiving_id = :receivingId ORDER BY id ASC',
|
||
{ replacements: { beforeMaxId, receivingId } }
|
||
);
|
||
console.log(`[TX] 新增 transaction 记录数: ${txRows.length}`);
|
||
for (const row of txRows) {
|
||
console.log(`[TX] record id=${row.id}: type=${row.transaction_type}, order_type=${row.order_type}, stock_id=${row.stock_id}, qty=${row.quantity}, entry_order_id=${row.entry_order_id}, warehouse_id=${row.warehouse_id}, store_id=${row.store_id}`);
|
||
}
|
||
|
||
// 1. 应至少有 2 条记录(每条明细一条)
|
||
assert.ok(txRows.length >= 2, `应至少有 2 条 transaction 记录, 实际: ${txRows.length}`);
|
||
|
||
// 2. 逐条验证字段
|
||
for (let i = 0; i < txRows.length; i++) {
|
||
const row = txRows[i];
|
||
|
||
// transaction_type
|
||
assert.equal(row.transaction_type, 'INBOUND',
|
||
`record ${row.id}: transaction_type 应为 INBOUND, 实际: ${row.transaction_type}`);
|
||
|
||
// order_type
|
||
assert.equal(row.order_type, 'SCRK',
|
||
`record ${row.id}: order_type 应为 SCRK, 实际: ${row.order_type}`);
|
||
|
||
// quantity > 0
|
||
assert.ok(Number(row.quantity) > 0,
|
||
`record ${row.id}: quantity 应 > 0, 实际: ${row.quantity}`);
|
||
|
||
// 前后快照字段存在
|
||
assert.ok(Number.isFinite(Number(row.before_quantity)),
|
||
`record ${row.id}: before_quantity 应存在, 实际: ${row.before_quantity}`);
|
||
assert.ok(Number.isFinite(Number(row.after_quantity)),
|
||
`record ${row.id}: after_quantity 应存在, 实际: ${row.after_quantity}`);
|
||
assert.ok(Number.isFinite(Number(row.before_locked_quantity)),
|
||
`record ${row.id}: before_locked_quantity 应存在, 实际: ${row.before_locked_quantity}`);
|
||
assert.ok(Number.isFinite(Number(row.after_locked_quantity)),
|
||
`record ${row.id}: after_locked_quantity 应存在, 实际: ${row.after_locked_quantity}`);
|
||
|
||
// 快照关系应与流水数量一致
|
||
assert.equal(Number(row.after_quantity) - Number(row.before_quantity), Number(row.quantity),
|
||
`record ${row.id}: after_quantity - before_quantity 应等于 quantity`);
|
||
assert.equal(Number(row.after_locked_quantity), Number(row.before_locked_quantity),
|
||
`record ${row.id}: 入库路径锁定数量前后应保持一致`);
|
||
|
||
// stock_id > 0
|
||
assert.ok(Number(row.stock_id) > 0,
|
||
`record ${row.id}: stock_id 应 > 0, 实际: ${row.stock_id}`);
|
||
|
||
// warehouse_id
|
||
assert.equal(Number(row.warehouse_id), TEST_WAREHOUSE_ID,
|
||
`record ${row.id}: warehouse_id 应为 ${TEST_WAREHOUSE_ID}, 实际: ${row.warehouse_id}`);
|
||
|
||
// entry_order_id 不为空
|
||
assert.ok(Number(row.entry_order_id) > 0,
|
||
`record ${row.id}: entry_order_id 应 > 0, 实际: ${row.entry_order_id}`);
|
||
|
||
// entry_order_id 与返回一致
|
||
assert.equal(Number(row.entry_order_id), Number(entryOrderId),
|
||
`record ${row.id}: entry_order_id(${row.entry_order_id}) 应等于返回值(${entryOrderId})`);
|
||
|
||
// receiving_id 与传入一致
|
||
assert.equal(Number(row.receiving_id), Number(receivingId),
|
||
`record ${row.id}: receiving_id(${row.receiving_id}) 应等于 ${receivingId}`);
|
||
|
||
// order_no 不为空
|
||
assert.ok(row.order_no && row.order_no.length > 0,
|
||
`record ${row.id}: order_no 不应为空`);
|
||
|
||
// order_no 与返回的 entry_order_code 一致
|
||
assert.equal(row.order_no, entryOrderCode,
|
||
`record ${row.id}: order_no(${row.order_no}) 应等于 ${entryOrderCode}`);
|
||
|
||
// store_id > 0
|
||
assert.ok(Number(row.store_id) > 0,
|
||
`record ${row.id}: store_id 应 > 0, 实际: ${row.store_id}`);
|
||
}
|
||
|
||
// 3. 验证入库数量与明细匹配
|
||
// 按 stock_id 分组,对比预期数量
|
||
for (let i = 0; i < products.length; i++) {
|
||
const stockId = products[i].id;
|
||
const expectedQty = quantities[i];
|
||
const matchingRow = txRows.find(r => Number(r.stock_id) === stockId);
|
||
if (matchingRow) {
|
||
assert.equal(Number(matchingRow.quantity), expectedQty,
|
||
`stock_id=${stockId}: quantity(${matchingRow.quantity}) 应等于 ${expectedQty}`);
|
||
console.log(`[TX] ✓ stock_id=${stockId} 数量匹配: ${matchingRow.quantity} === ${expectedQty}`);
|
||
} else {
|
||
console.log(`[TX] ⚠ stock_id=${stockId} 未找到对应 transaction 记录(可能 stock_warehouse.id 不等于传入 product.id)`);
|
||
}
|
||
}
|
||
|
||
console.log(`[TX] ✓ 全部断言通过,共 ${txRows.length} 条 INBOUND/SCRK 记录`);
|
||
});
|
||
});
|