Files
accounted/lib/import/bank-file/__tests__/parser.test.ts
T
MattssonandClaude Fable 5 f24b26a139 fix: similar-sweep currency remediation, security hardening and v1 API fixes (#1215)
* fix(security): gate replace_sie_import behind owner/admin membership

The RPC was SECURITY DEFINER with EXECUTE granted to PUBLIC and anon, no
company_members lookup, no auth.uid() reference and no unauthorized raise,
while setting gnubok.allow_delete to disarm the BFL immutability and
retention triggers. Any caller holding a company_id and an import id could
hard delete another tenant's verifikationer. Confirmed live in production.

Applies the same fail closed owner/admin guard that undo_sie_import already
carries (migration 20260624120000), resolving the actor from
COALESCE(p_user_id, auth.uid()) so it denies when the role is NULL, then
revokes EXECUTE from PUBLIC and anon. search_path and the raised
statement_timeout are restated, since CREATE OR REPLACE drops settings that
are not repeated.

userId is a required parameter on replaceSIEImport: the service client has a
NULL auth.uid(), so a caller without an explicit actor now fails to compile
rather than hitting the closed gate at runtime.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(security): validate arcim OAuth callback state server side

The callback route is skipAuth and decoded the state parameter as plain
base64url JSON, trusting consentId and provider from it. A one time code was
minted at flow start and never read. An unauthenticated attacker who learned
a consent id could run an OAuth flow on their own provider account and post
the callback with a forged state, landing their tokens on another tenant's
consent, so the victim's next migration imported the attacker's ledger.

State is now an opaque randomBytes(32) pointer to a provider_otc row,
consumed by a single atomic UPDATE guarded on used_at IS NULL and
expires_at, so a replay loses the row lock race and updates nothing.
provider is read from provider_consents rather than trusted from the client.
provider_otc already existed for exactly this purpose and was never wired up.

Also scopes getConsent to an owning company, closing a cross tenant status
oracle where the preview and migrate paths echoed a consent's status before
the scoped check ran.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(security): scope documents storage to company_id (phase A)

The documents bucket policies matched on auth.uid(), and upload keys were
documents/{userId}/..., so company membership was never consulted. Removing a
member revoked nothing: their session still authenticated and they kept
direct Storage read access to every receipt, supplier invoice and bank
statement they had uploaded. The same bug was fixed for sie-files in
20260416120000; this bucket was left behind.

Phase A is additive. Company scoped policies are added alongside the
uploader scoped ones, uploads move to documents/{companyId}/{userId}/..., and
reads accept either layout so nothing breaks mid migration. Phase C, which
drops the old policies, is gated on the backfill reporting zero remaining
legacy prefix objects.

The policy compares the company segment as text rather than casting to uuid
the way sie-files does: this bucket holds keys whose second segment is not a
uuid (MCP audit packages), and Postgres does not guarantee the bucket prefix
qual runs before the cast, so a planner reordering would raise 22P02 and fail
the whole query instead of filtering the row out.

deleteDocument now removes both candidate keys. Removing only the stored
pointer would leave a readable orphan copy of a document the user asked to
erase.

The backfill script is included but has never been run. It defaults to dry
run, refuses .env.local by name, and verifies each copy is readable and
SHA-256 identical before repointing the row.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(security): enforce events:read scope and membership on /api/events

This was the only one of the three validateApiKey call sites with no
downstream guard: v1 and the MCP server both check scope and re-verify
company membership, this route did neither. An events:read scope existed and
was documented as gating the endpoint but was never called, so a legacy key
falling back to DEFAULT_SCOPES read the full log. The bound company id went
straight from the api_keys row into a service role query, so a key whose user
had been removed from the company kept reading.

Adds the scope check before any database access, re-verifies company_members
with archived_at IS NULL, honours test mode by stamping X-Gnubok-Mode instead
of ignoring it, applies minimisePayload so the pull surface can never return
a wider payload than the push surface, and replaces the three flat error
strings with the canonical envelope.

Test key reads are served rather than blocked: TEST_KEY_WRITE_BLOCKED is
gated on mutations in with-api-v1, so a read gets the same treatment as every
other v1 read endpoint.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* perf(bookkeeping): sweep remaining journal_entries!inner embeds

A previous refactor removed this pattern from lib/reports and introduced
fetchEntryLines, but the class was never swept. Seventeen sites remained and
had become the top application consumer of production database time:
measured across the resulting query shapes, 32,694 calls and 25,848 seconds
of execution, mean 790ms, with shapes averaging 2.6s and 3.0s and maxing at
7,962ms against the 8s statement_timeout, which surfaced to users as 500s on
the booking path.

PostgREST compiles an embed with filters on the embedded side into a
correlated INNER JOIN LATERAL with a parameterized LIMIT, which stops
Postgres reordering the join, so each query walked the whole
journal_entry_lines table across all tenants. Driving from the entries side
instead turns that into two indexed round trips.

Converted sites keep their existing shape: the helper reattaches the parent
entry under the same key the embed produced. Several conversions also remove
a latent silent truncation where an unpaginated query was capped at
PostgREST's 1000 row ceiling.

Two deliberate exceptions. The free text ilike legs of the MCP display query
stay on the embed, because each is capped at legLimit and that cap drives the
truncation contract the tool reports, while the helper is unbounded. The
accounts route moves to the existing get_account_usage_counts RPC instead,
since its embed was a head count and the helper returns rows.

commitEntry's write path is untouched: the change there is confined to the
read query of the pre-commit dimension rule check.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(api): anchor v1 list cursors on created_at

Page two returned page one, forever, while still advertising a fresh
next_cursor. The three routes sorted by and encoded a Postgres date column,
which serializes as YYYY-MM-DD, but decodeDefaultCursor validates the cursor
timestamp as full ISO-8601 and returned null, so the keyset filter was never
applied and has_more never went false. An integrator syncing verifikat looped
on the newest rows indefinitely.

The transactions route already solved this and its comment names the trap;
the fix was never ported. All three now order and encode on created_at with
an id tie break, matching the transactions keyset predicate exactly.
ISO_TIMESTAMP is deliberately left alone: relaxing it would silently change
sort semantics on the route that currently works.

Default ordering therefore moves from business date to insert order. Every
business date is still on the row, and the invoices list gains date_from and
date_to filters so a date range is still reachable; the other two already had
them.

The tests use an in-memory PostgREST that actually evaluates the filters,
because the repo's pass-through mock cannot catch this class of bug: the bug
is that the filter is never sent. They walk to exhaustion with a hard
iteration cap, so an unterminated walk fails instead of hanging.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(api): separate dry run from commit in the idempotency hash

The request hash was built from url.pathname, which excludes the query
string, so a dry run and its commit hashed identically. Following the flow
documented in dry-run.ts, re-issuing the request with the same
Idempotency-Key returned the cached preview with Idempotent-Replayed set and
wrote nothing, while reporting 200. An agent or integrator saw success for a
write that never happened.

dry_run is folded into the hash only when true, not as an unconditional
boolean. Including it as false would change the hash of every ordinary write,
and with a 24h idempotency TTL any key in flight across the deploy would fail
the request_hash comparison and 409 on a legitimate retry. Both hash call
sites now go through one shared helper so they cannot drift into a permanent
cache miss, and dry run responses are no longer stored at all.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* ci: install the Bedrock SDK out of tree in the compliance review

The Swedish accounting compliance gate had failed ten consecutive runs and so
was posting nothing. With --no-package-lock npm discarded the lockfile and
re-resolved the whole tree from package.json, floating @hookform/resolvers to
5.4.3, whose valibot ^1 peer conflicts with the pinned valibot 0.39.0.

Installing into the parent of the checkout resolves only that one package, so
an unrelated peer conflict can never take the gate down again. Node still
finds it because ESM bare specifiers walk up parent node_modules; NODE_PATH
would not have worked, as it is CommonJS only. --legacy-peer-deps was
rejected because it masks future genuine peer conflicts and still reifies the
full tree.

The same step's SDK version is aligned from 0.31.0 back to the 0.29.1 that
package.json and check:guards enforce after the streaming outage. That drift
went unnoticed because the pin guard only inspects package.json and the
lockfile, never workflow files.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* build(docker): generate crontabs from vercel.json

vercel.json defines 16 cron jobs; both Docker crontabs carried 9, and were
byte identical to each other. Self hosted deployments therefore never sent
recurring invoices, never dispatched webhooks and never cleaned up
idempotency keys. tax-deadlines also ran once a year on 2 January instead of
daily, and documents/verify weekly instead of daily.

Extension crons are included rather than excluded. The Dockerfile copies the
whole tree before building, so every extension cron route is compiled into
the image regardless of the enabled preset, and each returns 200 when its
extension is unconfigured, so curl -sf logs no failure. Two such entries were
already present in the crontab for extensions absent from the preset, which
settles the intent.

documents/verify is treated as drift rather than a self hosted concession:
the weekly cadence was present in the hosted crontab too, and the run is
capped at 200 documents walking a nulls-first queue, so weekly drains the
integrity queue seven times slower on a check that exists for BFL retention.

webhooks/dispatch keeps its per minute cadence, adding 1,440 requests a day
on self hosted. A gentler tick would silently stretch the first retry, since
the retry ladder opens at 60 seconds. SCHEDULE_OVERRIDES is the one line
place to change that.

A parity test asserts the path sets match minus a documented exclusion list,
and ratchets three cron routes that are currently scheduled nowhere so they
are named rather than silently rotting.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(observability): add a provider agnostic error sink

There is no error tracking in this codebase: logs go to console and Vercel
retention and nowhere else, nothing alerts on the 16 cron jobs, and seven
code comments across lib, app, components and extensions asserted that Sentry
captures errors when Sentry is not a dependency. The two most recent bug
fixes on this repo were both discovered by customer email.

This adds the sink, not a vendor. No dependency is taken: the interface has a
no-op default and a registration point, so behaviour is unchanged until an
adapter is registered. Releases are tagged from the build id already inlined
by next.config.ts.

Redaction moved out of lib/logger.ts into a leaf module that both the logger
and the sink import, so there is one denylist and no path from application
data to a third party can skip the personnummer regex, including direct sink
calls that bypass the logger. That matters here because these logs carry
personnummer and financial data.

verifyCronSecret now reports its own 401s, which covers all 16 jobs without
touching a route file and catches the case where CRON_SECRET is rotated
without updating the scheduler and every job silently 401s forever. The
threshold is one failure rather than the backup alert's three: suppressing
the first occurrence is precisely how an outage stays invisible.

The seven misleading comments are corrected to describe what the code
actually does, including the two cases that still are not covered: the client
side one, since the sink is server side, and a warn level call that is not
forwarded.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix: remediate the 2026-07-26 similar-sweep findings across all surfaces

Resolves the ~150-finding sweep (dev_docs/similar-sweep-2026-07-26.md) with
one agent per finding; every behavioural fix carries a regression test proven
to fail at HEAD. Full status, corrections to the sweep, refusals and open
decisions in dev_docs/similar-sweep-2026-07-26-remediation-status.md.

Structural roots closed:
- resolveSekAmountOrNull(): honest SEK resolution refuses instead of booking
  1:1; four duplicated toSek closures now refuse via INVOICE_FX_RATE_MISSING
- ledger-line-amount.ts: journal_entry_lines.currency labels the document,
  not the amount; SQL pre-filter decoy proven and fixed
- sparse-patch.ts: .partial() does not strip .default() in Zod 4.4.3; the
  exploitable salary payslip-line PATCH and KPI preferences sinks fixed
- tests/schema: migration-replay phantom-column guard (13k+ refs, closed
  CHECK sets, onConflict targets); found 28 real defects, all fixed, all
  four baselines now empty
- three new ratchet guards: sek-labelled-amount, cross-extension-import,
  ungated-extension-route

Highlights: lawful VAT-rate set on all seven invoice surfaces (ML 6 kap),
RC input VAT mismatch wired on web + both MCP callers, missing-underlag
resource delegates to the shared RPC predicate, push-notifications consent
polarity fail-closed, deadlines undo honours requested state, silent-failure
and read-side-fabrication classes fixed across settings/KPI/inbox/Stripe/
Arcim/kassaflodesanalys, error-envelope stringification fixed at 10+ sites
with isSwedishUserMessage extended.

Also includes the parallel session's MCP invoice tools (update_invoice,
recurring schedules, invoice deliveries) which share files with the sweep
work and are verified green together.

13 new migrations are NOT applied anywhere; they apply via branch merge.
20260726120000 backfills 1247 supplier-invoice rows. pg tests for new
DDL are written but unrun (no local Postgres).

Verified: 11088 tests / 881 files green, tsc 0 non-test errors, lint 0
errors, check:guards passing, MCP payload 57475/57500.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(migrations): rename replace_sie_import migration off main's 20260726090000 version

origin/main shipped 20260726090000_agent_quota_rpc_caller_guard.sql; keeping
our replace_sie_import migration on the same version would abort the Supabase
apply with a schema_migrations_pkey duplicate at merge time.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(review): remediate pre-publish deep-review findings across all slices

A 13-agent review of the full branch diff surfaced 1 critical, 5 high and
~45 further findings; this commit resolves them in one pass:

