WMS_MAIN/test/app/service/systems/storage.receiving.report.test.js
2026-04-17 19:21:57 +08:00

731 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 ReceivingService = require('../../../../app/service/systems/storage/receiving');
const DAY_MS = 24 * 60 * 60 * 1000;
function daysFromNow(days) {
return new Date(Date.now() + (days * DAY_MS));
}
function createService() {
const excelCalls = [];
const noticeCalls = [];
const ctx = {
app: {
config: {},
Sequelize: {
Op: {},
},
},
user: {
store_id: 100000,
store_name: '测试仓库',
},
logger: {
info() {},
warn() {},
error() {},
},
service: {
systems: {
excel: {
async generateAndUpload(options) {
excelCalls.push(options);
const fileUrl = `https://cdn.example.com/${options.filename}`;
return {
fileKey: options.filename,
key: options.filename,
filename: options.filename,
url: fileUrl,
fileUrl,
};
},
},
notice: {
async send(options) {
noticeCalls.push(options);
return {
success: true,
data: {
matchedHookCount: 1,
sentCount: 1,
failedCount: 0,
},
};
},
},
},
},
};
const service = new ReceivingService(ctx);
return {
service,
excelCalls,
noticeCalls,
};
}
function createCompleteReceivingService({
uploadShouldFail = false,
detailOverrides = {},
systemProductOverrides = {},
hydrateSystemProductFromQuery = false,
itemImages,
} = {}) {
const steps = [];
const noticeCalls = [];
const transaction = {
LOCK: {
UPDATE: 'UPDATE',
},
finished: false,
async commit() {
this.finished = 'commit';
steps.push('commit');
},
async rollback() {
this.finished = 'rollback';
steps.push('rollback');
},
};
const detailRecord = {
id: 501,
system_product_id: 10001,
product_name: '测试商品A',
barcode: 'SKU-001',
actual_quantity: 8,
weight: 12,
production_date: null,
expiry_date: null,
system_product: {
id: 10001,
item_name: '测试商品A',
item_code: 'SKU-001',
inbound_min_days: 0,
shelf_life_days: 0,
remaining_threshold_days: 0,
is_shelf_life_mgmt: 'N',
is_batch_mgmt: 'N',
...systemProductOverrides,
},
...detailOverrides,
};
const defaultItemImages = [{
business_id: 501,
file_id: 7001,
file: {
file_url: 'https://example.com/item-501.png',
},
}];
const ctx = {
app: {
config: {},
Sequelize: {
Op: {
in: 'in',
},
},
},
user: {
store_id: 100000,
store_name: '测试仓库',
employees_id: 10001,
employees_name: '测试员',
},
logger: {
info() {},
warn() {},
error() {},
},
model: {
async transaction() {
return transaction;
},
Receiving: {
async findOne(options = {}) {
const includeSystemProduct = hydrateSystemProductFromQuery
&& Array.isArray(options.include)
&& options.include.some(includeItem => Array.isArray(includeItem && includeItem.include)
&& includeItem.include.some(childInclude => childInclude && childInclude.as === 'system_product'));
const receivingDetail = includeSystemProduct && !detailRecord.system_product
? {
...detailRecord,
system_product: {
id: 10001,
item_name: '测试商品A',
item_code: 'SKU-001',
inbound_min_days: 0,
shelf_life_days: 0,
remaining_threshold_days: 0,
is_shelf_life_mgmt: 'N',
is_batch_mgmt: 'N',
...systemProductOverrides,
},
}
: detailRecord;
return {
id: 123,
warehouse_id: 100000,
store_id: 1000000,
store_name: '测试货主',
receiving_number: 'RCV202604040001',
status: 'receiving',
remark: '',
details: [ receivingDetail ],
};
},
async update() {
return [ 1 ];
},
},
FileReference: {
async findAll({ where }) {
if (where.business_type === 'receivingItem') {
return Array.isArray(itemImages) ? itemImages : defaultItemImages;
}
return [];
},
},
},
};
const service = new ReceivingService(ctx);
service.sendCompletionNotice = async options => {
steps.push(options.completionReport ? 'notice:file' : 'notice:text');
noticeCalls.push(options);
return {
success: true,
};
};
service.uploadCompletionExcelReport = async () => {
steps.push('excel');
if (uploadShouldFail) {
throw new Error('upload failed');
}
return {
fileKey: '收货明细(已完成收货)_RCV202604040001.xlsx',
url: 'https://cdn.example.com/收货明细(已完成收货)_RCV202604040001.xlsx',
};
};
return {
service,
steps,
noticeCalls,
};
}
function createReceivingSnapshot(deliveryMethod) {
return {
id: 123,
receiving_number: 'RCV202604040001',
warehouse_id: 100000,
store_id: 1000000,
store_name: '测试货主',
delivery_method: deliveryMethod,
license_plate: '粤A12345',
tracking_number: 'YT123456789',
total_boxes: 3,
total_pallets: 1,
remark: '完成收货测试',
receiving_end_time: new Date('2026-04-04T12:30:00Z'),
details: [
{
id: 501,
product_name: '测试商品A',
system_product_id: 10001,
barcode: 'SKU-001',
actual_quantity: 8,
weight: 12,
},
],
};
}
describe('test/app/service/systems/storage.receiving.report.test.js', () => {
it('should build and upload completion excel in a single sheet with one preview column', async () => {
const { service, excelCalls } = createService();
const result = await service.uploadCompletionExcelReport({
receiving: {
id: 123,
receiving_number: 'RCV202604040001',
store_name: '测试货主',
warehouse_id: 100000,
delivery_method: 'truck',
license_plate: '粤A12345',
tracking_number: 'YT123456789',
total_boxes: 3,
total_pallets: 1,
remark: '完成收货测试',
receiving_end_time: new Date('2026-04-04T12:30:00Z'),
details: [
{
id: 501,
product_name: '测试商品A',
system_product_id: 10001,
barcode: 'SKU-001',
actual_quantity: 8,
weight: 12,
},
],
},
operator: {
employees_name: '测试员',
},
stats: {
total_details: 1,
matched_details: 1,
unmatched_details: 0,
total_quantity: 8,
},
detailImageMap: new Map([
[ '501', [
{ url: 'https://example.com/image-1.png' },
{ url: 'https://example.com/image-2.png' },
]],
]),
receivingImages: [
{ url: 'https://example.com/main-image.png' },
],
});
assert.equal(excelCalls.length, 1);
const [ options ] = excelCalls;
assert.equal(options.filename, '收货明细(已完成收货)_RCV202604040001.xlsx');
assert.ok(String(options.dir || '').includes('receiving/completed'));
assert.equal(options.expireDays, 90);
assert.ok(Array.isArray(options.sheets));
assert.equal(options.sheets.length, 1);
const [ sheet ] = options.sheets;
assert.equal(sheet.name, '收货清单');
assert.ok(Array.isArray(sheet.rows));
assert.equal(sheet.skipHeader, true);
const receivingNumberRow = sheet.rows.find(item => Array.isArray(item) && item[0] === '收货单号');
assert.ok(receivingNumberRow, '应在主表区域包含收货单号行');
const deliveryMethodRow = sheet.rows.find(item => Array.isArray(item) && item[0] === '来货方式');
assert.ok(deliveryMethodRow, '应在主表区域包含来货方式行');
assert.equal(deliveryMethodRow[1], '货车');
const summaryImageRow = sheet.rows.find(item => Array.isArray(item) && item[0] === '收货图片');
assert.ok(summaryImageRow, '应在主表区域包含收货图片行');
assert.match(String(summaryImageRow[1]?.text || summaryImageRow[1] || ''), /main-image/);
const detailHeaderRow = sheet.rows.find(item => Array.isArray(item) && item[0] === '序号' && item[1] === '商品名称');
assert.ok(detailHeaderRow, '明细表头应出现在下方明细区开始处');
const detailRow = sheet.rows.find(item => Array.isArray(item) && item[1] === '测试商品A');
assert.ok(detailRow, '应在单 sheet 中包含明细行');
assert.match(String(detailRow[11]?.text || detailRow[11] || ''), /image-1\.png/);
assert.equal(detailRow[10], '');
assert.ok(Array.isArray(sheet.styledRows));
assert.ok(sheet.styledRows.some(item => item && item.style && item.style.font && item.style.font.bold), '应包含表头加粗样式');
assert.ok(Array.isArray(sheet.embeddedImages));
assert.equal(sheet.embeddedImages.length, 3);
assert.equal(result.url, 'https://cdn.example.com/收货明细(已完成收货)_RCV202604040001.xlsx');
});
it('should send receiving completed notice with the unified event payload', async () => {
const { service, noticeCalls } = createService();
const result = await service.sendCompletionNotice({
receiving: {
id: 123,
receiving_number: 'RCV202604040001',
warehouse_id: 100000,
store_id: 1000000,
store_name: '测试货主',
},
operator: {
employees_name: '测试员',
},
stats: {
total_details: 1,
matched_details: 1,
unmatched_details: 0,
total_quantity: 8,
},
completionReport: {
fileKey: '收货明细(已完成收货)_RCV202604040001.xlsx',
url: 'https://cdn.example.com/收货明细(已完成收货)_RCV202604040001.xlsx',
},
});
assert.equal(noticeCalls.length, 1);
const [ options ] = noticeCalls;
assert.equal(Number(options.warehouseId), 100000);
assert.equal(Number(options.storeId), 1000000);
assert.equal(options.businessName, 'receiving');
assert.equal(options.event, 'receiving_completed');
assert.equal(options.messageType, 'file');
assert.equal(options.url, 'https://cdn.example.com/收货明细(已完成收货)_RCV202604040001.xlsx');
assert.equal(options.subject.id, 100000);
assert.equal(options.subject.name, '测试仓库');
assert.match(String(options.content || ''), /收货单号:RCV202604040001 已完成/);
assert.equal(result.success, true);
});
it('should show only license plate for truck in notice content and report main rows', async () => {
const { service, excelCalls, noticeCalls } = createService();
const receiving = createReceivingSnapshot('truck');
await service.sendCompletionNotice({
receiving,
operator: {
employees_name: '测试员',
},
stats: {
total_details: 1,
matched_details: 1,
unmatched_details: 0,
total_quantity: 8,
},
});
await service.uploadCompletionExcelReport({
receiving,
operator: {
employees_name: '测试员',
},
stats: {
total_details: 1,
matched_details: 1,
unmatched_details: 0,
total_quantity: 8,
},
detailImageMap: new Map(),
receivingImages: [],
});
assert.equal(noticeCalls.length, 1);
assert.match(String(noticeCalls[0].content || ''), /车牌号:粤A12345/);
assert.ok(!String(noticeCalls[0].content || '').includes('物流单号'));
assert.equal(excelCalls.length, 1);
const [ sheet ] = excelCalls[0].sheets;
const labels = sheet.rows.filter(Array.isArray).map(item => String(item[0] || ''));
assert.ok(labels.includes('车牌号'));
assert.ok(!labels.includes('物流单号'));
});
it('should show only tracking number for express in notice content and report main rows', async () => {
const { service, excelCalls, noticeCalls } = createService();
const receiving = createReceivingSnapshot('express');
await service.sendCompletionNotice({
receiving,
operator: {
employees_name: '测试员',
},
stats: {
total_details: 1,
matched_details: 1,
unmatched_details: 0,
total_quantity: 8,
},
});
await service.uploadCompletionExcelReport({
receiving,
operator: {
employees_name: '测试员',
},
stats: {
total_details: 1,
matched_details: 1,
unmatched_details: 0,
total_quantity: 8,
},
detailImageMap: new Map(),
receivingImages: [],
});
assert.equal(noticeCalls.length, 1);
assert.match(String(noticeCalls[0].content || ''), /物流单号:YT123456789/);
assert.ok(!String(noticeCalls[0].content || '').includes('车牌号'));
assert.equal(excelCalls.length, 1);
const [ sheet ] = excelCalls[0].sheets;
const labels = sheet.rows.filter(Array.isArray).map(item => String(item[0] || ''));
assert.ok(labels.includes('物流单号'));
assert.ok(!labels.includes('车牌号'));
});
it('should hide both contact fields for other delivery methods', async () => {
const { service, excelCalls, noticeCalls } = createService();
const receiving = createReceivingSnapshot('other');
await service.sendCompletionNotice({
receiving,
operator: {
employees_name: '测试员',
},
stats: {
total_details: 1,
matched_details: 1,
unmatched_details: 0,
total_quantity: 8,
},
});
await service.uploadCompletionExcelReport({
receiving,
operator: {
employees_name: '测试员',
},
stats: {
total_details: 1,
matched_details: 1,
unmatched_details: 0,
total_quantity: 8,
},
detailImageMap: new Map(),
receivingImages: [],
});
assert.equal(noticeCalls.length, 1);
assert.ok(!String(noticeCalls[0].content || '').includes('车牌号'));
assert.ok(!String(noticeCalls[0].content || '').includes('物流单号'));
assert.equal(excelCalls.length, 1);
const [ sheet ] = excelCalls[0].sheets;
const labels = sheet.rows.filter(Array.isArray).map(item => String(item[0] || ''));
assert.ok(!labels.includes('车牌号'));
assert.ok(!labels.includes('物流单号'));
});
it('should support nested notice.index service shape from Egg loader', async () => {
const noticeCalls = [];
const ctx = {
app: {
config: {},
Sequelize: {
Op: {},
},
},
user: {
store_id: 100000,
store_name: '测试仓库',
},
logger: {
info() {},
warn() {},
error() {},
},
service: {
systems: {
notice: {
index: {
async send(options) {
noticeCalls.push(options);
return {
success: true,
message: 'ok',
data: {
matchedHookCount: 1,
sentCount: 1,
failedCount: 0,
},
};
},
},
},
},
},
};
const service = new ReceivingService(ctx);
const result = await service.sendCompletionNotice({
receiving: {
id: 123,
receiving_number: 'RCV202604040001',
warehouse_id: 100000,
store_id: 1000000,
},
operator: {
employees_name: '测试员',
},
stats: {
total_details: 1,
matched_details: 1,
unmatched_details: 0,
total_quantity: 8,
},
});
assert.equal(noticeCalls.length, 1);
assert.equal(result.success, true);
assert.equal(result.message, 'ok');
});
it('should trigger text notice before excel and then send file notice after upload succeeds', async () => {
const { service, steps, noticeCalls } = createCompleteReceivingService();
const result = await service.completeReceiving({ id: 123 });
await Promise.resolve();
await Promise.resolve();
assert.equal(result.success, true);
assert.deepEqual(steps, [ 'commit', 'notice:text', 'excel', 'notice:file' ]);
assert.equal(noticeCalls.length, 2);
assert.equal(noticeCalls[0].completionReport ?? null, null);
assert.equal(Number(noticeCalls[0].receiving.store_id), 1000000);
assert.equal(noticeCalls[1].completionReport.url, 'https://cdn.example.com/收货明细(已完成收货)_RCV202604040001.xlsx');
});
it('should only send text notice when completion excel generation fails', async () => {
const { service, steps, noticeCalls } = createCompleteReceivingService({ uploadShouldFail: true });
const result = await service.completeReceiving({ id: 123 });
await Promise.resolve();
await Promise.resolve();
assert.equal(result.success, true);
assert.equal(result.data.completion_report, null);
assert.deepEqual(steps, [ 'commit', 'notice:text', 'excel' ]);
assert.equal(noticeCalls.length, 1);
assert.equal(noticeCalls[0].completionReport ?? null, null);
assert.equal(Number(noticeCalls[0].receiving.store_id), 1000000);
});
it('should reject completion when batch-managed product misses batch number', async () => {
const { service, steps, noticeCalls } = createCompleteReceivingService({
detailOverrides: {
system_product: null,
batch_number: ' ',
production_date: daysFromNow(-10),
expiry_date: daysFromNow(30),
},
systemProductOverrides: {
is_shelf_life_mgmt: 'Y',
is_batch_mgmt: 'Y',
inbound_min_days: 3,
},
hydrateSystemProductFromQuery: true,
});
const result = await service.completeReceiving({ id: 123 });
assert.equal(result.success, false);
assert.equal(result.code, 'BATCH_NUMBER_REQUIRED');
assert.match(result.message, /批次号/);
assert.ok(Array.isArray(result.data.invalid_details));
assert.equal(result.data.invalid_details[0].detail_id, 501);
assert.deepEqual(steps, [ 'rollback' ]);
assert.equal(noticeCalls.length, 0);
});
it('should reject completion when batch-managed product misses production date or expiry date', async () => {
const { service, steps, noticeCalls } = createCompleteReceivingService({
detailOverrides: {
batch_number: 'BATCH-20260414-001',
production_date: null,
expiry_date: null,
},
systemProductOverrides: {
is_shelf_life_mgmt: 'Y',
is_batch_mgmt: 'Y',
},
});
const result = await service.completeReceiving({ id: 123 });
assert.equal(result.success, false);
assert.equal(result.code, 'PRODUCTION_DATE_REQUIRED');
assert.match(result.message, /生产日期/);
assert.match(result.message, /有效期/);
assert.ok(Array.isArray(result.data.invalid_details));
assert.equal(result.data.invalid_details[0].detail_id, 501);
assert.deepEqual(steps, [ 'rollback' ]);
assert.equal(noticeCalls.length, 0);
});
it('should load batch-managed product data from query include before validating completion', async () => {
const { service, steps, noticeCalls } = createCompleteReceivingService({
detailOverrides: {
system_product: null,
batch_number: 'BATCH-20260414-002',
production_date: null,
expiry_date: null,
},
systemProductOverrides: {
is_shelf_life_mgmt: 'Y',
is_batch_mgmt: 'Y',
inbound_min_days: 3,
},
hydrateSystemProductFromQuery: true,
});
const result = await service.completeReceiving({ id: 123 });
assert.equal(result.success, false);
assert.equal(result.code, 'PRODUCTION_DATE_REQUIRED');
assert.match(result.message, /生产日期/);
assert.deepEqual(steps, [ 'rollback' ]);
assert.equal(noticeCalls.length, 0);
});
it('should reject completion when batch-managed product expires too soon for the minimum receiving days', async () => {
const { service, steps, noticeCalls } = createCompleteReceivingService({
detailOverrides: {
batch_number: 'BATCH-20260414-003',
production_date: daysFromNow(-10),
expiry_date: daysFromNow(2),
},
systemProductOverrides: {
is_shelf_life_mgmt: 'Y',
is_batch_mgmt: 'Y',
inbound_min_days: 3,
},
});
const result = await service.completeReceiving({ id: 123 });
assert.equal(result.success, false);
assert.equal(result.code, 'EXPIRY_DATE_TOO_SOON');
assert.match(result.message, /最小允许收货天数/);
assert.match(result.message, /无法完成收货/);
assert.ok(Array.isArray(result.data.invalid_details));
assert.equal(result.data.invalid_details[0].detail_id, 501);
assert.equal(result.data.invalid_details[0].inbound_min_days, 3);
assert.deepEqual(steps, [ 'rollback' ]);
assert.equal(noticeCalls.length, 0);
});
it('should allow completion when batch-managed product has valid production and expiry dates', async () => {
const { service, steps, noticeCalls } = createCompleteReceivingService({
detailOverrides: {
batch_number: 'BATCH-20260414-004',
production_date: daysFromNow(-10),
expiry_date: daysFromNow(30),
},
systemProductOverrides: {
is_shelf_life_mgmt: 'Y',
is_batch_mgmt: 'Y',
inbound_min_days: 3,
},
});
const result = await service.completeReceiving({ id: 123 });
await Promise.resolve();
await Promise.resolve();
assert.equal(result.success, true);
assert.deepEqual(steps, [ 'commit', 'notice:text', 'excel', 'notice:file' ]);
assert.equal(noticeCalls.length, 2);
assert.equal(Number(result.data.stats.matched_details), 1);
assert.equal(Number(result.data.stats.unmatched_details), 0);
});
});