From ebf061a1c11fb0756b1867b62edaf716ced9b541 Mon Sep 17 00:00:00 2001 From: nyg Date: Thu, 19 Nov 2026 21:12:59 +0100 Subject: [PATCH] feat: classify Dutch, German, Spanish, Italian, Czech and Portuguese rows --- README.md | 49 +-- .../dashboard/src/components/dropzone.tsx | 3 +- examples/dashboard/test/positions.test.ts | 8 +- src/classify/descriptions.ts | 101 ++++-- src/classify/matchers/cash.ts | 8 +- src/classify/matchers/dividend.ts | 8 +- src/classify/matchers/fees.ts | 5 +- src/classify/matchers/fx.ts | 35 +- src/classify/matchers/interest.ts | 2 +- src/classify/matchers/trade.ts | 14 +- src/dialects/de.ts | 32 ++ src/dialects/es.ts | 32 ++ src/dialects/index.ts | 3 + src/dialects/nl.ts | 28 ++ src/dialects/registry.ts | 12 +- test/classify.test.ts | 308 ++++++++++++++++++ test/dialect.test.ts | 130 ++++++-- test/integration.test.ts | 116 ++++++- test/redos.test.ts | 3 + 19 files changed, 790 insertions(+), 107 deletions(-) create mode 100644 src/dialects/de.ts create mode 100644 src/dialects/es.ts create mode 100644 src/dialects/nl.ts diff --git a/README.md b/README.md index b8bde41..b938fff 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ A modern, ESM-only TypeScript library that turns a DEGIRO account statement into - 🧮 **Exact money** with [`big.js`](https://github.com/MikeMcl/big.js) — no float drift - 🧩 **Extensible** dialects, classifiers and grouping strategies -- 🌐 **French and English exports** out of the box, and a layout-detecting fallback for every other language +- 🌐 **French, English, Dutch, German and Spanish exports** out of the box, Italian, Czech and Portuguese descriptions too, and a layout-detecting fallback for every other language - 🧠 **Typed domain model** — discriminated unions for movements & transactions - 🪶 **Lenient parsing** — per-row problems are collected, never thrown - 🌊 **Streaming** parser for very large files @@ -111,26 +111,35 @@ Parsing is **lenient**: a row with an unparseable date is dropped and reported a ## Supported exports -DEGIRO localizes the **header row** of `Account.csv` to the interface language. Two dialects recognise a header by its words, and a third recognises the file by its shape when neither does: +DEGIRO localizes the **header row** of `Account.csv` to the interface language. Five dialects recognise a header by its words, and a sixth recognises the file by its shape when none does: -| Dialect | `id` | Header | -| ---------------- | --------- | --------------------------------------------------------------------------------- | -| `frenchDialect` | `fr` | `Date,Heure,Date de,Produit,Code ISIN,Description,FX,Mouvements,,Solde,,ID Ordre` | -| `englishDialect` | `en` | `Date,Time,Value date,Product,ISIN,Description,FX,Change,,Balance,,Order Id` | -| `genericDialect` | `generic` | any header in DEGIRO's column layout, whatever the labels say | +| Dialect | `id` | Header | +| ---------------- | --------- | ---------------------------------------------------------------------------------------------- | +| `frenchDialect` | `fr` | `Date,Heure,Date de,Produit,Code ISIN,Description,FX,Mouvements,,Solde,,ID Ordre` | +| `englishDialect` | `en` | `Date,Time,Value date,Product,ISIN,Description,FX,Change,,Balance,,Order Id` | +| `dutchDialect` | `nl` | `Datum,Tijd,Valutadatum,Product,ISIN,Omschrijving,FX,Mutatie,,Saldo,,Order Id` | +| `germanDialect` | `de` | `Datum,Uhrzeit,Wertstellungsdatum,Produkt,ISIN,Beschreibung,FX,Änderung,,Saldo,,Auftrag ID` | +| `spanishDialect` | `es` | `Fecha,Hora,Fecha valor,Producto,ISIN,Descripción,Tipo,Variación,,Saldo,,ID Orden` | +| `genericDialect` | `generic` | any header in DEGIRO's column layout, whatever the labels say | -All three share the positional column layout, and the two language-aware ones share `DD-MM-YYYY` dates. They differ in how they read numbers: `frenchDialect` expects space thousands separators and a comma decimal mark, while `englishDialect` accepts either that or the US `1,060.20` form — DEGIRO does **not** switch the body of the file to English number formatting when you switch the interface language, so an English export can carry either. When a value contains both `,` and `.`, the last one is the decimal mark; a lone separator is a decimal mark unless the value is a run of exact 3-digit groups (`1,060,200`). +All six share the positional column layout, and the five language-aware ones share `DD-MM-YYYY` dates. They differ in how they read numbers: `frenchDialect` expects space thousands separators and a comma decimal mark, while the English, Dutch, German and Spanish dialects accept either that or the US `1,060.20` form — DEGIRO does **not** switch the body of the file to another number format when you switch the interface language, so an export can carry either. `dutchDialect` also accepts the header variant that says `Beschrijving` and `Order ID`. When a value contains both `,` and `.`, the last one is the decimal mark; a lone separator is a decimal mark unless the value is a run of exact 3-digit groups (`1,060,200`). -Descriptions are a separate axis: switching the interface language rewrites the header but leaves the description text alone, so an English-header export from a French account still says `Frais DEGIRO de courtage`. The built-in matchers therefore recognise both languages regardless of which dialect read the header. Anything they do not recognise becomes an `unknown` movement — never a dropped row. +Descriptions are a separate axis: switching the interface language rewrites the header but leaves the description text alone, so an English-header export from a French account still says `Frais DEGIRO de courtage`. The built-in matchers therefore recognise French, English, Dutch, German, Spanish, Italian, Czech and Portuguese wordings regardless of which dialect read the header. Anything they do not recognise becomes an `unknown` movement — never a dropped row. + +A few wordings need more than a lookup: + +- Dutch `Koop 15 @ 76,50 EUR` and German `Kauf 1 zu je 211 USD (US88160R1014)` name no product, and the Dutch form no ISIN either. The trade takes them from the row's `Product` and `ISIN` columns, and is only a trade when one of the two carries an ISIN. +- Czech calls both legs of a currency conversion `FX vyúčtování konverze měny`, so the sign of the amount decides between `fxCredit` and `fxDebit`. +- Rows that would need a new movement kind stay `unknown`: money-market fund price changes and conversions, corporate actions (splits, ISIN changes, delistings), promotions, transaction taxes, other fees (ADR/GDR, SOFORT, corporate-action fees), bond coupons and accrued interest, payments in lieu of a dividend, and deposit reservations. ### The fallback, for every other language -DEGIRO's column layout is the same in every language: twelve columns, where the mutation and the balance each pair a currency cell with an amount cell under a single header label — so the 9th and 11th header cells (0-based indices 8 and 10) are always empty. `genericDialect` recognises that shape and nothing else, reading no header text at all, and interprets dates (`DD-MM-YYYY`, `DD/MM/YYYY`, `YYYY-MM-DD`) and numbers by the same per-value rules as the English dialect. It is registered last, so a French or English export never reaches it. +DEGIRO's column layout is the same in every language: twelve columns, where the mutation and the balance each pair a currency cell with an amount cell under a single header label — so the 9th and 11th header cells (0-based indices 8 and 10) are always empty. `genericDialect` recognises that shape and nothing else, reading no header text at all, and interprets dates (`DD-MM-YYYY`, `DD/MM/YYYY`, `YYYY-MM-DD`) and numbers by the same per-value rules as the English dialect. It is registered last, so an export one of the language-aware dialects recognises never reaches it. Because it is a guess, it says so: `dialect.heuristic` is `true` and a warning lands on `ParseResult.warnings` naming the line it was decided on. Nothing silently depends on it. ```ts -const result = parseDegiroCsv(dutchCsv); +const result = parseDegiroCsv(italianCsv); result.dialect.id; // 'generic' result.dialect.heuristic; // true result.warnings[0].message; // 'No dialect recognised this header, so the "generic" fallback ...' @@ -139,7 +148,7 @@ result.warnings[0].message; // 'No dialect recognised this header, so the "gener Two smaller guesses ride along: - If the header tokenizes to a single cell, `parseDegiroCsv` retries with `;` and then a tab before giving up. Passing `delimiter` explicitly turns this off. -- `structuralTradeMatcher` and `structuralFxTradeMatcher` recover trades from the _shape_ of a description — ` @ ()` — and take the side from the sign of the mutation, money out being a buy. Both run at a negative priority, after every language-aware matcher has declined, so `Koop 1.060 SMI ETF@106,02 CHF (CH0019852802)` classifies as a buy without anyone teaching the library Dutch. +- `structuralTradeMatcher` and `structuralFxTradeMatcher` recover trades from the _shape_ of a description — ` @ ()` — and take the side from the sign of the mutation, money out being a buy. Both run at a negative priority, after every language-aware matcher has declined, so `Acquisto 1.060 SMI ETF@106,02 CHF (CH0019852802)` classifies as a buy without anyone teaching the library the Italian verb. Descriptions with no such shape — a dividend, a fee, a deposit in a language the matchers do not know — stay `unknown` with their amounts intact, so balances still reconcile and cash still adds up. Register a matcher for the wording to name them. @@ -298,16 +307,16 @@ Every stage is pluggable. You rarely need to fork the library to support a new e ### Custom dialect (new locale / layout) -French and English are built in; here is a third locale — Dutch headers, dot thousands, comma decimals: +Five header languages are built in; here is a sixth — Italian headers, dot thousands, comma decimals: ```ts import { parseDegiroCsv, DEGIRO_COLUMNS, parseDegiroDateTime, type Dialect } from 'libdegiro'; -const dutchDialect: Dialect = { - id: 'nl', - label: 'DEGIRO Dutch', +const italianDialect: Dialect = { + id: 'it', + label: 'DEGIRO Italian', columns: DEGIRO_COLUMNS, // the shared positional layout - matches: (header) => header.includes('Omschrijving') && header.includes('Mutatie'), + matches: (header) => header.includes('Descrizione') && header.includes('Variazioni'), parseDecimal: (raw) => { const n = raw.trim().replace(/\./g, '').replace(',', '.'); // 1.060,20 return /^-?\d+(\.\d+)?$/.test(n) ? n : null; @@ -316,12 +325,12 @@ const dutchDialect: Dialect = { parseDate: (d) => parseDegiroDateTime(d), }; -parseDegiroCsv(csv, { dialects: [dutchDialect] }); +parseDegiroCsv(csv, { dialects: [italianDialect] }); // or force it, skipping detection: -parseDegiroCsv(csv, { dialect: dutchDialect }); +parseDegiroCsv(csv, { dialect: italianDialect }); ``` -A dialect registered through `dialects` replaces the built-ins, including the fallback; pass `createDefaultDialectRegistry().register(dutchDialect, { prepend: true })` to keep them. +A dialect registered through `dialects` replaces the built-ins, including the fallback; pass `createDefaultDialectRegistry().register(italianDialect, { prepend: true })` to keep them. ### Custom classifier (new movement description) diff --git a/examples/dashboard/src/components/dropzone.tsx b/examples/dashboard/src/components/dropzone.tsx index 4b45ad5..bb5105f 100644 --- a/examples/dashboard/src/components/dropzone.tsx +++ b/examples/dashboard/src/components/dropzone.tsx @@ -60,7 +60,8 @@ export function Dropzone() {

Drop your DEGIRO Account.csv here

- English and French statements are both recognised. + French, English, Dutch, German and Spanish headers are recognised, and + other languages by their column layout.

diff --git a/examples/dashboard/test/positions.test.ts b/examples/dashboard/test/positions.test.ts index 7ce6d3e..9b7abf5 100644 --- a/examples/dashboard/test/positions.test.ts +++ b/examples/dashboard/test/positions.test.ts @@ -208,12 +208,12 @@ describe('describeHealthProblems', () => { }) it('warns when the layout fallback read the file, ahead of any rounding note', () => { - const dutchCsv = [ - 'Datum,Tijd,Valutadatum,Product,ISIN,Omschrijving,FX,Mutatie,,Saldo,,Order Id', - '18-11-2024,00:00,18-11-2024,,,Storting,,CHF,"9.000,00",CHF,"9.000,00",', + const italianCsv = [ + 'Data,Ora,Data Valore,Prodotto,ISIN,Descrizione,Borsa,Variazioni,,Saldo,,ID Ordine', + '18-11-2024,00:00,18-11-2024,,,Deposito,,CHF,"9.000,00",CHF,"9.000,00",', '', ].join('\n') - const parsed = parseDegiroCsv(dutchCsv) + const parsed = parseDegiroCsv(italianCsv) const report = withDiscrepancies(buildHealthReport(parsed, 0), [ discrepancy('rounding', '-0.01'), ]) diff --git a/src/classify/descriptions.ts b/src/classify/descriptions.ts index 5437cb0..e4b4639 100644 --- a/src/classify/descriptions.ts +++ b/src/classify/descriptions.ts @@ -4,9 +4,12 @@ import { Money } from '../money/money' /** Leading quantity: digits, then any number of grouped thousands. */ const LEADING_QTY = /^[0-9]+(?:[ .,\u00a0\u202f][0-9]{3})*/ const QTY_GROUPING = /[ .,\u00a0\u202f]/g -/** `Achat|Vente|Buy|Sell` and the whitespace that follows it. */ -const TRADE_VERB = /^(Achat|Vente|Buy|Sell)\s+/i -const BUY_SIDE = /^(achat|buy)$/i +/** `Achat|Vente|Buy|Sell|Koop|Verkoop|Kauf|Verkauf` and the whitespace that follows it. */ +const TRADE_VERB = /^(Achat|Vente|Buy|Sell|Koop|Verkoop|Kauf|Verkauf)\s+/i +const BUY_SIDE = /^(achat|buy|koop|kauf)$/i +const UNLABELLED_PRICE_SEPARATORS = ['@'] as const +/** German trades read `Kauf 1 zu je 211 USD`. */ +const LABELLED_PRICE_SEPARATORS = ['@', ' zu je '] as const const CURRENCY = /^[A-Za-z]{3}$/ const DIGIT = /[0-9]/ const TRAILING_SPACE = /\s$/ @@ -15,9 +18,11 @@ const FX_SETTLEMENT_PREFIX = /^(?:R[èe]glement transaction devise|(?:Currency|FX)\s+(?:transaction\s+)?settlement)\s*:\s*/i /** Currency pair such as `EUR/CHF`. */ const FX_PAIR = /^[A-Za-z]{3}\/[A-Za-z]{3}$/ -/** `Virement|Transfer|Deposit|Withdrawal vers|depuis|to|from ...`, up to the colon. */ -const CASH_TRANSFER = /^(?:Virement|Transfer|Deposit|Withdrawal)\s+(vers|depuis|to|from)\b/i -const TO_CASH_ACCOUNT = /^(vers|to)$/i +const TO_CASH_ACCOUNT = + /^(?:(?:virement|transfer|deposit|withdrawal)\s+(?:vers|to)|overboeking\s+naar|überweisung\s+auf|transferir\s+a|trasferisci\s+sul)\b/i +const FROM_CASH_ACCOUNT = + /^(?:(?:virement|transfer|deposit|withdrawal)\s+(?:depuis|from)|overboeking\s+van|auszahlung\s+von|transferir\s+desde|trasferisci\s+dal)\b/i +const AMOUNT_CHAR = /[0-9.,\s]/ /** Parse a localized integer quantity (with space thousands separators). */ export function parseQuantity(raw: string, dialect: Dialect): number | null { @@ -55,14 +60,16 @@ function splitTrailingCurrency(text: string): { head: string, currency: string } function parsePriceTail( priceTail: string, dialect: Dialect, + isinRequired: boolean, ): { unitPrice: Money | null, isin: string | null } { const trimmed = priceTail.trim() const open = trimmed.lastIndexOf('(') - if (open < 0 || !trimmed.endsWith(')')) { + const hasIsin = open >= 0 && trimmed.endsWith(')') + if (!hasIsin && isinRequired) { return { unitPrice: null, isin: null } } - const priceAndCurrency = splitTrailingCurrency(trimmed.slice(0, open).trim()) + const priceAndCurrency = splitTrailingCurrency(hasIsin ? trimmed.slice(0, open).trim() : trimmed) if (!priceAndCurrency) { return { unitPrice: null, isin: null } } @@ -70,7 +77,7 @@ function parsePriceTail( const price = dialect.parseDecimal(priceAndCurrency.head) return { unitPrice: price === null ? null : new Money(price, priceAndCurrency.currency), - isin: trimmed.slice(open + 1, -1).trim() || null, + isin: hasIsin ? trimmed.slice(open + 1, -1).trim() || null : null, } } @@ -78,25 +85,43 @@ function parseTradeBody( qtyAndProduct: string, priceTail: string, dialect: Dialect, + isinRequired: boolean, ): ParsedTradeShape { const qtyMatch = LEADING_QTY.exec(qtyAndProduct) const quantity = qtyMatch ? parseQuantity(qtyMatch[0].replace(QTY_GROUPING, ''), dialect) : null const rest = qtyMatch ? qtyAndProduct.slice(qtyMatch[0].length) : qtyAndProduct - return { quantity, product: rest.trim() || null, ...parsePriceTail(priceTail, dialect) } + return { + quantity, + product: rest.trim() || null, + ...parsePriceTail(priceTail, dialect, isinRequired), + } } -function splitAtPrice(text: string, from: number): { left: string, right: string } | null { - const at = text.indexOf('@', from) - if (at <= 0 || at === text.length - 1) { +function splitAtPrice( + text: string, + from: number, + separators: readonly string[], +): { left: string, right: string } | null { + let at = -1 + let length = 0 + for (const separator of separators) { + const index = text.indexOf(separator, from) + if (index >= 0 && (at < 0 || index < at)) { + at = index + length = separator.length + } + } + if (at <= 0 || at + length >= text.length) { return null } - return { left: text.slice(from, at), right: text.slice(at + 1) } + return { left: text.slice(from, at), right: text.slice(at + length) } } /** * Parse a trade description such as - * `"Achat 42 iShares Core MSCI World UCITS ETF USD (Acc)@96,11 CHF (IE00B4L5Y983)"`. + * `"Achat 42 iShares Core MSCI World UCITS ETF USD (Acc)@96,11 CHF (IE00B4L5Y983)"`, + * `"Koop 15 @ 76,50 EUR"` or `"Kauf 1 zu je 211 USD (US88160R1014)"`. * Returns `null` when the text is not a trade. */ export function parseTradeDescription(description: string, dialect: Dialect): ParsedTrade | null { @@ -106,13 +131,13 @@ export function parseTradeDescription(description: string, dialect: Dialect): Pa return null } - const split = splitAtPrice(trimmed, verb[0].length) + const split = splitAtPrice(trimmed, verb[0].length, LABELLED_PRICE_SEPARATORS) if (!split) { return null } const side = BUY_SIDE.test(verb[1] ?? '') ? 'buy' : 'sell' - return { side, ...parseTradeBody(split.left, split.right, dialect) } + return { side, ...parseTradeBody(split.left, split.right, dialect, false) } } export interface ParsedUnlabelledTrade extends ParsedTradeShape { @@ -129,14 +154,14 @@ export function parseUnlabelledTradeDescription( return null } - const split = splitAtPrice(trimmed, quantity) + const split = splitAtPrice(trimmed, quantity, UNLABELLED_PRICE_SEPARATORS) if (!split) { return null } return { prefix: trimmed.slice(0, quantity).trim(), - ...parseTradeBody(split.left, split.right, dialect), + ...parseTradeBody(split.left, split.right, dialect, true), } } @@ -184,32 +209,46 @@ export interface ParsedCashTransfer { readonly amount: Money | null } +function cashTransferDirection(text: string): ParsedCashTransfer['direction'] | null { + if (TO_CASH_ACCOUNT.test(text)) { + return 'toCashAccount' + } + if (FROM_CASH_ACCOUNT.test(text)) { + return 'fromCashAccount' + } + return null +} + +function trailingAmount(text: string): string { + let start = text.length + while (start > 0 && AMOUNT_CHAR.test(text.charAt(start - 1))) { + start -= 1 + } + return text.slice(start).trim() +} + /** * Parse a cash-transfer description such as - * `"Virement depuis votre Compte Espèces à la flatexDEGIRO Bank: 213,25 EUR"`. + * `"Virement depuis votre Compte Espèces à la flatexDEGIRO Bank: 213,25 EUR"`, with + * or without the colon before the amount. */ export function parseCashTransferDescription( description: string, dialect: Dialect, ): ParsedCashTransfer | null { const trimmed = description.trim() - const match = CASH_TRANSFER.exec(trimmed) - if (!match) { - return null - } - - const colon = trimmed.lastIndexOf(':') - if (colon < 0) { + const direction = cashTransferDirection(trimmed) + if (direction === null) { return null } - const stated = splitTrailingCurrency(trimmed.slice(colon + 1).trim()) - if (!stated || !DIGIT.test(stated.head.charAt(0))) { + const stated = splitTrailingCurrency(trimmed) + const amountText = stated ? trailingAmount(stated.head) : '' + if (!stated || !DIGIT.test(amountText.charAt(0))) { return null } - const direction = TO_CASH_ACCOUNT.test(match[1] ?? '') ? 'toCashAccount' : 'fromCashAccount' - const decimal = dialect.parseDecimal(stated.head) + const decimal = dialect.parseDecimal(amountText) const amount = decimal === null ? null : new Money(decimal, stated.currency) return { direction, amount } diff --git a/src/classify/matchers/cash.ts b/src/classify/matchers/cash.ts index 9ac37e0..720c32d 100644 --- a/src/classify/matchers/cash.ts +++ b/src/classify/matchers/cash.ts @@ -1,9 +1,11 @@ import { parseCashTransferDescription } from '../descriptions' import type { Matcher } from '../types' -const CASH_SWEEP = /^degiro cash sweep transfer/i -const DEPOSIT = /^(?:versement de fonds|(?:processed\s+)?(?:flatex\s+)?deposit)\b/i -const WITHDRAWAL = /^(?:retrait de fonds|(?:processed\s+)?(?:flatex\s+)?withdrawal)\b/i +const CASH_SWEEP = /^(?:degiro|flatex) cash sweep transfer/i +const DEPOSIT = + /^(?:versement de fonds|d[ée]p[ôo]t flatex|(?:processed\s+)?(?:flatex\s+|ideal\s+)?deposit|(?:ideal|flatex)\s+storting|(?:sofort\s+|flatex\s+)?einzahlung|ingreso(?!\s+cambio\b)|deposito|vklad)\b/i +const WITHDRAWAL = + /^(?:retrait de fonds|(?:processed\s+)?(?:flatex\s+)?withdrawal|flatex\s+terugstorting|auszahlung|prelievo(?!\s+fx\b))\b/i /** Matches a cash sweep between the DEGIRO account and the cash account. */ export const cashSweepMatcher: Matcher = { diff --git a/src/classify/matchers/dividend.ts b/src/classify/matchers/dividend.ts index ccf23b3..2e04905 100644 --- a/src/classify/matchers/dividend.ts +++ b/src/classify/matchers/dividend.ts @@ -1,8 +1,10 @@ import type { Matcher } from '../types' -const DIVIDEND_TAX = /^(?:imp[oô]ts? sur (?:le )?dividende|dividend tax|withholding tax)/i -const DIVIDEND = /^dividende?\b/i -const CAPITAL_RETURN = /^(?:remboursement de capital|capital return|return of capital)/i +const DIVIDEND_TAX = + /^(?:imp[oô]ts? sur (?:le )?dividende|dividend tax|withholding tax|dividendbelasting|dividendensteuer|retenci[óo]n del dividendo|ritenuta sul dividendo)/i +const DIVIDEND = /^(?:dividend[aeo]?\b|fondsaussch[üu]ttung)/i +const CAPITAL_RETURN = + /^(?:remboursement de capital|capital return|return of capital|kapitalr[üu]ckzahlung|kapitaalsuitkering)/i /** Matches dividend tax withholding (`Impôts sur dividende`). */ export const dividendTaxMatcher: Matcher = { diff --git a/src/classify/matchers/fees.ts b/src/classify/matchers/fees.ts index 42e2719..f6fdcfe 100644 --- a/src/classify/matchers/fees.ts +++ b/src/classify/matchers/fees.ts @@ -1,9 +1,10 @@ import { extractYear } from '../descriptions' import type { Matcher } from '../types' -const BROKERAGE = /^(?:frais degiro de courtage|degiro transaction)/i +const BROKERAGE = + /^(?:frais degiro de courtage|degiro transaction|degiro transactiekosten|(?:degiro )?transaktionsgeb[üu]hr|costes de transacci[óo]n|degiro commissioni di transazione|comiss[õo]es de transa[çc][ãa]o)/i const CONNECTIVITY = - /^(?:frais de connexion aux places boursi[èe]res|degiro exchange connect(?:ion|ivity) fee)/i + /^(?:frais de connexion aux places boursi[èe]res|(?:de)?giro exchange connect(?:ion|ivity) fee|degiro aansluitingskosten|einrichtung von handelsmodalit[äa]ten|degiro costi di connessione|degiro poplatek za obchodov[áa]n[íi] na zahrani[čc]n[íi]ch burz[áa]ch)/i /** Matches a brokerage / third-party transaction fee. */ export const brokerageFeeMatcher: Matcher = { diff --git a/src/classify/matchers/fx.ts b/src/classify/matchers/fx.ts index 699e14e..5386b23 100644 --- a/src/classify/matchers/fx.ts +++ b/src/classify/matchers/fx.ts @@ -1,9 +1,31 @@ +import type { Money } from '../../money/money' import { parseFxTradeDescription } from '../descriptions' import type { Matcher } from '../types' /** `Opération de change - Crédit/Débit` (accent spelling varies between legs). */ -const FX_CONVERSION = - /^(?:op[ée]ration de change|currency exchange|fx)[\s(-]*(cr[ée]dit|d[ée]bit)/i +const FX_CREDIT = + /^(?:(?:op[ée]ration de change|currency exchange|fx)[\s(-]*cr[ée]dit|valuta creditering|w[äa]hrungswechsel \(einbuchung\)|ingreso cambio de divisa|credito fx|cr[ée]dito de divisa)/i +const FX_DEBIT = + /^(?:(?:op[ée]ration de change|currency exchange|fx)[\s(-]*d[ée]bit|valuta debitering|w[äa]hrungswechsel \(ausbuchung\)|retirada cambio de divisa|prelievo fx|levantamento de divisa)/i +/** Czech names both legs alike, so only the sign tells them apart. */ +const FX_EITHER_LEG = /^fx vy[uú][čc]tov[áa]n[íi] konverze m[ěe]ny/i + +function directionFromSign(mutation: Money | null): 'credit' | 'debit' | null { + if (mutation === null || mutation.isZero()) { + return null + } + return mutation.isNegative() ? 'debit' : 'credit' +} + +function conversionDirection(description: string, mutation: Money | null): 'credit' | 'debit' | null { + if (FX_CREDIT.test(description)) { + return 'credit' + } + if (FX_DEBIT.test(description)) { + return 'debit' + } + return FX_EITHER_LEG.test(description) ? directionFromSign(mutation) : null +} /** Matches a currency-pair trade (`Achat/Vente EUR/CHF@ CCY`). */ export const fxTradeMatcher: Matcher = { @@ -32,14 +54,13 @@ export const fxTradeMatcher: Matcher = { export const fxConversionMatcher: Matcher = { name: 'fxConversion', match({ record }) { - const match = FX_CONVERSION.exec(record.description.trim()) - if (!match) { + const direction = conversionDirection(record.description.trim(), record.mutation) + if (direction === null) { return null } - const isCredit = /cr[ée]dit/i.test(match[1] ?? '') return { - kind: isCredit ? 'fxCredit' : 'fxDebit', - direction: isCredit ? 'credit' : 'debit', + kind: direction === 'credit' ? 'fxCredit' : 'fxDebit', + direction, rate: record.fxRate, orderId: record.orderId, amount: record.mutation, diff --git a/src/classify/matchers/interest.ts b/src/classify/matchers/interest.ts index 17e1d3f..68e6030 100644 --- a/src/classify/matchers/interest.ts +++ b/src/classify/matchers/interest.ts @@ -1,6 +1,6 @@ import type { Matcher } from '../types' -const INTEREST = /interest income|^flatex interest\b/i +const INTEREST = /interest income|^(?:flatex interest|interest|rente|zinsen|interesse)\b/i /** Matches interest credited or charged (`Flatex Interest Income`, `Flatex Interest`). */ export const interestMatcher: Matcher = { diff --git a/src/classify/matchers/trade.ts b/src/classify/matchers/trade.ts index e2663a2..125b921 100644 --- a/src/classify/matchers/trade.ts +++ b/src/classify/matchers/trade.ts @@ -1,13 +1,23 @@ import { parseTradeDescription } from '../descriptions' import type { Matcher } from '../types' +const FX_PAIR = /^[A-Za-z]{3}\/[A-Za-z]{3}$/ + +function isFxPair(product: string | null): boolean { + return product !== null && FX_PAIR.test(product) +} + /** Matches a security buy/sell (`Achat`/`Vente` of an instrument carrying an ISIN). */ export const tradeMatcher: Matcher = { name: 'trade', match({ record, dialect }) { const parsed = parseTradeDescription(record.description, dialect) + if (!parsed || isFxPair(parsed.product) || isFxPair(record.product)) { + return null + } // Security trades always carry an ISIN; FX pair trades do not. - if (!parsed || parsed.isin === null) { + const isin = record.isin ?? parsed.isin + if (isin === null) { return null } return { @@ -16,7 +26,7 @@ export const tradeMatcher: Matcher = { quantity: parsed.quantity ?? 0, unitPrice: parsed.unitPrice, product: record.product ?? parsed.product, - isin: record.isin ?? parsed.isin, + isin, orderId: record.orderId, amount: record.mutation, record, diff --git a/src/dialects/de.ts b/src/dialects/de.ts new file mode 100644 index 0000000..43c5d39 --- /dev/null +++ b/src/dialects/de.ts @@ -0,0 +1,32 @@ +import type { CsvRow } from '../csv/tokenizer' +import { + DEGIRO_COLUMNS, + hasHeaderTokens, + parseDegiroDateTime, + parseFlexibleDecimal, +} from './common' +import type { Dialect } from './types' + +const GERMAN_HEADER_TOKENS = [ + 'Datum', + 'Uhrzeit', + 'Produkt', + 'ISIN', + 'Beschreibung', + 'Änderung', + 'Saldo', +] as const + +export const germanDialect: Dialect = { + id: 'de', + label: 'DEGIRO German (Account.csv)', + columns: DEGIRO_COLUMNS, + matches(header: CsvRow): boolean { + return hasHeaderTokens(header, GERMAN_HEADER_TOKENS) + }, + parseDecimal: parseFlexibleDecimal, + parseDateTime: parseDegiroDateTime, + parseDate(date: string): Date | null { + return parseDegiroDateTime(date) + }, +} diff --git a/src/dialects/es.ts b/src/dialects/es.ts new file mode 100644 index 0000000..688e40e --- /dev/null +++ b/src/dialects/es.ts @@ -0,0 +1,32 @@ +import type { CsvRow } from '../csv/tokenizer' +import { + DEGIRO_COLUMNS, + hasHeaderTokens, + parseDegiroDateTime, + parseFlexibleDecimal, +} from './common' +import type { Dialect } from './types' + +const SPANISH_HEADER_TOKENS = [ + 'Fecha', + 'Hora', + 'Producto', + 'ISIN', + 'Descripción', + 'Variación', + 'Saldo', +] as const + +export const spanishDialect: Dialect = { + id: 'es', + label: 'DEGIRO Spanish (Account.csv)', + columns: DEGIRO_COLUMNS, + matches(header: CsvRow): boolean { + return hasHeaderTokens(header, SPANISH_HEADER_TOKENS) + }, + parseDecimal: parseFlexibleDecimal, + parseDateTime: parseDegiroDateTime, + parseDate(date: string): Date | null { + return parseDegiroDateTime(date) + }, +} diff --git a/src/dialects/index.ts b/src/dialects/index.ts index 15761cd..d03e89f 100644 --- a/src/dialects/index.ts +++ b/src/dialects/index.ts @@ -1,6 +1,9 @@ export * from './common' +export * from './de' export * from './en' +export * from './es' export * from './fr' export * from './generic' +export * from './nl' export * from './registry' export * from './types' diff --git a/src/dialects/nl.ts b/src/dialects/nl.ts new file mode 100644 index 0000000..ae830c0 --- /dev/null +++ b/src/dialects/nl.ts @@ -0,0 +1,28 @@ +import type { CsvRow } from '../csv/tokenizer' +import { + DEGIRO_COLUMNS, + hasHeaderTokens, + parseDegiroDateTime, + parseFlexibleDecimal, +} from './common' +import type { Dialect } from './types' + +const DUTCH_HEADER_TOKENS = ['Datum', 'Tijd', 'Product', 'ISIN', 'Mutatie', 'Saldo'] as const +const DUTCH_DESCRIPTION_LABELS = ['Omschrijving', 'Beschrijving'] as const + +export const dutchDialect: Dialect = { + id: 'nl', + label: 'DEGIRO Dutch (Account.csv)', + columns: DEGIRO_COLUMNS, + matches(header: CsvRow): boolean { + return ( + hasHeaderTokens(header, DUTCH_HEADER_TOKENS) && + DUTCH_DESCRIPTION_LABELS.some((label) => hasHeaderTokens(header, [label])) + ) + }, + parseDecimal: parseFlexibleDecimal, + parseDateTime: parseDegiroDateTime, + parseDate(date: string): Date | null { + return parseDegiroDateTime(date) + }, +} diff --git a/src/dialects/registry.ts b/src/dialects/registry.ts index f562937..b54e857 100644 --- a/src/dialects/registry.ts +++ b/src/dialects/registry.ts @@ -1,8 +1,11 @@ import type { CsvRow } from '../csv/tokenizer' import { UnknownDialectError } from '../errors' +import { germanDialect } from './de' import { englishDialect } from './en' +import { spanishDialect } from './es' import { frenchDialect } from './fr' import { genericDialect } from './generic' +import { dutchDialect } from './nl' import type { Dialect } from './types' /** Options for registering a dialect. */ @@ -64,7 +67,14 @@ export class DialectRegistry { /** Registry pre-populated with all built-in dialects. */ export function createDefaultDialectRegistry(): DialectRegistry { - return new DialectRegistry([frenchDialect, englishDialect, genericDialect]) + return new DialectRegistry([ + frenchDialect, + englishDialect, + dutchDialect, + germanDialect, + spanishDialect, + genericDialect, + ]) } /** Shared registry containing the built-in dialects. */ diff --git a/test/classify.test.ts b/test/classify.test.ts index 789ab82..94ded61 100644 --- a/test/classify.test.ts +++ b/test/classify.test.ts @@ -6,14 +6,24 @@ import { describe, expect,it } from 'vitest' import { createDefaultClassifierRegistry, defaultClassifier, + depositMatcher, + type Dialect, + dividendMatcher, + dutchDialect, englishDialect, frenchDialect, + genericDialect, + germanDialect, mapRow, type Matcher, Money, type Movement, + type MovementKind, type RawRecord, + spanishDialect, tokenizeCsv, + tradeMatcher, + withdrawalMatcher, } from '../src/index' const fixture = readFileSync( @@ -49,6 +59,26 @@ function record(description: string, overrides: Partial = {}): RawRec } } +function itClassifies(dialect: Dialect, cases: readonly (readonly [string, MovementKind])[]): void { + it.each(cases)('classifies "%s" as %s', (description, kind) => { + expect(defaultClassifier.classify(record(description), dialect).kind).toBe(kind) + }) +} + +function itReadsCashTransfers( + dialect: Dialect, + cases: readonly (readonly [string, 'toCashAccount' | 'fromCashAccount', string])[], +): void { + it.each(cases)('reads "%s" as a transfer %s of %s', (description, direction, stated) => { + const movement = defaultClassifier.classify(record(description), dialect) + expect(movement.kind).toBe('cashTransfer') + if (movement.kind === 'cashTransfer') { + expect(movement.direction).toBe(direction) + expect(movement.statedAmount?.toString()).toBe(stated) + } + }) +} + describe('classification of the full sample export', () => { it('classifies every row (no unknown movements)', () => { const movements = classifyAll() @@ -294,6 +324,284 @@ describe('English descriptions', () => { }) }) +describe('Dutch descriptions', () => { + const classify = (rec: RawRecord) => defaultClassifier.classify(rec, dutchDialect) + + itClassifies(dutchDialect, [ + ['DEGIRO Transactiekosten en/of kosten van derden', 'brokerageFee'], + ['DEGIRO Transactiekosten', 'brokerageFee'], + ['DEGIRO Aansluitingskosten 2021 (Borsa Italiana S.p.A. - MIL)', 'connectivityFee'], + ['Valuta Creditering', 'fxCredit'], + ['Valuta Debitering', 'fxDebit'], + ['Dividend', 'dividend'], + ['Dividendbelasting', 'dividendTax'], + ['Kapitaalsuitkering', 'capitalReturn'], + ['Rente', 'interest'], + ['iDEAL Deposit', 'deposit'], + ['iDEAL storting', 'deposit'], + ['flatex Storting', 'deposit'], + ['flatex terugstorting', 'withdrawal'], + ]) + + itReadsCashTransfers(dutchDialect, [ + ['Overboeking naar uw geldrekening bij flatexDEGIRO Bank: 0,92 EUR', 'toCashAccount', '0.92 EUR'], + ['Overboeking van uw geldrekening bij flatexDEGIRO Bank: 213,25 EUR', 'fromCashAccount', '213.25 EUR'], + ['Overboeking van uw geldrekening bij flatexDEGIRO Bank 26,45 EUR', 'fromCashAccount', '26.45 EUR'], + ]) + + it('reads a buy that names neither product nor ISIN from the columns', () => { + // Given + const row = record('Koop 15 @ 76,50 EUR', { + product: 'VANGUARD FTSE ALL-WORLD UCITS ETF', + isin: 'IE00B3RBWM25', + mutation: Money.of('-1147.50', 'EUR'), + }) + + // When + const movement = classify(row) + + // Then + expect(movement.kind).toBe('buy') + if (movement.kind === 'buy') { + expect(movement.quantity).toBe(15) + expect(movement.unitPrice?.toString()).toBe('76.5 EUR') + expect(movement.product).toBe('VANGUARD FTSE ALL-WORLD UCITS ETF') + expect(movement.isin).toBe('IE00B3RBWM25') + } + }) + + it('reads a sell from its verb', () => { + // Given + const row = record('Verkoop 7 @ 112,40 EUR', { isin: 'IE00B3RBWM25' }) + + // When + const movement = classify(row) + + // Then + expect(movement.kind).toBe('sell') + if (movement.kind === 'sell') { + expect(movement.quantity).toBe(7) + expect(movement.unitPrice?.toString()).toBe('112.4 EUR') + } + }) + + it('leaves a trade with no ISIN anywhere unknown', () => { + expect(classify(record('Koop 15 @ 76,50 EUR')).kind).toBe('unknown') + }) + + it('reads a currency pair as an FX trade, never a security trade', () => { + // Given + const row = record('Koop 4.800 EUR/CHF@0,9412 CHF ()', { product: 'EUR/CHF', isin: 'IE00B3RBWM25' }) + + // When + const movement = classify(row) + const asSecurity = tradeMatcher.match({ record: row, dialect: dutchDialect }) + + // Then + expect(movement.kind).toBe('fxTrade') + expect(asSecurity).toBeNull() + }) + + it('does not read an FX pair in the product column as a security trade', () => { + // Given + const row = record('Koop 100 @ 0,94 CHF', { product: 'EUR/CHF', isin: 'IE00B3RBWM25' }) + + // When + const movement = tradeMatcher.match({ record: row, dialect: dutchDialect }) + + // Then + expect(movement).toBeNull() + }) +}) + +describe('German descriptions', () => { + const classify = (rec: RawRecord) => defaultClassifier.classify(rec, germanDialect) + + itClassifies(germanDialect, [ + ['Transaktionsgebühr', 'brokerageFee'], + ['DEGIRO Transaktionsgebühren und/oder Fremdkosten', 'brokerageFee'], + ['Einrichtung von Handelsmodalitäten 2019 (New York Stock Exchange - NSY)', 'connectivityFee'], + ['Währungswechsel (Einbuchung)', 'fxCredit'], + ['Währungswechsel (Ausbuchung)', 'fxDebit'], + ['Dividende', 'dividend'], + ['Fondsausschüttung', 'dividend'], + ['Dividendensteuer', 'dividendTax'], + ['Kapitalrückzahlung', 'capitalReturn'], + ['Zinsen für Leerverkauf', 'interest'], + ['Einzahlung', 'deposit'], + ['SOFORT Einzahlung', 'deposit'], + ['flatex Einzahlung', 'deposit'], + ['Auszahlung', 'withdrawal'], + ['flatex Cash Sweep Transfer', 'cashSweep'], + ]) + + itReadsCashTransfers(germanDialect, [ + ['Überweisung auf Ihr Geldkonto bei der flatex Bank: 2,37 EUR', 'toCashAccount', '2.37 EUR'], + ['Auszahlung von Ihrem Geldkonto bei der flatex Bank: 542,8 EUR', 'fromCashAccount', '542.8 EUR'], + ]) + + it('extracts the year of a connectivity fee', () => { + const movement = classify(record('Einrichtung von Handelsmodalitäten 2019 (New York Stock Exchange - NSY)')) + expect(movement.kind === 'connectivityFee' && movement.year).toBe(2019) + }) + + it('reads a buy that names no product, taking the ISIN from the description', () => { + // Given + const row = record('Kauf 1 zu je 211 USD (US88160R1014)', { product: 'TESLA INC' }) + + // When + const movement = classify(row) + + // Then + expect(movement.kind).toBe('buy') + if (movement.kind === 'buy') { + expect(movement.quantity).toBe(1) + expect(movement.unitPrice?.toString()).toBe('211 USD') + expect(movement.product).toBe('TESLA INC') + expect(movement.isin).toBe('US88160R1014') + } + }) + + it('reads a sell from its verb', () => { + // Given + const row = record('Verkauf 25 zu je 67,4 USD (US0378331005)') + + // When + const movement = classify(row) + + // Then + expect(movement.kind).toBe('sell') + if (movement.kind === 'sell') { + expect(movement.quantity).toBe(25) + expect(movement.unitPrice?.toString()).toBe('67.4 USD') + expect(movement.isin).toBe('US0378331005') + } + }) +}) + +describe('Spanish descriptions', () => { + itClassifies(spanishDialect, [ + ['Costes de transacción y/o externos de DEGIRO', 'brokerageFee'], + ['Ingreso Cambio de Divisa', 'fxCredit'], + ['Retirada Cambio de Divisa', 'fxDebit'], + ['Dividendo', 'dividend'], + ['Retención del dividendo', 'dividendTax'], + ['Ingreso', 'deposit'], + ]) + + itReadsCashTransfers(spanishDialect, [ + ['Transferir a su Cuenta de Efectivo en flatexDEGIRO Bank: 43,9 EUR', 'toCashAccount', '43.9 EUR'], + ['Transferir desde su Cuenta de Efectivo en flatexDEGIRO Bank: 12,5 EUR', 'fromCashAccount', '12.5 EUR'], + ]) +}) + +describe('Italian descriptions', () => { + itClassifies(genericDialect, [ + ['DEGIRO Commissioni di transazione e/o di terze parti', 'brokerageFee'], + ['DEGIRO Costi di connessione 2021 (Xetra - XET)', 'connectivityFee'], + ['Credito FX', 'fxCredit'], + ['Prelievo FX', 'fxDebit'], + ['Dividendo', 'dividend'], + ['Ritenuta sul dividendo', 'dividendTax'], + ['Interesse', 'interest'], + ['Deposito', 'deposit'], + ['Deposito flatex', 'deposit'], + ['Prelievo', 'withdrawal'], + ['Prelievo flatex', 'withdrawal'], + ]) + + itReadsCashTransfers(genericDialect, [ + ['Trasferisci sul tuo conto deposito presso flatexDEGIRO Bank: 7,25 EUR', 'toCashAccount', '7.25 EUR'], + ['Trasferisci dal tuo conto deposito presso flatexDEGIRO Bank: 1.250,5 EUR', 'fromCashAccount', '1250.5 EUR'], + ]) +}) + +describe('Czech descriptions', () => { + const classify = (rec: RawRecord) => defaultClassifier.classify(rec, genericDialect) + + itClassifies(genericDialect, [ + ['DEGIRO poplatek za Obchodování na zahraničních burzách 2023 (Borsa Italiana - MIL)', 'connectivityFee'], + ['Dividenda', 'dividend'], + ['Vklad', 'deposit'], + ]) + + it.each([ + ['FX vyučtování konverze měny', '125.40', 'fxCredit'], + ['FX vyučtování konverze měny', '-115.00', 'fxDebit'], + ['FX vyúčtování konverze měny', '-115.00', 'fxDebit'], + ] as const)('takes "%s" of %s as %s from the sign', (description, amount, kind) => { + expect(classify(record(description, { mutation: Money.of(amount, 'EUR') })).kind).toBe(kind) + }) + + it('leaves an FX leg with no amount to sign unknown', () => { + expect(classify(record('FX vyučtování konverze měny')).kind).toBe('unknown') + }) +}) + +describe('Portuguese descriptions', () => { + itClassifies(genericDialect, [ + ['Comissões de transação DEGIRO e/ou taxas de terceiros', 'brokerageFee'], + ['Crédito de divisa', 'fxCredit'], + ['Levantamento de divisa', 'fxDebit'], + ]) +}) + +describe('French and English wordings seen in other statements', () => { + itClassifies(englishDialect, [ + ['Dépôt flatex', 'deposit'], + ['Giro Exchange Connection Fee 2022', 'connectivityFee'], + ['Interest', 'interest'], + ]) +}) + +describe('wordings that share a prefix with another kind', () => { + it.each(['Dividendbelasting', 'Dividendensteuer', 'Retención del dividendo', 'Ritenuta sul dividendo'])( + 'never reads the tax row "%s" as a dividend', + (description) => { + expect(dividendMatcher.match({ record: record(description), dialect: genericDialect })).toBeNull() + }, + ) + + it('never reads a Spanish FX credit as a deposit', () => { + expect( + depositMatcher.match({ record: record('Ingreso Cambio de Divisa'), dialect: spanishDialect }), + ).toBeNull() + }) + + it('never reads an Italian FX debit as a withdrawal', () => { + expect(withdrawalMatcher.match({ record: record('Prelievo FX'), dialect: genericDialect })).toBeNull() + }) +}) + +describe('rows that need a new kind', () => { + it.each([ + 'Koersverandering geldmarktfonds (EUR)', + 'Conversie geldmarktfonds: Koop 100 @ 1 EUR', + 'Geldmarktfonds Umwandlung: Kauf 709,65 zu je 1 EUR', + 'STOCK SPLIT: Koop 4 @ 25 EUR', + 'DELISTING: Verkauf 4 zu je 0 EUR', + 'Transactiebelasting', + 'Französische Transaktionssteuer', + 'Verrekening Welkomstactie', + 'SOFORT Zahlungsgebühr', + 'ADR/GDR Externe Kosten', + 'Coupon', + 'Meegekochte Rente', + 'Vervangende Betaling', + 'Belasting op vervangend dividend', + 'Reservation iDEAL / Sofort Deposit', + ])('leaves "%s" unknown', (description) => { + // Given + const row = record(description, { isin: 'IE00B3RBWM25', mutation: Money.of('-100', 'EUR') }) + + // When + const movement = defaultClassifier.classify(row, genericDialect) + + // Then + expect(movement.kind).toBe('unknown') + }) +}) + describe('classifier extensibility', () => { it('classifies an otherwise-unknown description via a custom matcher', () => { // A referral bonus is not understood by the built-ins... diff --git a/test/dialect.test.ts b/test/dialect.test.ts index ff1ec9c..c24ea8c 100644 --- a/test/dialect.test.ts +++ b/test/dialect.test.ts @@ -4,14 +4,17 @@ import { createDefaultDialectRegistry, type Dialect, DialectRegistry, + dutchDialect, englishDialect, frenchDialect, genericDialect, + germanDialect, matchesDegiroLayout, parseFlexibleDateTime, parseFlexibleDecimal, parseFrenchDateTime, parseFrenchDecimal, + spanishDialect, UnknownDialectError, } from '../src/index' @@ -135,6 +138,104 @@ describe('englishDialect', () => { }) }) +const dutchHeader = [ + 'Datum', + 'Tijd', + 'Valutadatum', + 'Product', + 'ISIN', + 'Omschrijving', + 'FX', + 'Mutatie', + '', + 'Saldo', + '', + 'Order Id', +] + +const germanHeader = [ + 'Datum', + 'Uhrzeit', + 'Wertstellungsdatum', + 'Produkt', + 'ISIN', + 'Beschreibung', + 'FX', + 'Änderung', + '', + 'Saldo', + '', + 'Auftrag ID', +] + +const spanishHeader = [ + 'Fecha', + 'Hora', + 'Fecha valor', + 'Producto', + 'ISIN', + 'Descripción', + 'Tipo', + 'Variación', + '', + 'Saldo', + '', + 'ID Orden', +] + +const italianHeader = [ + 'Data', + 'Ora', + 'Data Valore', + 'Prodotto', + 'ISIN', + 'Descrizione', + 'Borsa', + 'Variazioni', + '', + 'Saldo', + '', + 'ID Ordine', +] + +describe.each([ + ['nl', dutchDialect, dutchHeader], + ['de', germanDialect, germanHeader], + ['es', spanishDialect, spanishHeader], +] as const)('the %s dialect', (id, dialect, header) => { + const others = [frenchHeader, englishHeader, dutchHeader, germanHeader, spanishHeader, italianHeader] + + it('matches its own header and no other', () => { + expect(others.filter((candidate) => dialect.matches(candidate))).toEqual([header]) + }) + + it('is detected by the default registry instead of the fallback', () => { + expect(createDefaultDialectRegistry().detect(header).id).toBe(id) + expect(dialect.heuristic).toBeUndefined() + }) + + it('shares the positional layout with the French dialect', () => { + expect(dialect.columns).toEqual(frenchDialect.columns) + }) + + it('reads DD-MM-YYYY dates as UTC and both number formats', () => { + expect(dialect.parseDateTime('01-02-2025', '12:21')?.toISOString()).toBe( + '2025-02-01T12:21:00.000Z', + ) + expect(dialect.parseDecimal('-1.147,50')).toBe('-1147.50') + expect(dialect.parseDecimal('-1,147.50')).toBe('-1147.50') + }) +}) + +describe('dutchDialect', () => { + it('matches the variant header that says Beschrijving and Order ID', () => { + const variant = dutchHeader.map((cell) => + cell === 'Omschrijving' ? 'Beschrijving' : cell === 'Order Id' ? 'Order ID' : cell, + ) + expect(dutchDialect.matches(variant)).toBe(true) + }) +}) + describe('parseFlexibleDateTime', () => { it('reads the DEGIRO DD-MM-YYYY format', () => { expect(parseFlexibleDateTime('01-02-2025', '12:21')?.toISOString()).toBe( @@ -154,24 +255,9 @@ describe('parseFlexibleDateTime', () => { }) describe('genericDialect', () => { - const dutchHeader = [ - 'Datum', - 'Tijd', - 'Valutadatum', - 'Product', - 'ISIN', - 'Omschrijving', - 'FX', - 'Mutatie', - '', - 'Saldo', - '', - 'Order Id', - ] - it('recognises a header in a language it has never seen', () => { - expect(genericDialect.matches(dutchHeader)).toBe(true) - expect(matchesDegiroLayout(dutchHeader)).toBe(true) + expect(genericDialect.matches(italianHeader)).toBe(true) + expect(matchesDegiroLayout(italianHeader)).toBe(true) }) it('recognises the French and English headers too, being a superset', () => { @@ -187,16 +273,16 @@ describe('genericDialect', () => { it('rejects anything that is not the DEGIRO column layout', () => { expect(genericDialect.matches(['Date', 'Amount', 'Balance'])).toBe(false) - expect(genericDialect.matches([...dutchHeader, 'Extra'])).toBe(false) - expect(genericDialect.matches(dutchHeader.map((c, i) => (i === 3 ? '' : c)))).toBe(false) - expect(genericDialect.matches(dutchHeader.map((c, i) => (i === 8 ? 'Filled' : c)))).toBe(false) + expect(genericDialect.matches([...italianHeader, 'Extra'])).toBe(false) + expect(genericDialect.matches(italianHeader.map((c, i) => (i === 3 ? '' : c)))).toBe(false) + expect(genericDialect.matches(italianHeader.map((c, i) => (i === 8 ? 'Filled' : c)))).toBe(false) }) it('is matched only after the language-aware dialects', () => { const registry = createDefaultDialectRegistry() expect(registry.detect(frenchHeader).id).toBe('fr') expect(registry.detect(englishHeader).id).toBe('en') - expect(registry.detect(dutchHeader).id).toBe('generic') + expect(registry.detect(italianHeader).id).toBe('generic') }) }) @@ -225,6 +311,6 @@ describe('DialectRegistry', () => { } const registry = createDefaultDialectRegistry().register(custom, { prepend: true }) expect(registry.detect(frenchHeader).id).toBe('custom') - expect(registry.all().map((d) => d.id)).toEqual(['custom', 'fr', 'en', 'generic']) + expect(registry.all().map((d) => d.id)).toEqual(['custom', 'fr', 'en', 'nl', 'de', 'es', 'generic']) }) }) diff --git a/test/integration.test.ts b/test/integration.test.ts index 00bcb30..03b8720 100644 --- a/test/integration.test.ts +++ b/test/integration.test.ts @@ -154,18 +154,116 @@ describe('an English export written in English, with US number formatting', () = }) }) +const dutchCsv = [ + 'Datum,Tijd,Valutadatum,Product,ISIN,Omschrijving,FX,Mutatie,,Saldo,,Order Id', + '06-04-2025,07:00,06-04-2025,,,Valuta Creditering,"1,0850",USD,"108,50",USD,"108,50",n3', + '06-04-2025,07:00,06-04-2025,,,Valuta Debitering,"1,0850",EUR,"-100,00",EUR,"156,07",n3', + '05-04-2025,11:00,05-04-2025,,,flatex terugstorting,,EUR,"-500,00",EUR,"256,07",', + '04-04-2025,09:00,04-04-2025,,,Degiro Cash Sweep Transfer,,EUR,"26,45",EUR,"756,07",', + '04-04-2025,09:00,04-04-2025,,,"Overboeking van uw geldrekening bij flatexDEGIRO Bank 26,45 EUR",,,,EUR,"729,62",', + '03-04-2025,09:00,03-04-2025,,,Degiro Cash Sweep Transfer,,EUR,"-256,07",EUR,"756,07",', + '03-04-2025,09:00,03-04-2025,,,"Overboeking naar uw geldrekening bij flatexDEGIRO Bank: 256,07 EUR",,,,EUR,"1012,14",', + '02-04-2025,14:05,02-04-2025,VANGUARD FTSE ALL-WORLD UCITS ETF,IE00B3RBWM25,DEGIRO Transactiekosten en/of kosten van derden,,EUR,"-1,00",EUR,"756,07",n2', + '02-04-2025,14:05,02-04-2025,VANGUARD FTSE ALL-WORLD UCITS ETF,IE00B3RBWM25,"Verkoop 5 @ 80,00 EUR",,EUR,"400,00",EUR,"757,07",n2', + '01-04-2025,10:00,01-04-2025,,,DEGIRO Aansluitingskosten 2025 (Euronext Amsterdam - EAM),,EUR,"-2,50",EUR,"357,07",', + '31-03-2025,23:59,31-03-2025,,,Rente,,EUR,"-0,42",EUR,"359,57",', + '10-03-2025,07:30,10-03-2025,VANGUARD FTSE ALL-WORLD UCITS ETF,IE00B3RBWM25,Dividendbelasting,,EUR,"-1,85",EUR,"359,99",', + '10-03-2025,07:30,10-03-2025,VANGUARD FTSE ALL-WORLD UCITS ETF,IE00B3RBWM25,Dividend,,EUR,"12,34",EUR,"361,84",', + '04-03-2025,09:15,04-03-2025,VANGUARD FTSE ALL-WORLD UCITS ETF,IE00B3RBWM25,DEGIRO Transactiekosten en/of kosten van derden,,EUR,"-3,00",EUR,"349,50",n1', + '04-03-2025,09:15,04-03-2025,VANGUARD FTSE ALL-WORLD UCITS ETF,IE00B3RBWM25,"Koop 15 @ 76,50 EUR",,EUR,"-1147,50",EUR,"352,50",n1', + '03-03-2025,08:00,03-03-2025,,,iDEAL storting,,EUR,"1500,00",EUR,"1500,00",', + '', +].join('\n') + +const germanCsv = [ + 'Datum,Uhrzeit,Wertstellungsdatum,Produkt,ISIN,Beschreibung,FX,Änderung,,Saldo,,Auftrag ID', + '05-04-2025,11:00,05-04-2025,,,Auszahlung,,EUR,"-300,00",EUR,"499,98",', + '03-04-2025,09:00,03-04-2025,,,flatex Cash Sweep Transfer,,EUR,"0,50",EUR,"799,98",', + '03-04-2025,09:00,03-04-2025,,,"Auszahlung von Ihrem Geldkonto bei der flatex Bank: 0,5 EUR",,,,EUR,"799,48",', + '02-04-2025,09:00,02-04-2025,,,flatex Cash Sweep Transfer,,EUR,"-299,98",EUR,"799,98",', + '02-04-2025,09:00,02-04-2025,,,"Überweisung auf Ihr Geldkonto bei der flatex Bank: 299,98 EUR",,,,EUR,"1099,96",', + '01-04-2025,10:00,01-04-2025,,,Einrichtung von Handelsmodalitäten 2025 (New York Stock Exchange - NSY),,EUR,"-2,50",EUR,"799,98",', + '31-03-2025,23:59,31-03-2025,,,Zinsen für Leerverkauf,,EUR,"-0,15",EUR,"802,48",', + '14-03-2025,07:00,14-03-2025,APPLE INC,US0378331005,Dividendensteuer,,USD,"-0,38",USD,"2,12",', + '14-03-2025,07:00,14-03-2025,APPLE INC,US0378331005,Dividende,,USD,"2,50",USD,"2,50",', + '04-03-2025,15:30,04-03-2025,,,Währungswechsel (Ausbuchung),"1,0800",EUR,"-195,37",EUR,"802,63",d1', + '04-03-2025,15:30,04-03-2025,,,Währungswechsel (Einbuchung),"1,0800",USD,"211,00",USD,"0,00",d1', + '04-03-2025,15:30,04-03-2025,TESLA INC,US88160R1014,Transaktionsgebühr,,EUR,"-2,00",EUR,"998,00",d1', + '04-03-2025,15:30,04-03-2025,TESLA INC,US88160R1014,Kauf 1 zu je 211 USD (US88160R1014),,USD,"-211,00",USD,"-211,00",d1', + '03-03-2025,08:00,03-03-2025,,,SOFORT Einzahlung,,EUR,"1000,00",EUR,"1000,00",', + '', +].join('\n') + +const spanishCsv = [ + 'Fecha,Hora,Fecha valor,Producto,ISIN,Descripción,Tipo,Variación,,Saldo,,ID Orden', + '03-04-2025,09:00,03-04-2025,,,Degiro Cash Sweep Transfer,,EUR,"12,50",EUR,"43,90",', + '03-04-2025,09:00,03-04-2025,,,"Transferir desde su Cuenta de Efectivo en flatexDEGIRO Bank: 12,5 EUR",,,,EUR,"31,40",', + '02-04-2025,09:00,02-04-2025,,,Degiro Cash Sweep Transfer,,EUR,"-43,90",EUR,"43,90",', + '02-04-2025,09:00,02-04-2025,,,"Transferir a su Cuenta de Efectivo en flatexDEGIRO Bank: 43,9 EUR",,,,EUR,"87,80",', + '01-04-2025,10:00,01-04-2025,,,Giro Exchange Connection Fee 2025 (Euronext Amsterdam - EAM),,EUR,"-2,50",EUR,"43,90",', + '21-03-2025,07:00,21-03-2025,,,Ingreso Cambio de Divisa,"1,0850",USD,"54,25",USD,"54,25",e2', + '21-03-2025,07:00,21-03-2025,,,Retirada Cambio de Divisa,"1,0850",EUR,"-50,00",EUR,"46,40",e2', + '20-03-2025,07:00,20-03-2025,VANGUARD FTSE ALL-WORLD UCITS ETF,IE00B3RBWM25,Retención del dividendo,,EUR,"-0,80",EUR,"96,40",', + '20-03-2025,07:00,20-03-2025,VANGUARD FTSE ALL-WORLD UCITS ETF,IE00B3RBWM25,Dividendo,,EUR,"4,20",EUR,"97,20",', + '04-03-2025,09:10,04-03-2025,VANGUARD FTSE ALL-WORLD UCITS ETF,IE00B3RBWM25,Costes de transacción y/o externos de DEGIRO,,EUR,"-2,00",EUR,"93,00",e1', + '04-03-2025,09:10,04-03-2025,VANGUARD FTSE ALL-WORLD UCITS ETF,IE00B3RBWM25,"Compra 10 Vanguard FTSE All-World UCITS ETF USD Dis@90,5 EUR (IE00B3RBWM25)",,EUR,"-905,00",EUR,"95,00",e1', + '03-03-2025,08:00,03-03-2025,,,Ingreso,,EUR,"1000,00",EUR,"1000,00",', + '', +].join('\n') + +describe.each([ + [ + 'Dutch', + 'nl', + dutchCsv, + ['fxCredit', 'fxDebit', 'withdrawal', 'cashSweep', 'cashTransfer', 'cashSweep', 'cashTransfer', 'brokerageFee', 'sell', 'connectivityFee', 'interest', 'dividendTax', 'dividend', 'brokerageFee', 'buy', 'deposit'], + ['EUR', 'USD'], + ], + [ + 'German', + 'de', + germanCsv, + ['withdrawal', 'cashSweep', 'cashTransfer', 'cashSweep', 'cashTransfer', 'connectivityFee', 'interest', 'dividendTax', 'dividend', 'fxDebit', 'fxCredit', 'brokerageFee', 'buy', 'deposit'], + ['EUR', 'USD'], + ], + [ + 'Spanish', + 'es', + spanishCsv, + ['cashSweep', 'cashTransfer', 'cashSweep', 'cashTransfer', 'connectivityFee', 'fxCredit', 'fxDebit', 'dividendTax', 'dividend', 'brokerageFee', 'buy', 'deposit'], + ['EUR', 'USD'], + ], +] as const)('end-to-end on a %s export', (_language, id, csv, kinds, currencies) => { + const result = parseDegiroCsv(csv) + + it('detects its dialect and reads every row without an issue', () => { + expect(result.dialect.id).toBe(id) + expect(result.issues).toHaveLength(0) + }) + + it('classifies every row', () => { + expect(result.movements.map((movement) => movement.kind)).toEqual(kinds) + }) + + it('reconciles the running balance of each currency exactly', () => { + const report = reconcileBalances(result.movements) + expect(report.exact).toBe(true) + expect(report.byCurrency.map((currency) => currency.currency).sort((a, b) => a.localeCompare(b))).toEqual(currencies) + }) +}) + describe('an export in a language no dialect knows', () => { - const dutchCsv = [ - 'Datum,Tijd,Valutadatum,Product,ISIN,Omschrijving,FX,Mutatie,,Saldo,,Order Id', - '20-11-2024,09:01,20-11-2024,SMI ETF,CH0019852802,"Koop 1.060 SMI ETF@106,02 CHF (CH0019852802)",,CHF,"-112.381,20",CHF,"7.939,80",o1', - '20-11-2024,09:01,20-11-2024,SMI ETF,CH0019852802,"Verkoop 10 SMI ETF@106,02 CHF (CH0019852802)",,CHF,"1.060,20",CHF,"9.000,00",o2', - '19-11-2024,00:00,19-11-2024,,,"Valuta Creditering","1,0888",CHF,"500,00",CHF,"500,00",o3', - '18-11-2024,00:00,18-11-2024,,,Storting,,CHF,"9.000,00",CHF,"9.000,00",', + const italianCsv = [ + 'Data,Ora,Data Valore,Prodotto,ISIN,Descrizione,Borsa,Variazioni,,Saldo,,ID Ordine', + '20-11-2024,09:01,20-11-2024,SMI ETF,CH0019852802,"Acquisto 1.060 SMI ETF@106,02 CHF (CH0019852802)",,CHF,"-112.381,20",CHF,"7.939,80",o1', + '20-11-2024,09:01,20-11-2024,SMI ETF,CH0019852802,"Vendita 10 SMI ETF@106,02 CHF (CH0019852802)",,CHF,"1.060,20",CHF,"9.000,00",o2', + '19-11-2024,00:00,19-11-2024,,,"Credito FX","1,0888",CHF,"500,00",CHF,"500,00",o3', + '18-11-2024,00:00,18-11-2024,,,"Variazione di prezzo Fondo Comune Monetario (CHF)",,CHF,"9.000,00",CHF,"9.000,00",', '17-11-2024,00:00,17-11-2024,,,"Valutatransactie afwikkeling: Verkoop 1.900 EUR/CHF@0,9412 CHF ()",,EUR,"-1.900,00",EUR,"0,00",o4', '', ].join('\n') - const result = parseDegiroCsv(dutchCsv) + const result = parseDegiroCsv(italianCsv) it('falls back to the positional layout and reads every row', () => { expect(result.dialect.id).toBe('generic') @@ -191,7 +289,6 @@ describe('an export in a language no dialect knows', () => { expect(buy.isin).toBe('CH0019852802') } - // Same Dutch verb shape, opposite mutation sign. expect(result.movements[1]?.kind).toBe('sell') }) @@ -221,7 +318,7 @@ describe('a semicolon-delimited export', () => { it('retries the delimiter when the header tokenizes to one cell', () => { const result = parseDegiroCsv(csv) - expect(result.dialect.id).toBe('generic') + expect(result.dialect.id).toBe('nl') expect(result.records).toHaveLength(1) expect(result.records[0]?.balance?.toString()).toBe('9000 CHF') }) @@ -232,7 +329,6 @@ describe('a semicolon-delimited export', () => { }) describe('extensibility: a custom dialect and custom matchers', () => { - // A locale libdegiro does not ship: Dutch headers, dot thousands, comma decimals. const dutchDialect: Dialect = { id: 'nl', label: 'DEGIRO Dutch (custom)', diff --git a/test/redos.test.ts b/test/redos.test.ts index e9bf7d7..dc267d1 100644 --- a/test/redos.test.ts +++ b/test/redos.test.ts @@ -29,6 +29,9 @@ const cases: readonly (readonly [string, string])[] = [ ['a cash transfer of nothing but spaces', `Virement vers ${' '.repeat(REPEAT)}`], ['a cash transfer amount of nothing but spaces', `Virement vers x:${' '.repeat(REPEAT)}1 EUR`], ['an FX conversion trailed by spaces', `FX${' '.repeat(REPEAT)}`], + ['a German trade price separator trailed by spaces', `Kauf 1 zu je ${' '.repeat(REPEAT)}`], + ['a cash transfer with no colon and a run of spaces', `Overboeking van ${' '.repeat(REPEAT)}1 EUR`], + ['a Czech FX leg trailed by spaces', `FX vyučtování${' '.repeat(REPEAT)}`], ] describe('hostile descriptions are classified in linear time', () => {