- replace_sie_import / undo_sie_import: p_user_id honored only for
  service_role callers; any other caller is pinned to auth.uid()
  (impersonation gate bypass), authz raise errcode 42501 mapped to a
  Swedish 403 in the route, new caller-guard migration for undo
- bulk_book_transactions refuses homogeneous non-SEK batches instead of
  writing foreign magnitudes into SEK ledger columns
- credit-note cap trigger: company-match on credited_invoice_id, no
  cross-tenant figures in exception text
- link_voucher RPCs resolve NULL invoice currency as SEK end to end
- personal-number ciphertext CHECK split into NOT VALID + VALIDATE
- same-currency foreign settlements clear 1510 at booking rate and book
  realized diff to 3960/7960; rate-less foreign write paths refuse
- receivables revaluation covers partially_paid and outstanding amounts
- period lock guard paginates candidates past the PostgREST 1000 cap
- documents: service-client storage removals after authz, dual-layout
  reads in integrity cron and archive export, backfill delete-source
  sweep actually deletes with hash verification and shared-key grouping
- invoice matching normalizes NULL/lowercase currencies (regression),
  duplicate candidates stop claiming amount matches they never ran
- match-invoice aborts on any booking failure (no paid-without-verifikat)
- refresh-exchange-rate reverts on concurrent booking (TOCTOU window)
- KPI preferences upsert arbiter aligned to the company-scoped constraint
- personnummer_last4 stripped from all salary responses incl. MCP tools
- worked-hours batch restores destroyed rows on conflict and error paths
- MCP: shared duplicate-claim builder (no more 'null kr'), short-circuit
  on tag_journal_lines overflow, auto_send schedules stage as high risk
- observability sink redacts emails/IBANs/API keys and keeps redacted
  stacks in prod; assorted small guards (safe-return-to /@, dry_run=True,
  cursor helper off-by-one, OAuth state TTL 10 min, arcim saveMappings
  call removed)

Full dispositions, deferred items and hand-verified accounting numbers
are documented in the PR body and DECISIONS.md.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(personnummer): implement masking and encryption for personal numbers with tests

* fix(review): address CI and compliance-bot findings for PR #1215

