WMS_MAIN/test/app/controller/system.storage.inventory.matchPutaway.test.js
liufumingren 77435aeb79 1
2026-06-23 18:48:33 +08:00

479 lines
22 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'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} 的仓库角色`);
}
// ──── 获取系统商品(至少 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-MP-${Date.now().toString().slice(-6)}`,
loading_method: 'without_pallet',
remark: `matchPutaway集成测试 ${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 reviewReceiving(token, receivingId) {
const res = await invokeSystemMethod('storage.receiving.reviewReceiving', {
ids: [ receivingId ],
}, token, EXTRA_HEADERS);
assert.equal(res.status, 200, `审核收货单HTTP失败: ${JSON.stringify(res.body)}`);
assert.equal(res.body.flag, 'success', `审核收货单失败: ${res.body.message}`);
const resCode = Number(res.body?.data?.code || res.body?.code || 0);
assert.equal(resCode, 200, `审核收货单业务失败: ${JSON.stringify(res.body)}`);
}
// ──── 创建测试入库单(直接数据库插入) ────
async function createTestEntryOrder(sequelize, { warehouseId, storeId, items }) {
const code = `TEST-ENTRY-${Date.now()}`;
const [ results ] = await sequelize.query(
`INSERT INTO wms_entry_order (entry_order_code, order_type, total_order_lines, order_create_time, source_type, order_status, sync_status, is_enabled, warehouse_id, store_id, created_at, updated_at)
VALUES (:code, 'CGRK', :lines, NOW(), 'API', 'CREATED', 'PENDING', 1, :warehouseId, :storeId, NOW(), NOW())`,
{ replacements: { code, lines: items.length, warehouseId, storeId }, type: Sequelize.QueryTypes.INSERT }
);
const orderId = results;
for (let i = 0; i < items.length; i++) {
await sequelize.query(
`INSERT INTO wms_entry_items (order_id, order_line_no, item_code, item_id, count, inventory_type, stock_id, received_quantity, confirm_quantity)
VALUES (:orderId, :lineNo, :itemCode, :itemId, :count, 'ZP', :stockId, 0, 0)`,
{ replacements: { orderId, lineNo: i + 1, itemCode: items[i].item_code, itemId: items[i].id, count: items[i].quantity, stockId: items[i].id } }
);
}
return { id: orderId, code };
}
// ──── matchPutaway 调用 ────
async function matchPutaway(token, receivingIds, entryOrderIds) {
return invokeSystemMethod('storage.inventory.matchPutaway', {
receiving_ids: receivingIds,
entry_order_ids: entryOrderIds,
}, token, EXTRA_HEADERS);
}
describe('test/app/controller/system.storage.inventory.matchPutaway.test.js', () => {
let authToken;
let products; // 至少 2 个
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);
console.log(`[SETUP] 测试商品: ${products.map(p => `${p.item_name}(${p.id})`).join(', ')}`);
sequelize = new Sequelize(config.database, config.username, config.password, {
host: config.host,
port: config.port,
dialect: 'mysql',
logging: false,
});
});
after(async function() {
if (sequelize) {
await sequelize.close();
console.log('[TEARDOWN] 数据库连接已关闭');
}
});
// ──────────────────────────────────────────────────────
// 1. 未审核拒绝
// ──────────────────────────────────────────────────────
it('should reject matchPutaway for unreviewed receiving', async function() {
this.timeout(60000);
const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId);
const detailId = await addAndFillDetail(authToken, receivingId, products[0], 2);
await bindDetailProduct(authToken, detailId, products[0].id);
await completeReceiving(authToken, receivingId);
const entryOrder = await createTestEntryOrder(sequelize, {
warehouseId: TEST_WAREHOUSE_ID,
storeId: TEST_STORE_ID,
items: [{
id: products[0].id,
item_code: products[0].item_code,
quantity: 2,
}],
});
const res = await matchPutaway(authToken, [ receivingId ], [ entryOrder.id ]);
console.log('[UNREVIEWED] matchPutaway 响应:', JSON.stringify(res.body, null, 2));
assert.equal(res.status, 200, `matchPutaway HTTP失败: ${JSON.stringify(res.body)}`);
assert.equal(res.body.flag, 'success', `matchPutaway flag失败: ${res.body.message}`);
const resultData = res.body?.data?.data || res.body?.data || {};
const resCode = Number(resultData.code || res.body?.code || 0);
assert.equal(resCode, 400, `未审核收货单应返回 400, 实际: ${resCode}`);
const message = String(resultData.message || res.body?.message || '');
assert.ok(message.includes('未审核'), `message 应包含"未审核", 实际: ${message}`);
});
// ──────────────────────────────────────────────────────
// 2. 精确匹配:收货量 = 入库计划量
// ──────────────────────────────────────────────────────
it('should match putaway when receiving equals entry order (exact match)', async function() {
this.timeout(60000);
const quantities = [ 10, 5 ];
// 1. 创建收货单 → 添加明细 → 绑定商品 → 完成收货
const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId);
console.log(`[EXACT] 收货单 ID: ${receivingId}`);
for (let i = 0; i < 2; i++) {
const detailId = await addAndFillDetail(authToken, receivingId, products[i], quantities[i]);
await bindDetailProduct(authToken, detailId, products[i].id);
console.log(`[EXACT] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, qty=${quantities[i]}`);
}
await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 2. 创建入库单(数量与收货完全一致)
const entryOrder = await createTestEntryOrder(sequelize, {
warehouseId: TEST_WAREHOUSE_ID,
storeId: TEST_STORE_ID,
items: products.map((p, i) => ({
id: p.id,
item_code: p.item_code,
quantity: quantities[i],
})),
});
console.log(`[EXACT] 入库单 ID: ${entryOrder.id}, code: ${entryOrder.code}`);
// 3. 调用 matchPutaway
const res = await matchPutaway(authToken, [ receivingId ], [ entryOrder.id ]);
console.log('[EXACT] matchPutaway 响应:', JSON.stringify(res.body, null, 2));
assert.equal(res.status, 200, `matchPutaway HTTP失败: ${JSON.stringify(res.body)}`);
assert.equal(res.body.flag, 'success', `matchPutaway flag失败: ${res.body.message}`);
const resultData = res.body?.data?.data || res.body?.data || {};
const resCode = Number(resultData.code || res.body?.code || 0);
assert.equal(resCode, 200, `matchPutaway 应返回 code=200, 实际: ${resCode}`);
// 4. 验证收货单 storage_status=all
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 || {};
console.log(`[EXACT] 收货单 storage_status: ${receivingAfter.storage_status}`);
assert.equal(receivingAfter.storage_status, 'all', `收货单应全部入库, 实际: ${receivingAfter.storage_status}`);
// 5. 验证入库单 order_status=COMPLETED(查数据库)
const [ entryRows ] = await sequelize.query(
'SELECT order_status FROM wms_entry_order WHERE id = :id',
{ replacements: { id: entryOrder.id }, type: Sequelize.QueryTypes.SELECT }
);
console.log(`[EXACT] 入库单 order_status: ${entryRows.order_status}`);
assert.equal(entryRows.order_status, 'COMPLETED', `入库单应已完成, 实际: ${entryRows.order_status}`);
// 6. 验证 receiving_results
const receivingResults = resultData.receiving_results || [];
const rcvResult = receivingResults.find(r => r.receiving_id === receivingId);
assert.ok(rcvResult, '返回结果中应包含收货单信息');
assert.equal(rcvResult.storage_status, 'all', '返回中 storage_status 应为 all');
// 7. 验证 entry_order_results
const entryOrderResults = resultData.entry_order_results || [];
const eoResult = entryOrderResults.find(r => r.entry_order_id === entryOrder.id);
assert.ok(eoResult, '返回结果中应包含入库单信息');
assert.equal(eoResult.order_status, 'COMPLETED', '返回中入库单状态应为 COMPLETED');
});
// ──────────────────────────────────────────────────────
// 3. 收货 > 入库计划(部分匹配,有剩余)
// ──────────────────────────────────────────────────────
it('should handle receiving > entry order (partial match with surplus)', async function() {
this.timeout(60000);
const rcvQuantities = [ 20, 15 ];
const entryQuantities = [ 10, 5 ];
// 1. 创建收货单(数量 20, 15)
const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId);
console.log(`[SURPLUS] 收货单 ID: ${receivingId}`);
for (let i = 0; i < 2; i++) {
const detailId = await addAndFillDetail(authToken, receivingId, products[i], rcvQuantities[i]);
await bindDetailProduct(authToken, detailId, products[i].id);
console.log(`[SURPLUS] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, rcvQty=${rcvQuantities[i]}`);
}
await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 2. 创建入库单(数量 10, 5 — 小于收货量)
const entryOrder = await createTestEntryOrder(sequelize, {
warehouseId: TEST_WAREHOUSE_ID,
storeId: TEST_STORE_ID,
items: products.map((p, i) => ({
id: p.id,
item_code: p.item_code,
quantity: entryQuantities[i],
})),
});
console.log(`[SURPLUS] 入库单 ID: ${entryOrder.id}, code: ${entryOrder.code}`);
// 3. 调用 matchPutaway
const res = await matchPutaway(authToken, [ receivingId ], [ entryOrder.id ]);
console.log('[SURPLUS] matchPutaway 响应:', JSON.stringify(res.body, null, 2));
assert.equal(res.status, 200, `matchPutaway HTTP失败: ${JSON.stringify(res.body)}`);
assert.equal(res.body.flag, 'success', `matchPutaway flag失败: ${res.body.message}`);
const resultData = res.body?.data?.data || res.body?.data || {};
const resCode = Number(resultData.code || res.body?.code || 0);
assert.equal(resCode, 200, `matchPutaway 应返回 code=200, 实际: ${resCode}`);
// 4. 验证收货单 storage_status=partial(只入了部分)
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 || {};
console.log(`[SURPLUS] 收货单 storage_status: ${receivingAfter.storage_status}`);
assert.equal(receivingAfter.storage_status, 'partial', `收货单应为部分入库, 实际: ${receivingAfter.storage_status}`);
// 验证各明细的 stored_quantity < actual_quantity
const detailsAfter = Array.isArray(receivingAfter.details) ? receivingAfter.details : [];
for (const d of detailsAfter) {
if (d.system_product_id) {
assert.ok(Number(d.stored_quantity) < Number(d.actual_quantity),
`明细 ${d.id}: stored(${d.stored_quantity}) 应小于 actual(${d.actual_quantity})`);
console.log(`[SURPLUS] 明细 ${d.id}: stored=${d.stored_quantity}, actual=${d.actual_quantity}, status=${d.storage_status}`);
}
}
// 5. 验证入库单 order_status=COMPLETED(计划量全部收满)
const [ entryRows ] = await sequelize.query(
'SELECT order_status FROM wms_entry_order WHERE id = :id',
{ replacements: { id: entryOrder.id }, type: Sequelize.QueryTypes.SELECT }
);
console.log(`[SURPLUS] 入库单 order_status: ${entryRows.order_status}`);
assert.equal(entryRows.order_status, 'COMPLETED', `入库单应已完成, 实际: ${entryRows.order_status}`);
});
// ──────────────────────────────────────────────────────
// 4. 收货 < 入库计划(收货不足)
// ──────────────────────────────────────────────────────
it('should handle receiving < entry order (insufficient receiving)', async function() {
this.timeout(60000);
const rcvQuantities = [ 5, 3 ];
const entryQuantities = [ 10, 8 ];
// 1. 创建收货单(数量 5, 3)
const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId);
console.log(`[INSUF] 收货单 ID: ${receivingId}`);
for (let i = 0; i < 2; i++) {
const detailId = await addAndFillDetail(authToken, receivingId, products[i], rcvQuantities[i]);
await bindDetailProduct(authToken, detailId, products[i].id);
console.log(`[INSUF] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, rcvQty=${rcvQuantities[i]}`);
}
await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 2. 创建入库单(数量 10, 8 — 大于收货量)
const entryOrder = await createTestEntryOrder(sequelize, {
warehouseId: TEST_WAREHOUSE_ID,
storeId: TEST_STORE_ID,
items: products.map((p, i) => ({
id: p.id,
item_code: p.item_code,
quantity: entryQuantities[i],
})),
});
console.log(`[INSUF] 入库单 ID: ${entryOrder.id}, code: ${entryOrder.code}`);
// 3. 调用 matchPutaway
const res = await matchPutaway(authToken, [ receivingId ], [ entryOrder.id ]);
console.log('[INSUF] matchPutaway 响应:', JSON.stringify(res.body, null, 2));
assert.equal(res.status, 200, `matchPutaway HTTP失败: ${JSON.stringify(res.body)}`);
assert.equal(res.body.flag, 'success', `matchPutaway flag失败: ${res.body.message}`);
const resultData = res.body?.data?.data || res.body?.data || {};
const resCode = Number(resultData.code || res.body?.code || 0);
assert.equal(resCode, 200, `matchPutaway 应返回 code=200, 实际: ${resCode}`);
// 4. 验证收货单 storage_status=all(收货全部入库了)
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 || {};
console.log(`[INSUF] 收货单 storage_status: ${receivingAfter.storage_status}`);
assert.equal(receivingAfter.storage_status, 'all', `收货单应全部入库, 实际: ${receivingAfter.storage_status}`);
// 5. 验证入库单 order_status=PARTIAL_RECEIVED(未全部完成)
const [ entryRows ] = await sequelize.query(
'SELECT order_status FROM wms_entry_order WHERE id = :id',
{ replacements: { id: entryOrder.id }, type: Sequelize.QueryTypes.SELECT }
);
console.log(`[INSUF] 入库单 order_status: ${entryRows.order_status}`);
assert.equal(entryRows.order_status, 'PENDING', `入库单应部分收货(状态保持PENDING), 实际: ${entryRows.order_status}`);
// 6. 验证 warnings 包含提示(收货量 < 入库计划量)
const warnings = resultData.warnings || [];
console.log('[INSUF] warnings:', warnings);
assert.ok(warnings.length > 0, '应包含 warnings 提示');
const hasInsufficientWarning = warnings.some(w =>
w.includes('收货可入库量') || w.includes('未全部入库完成')
);
assert.ok(hasInsufficientWarning, `warnings 应包含收货不足或未全部完成提示, 实际: ${JSON.stringify(warnings)}`);
});
});