From ca62d5bf7d3d6340b8db9287faa70ec182a15fb1 Mon Sep 17 00:00:00 2001 From: wannT-1 <200890097+wannT-1@users.noreply.github.com> Date: Wed, 3 Jun 2026 10:18:00 +0800 Subject: [PATCH 1/7] =?UTF-8?q?fix(portfolio-import):=20=E5=90=8C=E6=97=B6?= =?UTF-8?q?=E5=AD=98=E5=9C=A8=20Price=20=E4=B8=8E=E6=88=90=E6=9C=AC?= =?UTF-8?q?=E5=88=97=E6=97=B6=E6=94=B9=E7=94=A8=E6=9B=B4=E5=85=B7=E4=BD=93?= =?UTF-8?q?=E7=9A=84=E8=A1=A8=E5=A4=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 左侧的 Price/价格列不再抢走同一行里的 Cost、Avg Cost 或成本。只有没有更具体的成本列时,Price 才继续作为成本兜底。 Co-authored-by: wannT-1 --- .../src/portfolio-import/parsers.test.ts | 18 ++++++++++++++ .../shared/src/portfolio-import/parsers.ts | 24 +++++++++++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/packages/shared/src/portfolio-import/parsers.test.ts b/packages/shared/src/portfolio-import/parsers.test.ts index 3e0e175b..76baf324 100644 --- a/packages/shared/src/portfolio-import/parsers.test.ts +++ b/packages/shared/src/portfolio-import/parsers.test.ts @@ -172,6 +172,24 @@ describe('parseCsv', () => { expect(rows[0]).toMatchObject({ symbol: 'AAPL.US', quantity: 100, costPrice: 180.5 }) }) + it('keeps Price as a cost fallback only when no specific cost column exists', () => { + const rows = parseCsv('Symbol,Price,Shares\nAAPL.US,180.5,100') + expect(rows[0]).toMatchObject({ symbol: 'AAPL.US', quantity: 100, costPrice: 180.5, confidence: 1, issues: [] }) + }) + + it('uses the specific cost column when an earlier Price column is also present', () => { + const rows = parseCsv('Symbol,Price,Cost,Qty\nAAPL.US,190.25,180.5,100\n0700.HK,330,320,500') + expect(rows[0]).toMatchObject({ symbol: 'AAPL.US', quantity: 100, costPrice: 180.5, confidence: 1, issues: [] }) + expect(rows[1]).toMatchObject({ symbol: '0700.HK', quantity: 500, costPrice: 320 }) + }) + + it('prefers Avg Cost and 成本 over a generic price column', () => { + const english = parseCsv('Ticker,Price,Avg Cost,Shares\nAAPL.US,190.25,180.5,100') + expect(english[0]).toMatchObject({ symbol: 'AAPL.US', quantity: 100, costPrice: 180.5 }) + const chinese = parseCsv('代码,价格,成本,数量\n600519.SH,1700,1600,10') + expect(chinese[0]).toMatchObject({ symbol: '600519.SH', quantity: 10, costPrice: 1600, confidence: 1, issues: [] }) + }) + it('supports an explicit headerMapping override', () => { const rows = parseCsv('Ticker,Avg Cost,Units\nAAPL.US,180.5,100', { symbol: 'Ticker', cost: 'Avg Cost', quantity: 'Units' }) 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..7135d99b 100644 --- a/packages/shared/src/portfolio-import/parsers.ts +++ b/packages/shared/src/portfolio-import/parsers.ts @@ -26,18 +26,24 @@ export const HEADER_ALIASES: Record = { symbol: ['symbol', 'ticker', 'code', 'stock', '代码', '股票代码', '证券代码'], name: ['name', 'company', 'stockname', '名称', '股票名称', '证券名称'], quantity: ['quantity', 'qty', 'shares', '数量', '持股数量', '股数', '持仓数量'], + // Specific cost headers come first. `price` / `价格` are fallbacks only: + // a leftmost "Price" column must not steal the value when "Cost" or + // "Avg Cost" is also present. cost: [ 'cost', 'costprice', 'cost price', - 'price', 'avgcost', 'avg cost', + 'averagecost', + 'average cost', '成本', '成本价', '买入价', '持仓成本', '均价', + '价格', + 'price', ], currency: ['currency', 'ccy', '货币', '币种'], account: ['account', '账户', '账号', '组合'], @@ -175,6 +181,20 @@ function normalizeHeaderCell(cell: string): string { return cell.trim().toLowerCase().replace(/[\s_\-]/g, '') } +/** + * Pick a column by alias specificity, not by leftmost match. + * The first alias that appears anywhere in the row wins, so a generic + * fallback such as `price` does not override an earlier specific header + * that happens to sit further right. + */ +function columnForAliases(cells: readonly string[], aliases: readonly string[]): number { + for (const alias of aliases) { + const index = cells.indexOf(normalizeHeaderCell(alias)) + if (index >= 0) return index + } + return -1 +} + /** Field → resolved column index for one CSV file. */ export interface CsvColumnMap { isHeader: boolean @@ -204,7 +224,7 @@ export function resolveCsvColumns( found = cells.indexOf(normalizeHeaderCell(explicit)) } if (found === -1) { - found = cells.findIndex((cell) => HEADER_ALIASES[field].some((alias) => normalizeHeaderCell(alias) === cell)) + found = columnForAliases(cells, HEADER_ALIASES[field]) } if (found >= 0) byIndex.set(found, field) } From 92595eaeeae2fce3e2d990b848e2885eb36eefc6 Mon Sep 17 00:00:00 2001 From: wannT-1 <200890097+wannT-1@users.noreply.github.com> Date: Mon, 8 Jun 2026 14:42:00 +0800 Subject: [PATCH 2/7] =?UTF-8?q?fix(portfolio-import):=20=E6=95=B0=E5=80=BC?= =?UTF-8?q?=E8=A7=A3=E6=9E=90=E8=AF=86=E5=88=AB=20HK$/US$/=E4=BA=BA?= =?UTF-8?q?=E6=B0=91=E5=B8=81=E7=AD=89=E8=B4=A7=E5=B8=81=E7=AC=A6=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 券商导出把 HK$、US$、¥ 或 USD 粘在数量和成本上时,不再整格判成无效数字。只剩货币符号、没有数字的格子仍然保持无效。 Co-authored-by: wannT-1 --- .../src/portfolio-import/parsers.test.ts | 23 +++++++++++++++ .../shared/src/portfolio-import/parsers.ts | 28 ++++++++++++++++--- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/packages/shared/src/portfolio-import/parsers.test.ts b/packages/shared/src/portfolio-import/parsers.test.ts index 76baf324..d2fb4ae3 100644 --- a/packages/shared/src/portfolio-import/parsers.test.ts +++ b/packages/shared/src/portfolio-import/parsers.test.ts @@ -79,6 +79,22 @@ describe('toFiniteNumber', () => { expect(toFiniteNumber(' 1,234.56 ')).toBe(1234.56) }) + it('reads HK$, US$, yuan, and ISO currency glued onto the number', () => { + expect(toFiniteNumber('HK$1,234.50')).toBe(1234.5) + expect(toFiniteNumber('hk$180.5')).toBe(180.5) + expect(toFiniteNumber('US$180.50')).toBe(180.5) + expect(toFiniteNumber('¥180.5')).toBe(180.5) + expect(toFiniteNumber('¥1,600')).toBe(1600) + expect(toFiniteNumber('CN¥180')).toBe(180) + expect(toFiniteNumber('RMB 180.5')).toBe(180.5) + expect(toFiniteNumber('180.50 USD')).toBe(180.5) + expect(toFiniteNumber('320 HKD')).toBe(320) + expect(toFiniteNumber('-HK$12.5')).toBe(-12.5) + expect(toFiniteNumber('-$0.00')).toBe(0) + expect(toFiniteNumber('USD')).toBeUndefined() + expect(toFiniteNumber('HK$')).toBeUndefined() + }) + it('returns undefined for null, empty, and junk', () => { expect(toFiniteNumber(null)).toBeUndefined() expect(toFiniteNumber(undefined)).toBeUndefined() @@ -132,6 +148,13 @@ describe('parseCsv', () => { expect(mapped).toMatchObject({ symbol: 'AAPL.US', quantity: 1000, costPrice: 180.5, issues: [] }) }) + it('parses currency-prefixed cost cells from a brokerage CSV', () => { + const rows = parseCsv('Symbol,Quantity,Cost,Currency\nAAPL.US,"1,000","US$180.50",USD\n0700.HK,500,HK$320,HKD\n600519.SH,10,¥1600,CNY') + expect(rows[0]).toMatchObject({ symbol: 'AAPL.US', quantity: 1000, costPrice: 180.5, currency: 'USD', confidence: 1, issues: [] }) + expect(rows[1]).toMatchObject({ symbol: '0700.HK', quantity: 500, costPrice: 320, currency: 'HKD' }) + expect(rows[2]).toMatchObject({ symbol: '600519.SH', quantity: 10, costPrice: 1600, currency: 'CNY' }) + }) + it('flags formatting-only quantities and costs without inventing zeros', () => { const rows = parseCsv('Symbol,Quantity,Cost\nAAPL.US,100,$\nMSFT.US,",",180.5\n0700.HK,500,320') expect(rows).toHaveLength(3) diff --git a/packages/shared/src/portfolio-import/parsers.ts b/packages/shared/src/portfolio-import/parsers.ts index 7135d99b..b5b2778b 100644 --- a/packages/shared/src/portfolio-import/parsers.ts +++ b/packages/shared/src/portfolio-import/parsers.ts @@ -89,9 +89,28 @@ export function checkSymbol(raw: string): SymbolCheck { } } +/** + * Drop currency markers brokerage exports glue onto a number. + * `HK$1,234.50`, `US$180`, `¥180.5`, `180.50 USD` all reduce to the digits. + * A leading sign is preserved (`-HK$12` stays negative). + */ +function stripCurrencyAffixes(value: string): string { + let text = value.trim() + const sign = text.startsWith('-') || text.startsWith('+') ? text[0] : '' + if (sign !== '') text = text.slice(1).trim() + text = text.replace(/^(?:HK|US|S|A|C)\s*\$\s*/i, '') + text = text.replace(/^(?:CN|RMB)\s*[¥¥]\s*/i, '') + text = text.replace(/^(?:RMB|CNY|USD|HKD|SGD|EUR|GBP|AUD|CAD)\s*/i, '') + text = text.replace(/^[¥¥€£$]\s*/, '') + text = text.replace(/\s*(?:RMB|CNY|USD|HKD|SGD|EUR|GBP|AUD|CAD)\s*$/i, '') + text = text.replace(/\s*[$¥¥€£]\s*$/, '') + return `${sign}${text.trim()}` +} + /** * Coerce a CSV/paste cell to a finite number. Strings with thousands - * separators or a leading `$` are handled; empty/null/non-numeric → undefined. + * separators or a currency prefix (`$`, `HK$`, `US$`, `¥`, `USD`) are + * handled; empty/null/non-numeric → undefined. */ export function toFiniteNumber(value: unknown): number | undefined { if (typeof value === 'number') { @@ -100,17 +119,18 @@ export function toFiniteNumber(value: unknown): number | undefined { if (typeof value !== 'string') { return undefined } - const trimmed = value.trim() + const trimmed = stripCurrencyAffixes(value) if (trimmed === '') { return undefined } const cleaned = trimmed.replace(/[,$\s]/g, '') // Number('') is zero, but formatting alone does not supply a numeric value. - if (cleaned === '') { + if (cleaned === '' || cleaned === '+' || cleaned === '-') { return undefined } const parsed = Number(cleaned) - return Number.isFinite(parsed) ? parsed : undefined + if (!Number.isFinite(parsed)) return undefined + return parsed === 0 ? 0 : parsed } // ── CSV ──────────────────────────────────────────────────────────────────── From 7db1901b70d4a1fac363a1c012ada61691f28151 Mon Sep 17 00:00:00 2001 From: wannT-1 <200890097+wannT-1@users.noreply.github.com> Date: Fri, 12 Jun 2026 11:05:00 +0800 Subject: [PATCH 3/7] =?UTF-8?q?fix(portfolio-import):=20=E4=BC=9A=E8=AE=A1?= =?UTF-8?q?=E6=8B=AC=E5=8F=B7=E5=92=8C=E5=B0=BE=E9=9A=8F=E5=87=8F=E5=8F=B7?= =?UTF-8?q?=E6=8C=89=E8=B4=9F=E6=95=B0=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 对账单里的 (180.50)、(HK$1,234.50) 和 1,234.56- 不再被当成无效成本。只有括号或货币符号、没有数字时仍然无效。 Co-authored-by: wannT-1 --- .../src/portfolio-import/parsers.test.ts | 17 ++++++++++++ .../shared/src/portfolio-import/parsers.ts | 26 +++++++++++++++++-- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/packages/shared/src/portfolio-import/parsers.test.ts b/packages/shared/src/portfolio-import/parsers.test.ts index d2fb4ae3..1930fb18 100644 --- a/packages/shared/src/portfolio-import/parsers.test.ts +++ b/packages/shared/src/portfolio-import/parsers.test.ts @@ -95,6 +95,18 @@ describe('toFiniteNumber', () => { expect(toFiniteNumber('HK$')).toBeUndefined() }) + it('reads accounting parentheses and a trailing minus as negative amounts', () => { + expect(toFiniteNumber('(180.50)')).toBe(-180.5) + expect(toFiniteNumber('($1,234.56)')).toBe(-1234.56) + expect(toFiniteNumber('(HK$12.5)')).toBe(-12.5) + expect(toFiniteNumber('(¥180.5)')).toBe(-180.5) + expect(toFiniteNumber('1,234.56-')).toBe(-1234.56) + expect(toFiniteNumber('($0.00)')).toBe(0) + expect(toFiniteNumber('()')).toBeUndefined() + expect(toFiniteNumber('($)')).toBeUndefined() + expect(toFiniteNumber('-45.2')).toBe(-45.2) + }) + it('returns undefined for null, empty, and junk', () => { expect(toFiniteNumber(null)).toBeUndefined() expect(toFiniteNumber(undefined)).toBeUndefined() @@ -148,6 +160,11 @@ describe('parseCsv', () => { expect(mapped).toMatchObject({ symbol: 'AAPL.US', quantity: 1000, costPrice: 180.5, issues: [] }) }) + it('parses parenthesized cost cells as negative amounts', () => { + const [row] = parseCsv('Symbol,Quantity,Cost\nAAPL.US,(100),"(HK$1,234.50)"') + expect(row).toMatchObject({ symbol: 'AAPL.US', quantity: -100, costPrice: -1234.5, confidence: 1, issues: [] }) + }) + it('parses currency-prefixed cost cells from a brokerage CSV', () => { const rows = parseCsv('Symbol,Quantity,Cost,Currency\nAAPL.US,"1,000","US$180.50",USD\n0700.HK,500,HK$320,HKD\n600519.SH,10,¥1600,CNY') expect(rows[0]).toMatchObject({ symbol: 'AAPL.US', quantity: 1000, costPrice: 180.5, currency: 'USD', confidence: 1, issues: [] }) diff --git a/packages/shared/src/portfolio-import/parsers.ts b/packages/shared/src/portfolio-import/parsers.ts index b5b2778b..d821ab97 100644 --- a/packages/shared/src/portfolio-import/parsers.ts +++ b/packages/shared/src/portfolio-import/parsers.ts @@ -89,6 +89,26 @@ export function checkSymbol(raw: string): SymbolCheck { } } +/** + * Accounting exports write negatives as `(180.50)` or `180.50-`. + * Fullwidth parentheses are accepted. A normal leading minus is left for + * the numeric parse. + */ +function takeAccountingSign(value: string): { text: string; negative: boolean } { + let text = value.trim() + let negative = false + const wrapped = /^(?:\(|()\s*(.*?)\s*(?:\)|))$/.exec(text) + if (wrapped) { + negative = true + text = wrapped[1].trim() + } + if (text.endsWith('-') && !/^[+-]/.test(text)) { + negative = true + text = text.slice(0, -1).trim() + } + return { text, negative } +} + /** * Drop currency markers brokerage exports glue onto a number. * `HK$1,234.50`, `US$180`, `¥180.5`, `180.50 USD` all reduce to the digits. @@ -119,7 +139,8 @@ export function toFiniteNumber(value: unknown): number | undefined { if (typeof value !== 'string') { return undefined } - const trimmed = stripCurrencyAffixes(value) + const accounting = takeAccountingSign(value) + const trimmed = stripCurrencyAffixes(accounting.text) if (trimmed === '') { return undefined } @@ -130,7 +151,8 @@ export function toFiniteNumber(value: unknown): number | undefined { } const parsed = Number(cleaned) if (!Number.isFinite(parsed)) return undefined - return parsed === 0 ? 0 : parsed + if (parsed === 0) return 0 + return accounting.negative ? -Math.abs(parsed) : parsed } // ── CSV ──────────────────────────────────────────────────────────────────── From f5189dbeb197c65fc39d6812f5f0982b2fd1fcad Mon Sep 17 00:00:00 2001 From: wannT-1 <200890097+wannT-1@users.noreply.github.com> Date: Tue, 16 Jun 2026 16:27:00 +0800 Subject: [PATCH 4/7] =?UTF-8?q?fix(portfolio-import):=20=E5=85=A8=E8=A7=92?= =?UTF-8?q?=E6=95=B0=E5=AD=97=E5=92=8C=E5=88=86=E9=9A=94=E7=AC=A6=E6=8C=89?= =?UTF-8?q?=E5=8D=8A=E8=A7=92=E6=95=B0=E5=80=BC=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 中文表格里的全角数字、全角逗号、全角小数点和全角美元符号不再让数量或成本变成缺失字段。 Co-authored-by: wannT-1 --- .../shared/src/portfolio-import/parsers.test.ts | 14 ++++++++++++++ packages/shared/src/portfolio-import/parsers.ts | 12 +++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/portfolio-import/parsers.test.ts b/packages/shared/src/portfolio-import/parsers.test.ts index 1930fb18..778cf4c9 100644 --- a/packages/shared/src/portfolio-import/parsers.test.ts +++ b/packages/shared/src/portfolio-import/parsers.test.ts @@ -107,6 +107,15 @@ describe('toFiniteNumber', () => { expect(toFiniteNumber('-45.2')).toBe(-45.2) }) + it('folds fullwidth digits and separators before parsing', () => { + expect(toFiniteNumber('1,234.56')).toBe(1234.56) + expect(toFiniteNumber('$180.50')).toBe(180.5) + expect(toFiniteNumber('¥180')).toBe(180) + expect(toFiniteNumber('(180.50)')).toBe(-180.5) + expect(toFiniteNumber('-45.2')).toBe(-45.2) + expect(toFiniteNumber(',,,')).toBeUndefined() + }) + it('returns undefined for null, empty, and junk', () => { expect(toFiniteNumber(null)).toBeUndefined() expect(toFiniteNumber(undefined)).toBeUndefined() @@ -160,6 +169,11 @@ describe('parseCsv', () => { expect(mapped).toMatchObject({ symbol: 'AAPL.US', quantity: 1000, costPrice: 180.5, issues: [] }) }) + it('parses fullwidth quantity and cost cells', () => { + const [row] = parseCsv('代码,数量,成本\n600519.SH,10,1,600.50') + expect(row).toMatchObject({ symbol: '600519.SH', quantity: 10, costPrice: 1600.5, confidence: 1, issues: [] }) + }) + it('parses parenthesized cost cells as negative amounts', () => { const [row] = parseCsv('Symbol,Quantity,Cost\nAAPL.US,(100),"(HK$1,234.50)"') expect(row).toMatchObject({ symbol: 'AAPL.US', quantity: -100, costPrice: -1234.5, confidence: 1, issues: [] }) diff --git a/packages/shared/src/portfolio-import/parsers.ts b/packages/shared/src/portfolio-import/parsers.ts index d821ab97..6959bfb8 100644 --- a/packages/shared/src/portfolio-import/parsers.ts +++ b/packages/shared/src/portfolio-import/parsers.ts @@ -89,6 +89,16 @@ export function checkSymbol(raw: string): SymbolCheck { } } +/** Map fullwidth digits and separators onto the ASCII forms `Number` understands. */ +function foldNumericWidth(value: string): string { + return value + .replace(/[0-9]/g, (digit) => String.fromCharCode(digit.charCodeAt(0) - 0xfee0)) + .replace(/./g, '.') + .replace(/,/g, ',') + .replace(/[-−]/g, '-') + .replace(/$/g, '$') +} + /** * Accounting exports write negatives as `(180.50)` or `180.50-`. * Fullwidth parentheses are accepted. A normal leading minus is left for @@ -139,7 +149,7 @@ export function toFiniteNumber(value: unknown): number | undefined { if (typeof value !== 'string') { return undefined } - const accounting = takeAccountingSign(value) + const accounting = takeAccountingSign(foldNumericWidth(value)) const trimmed = stripCurrencyAffixes(accounting.text) if (trimmed === '') { return undefined From 1f5d92f6c5f26e33909a6f659396a80ec3a98f3e Mon Sep 17 00:00:00 2001 From: wannT-1 <200890097+wannT-1@users.noreply.github.com> Date: Fri, 19 Jun 2026 09:51:00 +0800 Subject: [PATCH 5/7] =?UTF-8?q?fix(portfolio-import):=20=E5=8E=BB=E6=8E=89?= =?UTF-8?q?=E8=A1=A8=E5=A4=B4=E5=92=8C=E6=95=B0=E5=AD=97=E9=87=8C=E7=9A=84?= =?UTF-8?q?=E9=9B=B6=E5=AE=BD=E5=AD=97=E7=AC=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 网页粘贴带上的零宽空格会让 Symbol 列表头匹配失败,整表变成没有代码的行。现在表头和数值会先去掉这些不可见字符。 Co-authored-by: wannT-1 --- packages/shared/src/portfolio-import/parsers.test.ts | 9 +++++++++ packages/shared/src/portfolio-import/parsers.ts | 11 +++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/packages/shared/src/portfolio-import/parsers.test.ts b/packages/shared/src/portfolio-import/parsers.test.ts index 778cf4c9..b4d3a56b 100644 --- a/packages/shared/src/portfolio-import/parsers.test.ts +++ b/packages/shared/src/portfolio-import/parsers.test.ts @@ -169,6 +169,15 @@ describe('parseCsv', () => { expect(mapped).toMatchObject({ symbol: 'AAPL.US', quantity: 1000, costPrice: 180.5, issues: [] }) }) + it('ignores zero-width characters glued to headers and numbers', () => { + const rows = parseCsv('\u200BSymbol,Quantity,Cost\nAAPL.US,1\u200B000,180.5') + expect(rows[0]).toMatchObject({ symbol: 'AAPL.US', quantity: 1000, costPrice: 180.5, confidence: 1, issues: [] }) + const wordJoiner = parseCsv('\u2060代码,数量,成本\n0700.HK,500,320') + expect(wordJoiner[0]).toMatchObject({ symbol: '0700.HK', quantity: 500, costPrice: 320, confidence: 1, issues: [] }) + expect(toFiniteNumber('1\u200B,000')).toBe(1000) + expect(toFiniteNumber('\u200B')).toBeUndefined() + }) + it('parses fullwidth quantity and cost cells', () => { const [row] = parseCsv('代码,数量,成本\n600519.SH,10,1,600.50') expect(row).toMatchObject({ symbol: '600519.SH', quantity: 10, costPrice: 1600.5, confidence: 1, issues: [] }) diff --git a/packages/shared/src/portfolio-import/parsers.ts b/packages/shared/src/portfolio-import/parsers.ts index 6959bfb8..295bfbce 100644 --- a/packages/shared/src/portfolio-import/parsers.ts +++ b/packages/shared/src/portfolio-import/parsers.ts @@ -149,7 +149,7 @@ export function toFiniteNumber(value: unknown): number | undefined { if (typeof value !== 'string') { return undefined } - const accounting = takeAccountingSign(foldNumericWidth(value)) + const accounting = takeAccountingSign(foldNumericWidth(stripInvisible(value))) const trimmed = stripCurrencyAffixes(accounting.text) if (trimmed === '') { return undefined @@ -229,8 +229,15 @@ export function splitCsvLine(line: string, delimiter: ',' | '\t' = csvDelimiter( return cells } +/** Characters `trim` does not remove, but spreadsheets and web paste often insert. */ +const INVISIBLE_CHARS = /[\uFEFF\u200B\u200C\u200D\u2060]/g + +function stripInvisible(value: string): string { + return value.replace(INVISIBLE_CHARS, '') +} + function normalizeHeaderCell(cell: string): string { - return cell.trim().toLowerCase().replace(/[\s_\-]/g, '') + return stripInvisible(cell).trim().toLowerCase().replace(/[\s_\-]/g, '') } /** From bdbc6e7c7abea04d3ddaa44aed46812a8cb434f9 Mon Sep 17 00:00:00 2001 From: wannT-1 <200890097+wannT-1@users.noreply.github.com> Date: Wed, 24 Jun 2026 15:36:00 +0800 Subject: [PATCH 6/7] =?UTF-8?q?fix(portfolio-import):=20=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E7=AC=A6=E5=8F=B7=E9=95=BF=E5=BA=A6=E4=B8=8E=E5=85=A8=E4=BB=93?= =?UTF-8?q?=201=E2=80=936=20=E4=BD=8D=E8=A7=84=E5=88=99=E5=AF=B9=E9=BD=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 7 位以上的代码(如 6005191.SH、TOOLONG.US)不再被当成可直接导入的标准符号。A 股 6 位代码仍然有效,校验注释里过时的 1–5 位说明也已改掉。 Co-authored-by: wannT-1 --- packages/longbridge-tools/src/validator.ts | 2 +- .../src/portfolio-import/parsers.test.ts | 26 +++++++++++++++++++ .../shared/src/portfolio-import/parsers.ts | 10 ++++--- 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/packages/longbridge-tools/src/validator.ts b/packages/longbridge-tools/src/validator.ts index 39ef1506..b6890f49 100644 --- a/packages/longbridge-tools/src/validator.ts +++ b/packages/longbridge-tools/src/validator.ts @@ -1,7 +1,7 @@ import { LongBridgeError } from './errors.ts'; // Symbol format: AAPL.US, 0700.HK, 600519.SH, 0388.HK, etc. -// Allow 1-5 chars of A-Z and 0-9 +// 1–6 characters. A-share listings are 6 digits; a 5-character limit rejects them. const SYMBOL_REGEX = /^[A-Z0-9]{1,6}\.(US|HK|SG|SH|SZ|HAS)$/; export function validateSymbol(symbol: string): boolean { diff --git a/packages/shared/src/portfolio-import/parsers.test.ts b/packages/shared/src/portfolio-import/parsers.test.ts index b4d3a56b..a42af2d1 100644 --- a/packages/shared/src/portfolio-import/parsers.test.ts +++ b/packages/shared/src/portfolio-import/parsers.test.ts @@ -46,6 +46,24 @@ describe('checkSymbol', () => { it('rejects unknown market suffixes', () => { expect(checkSymbol('AAPL.XX').ambiguous).toBe(true) }) + + it('does not treat over-long codes as canonical symbols', () => { + for (const symbol of ['6005191.SH', 'TOOLONG.US', 'DELISTED.US']) { + const check = checkSymbol(symbol) + expect(check.ambiguous).toBe(true) + expect(check.issue).toContain('not a recognized ticker') + } + const bare = checkSymbol('6005191') + expect(bare.ambiguous).toBe(true) + expect(bare.issue).toContain('not a recognized ticker') + expect(bare.issue).not.toContain('6005191.US') + }) + + it('still hints a market suffix for a 6-character bare ticker', () => { + const check = checkSymbol('600519') + expect(check.ambiguous).toBe(true) + expect(check.issue).toContain('600519.US') + }) }) describe('toFiniteNumber', () => { @@ -292,6 +310,14 @@ describe('parseCsv', () => { expect(parseCsv('\n\n')).toEqual([]) }) + it('keeps an over-long symbol for review instead of importing it as clean', () => { + const [row] = parseCsv('Symbol,Quantity,Cost\nTOOLONG.US,100,180.5\n600519.SH,10,1600') + expect(row.confidence).toBe(0.3) + expect(row.issues.some((issue) => issue.includes('not a recognized ticker'))).toBe(true) + const valid = parseCsv('Symbol,Quantity,Cost\n600519.SH,10,1600')[0] + expect(valid).toMatchObject({ symbol: '600519.SH', quantity: 10, costPrice: 1600, confidence: 1, issues: [] }) + }) + it('keeps a row when a required column is missing (review required)', () => { const rows = parseCsv('Symbol,Cost\nAAPL.US,180.5') expect(rows[0]).toMatchObject({ symbol: 'AAPL.US', costPrice: 180.5 }) diff --git a/packages/shared/src/portfolio-import/parsers.ts b/packages/shared/src/portfolio-import/parsers.ts index 295bfbce..ba98cceb 100644 --- a/packages/shared/src/portfolio-import/parsers.ts +++ b/packages/shared/src/portfolio-import/parsers.ts @@ -10,11 +10,15 @@ */ import type { ImportSource, PortfolioImportRow } from '@finagent/core' -/** Canonical symbol: 1–8 alphanumerics plus a known market suffix. */ -export const SYMBOL_RE = /^[A-Z0-9]{1,8}\.(US|HK|SG|SH|SZ|HAS)$/ +/** + * Canonical symbol: 1–6 alphanumerics plus a known market suffix. + * Matches `symbolSchema` / Longbridge validation. A-share codes are 6 digits; + * 7–8 character bodies are not canonical and must not import as clean rows. + */ +export const SYMBOL_RE = /^[A-Z0-9]{1,6}\.(US|HK|SG|SH|SZ|HAS)$/ /** Bare ticker with no market suffix — usable, but ambiguous (review). */ -export const BARE_TICKER_RE = /^[A-Z0-9]{1,8}$/ +export const BARE_TICKER_RE = /^[A-Z0-9]{1,6}$/ export type HeaderField = 'symbol' | 'name' | 'quantity' | 'cost' | 'currency' | 'account' From 41dd39b235374df156a120644e1b6dc2ba982614 Mon Sep 17 00:00:00 2001 From: wannT-1 <200890097+wannT-1@users.noreply.github.com> Date: Sat, 27 Jun 2026 13:14:00 +0800 Subject: [PATCH 7/7] =?UTF-8?q?docs:=20=E4=BF=AE=E6=AD=A3=E8=BF=87?= =?UTF-8?q?=E6=97=B6=E7=9A=84=201=E2=80=935=20=E4=BD=8D=E6=A0=87=E7=9A=84?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CLAUDE 和 API 参考里的 5 位上限会拒绝合法的 6 位 A 股代码(如 600519.SH)。文档改为与校验实现一致的 1–6 位。 Co-authored-by: wannT-1 --- CLAUDE.md | 2 +- docs/api-reference.md | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index 2bf196eb..3296fed4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -24,7 +24,7 @@ npx skills add longbridge/developers -g -y ### Critical Rules 1. **LongBridge CLI is user-installed** — NEVER bundle it in the app -2. **Symbol validation** — Validate with `/^[A-Z0-9]{1,5}\.(US|HK|SG|SH|SZ|HAS)$/` before exec +2. **Symbol validation** — Validate with `/^[A-Z0-9]{1,6}\.(US|HK|SG|SH|SZ|HAS)$/` before exec. The body is 1–6 characters: A-share codes such as `600519.SH` are 6 digits, so a 5-character limit rejects valid listings. 3. **Use execa array params** — Never string concatenation for commands 4. **Session isolation** — Use `atomFamily` for per-session state diff --git a/docs/api-reference.md b/docs/api-reference.md index 573d68da..43f45d49 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -16,6 +16,8 @@ Complete reference for all LongBridge CLI commands used by Finance Agent. | Indices | `.US` | `.VIX.US`, `.SPX.US` | Start with `.` | | Crypto | `.HAS` | `BTCUSD.HAS` | LongBridge crypto suffix | +The code before the suffix is 1–6 letters or digits. Shanghai and Shenzhen listings use 6-digit codes (`600519.SH`); a 5-character limit rejects them. Codes longer than 6 characters (`6005191.SH`, `TOOLONG.US`) are not valid Folio symbols. + --- ## Market Data Commands