Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 77 additions & 1 deletion services/platform/lib/utils/file-parsing.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,36 @@
import { describe, it, expect } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
import * as XLSX from 'xlsx';

import {
excelRecords,
excelHeaderText,
parseImportFile,
parseCSVWithMapper,
type RequiredColumn,
} from './file-parsing';

class TestFileReader {
result: string | ArrayBuffer | null = null;
private listeners = new Map<string, ((event: Event) => void)[]>();

addEventListener(type: string, listener: (event: Event) => void) {
this.listeners.set(type, [...(this.listeners.get(type) ?? []), listener]);
}

readAsArrayBuffer(file: Blob) {
void file.arrayBuffer().then((result) => {
this.result = result;
this.listeners
.get('load')
?.forEach((listener) => listener({ target: this } as unknown as Event));
});
}
}

// parseImportFile uses the browser FileReader API; this small adapter exercises
// the same byte path in the server test environment.
vi.stubGlobal('FileReader', TestFileReader);

type Row = { email: string; name?: string };

// A record mapper that accepts a couple of header aliases for email/name.
Expand Down Expand Up @@ -231,3 +255,55 @@ describe('excelRecords line numbers', () => {
]);
});
});

describe('Excel header cell conversion', () => {
it('accepts primitive, date, and rich-text values without object coercion', () => {
expect(excelHeaderText(' Email ')).toBe(' Email ');
expect(excelHeaderText(42)).toBe('42');
expect(excelHeaderText(false)).toBe('false');
expect(excelHeaderText(new Date('2024-01-02T03:04:05.000Z'))).toBe(
'2024-01-02T03:04:05.000Z',
);
expect(excelHeaderText({ text: 'Email address' })).toBe('Email address');
expect(excelHeaderText({ w: 'Formatted header' })).toBe('Formatted header');
expect(excelHeaderText({ unexpected: 'object' })).toBe('');
expect(excelHeaderText(null)).toBe('');
});
});

describe('Excel header validation', () => {
it('uses the worksheet header when the first data row has blank cells', async () => {
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(
workbook,
XLSX.utils.aoa_to_sheet([
['name', 'price', 'stock'],
['Blank amounts'],
['Full amounts', 12, 3],
]),
'Products',
);
const file = new File(
[XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })],
'products.xlsx',
);
const result = await parseImportFile(
file,
() => null,
(record) => record,
{
requiredColumns: [
{ label: 'price', aliases: ['price'] },
{ label: 'stock', aliases: ['stock'] },
],
},
);

expect(result.errors).toEqual([]);
expect(result.data).toEqual([
{ name: 'Blank amounts' },
{ name: 'Full amounts', price: 12, stock: 3 },
]);
expect(result.rows).toEqual([2, 3]);
});
});
33 changes: 28 additions & 5 deletions services/platform/lib/utils/file-parsing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -430,18 +430,43 @@ export function excelRecords(
}));
}

/** Convert a worksheet header cell to its textual column name safely. */
export function excelHeaderText(value: unknown): string {
if (typeof value === 'string') return value;
if (typeof value === 'number' || typeof value === 'boolean')
return String(value);
if (value instanceof Date) return value.toISOString();
if (typeof value === 'object' && value !== null) {
const text = (value as { text?: unknown; w?: unknown }).text;
if (typeof text === 'string') return text;
const formatted = (value as { text?: unknown; w?: unknown }).w;
if (typeof formatted === 'string') return formatted;
}
return '';
}

/**
* Parse an Excel file and return its rows with their lines.
* Dynamically imports xlsx to reduce initial bundle size.
*/
async function parseExcelFile(file: File): Promise<ExcelRecord[]> {
async function parseExcelFile(
file: File,
): Promise<{ headers: string[]; records: ExcelRecord[] }> {
const XLSX = await import('xlsx');
const buffer = await readFileAsArrayBuffer(file);
const data = new Uint8Array(buffer);
const workbook = XLSX.read(data, { type: 'array' });
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
return excelRecords(XLSX, worksheet);
const headerRows = XLSX.utils.sheet_to_json<unknown[]>(worksheet, {
header: 1,
range: 0,
blankrows: false,
});
const headers = (headerRows[0] ?? []).map((header) =>
excelHeaderText(header).trim().toLowerCase(),
);
return { headers, records: excelRecords(XLSX, worksheet) };
}

function isCSVFile(file: File): boolean {
Expand Down Expand Up @@ -473,12 +498,10 @@ export async function parseImportFile<T>(
});
return result;
} else if (isExcelFile(file)) {
const records = await parseExcelFile(file);
const { headers: headerKeys, records } = await parseExcelFile(file);

// Validate the header row (the keys of the first record) so a
// mismatched schema fails loudly rather than dropping data silently.
const headerKeys =
records.length > 0 ? Object.keys(records[0].record) : [];
const missing = detectMissingColumns(headerKeys, options.requiredColumns);
if (missing.length > 0) {
return emptyResult([missingColumnsError(missing, headerKeys)]);
Expand Down