diff --git a/packages/shared/src/portfolio-import/parsers.test.ts b/packages/shared/src/portfolio-import/parsers.test.ts index 3e0e175b..dde9b088 100644 --- a/packages/shared/src/portfolio-import/parsers.test.ts +++ b/packages/shared/src/portfolio-import/parsers.test.ts @@ -167,6 +167,20 @@ describe('parseCsv', () => { expect(rows[1]).toMatchObject({ symbol: '0700.HK', currency: 'HKD' }) }) + it('strips a leading UTF-8 BOM from English headers', () => { + const plain = 'Symbol,Quantity,Cost\nAAPL.US,10,100' + const rows = parseCsv(`\uFEFF${plain}`) + expect(rows).toEqual(parseCsv(plain)) + expect(rows[0]).toMatchObject({ symbol: 'AAPL.US', quantity: 10, costPrice: 100, confidence: 1, issues: [] }) + }) + + it('strips a leading UTF-8 BOM from 中文 headers', () => { + const plain = '代码,数量,成本\nAAPL.US,10,100' + const rows = parseCsv(`\uFEFF${plain}`) + expect(rows).toEqual(parseCsv(plain)) + expect(rows[0]).toMatchObject({ symbol: 'AAPL.US', quantity: 10, costPrice: 100, confidence: 1, issues: [] }) + }) + it('detects alias variants (qty / shares / price / code)', () => { const rows = parseCsv('Code,Shares,Price\nAAPL.US,100,180.5') expect(rows[0]).toMatchObject({ symbol: 'AAPL.US', quantity: 100, costPrice: 180.5 }) diff --git a/packages/shared/src/portfolio-import/parsers.ts b/packages/shared/src/portfolio-import/parsers.ts index a2a141fd..9db8aa44 100644 --- a/packages/shared/src/portfolio-import/parsers.ts +++ b/packages/shared/src/portfolio-import/parsers.ts @@ -20,7 +20,8 @@ export type HeaderField = 'symbol' | 'name' | 'quantity' | 'cost' | 'currency' | /** * Header aliases for CSV column detection (English + 中文). Header cells are - * matched after lowercasing and stripping spaces/underscores/hyphens. + * matched after stripping a leading UTF-8 BOM (U+FEFF), lowercasing, and + * removing spaces, underscores, and hyphens. */ export const HEADER_ALIASES: Record = { symbol: ['symbol', 'ticker', 'code', 'stock', '代码', '股票代码', '证券代码'], @@ -172,7 +173,9 @@ export function splitCsvLine(line: string, delimiter: ',' | '\t' = csvDelimiter( } function normalizeHeaderCell(cell: string): string { - return cell.trim().toLowerCase().replace(/[\s_\-]/g, '') + // Excel "CSV UTF-8" prefixes the first cell with U+FEFF. Strip that BOM + // before alias matching so the header matches the same file without one. + return cell.replace(/^\uFEFF+/, '').trim().toLowerCase().replace(/[\s_\-]/g, '') } /** Field → resolved column index for one CSV file. */