pg-real: the CI image's auth shim reads the legacy request.jwt.claim.role
GUC, so both service-role simulations (runAsServiceRole and the
invoice-delivery test's local helper) never satisfied auth.role() =
'service_role' and every legitimate p_user_id path failed closed; the
shared helper now sets both GUC shapes plus SET LOCAL ROLE with a
fail-loud sanity check, and the delivery test reuses it. The link-voucher
migration had recreated both RPCs from pre-rewrite file text,
reintroducing the NULL-unsafe membership pattern the
null-safe-tenant-guards ratchet bans; both guards now use
public.caller_is_company_member() with all currency changes preserved.

Compliance bots: the customers export now emits the standard masked form
instead of raw AES-256-GCM ciphertext in the Org-/personnummer column,
and maskCustomerRow returns a non-round-trippable placeholder on decrypt
failure instead of 500ing the list. MCP parity: gnubok_lock_period's
staging pre-check now runs the exact countUnbookedInPeriod the commit
path enforces (exported from period-service; local mirror deleted), and
gnubok_agi_status resolves AGI state run-scoped so a correction run no
longer renders as already filed.

Declined with evidence: PR-Agent's opening-balances null-zeroing concern
(all mergeable columns are NOT NULL with defaults per 20260713101000).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(review): address codex review findings on PR #1215

- restore 20260726140000 to its preview-recorded content and restate the
  NULL-safe tenant guard under 20260727130000: a recorded migration version
  never re-runs, so the in-place edit could not reach the preview branch
- replace toFixed() with sv-SE two-decimal formatting in the ROT/RUT cap
  warning texts and update the pinned test expectations
- drop the em dash in the fiscal-periods route comment
- strip trailing whitespace in import-existing.test.ts

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(reports): raise timeout on real PDF render tests

renderToBuffer does real @react-pdf layout work and exceeds the 5s
default when the full suite saturates the CPU; tests pass in isolation.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 03:34:56 +02:00

2218 lines
81 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Comprehensive tests for the bank file parser library.
*
* Covers auto-detection, parsing for all Swedish bank formats (Nordea, SEB,
* Swedbank, Handelsbanken), ISO 20022 camt.053 XML, external ID generation,
* file hashing, stats calculation, date range extraction, and edge cases.
*/
import { detectFileFormat, parseBankFile, generateExternalId, generateFileHash, getFormat, getAllFormats } from '../parser'
import type { ParsedBankTransaction, BankFileFormatId } from '../types'
import { parseGenericCSV, normalizeMinusSign } from '../formats/generic-csv'
import { parseCSVLine } from '../formats/nordea'
// ---------------------------------------------------------------------------
// Test data: realistic CSV/XML content for each Swedish bank format
// ---------------------------------------------------------------------------
const NORDEA_CSV = [
'Datum,Transaktion,Kategori,Belopp,Saldo',
'2024-01-15,SPOTIFY AB,,"-99,00","12 345,67"',
'2024-01-14,ICA MAXI LINDHAGEN,,"-432,50","12 444,67"',
'2024-01-13,LÖNEUTBETALNING,,"25 000,00","12 877,17"',
].join('\n')
const NORDEA_CSV_WITH_RESERVED = [
'Datum,Transaktion,Kategori,Belopp,Saldo',
'2024-01-15,SPOTIFY AB,,"-99,00","12 345,67"',
'2024-01-14,Reserverat köp CLAS OHLSON,,"-199,00","12 444,67"',
'2024-01-13,LÖNEUTBETALNING,,"25 000,00","12 643,67"',
].join('\n')
const NORDEA_CSV_SWEDISH_CHARS = [
'Datum,Transaktion,Kategori,Belopp,Saldo',
'2024-03-01,GÖTEBORGS HAMNCAFÉ,,"-85,00","5 000,00"',
'2024-03-02,ÅHLENS CITY,,"-249,00","4 751,00"',
'2024-03-03,ÄRLA GÅRD AB,,"1 200,00","5 951,00"',
].join('\n')
const SEB_CSV = [
'Bokföringsdag;Valutadag;Verifikationsnummer;Text;Belopp;Saldo',
'2024-01-15;2024-01-15;12345;SPOTIFY AB;-99,00;12345,67',
'2024-01-14;2024-01-14;12346;HEMKÖP FRIDHEMSPLAN;-432,50;12444,67',
'2024-01-13;2024-01-13;12347;LÖNEUTBETALNING;25000,00;12877,17',
].join('\n')
// SEB privatbanken web export: "Bokföringsdatum" (with ö AND -datum suffix)
const SEB_PRIVAT_CSV = [
'Bokföringsdatum;Valutadatum;Verifikationsnummer;Text;Belopp;Saldo',
'2025-12-30;2025-12-31;0;RÄNTA;7,84;1241,16',
'2025-09-15;2025-09-14;5490990004;53290171515;-1000,00;1233,32',
'2024-10-31;2024-10-31;5841990687;H31520956893;433,16;5147,56',
].join('\n')
const SWEDBANK_CSV = [
'Kontouppgifter',
'Clearingnummer,Kontonummer,Datum,Text,Belopp,Saldo',
'8123,12345678,2024-01-15,SPOTIFY AB,-99.00,12345.67',
'8123,12345678,2024-01-14,ICA MAXI,-432.50,12444.67',
'8123,12345678,2024-01-13,LÖNEUTBETALNING,25000.00,12877.17',
].join('\n')
const SWEDBANK_CSV_NO_METADATA = [
'Clearingnummer,Kontonummer,Datum,Text,Belopp,Saldo',
'8123,12345678,2024-02-01,TELIA SVERIGE,-299.00,10000.00',
'8123,12345678,2024-02-02,SKATTEVERKET INBETALNING,5000.00,15000.00',
].join('\n')
const HANDELSBANKEN_CSV = [
'Reskontradatum;Transaktionsdatum;Text;Belopp;Saldo',
'2024-01-15;2024-01-15;SPOTIFY AB;-99,00;12345,67',
'2024-01-14;2024-01-14;HEMKÖP;-432,50;12444,67',
'2024-01-13;2024-01-13;LÖNEUTBETALNING;25000,00;12877,17',
].join('\n')
const HANDELSBANKEN_CSV_WITH_PREL = [
'Reskontradatum;Transaktionsdatum;Text;Belopp;Saldo',
'2024-01-15;2024-01-15;SPOTIFY AB;-99,00;12345,67',
'2024-01-14;2024-01-14;Prel kortköp CLAS OHLSON;-199,00;12444,67',
'2024-01-13;2024-01-13;LÖNEUTBETALNING;25000,00;12643,67',
].join('\n')
// Real Handelsbanken web exports can prepend account/period metadata rows
// (and a blank line) before the actual column header.
const HANDELSBANKEN_CSV_WITH_PREAMBLE = [
'Kontonummer;6789 123 456 789',
'Kontohavare;Wiklund, Cristel',
'Period;2024-01-01 - 2024-01-31',
'',
'Reskontradatum;Transaktionsdatum;Text;Belopp;Saldo',
'2024-01-15;2024-01-15;SPOTIFY AB;-99,00;12345,67',
'2024-01-14;2024-01-14;HEMKÖP;-432,50;12444,67',
'2024-01-13;2024-01-13;LÖNEUTBETALNING;25000,00;12877,17',
].join('\n')
// Negative amounts exported with a Unicode minus (U+2212) instead of ASCII '-'.
const HANDELSBANKEN_CSV_UNICODE_MINUS = [
'Reskontradatum;Transaktionsdatum;Text;Belopp;Saldo',
'2024-01-15;2024-01-15;SPOTIFY AB;−139,00;12345,67',
'2024-01-14;2024-01-14;HEMKÖP;−1 432,50;12444,67',
'2024-01-13;2024-01-13;LÖNEUTBETALNING;25000,00;12877,17',
].join('\n')
// A quoted Text field that itself contains the semicolon delimiter.
const HANDELSBANKEN_CSV_QUOTED_SEMICOLON = [
'Reskontradatum;Transaktionsdatum;Text;Belopp;Saldo',
'2024-01-15;2024-01-15;"BETALNING; FAKTURA 100";-99,00;12345,67',
'2024-01-14;2024-01-14;HEMKÖP;-432,50;12444,67',
].join('\n')
const CAMT053_XML = `<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.02">
<BkToCstmrStmt>
<Stmt>
<Acct><Ccy>SEK</Ccy></Acct>
<Ntry>
<BookgDt><Dt>2024-01-15</Dt></BookgDt>
<Amt Ccy="SEK">99.00</Amt>
<CdtDbtInd>DBIT</CdtDbtInd>
<NtryRef>REF001</NtryRef>
<NtryDtls><TxDtls>
<RmtInf><Ustrd>SPOTIFY AB</Ustrd></RmtInf>
</TxDtls></NtryDtls>
</Ntry>
<Ntry>
<BookgDt><Dt>2024-01-14</Dt></BookgDt>
<Amt Ccy="SEK">25000.00</Amt>
<CdtDbtInd>CRDT</CdtDbtInd>
<NtryRef>REF002</NtryRef>
<NtryDtls><TxDtls>
<RmtInf><Ustrd>LÖNEUTBETALNING</Ustrd></RmtInf>
</TxDtls></NtryDtls>
</Ntry>
</Stmt>
</BkToCstmrStmt>
</Document>`
const CAMT053_XML_WITH_STRUCTURED_REF = `<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.02">
<BkToCstmrStmt>
<Stmt>
<Ntry>
<BookgDt><Dt>2024-02-01</Dt></BookgDt>
<Amt Ccy="SEK">1500.00</Amt>
<CdtDbtInd>CRDT</CdtDbtInd>
<NtryRef>REF100</NtryRef>
<NtryDtls><TxDtls>
<RmtInf>
<Strd><CdtrRefInf><Ref>OCR123456789</Ref></CdtrRefInf></Strd>
<Ustrd>Betalning faktura 1001</Ustrd>
</RmtInf>
</TxDtls></NtryDtls>
</Ntry>
</Stmt>
</BkToCstmrStmt>
</Document>`
const LANSFORSAKRINGAR_CSV = [
'"Datum";"Bokföringsdag";"Typ";"Text";"Belopp";"Saldo"',
'"2024-01-15";"2024-01-15";"Kortköp";"SPOTIFY AB";"-99,00";"12 345,67"',
'"2024-01-14";"2024-01-14";"Kortköp";"ICA MAXI";"-432,50";"12 444,67"',
'"2024-01-13";"2024-01-13";"Insättning";"LÖNEUTBETALNING";"25 000,00";"12 877,17"',
].join('\n')
const LANSFORSAKRINGAR_CSV_NO_HEADER = [
'"2024-01-15";"2024-01-15";"Kortköp";"SPOTIFY AB";"-99,00";"12 345,67"',
'"2024-01-14";"2024-01-14";"Kortköp";"ICA MAXI";"-432,50";"12 444,67"',
].join('\n')
const ICA_BANKEN_CSV = [
'Kontonamn: Lönekonto',
'Kontonummer: 1234 567 890',
'Saldo: 12 877,17',
'Tillgängligt belopp: 12 877,17',
'Period: 2024-01-01 - 2024-01-31',
'Exporterad: 2024-02-01',
'Datum;Text;Belopp;Saldo',
'2024-01-15;SPOTIFY AB;-99,00;12345,67',
'2024-01-14;ICA MAXI LINDHAGEN;-432,50;12444,67',
'2024-01-13;LÖNEUTBETALNING;25000,00;12877,17',
].join('\n')
const SKANDIA_CSV = [
'Datum;Beskrivning;Belopp;Saldo',
'2024-01-15;SPOTIFY AB;-99,00;12345,67',
'2024-01-14;HEMKÖP FRIDHEMSPLAN;-432,50;12444,67',
'2024-01-13;LÖNEUTBETALNING;25000,00;12877,17',
].join('\n')
const SKANDIA_CSV_WITH_BANKKATEGORI = [
'Datum;Beskrivning;Belopp;Saldo;Bankkategori',
'2024-01-15;SPOTIFY AB;-99,00;12345,67;Underhållning',
'2024-01-14;ICA MAXI;-432,50;12444,67;Livsmedel',
].join('\n')
const LUNAR_CSV = [
'Date,Text,Amount,Balance',
'2024-01-15,SPOTIFY AB,"-99,00","12.345,67"',
'2024-01-14,ICA MAXI LINDHAGEN,"-432,50","12.444,67"',
'2024-01-13,LÖNEUTBETALNING,"25.000,00","12.877,17"',
].join('\n')
// Real Lunar export as of 2026: Time and Transaction ID columns, "Title"
// instead of "Text", SPACE thousands separator, UTF-8 BOM (issue #915).
const LUNAR_CSV_2026 = '\uFEFF' + [
'Date,Time,Title,Amount,Balance,Transaction ID',
'2026-06-30,12:11,Incoming payment,"12 345,00","98 764,94",7f0a4c9e-1111-2222-3333-444455556666',
'2026-06-12,05:47,Fee,"-1,49","86 419,94",7f0a4c9e-1111-2222-3333-444455557777',
'2026-05-12,05:47,Card purchase,"-2 500,00","86 421,43",7f0a4c9e-1111-2222-3333-444455558888',
].join('\n')
// Northmill exports include a 5-line metadata preamble (Kontonummer, Saldo,
// Kontohavare, Org. Nr, Period) plus blank lines before the actual transaction
// header. Negative amounts use Unicode minus (U+2212), not ASCII hyphen.
const NORTHMILL_CSV = [
'Kontonummer,9750-8770139',
'Saldo,"251495,41",SEK',
'Kontohavare,Arcim Technology AB',
'Org. Nr,559538-6219',
'Period,2025-10-01,2026-04-07',
'',
'',
'',
'Bokföringsdag,Beskrivning,Belopp,Saldo,Valuta',
'2026-04-01,Månadsavgift företagspaket april,"\u2212139,00","251495,41",SEK',
'2026-01-22,200176580348155,"\u22121000,00","251912,41",SEK',
'2025-10-16,092221155575,"400000,00","422005,00",SEK',
'2025-10-01,Inbetalning av aktiekapital,"25000,00","25000,00",SEK',
].join('\n')
const UNKNOWN_CSV = [
'id,name,value,timestamp',
'1,Widget A,100,2024-01-15T10:00:00',
'2,Widget B,200,2024-01-16T11:00:00',
].join('\n')
const EMPTY_FILE = ''
const HEADER_ONLY_NORDEA = 'Datum,Transaktion,Kategori,Belopp,Saldo\n'
const NORDEA_BUSINESS_CSV = [
'Bokföringsdag;Belopp;Avsändare;Mottagare;Namn;Rubrik;Saldo;Valuta',
'2024-01-15;-99,00;;SPOTIFY AB;SPOTIFY AB;Kortköp;12 345,67;SEK',
'2024-01-14;-432,50;;ICA MAXI;ICA MAXI LINDHAGEN;Kortköp;12 444,67;SEK',
'2024-01-13;25 000,00;ARBETSGIVAREN AB;;ARBETSGIVAREN AB;Löneutbetalning;12 877,17;SEK',
].join('\n')
const NORDEA_BUSINESS_CSV_SWEDISH_CHARS = [
'Bokföringsdag;Belopp;Avsändare;Mottagare;Namn;Rubrik;Saldo;Valuta',
'2024-03-01;-85,00;;GÖTEBORGS HAMNCAFÉ;GÖTEBORGS HAMNCAFÉ;Kortköp;5 000,00;SEK',
'2024-03-02;-249,00;;ÅHLENS CITY;ÅHLENS CITY;Kortköp;4 751,00;SEK',
'2024-03-03;1 200,00;ÄRLA GÅRD AB;;ÄRLA GÅRD AB;Betalning;5 951,00;SEK',
].join('\n')
const HEADER_ONLY_NORDEA_BUSINESS = 'Bokföringsdag;Belopp;Avsändare;Mottagare;Namn;Rubrik;Saldo;Valuta\n'
const NORDEA_BUSINESS_CSV_VARIANT_A = [
'Bokföringsdag;Värdedag;Betalningstyp;Betalare/Mottagare;Meddelande/Referens;Belopp;Saldo',
'2024-01-15;2024-01-15;Kortbetalning;SPOTIFY AB;Spotify Premium;-99,00;12 345,67',
'2024-01-14;2024-01-14;Kortbetalning;ICA MAXI;Dagligvaror;-432,50;12 444,67',
'2024-01-13;2024-01-13;Inbetalning;ARBETSGIVAREN AB;Lön jan;25 000,00;12 877,17',
].join('\n')
const NORDEA_BUSINESS_CSV_VARIANT_B = [
'Bokföringsdatum;Valutadatum;Text;Belopp;Saldo',
'2024-01-15;2024-01-15;SPOTIFY AB;-99,00;12 345,67',
'2024-01-14;2024-01-14;ICA MAXI LINDHAGEN;-432,50;12 444,67',
'2024-01-13;2024-01-13;LÖNEUTBETALNING;25 000,00;12 877,17',
].join('\n')
const NORDEA_BUSINESS_CSV_VARIANT_C = [
'Datum;Belopp;Avsändare;Mottagare;Namn;Ytterligare detaljer;Meddelande;Egna anteckningar;Saldo;Valuta;',
'2026/03/02;-18,84;;;;Kortköp 260301 Google Workspace_elv;Google Workspac 7028;;10686,66;SEK;',
'2026/02/04;-1,85;;;;AVGIFTER NORDEA;;;10705,50;SEK;',
'2026/02/02;-87,14;;;;Kortköp 260201 Google Workspace_elv;Google Workspac 7028;;10707,35;SEK;',
'2026/01/15;15000,00;KUNDFÖRETAG AB;;;;Inbetalning;;25707,35;SEK;',
].join('\n')
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe('detectFileFormat', () => {
it('detects Nordea CSV from header keywords', () => {
const format = detectFileFormat(NORDEA_CSV, 'transaktioner.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('nordea')
})
it('detects Nordea Business CSV from semicolon-delimited header with bokföringsdag and rubrik', () => {
const format = detectFileFormat(NORDEA_BUSINESS_CSV, 'PLUSGIROKONTO FTG 212 68 87-5.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('nordea_business')
})
it('does not confuse Nordea Business with SEB (SEB has valutadag)', () => {
const format = detectFileFormat(NORDEA_BUSINESS_CSV, 'export.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('nordea_business')
})
it('detects Nordea Business CSV variant with Betalare/Mottagare combined column', () => {
const format = detectFileFormat(NORDEA_BUSINESS_CSV_VARIANT_A, 'nordea_ftg.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('nordea_business')
})
it('detects Nordea Business CSV variant with Bokföringsdatum header', () => {
const format = detectFileFormat(NORDEA_BUSINESS_CSV_VARIANT_B, 'nordea_ftg.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('nordea_business')
})
it('detects Nordea Business CSV variant with standalone Datum header and YYYY/MM/DD dates', () => {
const format = detectFileFormat(NORDEA_BUSINESS_CSV_VARIANT_C, 'nordea_ftg.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('nordea_business')
})
it('does not confuse Nordea Datum variant with Länsförsäkringar (which has Datum + Typ)', () => {
// Nordea Format D has Datum without Typ: must not be mistaken for LF
const format = detectFileFormat(NORDEA_BUSINESS_CSV_VARIANT_C, 'export.csv')
expect(format!.id).toBe('nordea_business')
})
it('does not misidentify SEB as Nordea Business when valutadag is present', () => {
const sebLike = 'Bokföringsdag;Valutadag;Verifikationsnummer;Text;Belopp;Saldo\n2024-01-15;2024-01-15;123;SPOTIFY;-99,00;12345,67'
const format = detectFileFormat(sebLike, 'export.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('seb')
})
it('detects SEB CSV from semicolon-delimited header with bokföringsdag', () => {
const format = detectFileFormat(SEB_CSV, 'kontoutdrag.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('seb')
})
it('detects Swedbank CSV from clearingnummer header', () => {
const format = detectFileFormat(SWEDBANK_CSV, 'export.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('swedbank')
})
it('detects Swedbank CSV when header is on the first line (no metadata)', () => {
const format = detectFileFormat(SWEDBANK_CSV_NO_METADATA, 'export.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('swedbank')
})
it('detects Handelsbanken CSV from reskontradatum/transaktionsdatum header', () => {
const format = detectFileFormat(HANDELSBANKEN_CSV, 'handelsbanken.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('handelsbanken')
})
it('detects camt.053 XML from namespace and .xml extension', () => {
const format = detectFileFormat(CAMT053_XML, 'statement.xml')
expect(format).not.toBeNull()
expect(format!.id).toBe('camt053')
})
it('detects camt.053 XML when content includes BkToCstmrStmt tag', () => {
const xmlContent = '<?xml version="1.0"?><Document><BkToCstmrStmt></BkToCstmrStmt></Document>'
const format = detectFileFormat(xmlContent, 'data.xml')
expect(format).not.toBeNull()
expect(format!.id).toBe('camt053')
})
it('does not detect camt.053 without .xml extension', () => {
// camt053 detection requires .xml extension
const format = detectFileFormat(CAMT053_XML, 'statement.csv')
// It should not match camt053 since extension is .csv
// But it could match something else if the content resembles a CSV header
// The important check is that it does NOT return camt053
if (format) {
expect(format.id).not.toBe('camt053')
}
})
it('detects Länsförsäkringar CSV from header with "typ" keyword', () => {
const format = detectFileFormat(LANSFORSAKRINGAR_CSV, 'lansforsakringar.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('lansforsakringar')
})
it('detects Länsförsäkringar CSV from two adjacent date fields (no header)', () => {
const format = detectFileFormat(LANSFORSAKRINGAR_CSV_NO_HEADER, 'export.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('lansforsakringar')
})
it('detects ICA Banken CSV from metadata rows before header', () => {
const format = detectFileFormat(ICA_BANKEN_CSV, 'ica.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('ica_banken')
})
it('detects Skandia CSV from "beskrivning" header keyword', () => {
const format = detectFileFormat(SKANDIA_CSV, 'skandia.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('skandia')
})
it('detects Skandia CSV from "bankkategori" header keyword', () => {
const format = detectFileFormat(SKANDIA_CSV_WITH_BANKKATEGORI, 'skandia.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('skandia')
})
it('detects Lunar CSV from English headers (date, text, amount, balance)', () => {
const format = detectFileFormat(LUNAR_CSV, 'lunar.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('lunar')
})
it('detects the 2026 Lunar CSV header (Title column, BOM) as lunar', () => {
const format = detectFileFormat(LUNAR_CSV_2026, 'lunar.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('lunar')
})
it('detects Northmill CSV from Kontonummer preamble + transaction header', () => {
const format = detectFileFormat(NORTHMILL_CSV, 'Northmill-Account-Statement.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('northmill')
})
it('does not detect Northmill on a file that just happens to mention Kontonummer in transactions', () => {
const fake = [
'Datum,Transaktion,Kategori,Belopp,Saldo',
'2024-01-15,Överföring kontonummer 1234,Inkomst,"100,00","1000,00"',
].join('\n')
const format = detectFileFormat(fake, 'test.csv')
// Should detect as Nordea, not Northmill: Northmill needs Kontonummer at start of first line
expect(format!.id).toBe('nordea')
})
it('returns null for unrecognized CSV content', () => {
const format = detectFileFormat(UNKNOWN_CSV, 'data.csv')
expect(format).toBeNull()
})
it('returns null for empty content', () => {
const format = detectFileFormat(EMPTY_FILE, 'empty.csv')
expect(format).toBeNull()
})
it('generic_csv format never auto-detects', () => {
// Even with simple CSV content, generic should not be picked
const simpleCSV = 'date,description,amount\n2024-01-15,Test,-100'
const format = detectFileFormat(simpleCSV, 'test.csv')
if (format) {
expect(format.id).not.toBe('generic_csv')
}
})
it('is case-insensitive on header detection', () => {
const upperNordea = 'DATUM,TRANSAKTION,KATEGORI,BELOPP,SALDO\n2024-01-15,Test,,"-100,00","5000,00"'
const format = detectFileFormat(upperNordea, 'test.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('nordea')
})
})
describe('parseBankFile: Nordea format', () => {
it('parses comma-delimited CSV with comma decimal separator', () => {
const result = parseBankFile(NORDEA_CSV, 'nordea.csv')
expect(result.format).toBe('nordea')
expect(result.format_name).toBe('Nordea')
expect(result.transactions).toHaveLength(3)
expect(result.issues).toHaveLength(0)
})
it('correctly parses negative amounts with comma decimal and space thousands', () => {
const result = parseBankFile(NORDEA_CSV, 'nordea.csv')
const spotify = result.transactions[0]
expect(spotify.amount).toBe(-99)
expect(spotify.description).toBe('SPOTIFY AB')
expect(spotify.date).toBe('2024-01-15')
expect(spotify.currency).toBe('SEK')
const ica = result.transactions[1]
expect(ica.amount).toBe(-432.5)
})
it('correctly parses positive amounts with space thousands separator', () => {
const result = parseBankFile(NORDEA_CSV, 'nordea.csv')
const salary = result.transactions[2]
expect(salary.amount).toBe(25000)
expect(salary.description).toBe('LÖNEUTBETALNING')
})
it('parses balance field with space thousands separator', () => {
const result = parseBankFile(NORDEA_CSV, 'nordea.csv')
const spotify = result.transactions[0]
expect(spotify.balance).toBe(12345.67)
})
it('filters out "Reserverat" (pending) transactions', () => {
const result = parseBankFile(NORDEA_CSV_WITH_RESERVED, 'nordea.csv')
expect(result.transactions).toHaveLength(2)
expect(result.stats.skipped_rows).toBe(1)
const descriptions = result.transactions.map((t) => t.description)
expect(descriptions).not.toContain(expect.stringContaining('Reserverat'))
})
it('handles Swedish characters (a-ring, a-diaeresis, o-diaeresis)', () => {
const result = parseBankFile(NORDEA_CSV_SWEDISH_CHARS, 'nordea.csv')
expect(result.transactions).toHaveLength(3)
expect(result.transactions[0].description).toBe('GÖTEBORGS HAMNCAFÉ')
expect(result.transactions[1].description).toBe('ÅHLENS CITY')
expect(result.transactions[2].description).toBe('ÄRLA GÅRD AB')
})
it('stores raw_line for each transaction', () => {
const result = parseBankFile(NORDEA_CSV, 'nordea.csv')
result.transactions.forEach((tx) => {
expect(tx.raw_line).toBeDefined()
expect(tx.raw_line!.length).toBeGreaterThan(0)
})
})
it('handles header-only file with no data rows', () => {
const result = parseBankFile(HEADER_ONLY_NORDEA, 'nordea.csv')
expect(result.format).toBe('nordea')
expect(result.transactions).toHaveLength(0)
expect(result.date_from).toBeNull()
expect(result.date_to).toBeNull()
expect(result.stats.parsed_rows).toBe(0)
})
})
describe('parseBankFile: Nordea Business format', () => {
it('parses semicolon-delimited CSV with correct columns', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV, 'nordea_ftg.csv')
expect(result.format).toBe('nordea_business')
expect(result.format_name).toBe('Nordea Företag')
expect(result.transactions).toHaveLength(3)
expect(result.issues).toHaveLength(0)
})
it('correctly parses negative amounts', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV, 'nordea_ftg.csv')
const spotify = result.transactions[0]
expect(spotify.amount).toBe(-99)
expect(spotify.date).toBe('2024-01-15')
expect(spotify.currency).toBe('SEK')
})
it('correctly parses positive amounts with space thousands separator', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV, 'nordea_ftg.csv')
const salary = result.transactions[2]
expect(salary.amount).toBe(25000)
expect(salary.date).toBe('2024-01-13')
})
it('builds description from Namn and Rubrik columns', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV, 'nordea_ftg.csv')
const spotify = result.transactions[0]
expect(spotify.description).toBe('SPOTIFY AB - Kortköp')
const salary = result.transactions[2]
expect(salary.description).toBe('ARBETSGIVAREN AB - Löneutbetalning')
})
it('extracts counterparty from Mottagare (expense) or Avsändare (income)', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV, 'nordea_ftg.csv')
// Expense: counterparty from Mottagare
expect(result.transactions[0].counterparty).toBe('SPOTIFY AB')
// Income: counterparty from Avsändare
expect(result.transactions[2].counterparty).toBe('ARBETSGIVAREN AB')
})
it('parses balance field', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV, 'nordea_ftg.csv')
expect(result.transactions[0].balance).toBe(12345.67)
expect(result.transactions[2].balance).toBe(12877.17)
})
it('handles Swedish characters', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV_SWEDISH_CHARS, 'nordea_ftg.csv')
expect(result.transactions).toHaveLength(3)
expect(result.transactions[0].description).toContain('GÖTEBORGS HAMNCAFÉ')
expect(result.transactions[1].description).toContain('ÅHLENS CITY')
expect(result.transactions[2].description).toContain('ÄRLA GÅRD AB')
})
it('stores raw_line for each transaction', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV, 'nordea_ftg.csv')
result.transactions.forEach((tx) => {
expect(tx.raw_line).toBeDefined()
expect(tx.raw_line!.length).toBeGreaterThan(0)
})
})
it('handles header-only file with no data rows', () => {
const result = parseBankFile(HEADER_ONLY_NORDEA_BUSINESS, 'nordea_ftg.csv')
expect(result.format).toBe('nordea_business')
expect(result.transactions).toHaveLength(0)
expect(result.date_from).toBeNull()
expect(result.date_to).toBeNull()
expect(result.stats.parsed_rows).toBe(0)
})
it('calculates correct date range', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV, 'nordea_ftg.csv')
expect(result.date_from).toBe('2024-01-13')
expect(result.date_to).toBe('2024-01-15')
})
it('calculates correct income and expense stats', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV, 'nordea_ftg.csv')
expect(result.stats.total_income).toBe(25000)
expect(result.stats.total_expenses).toBe(-531.5)
expect(result.stats.parsed_rows).toBe(3)
expect(result.stats.skipped_rows).toBe(0)
})
})
describe('parseBankFile: Nordea Business variant A (Betalare/Mottagare)', () => {
it('parses the alternate Nordea Business format with combined party column', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV_VARIANT_A, 'nordea_ftg.csv')
expect(result.format).toBe('nordea_business')
expect(result.transactions).toHaveLength(3)
expect(result.issues).toHaveLength(0)
})
it('builds description from Betalningstyp and Meddelande/Referens', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV_VARIANT_A, 'nordea_ftg.csv')
expect(result.transactions[0].description).toBe('Kortbetalning - Spotify Premium')
expect(result.transactions[2].description).toBe('Inbetalning - Lön jan')
})
it('extracts counterparty from combined Betalare/Mottagare column', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV_VARIANT_A, 'nordea_ftg.csv')
expect(result.transactions[0].counterparty).toBe('SPOTIFY AB')
expect(result.transactions[2].counterparty).toBe('ARBETSGIVAREN AB')
})
it('parses amounts and dates correctly', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV_VARIANT_A, 'nordea_ftg.csv')
expect(result.transactions[0].amount).toBe(-99)
expect(result.transactions[0].date).toBe('2024-01-15')
expect(result.transactions[2].amount).toBe(25000)
})
})
describe('parseBankFile: Nordea Business variant B (Bokföringsdatum)', () => {
it('parses the simple Nordea Business format with Bokföringsdatum', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV_VARIANT_B, 'nordea_ftg.csv')
expect(result.format).toBe('nordea_business')
expect(result.transactions).toHaveLength(3)
expect(result.issues).toHaveLength(0)
})
it('builds description from Text column', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV_VARIANT_B, 'nordea_ftg.csv')
expect(result.transactions[0].description).toBe('SPOTIFY AB')
expect(result.transactions[2].description).toBe('LÖNEUTBETALNING')
})
it('parses amounts correctly', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV_VARIANT_B, 'nordea_ftg.csv')
expect(result.transactions[0].amount).toBe(-99)
expect(result.transactions[1].amount).toBe(-432.5)
expect(result.transactions[2].amount).toBe(25000)
})
it('calculates correct stats', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV_VARIANT_B, 'nordea_ftg.csv')
expect(result.stats.total_income).toBe(25000)
expect(result.stats.total_expenses).toBe(-531.5)
expect(result.stats.parsed_rows).toBe(3)
})
})
describe('parseBankFile: Nordea Business variant C (Datum + YYYY/MM/DD)', () => {
it('parses the Nordea format with Datum header and slash dates', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV_VARIANT_C, 'nordea_ftg.csv')
expect(result.format).toBe('nordea_business')
expect(result.transactions).toHaveLength(4)
expect(result.issues).toHaveLength(0)
expect(result.stats.skipped_rows).toBe(0)
})
it('normalizes YYYY/MM/DD dates to YYYY-MM-DD', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV_VARIANT_C, 'nordea_ftg.csv')
expect(result.transactions[0].date).toBe('2026-03-02')
expect(result.transactions[1].date).toBe('2026-02-04')
expect(result.transactions[3].date).toBe('2026-01-15')
})
it('builds description from Ytterligare detaljer column', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV_VARIANT_C, 'nordea_ftg.csv')
expect(result.transactions[0].description).toBe('Kortköp 260301 Google Workspace_elv')
expect(result.transactions[1].description).toBe('AVGIFTER NORDEA')
})
it('extracts counterparty from Avsändare for income', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV_VARIANT_C, 'nordea_ftg.csv')
expect(result.transactions[3].counterparty).toBe('KUNDFÖRETAG AB')
expect(result.transactions[3].amount).toBe(15000)
})
it('parses amounts and balance correctly with comma decimals', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV_VARIANT_C, 'nordea_ftg.csv')
expect(result.transactions[0].amount).toBe(-18.84)
expect(result.transactions[0].balance).toBe(10686.66)
expect(result.transactions[0].currency).toBe('SEK')
})
it('handles trailing semicolons in header and data rows', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV_VARIANT_C, 'nordea_ftg.csv')
expect(result.stats.parsed_rows).toBe(4)
expect(result.stats.total_income).toBe(15000)
expect(result.stats.total_expenses).toBe(-107.83)
})
it('calculates correct date range', () => {
const result = parseBankFile(NORDEA_BUSINESS_CSV_VARIANT_C, 'nordea_ftg.csv')
expect(result.date_from).toBe('2026-01-15')
expect(result.date_to).toBe('2026-03-02')
})
})
describe('parseBankFile: SEB format', () => {
it('parses semicolon-delimited CSV with comma decimal separator', () => {
const result = parseBankFile(SEB_CSV, 'seb.csv')
expect(result.format).toBe('seb')
expect(result.format_name).toBe('SEB')
expect(result.transactions).toHaveLength(3)
expect(result.issues).toHaveLength(0)
})
it('correctly extracts columns using dynamic header mapping', () => {
const result = parseBankFile(SEB_CSV, 'seb.csv')
const spotify = result.transactions[0]
expect(spotify.date).toBe('2024-01-15')
expect(spotify.description).toBe('SPOTIFY AB')
expect(spotify.amount).toBe(-99)
expect(spotify.balance).toBe(12345.67)
})
it('parses positive income amounts correctly', () => {
const result = parseBankFile(SEB_CSV, 'seb.csv')
const salary = result.transactions[2]
expect(salary.amount).toBe(25000)
expect(salary.description).toBe('LÖNEUTBETALNING')
})
it('handles alternative SEB header names', () => {
const altSEB = [
'Bokforingsdatum;Valutadag;Verifikationsnummer;Text;Belopp;Saldo',
'2024-01-15;2024-01-15;12345;TEST;-50,00;1000,00',
].join('\n')
const result = parseBankFile(altSEB, 'seb_alt.csv')
expect(result.format).toBe('seb')
expect(result.transactions).toHaveLength(1)
expect(result.transactions[0].amount).toBe(-50)
})
it('auto-detects SEB privatbanken variant with Bokföringsdatum + Valutadatum headers', () => {
const format = detectFileFormat(SEB_PRIVAT_CSV, 'kontoutdrag.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('seb')
})
it('parses SEB privatbanken CSV (Bokföringsdatum / Valutadatum / RÄNTA / negative amounts)', () => {
const result = parseBankFile(SEB_PRIVAT_CSV, 'kontoutdrag.csv')
expect(result.format).toBe('seb')
expect(result.transactions).toHaveLength(3)
expect(result.issues).toHaveLength(0)
const ranta = result.transactions[0]
expect(ranta.date).toBe('2025-12-30')
expect(ranta.description).toBe('RÄNTA')
expect(ranta.amount).toBe(7.84)
expect(ranta.balance).toBe(1241.16)
const withdrawal = result.transactions[1]
expect(withdrawal.date).toBe('2025-09-15')
expect(withdrawal.amount).toBe(-1000)
const deposit = result.transactions[2]
expect(deposit.amount).toBe(433.16)
})
})
describe('parseBankFile: Swedbank format', () => {
it('parses comma-delimited CSV with PERIOD decimal separator', () => {
const result = parseBankFile(SWEDBANK_CSV, 'swedbank.csv')
expect(result.format).toBe('swedbank')
expect(result.format_name).toBe('Swedbank')
expect(result.transactions).toHaveLength(3)
expect(result.issues).toHaveLength(0)
})
it('correctly handles period decimal separator (the Swedish exception)', () => {
const result = parseBankFile(SWEDBANK_CSV, 'swedbank.csv')
const spotify = result.transactions[0]
expect(spotify.amount).toBe(-99)
expect(spotify.balance).toBe(12345.67)
const ica = result.transactions[1]
expect(ica.amount).toBe(-432.5)
})
it('skips metadata line when present (first line is account info)', () => {
const result = parseBankFile(SWEDBANK_CSV, 'swedbank.csv')
// With metadata line, there are 3 data rows after headerLineIdx=1
expect(result.transactions).toHaveLength(3)
// No transaction should have "Kontouppgifter" as description
const descriptions = result.transactions.map((t) => t.description)
expect(descriptions).not.toContain('Kontouppgifter')
})
it('works when header is on the first line (no metadata)', () => {
const result = parseBankFile(SWEDBANK_CSV_NO_METADATA, 'swedbank.csv')
expect(result.format).toBe('swedbank')
expect(result.transactions).toHaveLength(2)
expect(result.transactions[0].amount).toBe(-299)
expect(result.transactions[1].amount).toBe(5000)
})
it('extracts dates correctly', () => {
const result = parseBankFile(SWEDBANK_CSV, 'swedbank.csv')
expect(result.transactions[0].date).toBe('2024-01-15')
expect(result.transactions[2].date).toBe('2024-01-13')
})
})
describe('parseBankFile: Handelsbanken format', () => {
it('parses semicolon-delimited CSV with comma decimal separator', () => {
const result = parseBankFile(HANDELSBANKEN_CSV, 'handelsbanken.csv')
expect(result.format).toBe('handelsbanken')
expect(result.format_name).toBe('Handelsbanken')
expect(result.transactions).toHaveLength(3)
expect(result.issues).toHaveLength(0)
})
it('correctly parses amounts and balances', () => {
const result = parseBankFile(HANDELSBANKEN_CSV, 'handelsbanken.csv')
expect(result.transactions[0].amount).toBe(-99)
expect(result.transactions[0].balance).toBe(12345.67)
expect(result.transactions[2].amount).toBe(25000)
})
it('filters out "Prel" (preliminary) transactions', () => {
const result = parseBankFile(HANDELSBANKEN_CSV_WITH_PREL, 'handelsbanken.csv')
expect(result.transactions).toHaveLength(2)
expect(result.stats.skipped_rows).toBe(1)
const descriptions = result.transactions.map((t) => t.description)
expect(descriptions).not.toContain(expect.stringContaining('Prel'))
})
it('uses reskontradatum when both date columns are present', () => {
// Handelsbanken has both columns; reskontradatum (booking date) should be used
const result = parseBankFile(HANDELSBANKEN_CSV, 'handelsbanken.csv')
// In our test data both dates are the same, but verify it selects dates properly
expect(result.transactions[0].date).toBe('2024-01-15')
})
it('uses reskontradatum (booking date), not transaktionsdatum, as the primary date field', () => {
// A card purchase booked two days after the swipe: the PSD2 / Enable Banking
// feed delivers this row on its booking_date (the 16th). Emitting the
// transaktionsdatum here would put the same affärshändelse in a different
// exact-date content-dedup bucket and insert it twice.
const diffDates = [
'Reskontradatum;Transaktionsdatum;Text;Belopp;Saldo',
'2026-03-16;2026-03-14;KORTKÖP CLAS OHLSON;-100,00;5000,00',
].join('\n')
const result = parseBankFile(diffDates, 'shb.csv')
expect(result.transactions[0].date).toBe('2026-03-16')
})
it('falls back to transaktionsdatum when reskontradatum is absent', () => {
const txOnly = [
'Transaktionsdatum;Text;Belopp;Saldo',
'2026-03-14;KORTKÖP CLAS OHLSON;-100,00;5000,00',
].join('\n')
const result = parseBankFile(txOnly, 'shb.csv')
expect(result.format).toBe('handelsbanken')
expect(result.transactions).toHaveLength(1)
expect(result.issues).toHaveLength(0)
expect(result.transactions[0].date).toBe('2026-03-14')
})
it('detects Handelsbanken CSV when a metadata preamble precedes the header', () => {
const format = detectFileFormat(HANDELSBANKEN_CSV_WITH_PREAMBLE, 'kontoutdrag.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('handelsbanken')
})
it('skips the metadata preamble rows and parses the transactions', () => {
const result = parseBankFile(HANDELSBANKEN_CSV_WITH_PREAMBLE, 'kontoutdrag.csv')
expect(result.format).toBe('handelsbanken')
expect(result.transactions).toHaveLength(3)
expect(result.issues).toHaveLength(0)
expect(result.stats.skipped_rows).toBe(0)
const descriptions = result.transactions.map((t) => t.description)
expect(descriptions).not.toContain('Kontonummer')
expect(result.transactions[0].description).toBe('SPOTIFY AB')
expect(result.transactions[2].amount).toBe(25000)
})
it('parses negative amounts that use a Unicode minus (U+2212) instead of dropping them', () => {
const result = parseBankFile(HANDELSBANKEN_CSV_UNICODE_MINUS, 'shb.csv')
expect(result.transactions).toHaveLength(3)
expect(result.issues).toHaveLength(0)
expect(result.stats.skipped_rows).toBe(0)
expect(result.transactions[0].amount).toBe(-139)
expect(result.transactions[1].amount).toBe(-1432.5)
expect(result.transactions[2].amount).toBe(25000)
})
it('handles a quoted Text field that contains the semicolon delimiter', () => {
const result = parseBankFile(HANDELSBANKEN_CSV_QUOTED_SEMICOLON, 'shb.csv')
expect(result.transactions).toHaveLength(2)
expect(result.issues).toHaveLength(0)
expect(result.transactions[0].description).toBe('BETALNING; FAKTURA 100')
expect(result.transactions[0].amount).toBe(-99)
expect(result.transactions[1].amount).toBe(-432.5)
})
})
describe('parseBankFile: Länsförsäkringar format', () => {
it('parses semicolon-delimited CSV with quoted fields and comma decimal separator', () => {
const result = parseBankFile(LANSFORSAKRINGAR_CSV, 'lf.csv')
expect(result.format).toBe('lansforsakringar')
expect(result.format_name).toBe('Länsförsäkringar')
expect(result.transactions).toHaveLength(3)
expect(result.issues).toHaveLength(0)
})
it('correctly parses amounts with comma decimal and space thousands', () => {
const result = parseBankFile(LANSFORSAKRINGAR_CSV, 'lf.csv')
expect(result.transactions[0].amount).toBe(-99)
expect(result.transactions[0].description).toBe('SPOTIFY AB')
expect(result.transactions[0].date).toBe('2024-01-15')
expect(result.transactions[1].amount).toBe(-432.5)
expect(result.transactions[2].amount).toBe(25000)
})
it('parses balance field', () => {
const result = parseBankFile(LANSFORSAKRINGAR_CSV, 'lf.csv')
expect(result.transactions[0].balance).toBe(12345.67)
})
it('handles files without a header row (data-only)', () => {
const result = parseBankFile(LANSFORSAKRINGAR_CSV_NO_HEADER, 'lf.csv')
expect(result.format).toBe('lansforsakringar')
expect(result.transactions).toHaveLength(2)
expect(result.transactions[0].amount).toBe(-99)
expect(result.transactions[1].amount).toBe(-432.5)
})
it('calculates stats correctly', () => {
const result = parseBankFile(LANSFORSAKRINGAR_CSV, 'lf.csv')
expect(result.stats.total_income).toBe(25000)
expect(result.stats.total_expenses).toBe(-531.5)
expect(result.stats.parsed_rows).toBe(3)
})
it('extracts correct date range', () => {
const result = parseBankFile(LANSFORSAKRINGAR_CSV, 'lf.csv')
expect(result.date_from).toBe('2024-01-13')
expect(result.date_to).toBe('2024-01-15')
})
it('uses Bokföringsdag (booking date), not Datum, when the two differ', () => {
// Same rationale as Handelsbanken: the PSD2 feed keys the row on its
// booking_date, so the CSV must emit the same date or the affärshändelse
// lands in two different exact-date dedup buckets and inserts twice.
const diffDates = [
'"Datum";"Bokföringsdag";"Typ";"Text";"Belopp";"Saldo"',
'"2026-03-14";"2026-03-16";"Kortköp";"CLAS OHLSON";"-100,00";"5 000,00"',
].join('\n')
const result = parseBankFile(diffDates, 'lf.csv')
expect(result.format).toBe('lansforsakringar')
expect(result.transactions).toHaveLength(1)
expect(result.transactions[0].date).toBe('2026-03-16')
})
it('uses the Bokföringsdag column position on header-less files', () => {
// The header-less layout is pinned by isLFRow (two adjacent dates, comma
// number in field 4), so field 1 is Bokföringsdag. Header-ful and
// header-less exports of the same account must agree on the date, or the
// two upload paths duplicate each other.
const noHeaderDiffDates = [
'"2026-03-14";"2026-03-16";"Kortköp";"CLAS OHLSON";"-100,00";"5 000,00"',
'"2026-03-11";"2026-03-12";"Kortköp";"ICA MAXI";"-432,50";"5 100,00"',
].join('\n')
const result = parseBankFile(noHeaderDiffDates, 'lf.csv')
expect(result.format).toBe('lansforsakringar')
expect(result.transactions).toHaveLength(2)
expect(result.transactions[0].date).toBe('2026-03-16')
expect(result.transactions[1].date).toBe('2026-03-12')
})
})
describe('parseBankFile: ICA Banken format', () => {
it('parses semicolon-delimited CSV with metadata rows before header', () => {
const result = parseBankFile(ICA_BANKEN_CSV, 'ica.csv')
expect(result.format).toBe('ica_banken')
expect(result.format_name).toBe('ICA Banken')
expect(result.transactions).toHaveLength(3)
expect(result.issues).toHaveLength(0)
})
it('skips metadata rows and finds the correct header', () => {
const result = parseBankFile(ICA_BANKEN_CSV, 'ica.csv')
// No transaction should contain metadata text
const descriptions = result.transactions.map((t) => t.description)
expect(descriptions).not.toContain(expect.stringContaining('Kontonamn'))
expect(descriptions).not.toContain(expect.stringContaining('Exporterad'))
})
it('correctly parses amounts with comma decimal separator', () => {
const result = parseBankFile(ICA_BANKEN_CSV, 'ica.csv')
expect(result.transactions[0].amount).toBe(-99)
expect(result.transactions[0].description).toBe('SPOTIFY AB')
expect(result.transactions[0].date).toBe('2024-01-15')
expect(result.transactions[1].amount).toBe(-432.5)
expect(result.transactions[2].amount).toBe(25000)
})
it('parses balance field', () => {
const result = parseBankFile(ICA_BANKEN_CSV, 'ica.csv')
expect(result.transactions[0].balance).toBe(12345.67)
})
it('calculates stats correctly', () => {
const result = parseBankFile(ICA_BANKEN_CSV, 'ica.csv')
expect(result.stats.total_income).toBe(25000)
expect(result.stats.total_expenses).toBe(-531.5)
expect(result.stats.parsed_rows).toBe(3)
})
it('extracts correct date range', () => {
const result = parseBankFile(ICA_BANKEN_CSV, 'ica.csv')
expect(result.date_from).toBe('2024-01-13')
expect(result.date_to).toBe('2024-01-15')
})
})
describe('parseBankFile: Skandia format', () => {
it('parses semicolon-delimited CSV with comma decimal separator', () => {
const result = parseBankFile(SKANDIA_CSV, 'skandia.csv')
expect(result.format).toBe('skandia')
expect(result.format_name).toBe('Skandia')
expect(result.transactions).toHaveLength(3)
expect(result.issues).toHaveLength(0)
})
it('correctly parses amounts and descriptions', () => {
const result = parseBankFile(SKANDIA_CSV, 'skandia.csv')
expect(result.transactions[0].amount).toBe(-99)
expect(result.transactions[0].description).toBe('SPOTIFY AB')
expect(result.transactions[0].date).toBe('2024-01-15')
expect(result.transactions[1].amount).toBe(-432.5)
expect(result.transactions[1].description).toBe('HEMKÖP FRIDHEMSPLAN')
expect(result.transactions[2].amount).toBe(25000)
})
it('parses balance field', () => {
const result = parseBankFile(SKANDIA_CSV, 'skandia.csv')
expect(result.transactions[0].balance).toBe(12345.67)
})
it('handles files with bankkategori column', () => {
const result = parseBankFile(SKANDIA_CSV_WITH_BANKKATEGORI, 'skandia.csv')
expect(result.format).toBe('skandia')
expect(result.transactions).toHaveLength(2)
expect(result.transactions[0].amount).toBe(-99)
expect(result.transactions[1].amount).toBe(-432.5)
})
it('calculates stats correctly', () => {
const result = parseBankFile(SKANDIA_CSV, 'skandia.csv')
expect(result.stats.total_income).toBe(25000)
expect(result.stats.total_expenses).toBe(-531.5)
expect(result.stats.parsed_rows).toBe(3)
})
it('extracts correct date range', () => {
const result = parseBankFile(SKANDIA_CSV, 'skandia.csv')
expect(result.date_from).toBe('2024-01-13')
expect(result.date_to).toBe('2024-01-15')
})
})
describe('parseBankFile: Lunar format', () => {
it('parses comma-delimited CSV with English headers', () => {
const result = parseBankFile(LUNAR_CSV, 'lunar.csv')
expect(result.format).toBe('lunar')
expect(result.format_name).toBe('Lunar')
expect(result.transactions).toHaveLength(3)
expect(result.issues).toHaveLength(0)
})
it('correctly parses amounts with comma decimal and period thousand separator', () => {
const result = parseBankFile(LUNAR_CSV, 'lunar.csv')
expect(result.transactions[0].amount).toBe(-99)
expect(result.transactions[0].description).toBe('SPOTIFY AB')
expect(result.transactions[0].date).toBe('2024-01-15')
expect(result.transactions[1].amount).toBe(-432.5)
expect(result.transactions[2].amount).toBe(25000)
})
it('parses balance field with period thousand separator', () => {
const result = parseBankFile(LUNAR_CSV, 'lunar.csv')
expect(result.transactions[0].balance).toBe(12345.67)
expect(result.transactions[2].balance).toBe(12877.17)
})
it('calculates stats correctly', () => {
const result = parseBankFile(LUNAR_CSV, 'lunar.csv')
expect(result.stats.total_income).toBe(25000)
expect(result.stats.total_expenses).toBe(-531.5)
expect(result.stats.parsed_rows).toBe(3)
})
it('extracts correct date range', () => {
const result = parseBankFile(LUNAR_CSV, 'lunar.csv')
expect(result.date_from).toBe('2024-01-13')
expect(result.date_to).toBe('2024-01-15')
})
it('does not confuse Lunar (English) with Nordea (Swedish) headers', () => {
// Nordea has Swedish headers, Lunar has English
const nordeaResult = detectFileFormat(NORDEA_CSV, 'test.csv')
const lunarResult = detectFileFormat(LUNAR_CSV, 'test.csv')
expect(nordeaResult!.id).toBe('nordea')
expect(lunarResult!.id).toBe('lunar')
})
// Regression tests for issue #915: the real 2026 Lunar export uses a SPACE
// thousands separator ("12 345,00") and a "Title" column instead of "Text".
it('parses 2026 Lunar amounts with space thousands separator without truncation', () => {
const result = parseBankFile(LUNAR_CSV_2026, 'lunar.csv')
expect(result.format).toBe('lunar')
expect(result.transactions).toHaveLength(3)
expect(result.issues).toHaveLength(0)
expect(result.transactions[0].amount).toBe(12345)
expect(result.transactions[1].amount).toBe(-1.49)
expect(result.transactions[2].amount).toBe(-2500)
})
it('parses 2026 Lunar balance with space thousands separator', () => {
const result = parseBankFile(LUNAR_CSV_2026, 'lunar.csv')
expect(result.transactions[0].balance).toBe(98764.94)
expect(result.transactions[1].balance).toBe(86419.94)
expect(result.transactions[2].balance).toBe(86421.43)
})
it('takes the description from the Title column in the 2026 format', () => {
const result = parseBankFile(LUNAR_CSV_2026, 'lunar.csv')
expect(result.transactions[0].description).toBe('Incoming payment')
expect(result.transactions[1].description).toBe('Fee')
expect(result.transactions[2].description).toBe('Card purchase')
})
it('calculates 2026 format stats and date range correctly', () => {
const result = parseBankFile(LUNAR_CSV_2026, 'lunar.csv')
expect(result.stats.total_income).toBe(12345)
expect(result.stats.total_expenses).toBe(-2501.49)
expect(result.stats.parsed_rows).toBe(3)
expect(result.date_from).toBe('2026-05-12')
expect(result.date_to).toBe('2026-06-30')
})
it('still parses the legacy Lunar period thousands separator ("1.234,56")', () => {
const legacy = [
'Date,Text,Amount,Balance',
'2024-01-15,PAYMENT,"1.234,56","10.000,00"',
].join('\n')
const result = parseBankFile(legacy, 'lunar.csv')
expect(result.format).toBe('lunar')
expect(result.transactions[0].amount).toBe(1234.56)
expect(result.transactions[0].balance).toBe(10000)
})
})
describe('parseBankFile: Northmill format', () => {
it('skips the 5-line metadata preamble and blank lines, parses transaction rows', () => {
const result = parseBankFile(NORTHMILL_CSV, 'Northmill.csv')
expect(result.format).toBe('northmill')
expect(result.format_name).toBe('Northmill')
expect(result.transactions).toHaveLength(4)
expect(result.issues).toHaveLength(0)
})
it('correctly parses negative amounts that use Unicode minus (U+2212)', () => {
const result = parseBankFile(NORTHMILL_CSV, 'Northmill.csv')
// First transaction is "−139,00" with U+2212: must become -139, not NaN
expect(result.transactions[0].amount).toBe(-139)
expect(result.transactions[0].description).toBe('Månadsavgift företagspaket april')
expect(result.transactions[0].date).toBe('2026-04-01')
expect(result.transactions[1].amount).toBe(-1000)
expect(result.transactions[2].amount).toBe(400000)
expect(result.transactions[3].amount).toBe(25000)
})
it('extracts the saldo (running balance) column', () => {
const result = parseBankFile(NORTHMILL_CSV, 'Northmill.csv')
expect(result.transactions[0].balance).toBe(251495.41)
expect(result.transactions[3].balance).toBe(25000)
})
it('calculates income vs expenses correctly with Unicode minus amounts', () => {
const result = parseBankFile(NORTHMILL_CSV, 'Northmill.csv')
expect(result.stats.total_income).toBe(425000)
expect(result.stats.total_expenses).toBe(-1139)
expect(result.stats.parsed_rows).toBe(4)
expect(result.stats.skipped_rows).toBe(0)
})
it('extracts the correct date range from the transactions, not the Period metadata row', () => {
const result = parseBankFile(NORTHMILL_CSV, 'Northmill.csv')
expect(result.date_from).toBe('2025-10-01')
expect(result.date_to).toBe('2026-04-01')
})
})
describe('parseBankFile: camt.053 XML format', () => {
it('parses XML with credit and debit entries', () => {
const result = parseBankFile(CAMT053_XML, 'statement.xml')
expect(result.format).toBe('camt053')
expect(result.format_name).toBe('ISO 20022 camt.053')
expect(result.transactions).toHaveLength(2)
})
it('applies DBIT indicator as negative amount', () => {
const result = parseBankFile(CAMT053_XML, 'statement.xml')
const debit = result.transactions.find((t) => t.description === 'SPOTIFY AB')
expect(debit).toBeDefined()
expect(debit!.amount).toBe(-99)
})
it('applies CRDT indicator as positive amount', () => {
const result = parseBankFile(CAMT053_XML, 'statement.xml')
const credit = result.transactions.find((t) => t.description === 'LÖNEUTBETALNING')
expect(credit).toBeDefined()
expect(credit!.amount).toBe(25000)
})
it('extracts entry reference into raw_line for external ID generation', () => {
const result = parseBankFile(CAMT053_XML, 'statement.xml')
const debit = result.transactions[0]
expect(debit.raw_line).toBe('REF001')
})
it('extracts OCR reference from structured remittance info', () => {
const result = parseBankFile(CAMT053_XML_WITH_STRUCTURED_REF, 'statement.xml')
expect(result.transactions).toHaveLength(1)
expect(result.transactions[0].reference).toBe('OCR123456789')
})
it('uses unstructured remittance info as description', () => {
const result = parseBankFile(CAMT053_XML, 'statement.xml')
expect(result.transactions[0].description).toBe('SPOTIFY AB')
})
it('extracts currency from Amount element', () => {
const result = parseBankFile(CAMT053_XML, 'statement.xml')
result.transactions.forEach((tx) => {
expect(tx.currency).toBe('SEK')
})
})
it('handles XML with no Ntry elements', () => {
const emptyXml = `<?xml version="1.0"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.02">
<BkToCstmrStmt><Stmt></Stmt></BkToCstmrStmt></Document>`
const result = parseBankFile(emptyXml, 'empty.xml')
expect(result.format).toBe('camt053')
expect(result.transactions).toHaveLength(0)
expect(result.issues.length).toBeGreaterThan(0)
expect(result.issues[0].message).toContain('No <Ntry> elements')
})
})
describe('parseBankFile: explicit format override', () => {
it('uses the specified format instead of auto-detection', () => {
// Force parsing Nordea content as SEB (will produce issues but should use SEB format)
const result = parseBankFile(
'Datum,Transaktion,Kategori,Belopp,Saldo\n2024-01-15,Test,,"-100,00","5000,00"',
'nordea.csv',
'seb'
)
expect(result.format).toBe('seb')
})
it('returns error for unknown formatId', () => {
const result = parseBankFile(NORDEA_CSV, 'test.csv', 'unknown_format' as BankFileFormatId)
expect(result.format).toBe('unknown_format')
expect(result.format_name).toBe('Unknown')
expect(result.transactions).toHaveLength(0)
expect(result.issues).toHaveLength(1)
expect(result.issues[0].severity).toBe('error')
expect(result.issues[0].message).toContain('Unknown format')
})
it('returns format detection error when no format matches and no override given', () => {
const result = parseBankFile(UNKNOWN_CSV, 'unknown.csv')
expect(result.format).toBe('generic_csv')
expect(result.format_name).toBe('Unknown')
expect(result.transactions).toHaveLength(0)
expect(result.issues).toHaveLength(1)
expect(result.issues[0].message).toContain('Kunde inte identifiera bankformat')
})
it('can force generic_csv format by explicit ID', () => {
const csvContent = '2024-01-15,Some purchase,-50.00\n2024-01-16,Income,1000.00'
const result = parseBankFile(csvContent, 'test.csv', 'generic_csv')
// generic_csv uses a default mapping (date=0, description=1, amount=2)
// But the first line is treated as header (skip_rows=1), so only second row is data
expect(result.format).toBe('generic_csv')
})
})
describe('generateExternalId', () => {
const baseTx: ParsedBankTransaction = {
date: '2024-01-15',
description: 'SPOTIFY AB',
amount: -99,
currency: 'SEK',
balance: 12345.67,
reference: null,
counterparty: null,
raw_line: '2024-01-15,SPOTIFY AB,,"-99,00","12 345,67"',
}
it('generates SHA-256 composite key for CSV formats', () => {
const id = generateExternalId(baseTx, 'nordea', 0)
expect(id).toMatch(/^nordea_[0-9a-f]{16}$/)
})
it('generates different IDs for different row indices (same transaction data)', () => {
const id1 = generateExternalId(baseTx, 'nordea', 0)
const id2 = generateExternalId(baseTx, 'nordea', 1)
expect(id1).not.toBe(id2)
})
it('generates different IDs for different formats (same data, same row index)', () => {
const nordeaId = generateExternalId(baseTx, 'nordea', 0)
const sebId = generateExternalId(baseTx, 'seb', 0)
expect(nordeaId).not.toBe(sebId)
})
it('generates deterministic IDs for the same inputs', () => {
const id1 = generateExternalId(baseTx, 'nordea', 0)
const id2 = generateExternalId(baseTx, 'nordea', 0)
expect(id1).toBe(id2)
})
it('uses entry reference for camt.053 transactions with NtryRef', () => {
const camtTx: ParsedBankTransaction = {
date: '2024-01-15',
description: 'SPOTIFY AB',
amount: -99,
currency: 'SEK',
raw_line: 'REF001', // NtryRef stored in raw_line
}
const id = generateExternalId(camtTx, 'camt053', 0)
expect(id).toBe('camt053_REF001')
})
it('falls back to hash for camt.053 when raw_line starts with camt053_entry_', () => {
const camtTx: ParsedBankTransaction = {
date: '2024-01-15',
description: 'SPOTIFY AB',
amount: -99,
currency: 'SEK',
raw_line: 'camt053_entry_0', // Auto-generated fallback reference
}
const id = generateExternalId(camtTx, 'camt053', 0)
// Should fall through to hash-based ID since raw_line starts with 'camt053_entry_'
expect(id).toMatch(/^camt053_[0-9a-f]{16}$/)
})
it('falls back to hash for camt.053 when raw_line is undefined', () => {
const camtTx: ParsedBankTransaction = {
date: '2024-01-15',
description: 'SPOTIFY AB',
amount: -99,
currency: 'SEK',
}
const id = generateExternalId(camtTx, 'camt053', 0)
expect(id).toMatch(/^camt053_[0-9a-f]{16}$/)
})
it('includes amount in hash so different amounts produce different IDs', () => {
const tx1 = { ...baseTx, amount: -99 }
const tx2 = { ...baseTx, amount: -100 }
const id1 = generateExternalId(tx1, 'nordea', 0)
const id2 = generateExternalId(tx2, 'nordea', 0)
expect(id1).not.toBe(id2)
})
it('includes description in hash so different descriptions produce different IDs', () => {
const tx1 = { ...baseTx, description: 'SPOTIFY AB' }
const tx2 = { ...baseTx, description: 'NETFLIX' }
const id1 = generateExternalId(tx1, 'nordea', 0)
const id2 = generateExternalId(tx2, 'nordea', 0)
expect(id1).not.toBe(id2)
})
})
describe('generateFileHash', () => {
it('returns a SHA-256 hex string', () => {
const hash = generateFileHash(NORDEA_CSV)
expect(hash).toMatch(/^[0-9a-f]{64}$/)
})
it('produces deterministic output for the same input', () => {
const hash1 = generateFileHash(NORDEA_CSV)
const hash2 = generateFileHash(NORDEA_CSV)
expect(hash1).toBe(hash2)
})
it('produces different hashes for different content', () => {
const hash1 = generateFileHash(NORDEA_CSV)
const hash2 = generateFileHash(SEB_CSV)
expect(hash1).not.toBe(hash2)
})
it('produces different hash even for tiny content differences', () => {
const hash1 = generateFileHash('abc')
const hash2 = generateFileHash('abd')
expect(hash1).not.toBe(hash2)
})
it('handles empty string', () => {
const hash = generateFileHash('')
expect(hash).toMatch(/^[0-9a-f]{64}$/)
})
})
describe('stats calculation', () => {
it('calculates total_income as sum of positive amounts (Nordea)', () => {
const result = parseBankFile(NORDEA_CSV, 'nordea.csv')
expect(result.stats.total_income).toBe(25000)
})
it('calculates total_expenses as sum of negative amounts (Nordea)', () => {
const result = parseBankFile(NORDEA_CSV, 'nordea.csv')
// -99 + -432.5 = -531.5
expect(result.stats.total_expenses).toBe(-531.5)
})
it('calculates parsed_rows correctly', () => {
const result = parseBankFile(NORDEA_CSV, 'nordea.csv')
expect(result.stats.parsed_rows).toBe(3)
})
it('calculates total_rows (excluding header)', () => {
const result = parseBankFile(NORDEA_CSV, 'nordea.csv')
// 4 lines total - 1 header = 3 data rows
expect(result.stats.total_rows).toBe(3)
})
it('tracks skipped_rows for reserved/preliminary transactions', () => {
const result = parseBankFile(NORDEA_CSV_WITH_RESERVED, 'nordea.csv')
expect(result.stats.skipped_rows).toBe(1)
expect(result.stats.parsed_rows).toBe(2)
})
it('calculates stats correctly for SEB format', () => {
const result = parseBankFile(SEB_CSV, 'seb.csv')
expect(result.stats.total_income).toBe(25000)
expect(result.stats.total_expenses).toBe(-531.5)
expect(result.stats.parsed_rows).toBe(3)
expect(result.stats.skipped_rows).toBe(0)
})
it('calculates stats correctly for Swedbank format', () => {
const result = parseBankFile(SWEDBANK_CSV, 'swedbank.csv')
expect(result.stats.total_income).toBe(25000)
expect(result.stats.total_expenses).toBe(-531.5)
expect(result.stats.parsed_rows).toBe(3)
})
it('calculates stats correctly for camt.053 XML', () => {
const result = parseBankFile(CAMT053_XML, 'statement.xml')
expect(result.stats.total_income).toBe(25000)
expect(result.stats.total_expenses).toBe(-99)
expect(result.stats.parsed_rows).toBe(2)
expect(result.stats.total_rows).toBe(2)
})
it('uses Math.round(x * 100) / 100 for monetary precision', () => {
// Create a file that would produce floating point imprecision
const precisionCSV = [
'Datum,Transaktion,Kategori,Belopp,Saldo',
'2024-01-01,TX1,,"-0,10","100,00"',
'2024-01-02,TX2,,"-0,20","99,90"',
'2024-01-03,TX3,,"-0,30","99,70"',
].join('\n')
const result = parseBankFile(precisionCSV, 'precision.csv')
// 0.1 + 0.2 + 0.3 = 0.6000000000000001 without rounding
// With Math.round(x * 100) / 100, it should be -0.6
expect(result.stats.total_expenses).toBe(-0.6)
})
})
describe('date range extraction', () => {
it('sets date_from to the earliest date', () => {
const result = parseBankFile(NORDEA_CSV, 'nordea.csv')
expect(result.date_from).toBe('2024-01-13')
})
it('sets date_to to the latest date', () => {
const result = parseBankFile(NORDEA_CSV, 'nordea.csv')
expect(result.date_to).toBe('2024-01-15')
})
it('returns null dates for empty transaction set', () => {
const result = parseBankFile(HEADER_ONLY_NORDEA, 'nordea.csv')
expect(result.date_from).toBeNull()
expect(result.date_to).toBeNull()
})
it('handles single-transaction file (date_from equals date_to)', () => {
const singleRow = [
'Datum,Transaktion,Kategori,Belopp,Saldo',
'2024-06-15,ENSKILD BETALNING,,"-500,00","10 000,00"',
].join('\n')
const result = parseBankFile(singleRow, 'single.csv')
expect(result.date_from).toBe('2024-06-15')
expect(result.date_to).toBe('2024-06-15')
})
it('calculates correct date range for camt.053', () => {
const result = parseBankFile(CAMT053_XML, 'statement.xml')
expect(result.date_from).toBe('2024-01-14')
expect(result.date_to).toBe('2024-01-15')
})
it('sorts dates lexicographically (YYYY-MM-DD is naturally sortable)', () => {
const multiMonth = [
'Datum,Transaktion,Kategori,Belopp,Saldo',
'2024-12-31,DEC TX,,"-10,00","1000,00"',
'2024-01-01,JAN TX,,"-20,00","990,00"',
'2024-06-15,JUN TX,,"-30,00","960,00"',
].join('\n')
const result = parseBankFile(multiMonth, 'multimonth.csv')
expect(result.date_from).toBe('2024-01-01')
expect(result.date_to).toBe('2024-12-31')
})
})
describe('empty file handling', () => {
it('returns error result for completely empty file (no auto-detect match)', () => {
const result = parseBankFile(EMPTY_FILE, 'empty.csv')
expect(result.transactions).toHaveLength(0)
expect(result.issues.length).toBeGreaterThan(0)
expect(result.date_from).toBeNull()
expect(result.date_to).toBeNull()
expect(result.stats.parsed_rows).toBe(0)
})
it('returns zero transactions for file with only whitespace', () => {
const whitespace = ' \n \n '
const result = parseBankFile(whitespace, 'blank.csv')
expect(result.transactions).toHaveLength(0)
})
it('returns zero transactions for Nordea header-only file', () => {
const result = parseBankFile(HEADER_ONLY_NORDEA, 'nordea.csv')
expect(result.format).toBe('nordea')
expect(result.transactions).toHaveLength(0)
expect(result.stats.total_rows).toBe(0)
})
})
describe('getFormat and getAllFormats', () => {
it('getFormat returns the correct format by ID', () => {
const nordea = getFormat('nordea')
expect(nordea).toBeDefined()
expect(nordea!.id).toBe('nordea')
expect(nordea!.name).toBe('Nordea')
const seb = getFormat('seb')
expect(seb).toBeDefined()
expect(seb!.id).toBe('seb')
})
it('getFormat returns undefined for unknown ID', () => {
const unknown = getFormat('nonexistent' as BankFileFormatId)
expect(unknown).toBeUndefined()
})
it('getAllFormats returns all registered formats', () => {
const formats = getAllFormats()
expect(formats.length).toBeGreaterThanOrEqual(10)
const ids = formats.map((f) => f.id)
expect(ids).toContain('nordea')
expect(ids).toContain('seb')
expect(ids).toContain('swedbank')
expect(ids).toContain('handelsbanken')
expect(ids).toContain('lansforsakringar')
expect(ids).toContain('ica_banken')
expect(ids).toContain('skandia')
expect(ids).toContain('lunar')
expect(ids).toContain('camt053')
expect(ids).toContain('generic_csv')
})
it('camt053 is listed before bank-specific CSV formats (detection priority)', () => {
const formats = getAllFormats()
const camtIdx = formats.findIndex((f) => f.id === 'camt053')
const nordeaIdx = formats.findIndex((f) => f.id === 'nordea')
expect(camtIdx).toBeLessThan(nordeaIdx)
})
it('generic_csv is listed last (manual fallback only)', () => {
const formats = getAllFormats()
const genericIdx = formats.findIndex((f) => f.id === 'generic_csv')
expect(genericIdx).toBe(formats.length - 1)
})
})
describe('edge cases and robustness', () => {
it('handles Windows-style line endings (CRLF)', () => {
const crlfContent = 'Datum,Transaktion,Kategori,Belopp,Saldo\r\n2024-01-15,SPOTIFY AB,,"-99,00","12 345,67"\r\n'
const result = parseBankFile(crlfContent, 'nordea.csv')
expect(result.format).toBe('nordea')
expect(result.transactions).toHaveLength(1)
expect(result.transactions[0].amount).toBe(-99)
})
it('handles BOM (Byte Order Mark) prefix', () => {
const bomContent = '\uFEFF' + NORDEA_CSV
const result = parseBankFile(bomContent, 'nordea.csv')
expect(result.format).toBe('nordea')
expect(result.transactions).toHaveLength(3)
})
it('handles rows with invalid dates gracefully', () => {
const invalidDate = [
'Bokföringsdag;Valutadag;Verifikationsnummer;Text;Belopp;Saldo',
'not-a-date;2024-01-15;12345;SPOTIFY AB;-99,00;12345,67',
'2024-01-14;2024-01-14;12346;VALID TX;-50,00;12395,67',
].join('\n')
const result = parseBankFile(invalidDate, 'seb.csv')
expect(result.transactions).toHaveLength(1)
expect(result.transactions[0].description).toBe('VALID TX')
expect(result.issues.length).toBeGreaterThan(0)
expect(result.stats.skipped_rows).toBe(1)
})
it('handles rows with invalid amounts gracefully', () => {
const invalidAmount = [
'Datum,Transaktion,Kategori,Belopp,Saldo',
'2024-01-15,SPOTIFY AB,,"abc","12 345,67"',
'2024-01-14,VALID TX,,"-50,00","12 395,67"',
].join('\n')
const result = parseBankFile(invalidAmount, 'nordea.csv')
expect(result.transactions).toHaveLength(1)
expect(result.transactions[0].description).toBe('VALID TX')
expect(result.stats.skipped_rows).toBe(1)
})
it('handles trailing blank lines', () => {
const trailing = NORDEA_CSV + '\n\n\n'
const result = parseBankFile(trailing, 'nordea.csv')
expect(result.transactions).toHaveLength(3)
})
it('handles Handelsbanken CSV with only reskontradatum (no transaktionsdatum)', () => {
const onlyReskontra = [
'Reskontradatum;Text;Belopp;Saldo',
'2024-01-15;SPOTIFY AB;-99,00;12345,67',
].join('\n')
const format = detectFileFormat(onlyReskontra, 'shb.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('handelsbanken')
})
it('handles large amounts without overflow', () => {
const largeAmounts = [
'Datum,Transaktion,Kategori,Belopp,Saldo',
'2024-01-15,BIG TRANSFER,,"1 500 000,00","2 000 000,00"',
].join('\n')
const result = parseBankFile(largeAmounts, 'nordea.csv')
expect(result.transactions).toHaveLength(1)
expect(result.transactions[0].amount).toBe(1500000)
expect(result.transactions[0].balance).toBe(2000000)
})
it('handles zero amounts', () => {
const zeroAmount = [
'Datum,Transaktion,Kategori,Belopp,Saldo',
'2024-01-15,FEE REVERSAL,,"0,00","5 000,00"',
].join('\n')
const result = parseBankFile(zeroAmount, 'nordea.csv')
expect(result.transactions).toHaveLength(1)
expect(result.transactions[0].amount).toBe(0)
})
})
// --- Fix 5: SEB duplicate condition removal ---
describe('SEB detection: no duplicate conditions', () => {
it('detects SEB with bokföringsdag header', () => {
const content = 'Bokföringsdag;Valutadag;Text;Belopp;Saldo\n2024-01-15;2024-01-15;Test;-100,00;5000,00'
const format = detectFileFormat(content, 'seb.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('seb')
})
it('detects SEB with bokforingsdatum header (no diacritics)', () => {
const content = 'Bokforingsdatum;Valutadag;Text;Belopp;Saldo\n2024-01-15;2024-01-15;Test;-100,00;5000,00'
const format = detectFileFormat(content, 'seb.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('seb')
})
})
// --- Fix 6: Länsförsäkringar false positive prevention ---
describe('Länsförsäkringar detection: false positive prevention', () => {
it('detects valid LF data rows with comma-decimal amounts', () => {
const format = detectFileFormat(LANSFORSAKRINGAR_CSV, 'lf.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('lansforsakringar')
})
it('detects LF header-less data with two dates and comma-decimal amount', () => {
const format = detectFileFormat(LANSFORSAKRINGAR_CSV_NO_HEADER, 'lf.csv')
expect(format).not.toBeNull()
expect(format!.id).toBe('lansforsakringar')
})
it('does not false-positive on generic semicolon CSV with two date columns but non-numeric 5th field', () => {
// This CSV has two date columns + 5 fields but the 5th field is not a number
const falsePositive = [
'"2024-01-15";"2024-01-15";"Typ";"Text";"not-a-number"',
].join('\n')
const format = detectFileFormat(falsePositive, 'generic.csv')
// Should NOT detect as Länsförsäkringar
expect(format?.id).not.toBe('lansforsakringar')
})
})
// --- Fix 7: Generic CSV column bounds checking ---
describe('parseGenericCSV: column bounds checking', () => {
it('skips rows with too few columns and adds warning', () => {
const content = [
'Date,Description,Amount',
'2024-01-15,Test,-100.00',
'2024-01-16,Short', // Only 2 columns, mapping needs column 2 (amount)
].join('\n')
const result = parseGenericCSV(content, {
date: 0,
description: 1,
amount: 2,
delimiter: ',',
decimal_separator: '.',
skip_rows: 1,
date_format: 'YYYY-MM-DD',
})
expect(result.transactions).toHaveLength(1)
expect(result.transactions[0].description).toBe('Test')
expect(result.stats.skipped_rows).toBe(1)
expect(result.issues.some((i) => i.message.includes('columns but mapping requires'))).toBe(true)
})
it('skips rows when mapping index exceeds field count', () => {
const content = [
'A,B',
'val1,val2',
].join('\n')
const result = parseGenericCSV(content, {
date: 0,
description: 1,
amount: 5, // Column 5 does not exist (only 2 columns)
delimiter: ',',
decimal_separator: '.',
skip_rows: 1,
date_format: 'YYYY-MM-DD',
})
expect(result.transactions).toHaveLength(0)
expect(result.stats.skipped_rows).toBe(1)
expect(result.issues).toHaveLength(1)
})
it('parses normally when all columns are within bounds', () => {
const content = [
'Date,Description,Amount',
'2024-01-15,SPOTIFY,-99.00',
'2024-01-16,SALARY,25000.00',
].join('\n')
const result = parseGenericCSV(content, {
date: 0,
description: 1,
amount: 2,
delimiter: ',',
decimal_separator: '.',
skip_rows: 1,
date_format: 'YYYY-MM-DD',
})
expect(result.transactions).toHaveLength(2)
expect(result.stats.skipped_rows).toBe(0)
expect(result.issues).toHaveLength(0)
})
it('parses amounts that use Unicode minus (U+2212): was NaN before normalization', () => {
const content = [
'Date,Description,Amount',
'2024-01-15,SPOTIFY,"\u221299,00"',
'2024-01-16,REFUND,"\u201350,00"',
'2024-01-17,SALARY,"25000,00"',
].join('\n')
const result = parseGenericCSV(content, {
date: 0,
description: 1,
amount: 2,
delimiter: ',',
decimal_separator: ',',
skip_rows: 1,
date_format: 'YYYY-MM-DD',
})
expect(result.transactions).toHaveLength(3)
expect(result.transactions[0].amount).toBe(-99)
expect(result.transactions[1].amount).toBe(-50)
expect(result.transactions[2].amount).toBe(25000)
})
it('skips metadata rows when skip_rows is set higher than 1 (multi-row preamble)', () => {
// Mimics a file with 5 metadata rows + header + 2 transactions.
const content = [
'Account,12345',
'Owner,Acme AB',
'Period,2024-01,2024-12',
'Currency,SEK',
'Type,Statement',
'Date,Description,Amount',
'2024-01-15,SPOTIFY,-99.00',
'2024-01-16,SALARY,25000.00',
].join('\n')
const result = parseGenericCSV(content, {
date: 0,
description: 1,
amount: 2,
delimiter: ',',
decimal_separator: '.',
skip_rows: 6,
date_format: 'YYYY-MM-DD',
})
expect(result.transactions).toHaveLength(2)
expect(result.transactions[0].amount).toBe(-99)
expect(result.transactions[1].amount).toBe(25000)
expect(result.issues).toHaveLength(0)
})
})
describe('normalizeMinusSign', () => {
it('replaces U+2212 (minus sign) with ASCII hyphen', () => {
expect(normalizeMinusSign('\u2212139,00')).toBe('-139,00')
})
it('replaces U+2013 (en dash) and U+2014 (em dash) with ASCII hyphen', () => {
expect(normalizeMinusSign('\u2013100')).toBe('-100')
expect(normalizeMinusSign('\u2014250')).toBe('-250')
})
it('leaves ASCII hyphen and digits untouched', () => {
expect(normalizeMinusSign('-139.00')).toBe('-139.00')
expect(normalizeMinusSign('139.00')).toBe('139.00')
})
it('makes parseFloat work on Unicode-minus strings (regression for Northmill)', () => {
expect(parseFloat('\u2212139.00')).toBeNaN()
expect(parseFloat(normalizeMinusSign('\u2212139.00'))).toBe(-139)
})
})
// --- Fix 8: parseCSVLine unclosed quote handling ---
describe('parseCSVLine: unclosed quote handling', () => {
it('handles normal quoted fields correctly', () => {
const fields = parseCSVLine('"hello","world"', ',')
expect(fields).toEqual(['hello', 'world'])
})
it('handles escaped quotes (doubled) inside fields', () => {
const fields = parseCSVLine('"he said ""hi""",other', ',')
expect(fields).toEqual(['he said "hi"', 'other'])
})
it('produces a result even with unclosed quotes instead of hanging', () => {
// Unclosed quote: the parser should not hang or crash
const fields = parseCSVLine('"unclosed,field2,field3', ',')
// With unclosed quote, everything after the opening quote is one field
// The important thing is it doesn't crash and returns something
expect(fields.length).toBeGreaterThan(0)
})
it('preserves data with unclosed quote rather than losing it', () => {
const fields = parseCSVLine('normal,"unclosed value', ',')
// Should have at least the first field and whatever was accumulated
expect(fields.length).toBe(2)
expect(fields[0]).toBe('normal')
// The unclosed quoted field should still contain the text
expect(fields[1]).toContain('unclosed value')
})
it('handles semicolon delimiter with quotes', () => {
const fields = parseCSVLine('"2024-01-15";"SPOTIFY AB";"-99,00"', ';')
expect(fields).toEqual(['2024-01-15', 'SPOTIFY AB', '-99,00'])
})
})
// ---------------------------------------------------------------------------
// Wise (TransferWise) multi-currency transaction history
// ---------------------------------------------------------------------------
const WISE_HEADER =
'ID,Status,Direction,"Created on","Finished on","Source fee amount","Source fee currency","Target fee amount","Target fee currency","Source name","Source amount (after fees)","Source currency","Target name","Target amount (after fees)","Target currency","Exchange rate",Reference,Batch,"Created by",Category,Note'
const WISE_CSV = [
WISE_HEADER,
'TRANSFER-2247230173,COMPLETED,IN,"2026-07-13 13:39:01","2026-07-13 13:39:08",,,,,"Bluedot Impact Ltd",2500.0,USD,"Aligned Intelligence AB",2500.0,USD,1,Facilitation,,,"Money added",',
'TRANSFER-2214309703,COMPLETED,IN,"2026-06-26 20:53:33","2026-06-26 20:54:14",2.20,SEK,,,"Aligned Intelligence AB",200.0,SEK,"Aligned Intelligence AB",200.0,SEK,1.0,,,"Peter Alexander Reinthal","Money added",',
'PLAN_ORDER-28688820,COMPLETED,OUT,"2026-06-24 06:13:45","2026-06-24 06:41:51",,,,,,520.00,SEK,TransferWise,520.00,SEK,1.00000000,28688820,,"Peter Alexander Reinthal",General,',
'TRANSFER-2208605608,COMPLETED,IN,"2026-06-24 06:13:45","2026-06-24 06:41:50",0.00,SEK,,,"Aligned Intelligence AB",520.0,SEK,"Aligned Intelligence AB",520.0,SEK,1.0,invoice-28688820,,"Peter Alexander Reinthal","Money added",',
].join('\n')
describe('Wise format', () => {
it('auto-detects the Wise header', () => {
const format = detectFileFormat(WISE_CSV, 'transactionhistory.csv')
expect(format?.id).toBe('wise')
})
const byId = (txs: ParsedBankTransaction[], id: string) => txs.find((t) => t.raw_line === id)
it('signs IN as income and OUT as expense, on the moved-side currency', () => {
const result = parseBankFile(WISE_CSV, 'wise.csv')
expect(result.format).toBe('wise')
const usdIn = byId(result.transactions, 'TRANSFER-2247230173')
expect(usdIn).toMatchObject({ amount: 2500, currency: 'USD', date: '2026-07-13' })
const sekOut = byId(result.transactions, 'PLAN_ORDER-28688820')
expect(sekOut).toMatchObject({ amount: -520, currency: 'SEK', date: '2026-06-24' })
expect(sekOut?.counterparty).toBe('TransferWise')
})
it('emits a non-zero fee as its own negative "Wise avgift" row', () => {
const result = parseBankFile(WISE_CSV, 'wise.csv')
const fee = byId(result.transactions, 'TRANSFER-2214309703-fee')
expect(fee).toBeDefined()
expect(fee?.amount).toBe(-2.2)
expect(fee?.currency).toBe('SEK')
expect(fee?.description).toMatch(/^Wise avgift/)
// A 0.00 fee produces no extra row.
expect(byId(result.transactions, 'TRANSFER-2208605608-fee')).toBeUndefined()
// 4 movements + 1 fee row.
expect(result.transactions).toHaveLength(5)
})
it('keys external_id on the stable Wise ID, including fee rows', () => {
const result = parseBankFile(WISE_CSV, 'wise.csv')
const main = byId(result.transactions, 'TRANSFER-2247230173')!
const fee = byId(result.transactions, 'TRANSFER-2214309703-fee')!
expect(generateExternalId(main, 'wise', 0)).toBe('wise_TRANSFER-2247230173')
expect(generateExternalId(fee, 'wise', 1)).toBe('wise_TRANSFER-2214309703-fee')
})
it('skips rows that are not COMPLETED', () => {
const withCancelled = [
WISE_HEADER,
'TRANSFER-9,CANCELLED,IN,"2026-06-01 10:00:00","2026-06-01 10:00:00",,,,,"X",100.0,SEK,"Y",100.0,SEK,1,,,,General,',
'TRANSFER-2247230173,COMPLETED,IN,"2026-07-13 13:39:01","2026-07-13 13:39:08",,,,,"Bluedot Impact Ltd",2500.0,USD,"Aligned Intelligence AB",2500.0,USD,1,Facilitation,,,"Money added",',
].join('\n')
const result = parseBankFile(withCancelled, 'wise.csv')
expect(result.transactions).toHaveLength(1)
expect(result.transactions[0].raw_line).toBe('TRANSFER-2247230173')
expect(result.stats.skipped_rows).toBe(1)
})
})
describe('Wise format hardening', () => {
const row = (over: Partial<Record<string, string>> = {}) => {
const f: Record<string, string> = {
id: 'TRANSFER-1', status: 'COMPLETED', direction: 'IN',
created: '2026-06-01 10:00:00', finished: '2026-06-01 10:00:00',
sfeeA: '', sfeeC: '', tfeeA: '', tfeeC: '',
sname: 'X', samt: '100.0', scur: 'SEK', tname: 'Y', tamt: '100.0', tcur: 'SEK',
rate: '1', ref: '', batch: '', by: '', cat: 'General', note: '', ...over,
}
return [
f.id, f.status, f.direction, `"${f.created}"`, `"${f.finished}"`,
f.sfeeA, f.sfeeC, f.tfeeA, f.tfeeC, `"${f.sname}"`, f.samt, f.scur,
`"${f.tname}"`, f.tamt, f.tcur, f.rate, f.ref, f.batch, `"${f.by}"`, f.cat, f.note,
].join(',')
}
it('fails hard on an unsupported Direction (e.g. NEUTRAL conversion)', () => {
const csv = [WISE_HEADER, row({ id: 'PLAN_ORDER-9', direction: 'NEUTRAL', scur: 'USD', tcur: 'SEK' })].join('\n')
expect(() => parseBankFile(csv, 'wise.csv')).toThrow(/unsupported Direction "NEUTRAL"/)
})
it('does not import a row with a blank status', () => {
const csv = [WISE_HEADER, row({ status: '' })].join('\n')
const result = parseBankFile(csv, 'wise.csv')
expect(result.transactions).toHaveLength(0)
expect(result.stats.skipped_rows).toBe(1)
})
it('rejects a partially numeric amount instead of coercing it', () => {
const csv = [WISE_HEADER, row({ samt: '12abc', tamt: '12abc' })].join('\n')
const result = parseBankFile(csv, 'wise.csv')
expect(result.transactions).toHaveLength(0)
expect(result.issues.some((iss) => /Invalid amount/.test(iss.message))).toBe(true)
})
it('skips a row with no movement currency rather than defaulting to SEK', () => {
const csv = [WISE_HEADER, row({ direction: 'IN', tcur: '' })].join('\n')
const result = parseBankFile(csv, 'wise.csv')
expect(result.transactions).toHaveLength(0)
expect(result.issues.some((iss) => /Missing\/invalid currency/.test(iss.message))).toBe(true)
})
it('does not inherit the movement currency for a fee with no currency', () => {
const csv = [WISE_HEADER, row({ sfeeA: '2.20', sfeeC: '' })].join('\n')
const result = parseBankFile(csv, 'wise.csv')
// Main row still imports; the fee is dropped with a warning, not booked in SEK.
expect(result.transactions).toHaveLength(1)
expect(result.transactions[0].raw_line).toBe('TRANSFER-1')
expect(result.issues.some((iss) => /no currency/.test(iss.message))).toBe(true)
})
})