305 lines
9.0 KiB
JavaScript
305 lines
9.0 KiB
JavaScript
'use strict';
|
|
|
|
const assert = require('node:assert/strict');
|
|
const fs = require('node:fs/promises');
|
|
const os = require('node:os');
|
|
const path = require('node:path');
|
|
const XLSX = require('xlsx');
|
|
const ExcelService = require('../../../../app/service/systems/excel');
|
|
|
|
function createService(overrides = {}) {
|
|
const uploads = [];
|
|
const notifyCalls = [];
|
|
const ctx = {
|
|
app: {
|
|
config: {},
|
|
},
|
|
logger: {
|
|
info() {},
|
|
error() {},
|
|
},
|
|
service: {
|
|
systems: {
|
|
upload: {
|
|
async uploadFile(fileStream, options = {}) {
|
|
const chunks = [];
|
|
for await (const chunk of fileStream) {
|
|
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
}
|
|
|
|
const body = Buffer.concat(chunks);
|
|
uploads.push({
|
|
filename: fileStream.filename,
|
|
mimeType: fileStream.mimeType,
|
|
fileSize: fileStream.fileSize,
|
|
options,
|
|
body,
|
|
});
|
|
|
|
return {
|
|
fileName: options.key,
|
|
cosUrl: `https://cos.example.com/${options.key}`,
|
|
cdnUrl: `https://cdn.example.com/${options.key}`,
|
|
url: `https://cdn.example.com/${options.key}`,
|
|
};
|
|
},
|
|
async uploadSuccessNotify(data) {
|
|
notifyCalls.push(data);
|
|
return {
|
|
code: 0,
|
|
data: {
|
|
fileId: 9527,
|
|
fileKey: data.url,
|
|
fileUrl: `https://cdn.example.com/${data.url}`,
|
|
},
|
|
};
|
|
},
|
|
},
|
|
},
|
|
},
|
|
...overrides,
|
|
};
|
|
|
|
const service = new ExcelService(ctx);
|
|
return {
|
|
service,
|
|
uploads,
|
|
notifyCalls,
|
|
ctx,
|
|
};
|
|
}
|
|
|
|
describe('test/app/service/systems/excel.test.js', () => {
|
|
it('should generate workbook buffer and parse rows back', async () => {
|
|
const { service } = createService();
|
|
|
|
const buffer = await service.generateBuffer({
|
|
sheets: [
|
|
{
|
|
name: '入库单',
|
|
columns: [
|
|
{ header: '单号', key: 'order_no', width: 20 },
|
|
{ header: '货主', key: 'owner_name', width: 18 },
|
|
{ header: '箱数', key: 'total_boxes', width: 10 },
|
|
],
|
|
rows: [
|
|
{
|
|
order_no: 'RK20260404001',
|
|
owner_name: '测试货主',
|
|
total_boxes: 12,
|
|
},
|
|
],
|
|
},
|
|
],
|
|
});
|
|
|
|
assert.ok(Buffer.isBuffer(buffer));
|
|
assert.ok(buffer.length > 0);
|
|
|
|
const parsed = await service.parseBuffer(buffer);
|
|
assert.deepEqual(parsed.sheetNames, [ '入库单' ]);
|
|
assert.equal(parsed.sheets[0].rows[0].单号, 'RK20260404001');
|
|
assert.equal(parsed.sheets[0].rows[0].货主, '测试货主');
|
|
assert.equal(parsed.sheets[0].rows[0].箱数, '12');
|
|
});
|
|
|
|
it('should normalize duplicated or empty headers when parsing', async () => {
|
|
const { service } = createService();
|
|
|
|
const buffer = await service.generateBuffer({
|
|
sheets: [
|
|
{
|
|
name: '重复表头',
|
|
rows: [
|
|
[ '名称', '名称', '' ],
|
|
[ 'A', 'B', 'C' ],
|
|
],
|
|
},
|
|
],
|
|
});
|
|
|
|
const parsed = await service.parseBuffer(buffer);
|
|
assert.deepEqual(parsed.sheets[0].headers, [ '名称', '名称_2', 'column_3' ]);
|
|
assert.equal(parsed.sheets[0].rows[0].名称, 'A');
|
|
assert.equal(parsed.sheets[0].rows[0].名称_2, 'B');
|
|
assert.equal(parsed.sheets[0].rows[0].column_3, 'C');
|
|
});
|
|
|
|
it('should generate excel and upload to custom directory', async () => {
|
|
const { service, uploads, notifyCalls } = createService();
|
|
|
|
const result = await service.generateAndUpload({
|
|
filename: '收货报表.xlsx',
|
|
dir: 'exports/receiving',
|
|
saveRecord: true,
|
|
businessType: 'receiving',
|
|
businessId: 1001,
|
|
expireDays: 90,
|
|
sheets: [
|
|
{
|
|
name: '报表',
|
|
columns: [
|
|
{ header: '单号', key: 'order_no' },
|
|
],
|
|
rows: [
|
|
{ order_no: 'RK1001' },
|
|
],
|
|
},
|
|
],
|
|
});
|
|
|
|
assert.equal(uploads.length, 1);
|
|
assert.equal(uploads[0].filename, '收货报表.xlsx');
|
|
assert.equal(uploads[0].mimeType, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
|
assert.ok(uploads[0].options.key.includes('exports/receiving/'));
|
|
assert.ok(Buffer.isBuffer(uploads[0].body));
|
|
assert.ok(uploads[0].body.length > 0);
|
|
assert.equal(notifyCalls[0].expireDays, 90);
|
|
assert.match(String(notifyCalls[0].md5Hash || ''), /^[a-f0-9]{32}$/i);
|
|
assert.match(String(notifyCalls[0].sha1Hash || ''), /^[a-f0-9]{40}$/i);
|
|
assert.ok(String(result.fileKey || '').includes('exports/receiving/'));
|
|
assert.equal(result.fileRecord.fileId, 9527);
|
|
});
|
|
|
|
it('should write files atomically without touching the target path directly', async () => {
|
|
const { service } = createService();
|
|
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'wms-excel-'));
|
|
const targetPath = path.join(tempDir, '收货报表.xlsx');
|
|
const writeCalls = [];
|
|
const originalWriteFile = fs.writeFile;
|
|
|
|
fs.writeFile = async function patchedWriteFile(filePath, ...args) {
|
|
writeCalls.push(String(filePath));
|
|
return originalWriteFile.call(this, filePath, ...args);
|
|
};
|
|
|
|
try {
|
|
await service.writeFile(targetPath, {
|
|
sheets: [
|
|
{
|
|
name: '报表',
|
|
columns: [
|
|
{ header: '单号', key: 'order_no' },
|
|
],
|
|
rows: [
|
|
{ order_no: 'RK1001' },
|
|
],
|
|
},
|
|
],
|
|
});
|
|
} finally {
|
|
fs.writeFile = originalWriteFile;
|
|
}
|
|
|
|
assert.ok(writeCalls.length > 0);
|
|
assert.ok(writeCalls.every(filePath => filePath !== targetPath));
|
|
|
|
const buffer = await fs.readFile(targetPath);
|
|
assert.ok(buffer.length > 0);
|
|
|
|
const workbook = XLSX.read(buffer, { type: 'buffer' });
|
|
assert.deepEqual(workbook.SheetNames, [ '报表' ]);
|
|
|
|
await fs.rm(tempDir, { recursive: true, force: true });
|
|
});
|
|
|
|
it('should honor skipHeader when object rows are used', async () => {
|
|
const { service } = createService();
|
|
|
|
const buffer = await service.generateBuffer({
|
|
sheets: [
|
|
{
|
|
name: '跳过首表头',
|
|
columns: [
|
|
{ header: '分区', key: 'section', width: 12 },
|
|
{ header: '字段', key: 'field', width: 16 },
|
|
{ header: '值', key: 'value', width: 18 },
|
|
],
|
|
rows: [
|
|
{ section: '主表', field: '收货单号', value: 'R001' },
|
|
{ section: '明细表头', field: '字段', value: '值' },
|
|
],
|
|
skipHeader: true,
|
|
},
|
|
],
|
|
});
|
|
|
|
const workbook = XLSX.read(buffer, { type: 'buffer' });
|
|
const rawRows = XLSX.utils.sheet_to_json(workbook.Sheets['跳过首表头'], {
|
|
header: 1,
|
|
defval: '',
|
|
});
|
|
|
|
assert.deepEqual(rawRows[0], [ '主表', '收货单号', 'R001' ]);
|
|
assert.deepEqual(rawRows[1], [ '明细表头', '字段', '值' ]);
|
|
});
|
|
|
|
it('should support embedded images when url is a data URL', async () => {
|
|
const { service } = createService();
|
|
const imageDataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9WnR8i8AAAAASUVORK5CYII=';
|
|
|
|
const buffer = await service.generateBuffer({
|
|
sheets: [
|
|
{
|
|
name: 'URL图片',
|
|
rows: [[ '图片', '见右侧' ]],
|
|
embeddedImages: [
|
|
{
|
|
row: 1,
|
|
col: 2,
|
|
url: imageDataUrl,
|
|
width: 40,
|
|
height: 40,
|
|
},
|
|
],
|
|
},
|
|
],
|
|
});
|
|
|
|
assert.ok(Buffer.isBuffer(buffer));
|
|
assert.ok(buffer.length > 0);
|
|
});
|
|
|
|
it('should generate workbook with embedded image previews when image config exists', async () => {
|
|
const { service } = createService();
|
|
const imageDataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9WnR8i8AAAAASUVORK5CYII=';
|
|
|
|
const buffer = await service.generateBuffer({
|
|
sheets: [
|
|
{
|
|
name: '图片预览',
|
|
columns: [
|
|
{ header: '名称', key: 'name', width: 20 },
|
|
{ header: '链接', key: 'url', width: 30 },
|
|
{ header: '图片', key: 'preview', width: 22 },
|
|
],
|
|
rows: [
|
|
{
|
|
name: '示例图片',
|
|
url: 'https://example.com/demo.png',
|
|
preview: '见右侧',
|
|
},
|
|
],
|
|
embeddedImages: [
|
|
{
|
|
row: 2,
|
|
col: 3,
|
|
dataUrl: imageDataUrl,
|
|
width: 60,
|
|
height: 60,
|
|
fallbackText: '示例图片',
|
|
},
|
|
],
|
|
},
|
|
],
|
|
});
|
|
|
|
assert.ok(Buffer.isBuffer(buffer));
|
|
assert.ok(buffer.length > 0);
|
|
|
|
const parsed = await service.parseBuffer(buffer);
|
|
assert.deepEqual(parsed.sheetNames, [ '图片预览' ]);
|
|
assert.equal(parsed.sheets[0].rows[0].名称, '示例图片');
|
|
});
|
|
});
|