Files
accounted/extensions/general/enable-banking/lib/sync.ts
T
Jakob Wennberg 70845edf69 feat(transactions): structured transaction_method instead of channel-in-the-name (#1459)
* feat(transactions): structured transaction_method instead of channel-in-the-name

Swedish bank feeds embed the payment channel in the description string
("Vercel Jul Överföring via internet", "ANTHROPIC* ... Kortköp/uttag"):
the PSD2 remittance array is joined into one string and the ISO 20022
type codes were dropped at insert. This promotes the channel to data:

- transactions.transaction_method (text + CHECK closed vocabulary: card,
  transfer, bankgiro, plusgiro, swish, autogiro, e_invoice, international,
  deposit, withdrawal, salary, fee, interest, adjustment) plus verbatim
  bank_transaction_code / proprietary_bank_transaction_code evidence
  columns (data_quality_master Appendix B "Layer-A capture").
- classifyTransactionMethod() in lib/transactions/transaction-method.ts:
  explicit source method (Stripe txn.type) > trailing Swedish channel
  phrase > ISO 20022 family/subfamily > proprietary-code keywords > MCC.
  It also splits the clean display title off the description.
- Ingest stores the clean title as description and the full bank string
  as original_description; dedup is untouched (external_id is date+öre,
  the content bridge reads original_description and is prefix-based, and
  a trailing strip leaves a prefix). Enable Banking passes the codes
  through; the Stripe feed sets methods from its balance-txn types.
- Backfill migration classifies existing rows from the description text
  (+ MCC and Stripe prefixes) and strips unedited titles; user-edited
  titles are never rewritten.
- mapping-engine also matches original_description so user rules written
  against the full bank text keep firing.
- UI: the inbox row shows the clean name; clicking it now folds out
  "Betalsätt: Kortköp" etc. (sv/en), making every classified row
  expandable.

A card purchase implies a physical receipt, a Bankgiro/e-invoice payment
implies a supplier invoice: downstream automations can now branch on the
rail instead of regexing display strings.

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

* fix(transactions): anchor counterparty-template identity on original_description

Audit follow-up to the phrase-strip change: counterparty template lookup
AND learning derived their key from merchant_name || description. With
the working title now stripped ("SPOTIFY AB Kortköp" -> "SPOTIFY AB"),
templates learned from the full bank string would only re-match via the
occurrence-gated single-token tier, and single-token counterparties with
fewer than 3 bookings would silently stop matching.

Both sides now read merchant_name || original_description || description:
the immutable bank original is identical across eras (and across user
renames), so every stored key and alias keeps matching exactly. Same
anchoring rationale as buildMerchantHistory in category-suggestions.

Existing tests that relied on the fixture's default original_description
now state it explicitly; two new regression tests pin the era stability
(lookup via alias on the full string, learning key derivation).

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

* fix(transactions): review follow-ups on method classification

- methodFromCodes: two-pass subfamily-then-family scan so a SALA/XBCT
  refinement on the proprietary code beats a bare family match on the
  ISO code, matching the documented precedence; pinned by a test.
- mapping-engine: regression tests for merchant/description patterns
  that only match original_description, including the invalid-regex
  substring fallback and the no-match default.
- Stripe: regression test for the SDK-unmodeled 'tax' balance-txn type
  mapping to 'fee'.

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

* fix(transactions): scope method classification to feed rows + adjective guard

Multi-bank risk hardening before the backfill ships:

- Feed-row scope: classification and title stripping now require a real
  import feed (import_source present, not manual/mcp), both at the
  ingest boundary (USER_CREATED_IMPORT_SOURCES, now exported) and in
  every backfill statement. User-authored titles like "Egen insättning"
  on manual/MCP rows are never classified and never rewritten.
- Adjective guard (TS + SQL): a strip that would leave the title ending
  in a possessive/scope adjective (egen/eget/privat/intern/extern ...)
  is skipped, so "Egen insättning" stays whole even on bank-feed rows;
  the method column still classifies (deposit).
- Unknown bank phrasings remain untouched by construction: an unmatched
  phrase means no method and no rewrite, so the worst case for any bank
  whose vocabulary we have not seen is the status quo.

Pinned by new unit + pg-real cases (user-created exclusion for
NULL/manual/mcp, adjective guard, feed defaults in the pg fixture).

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

* chore(migrations): re-timestamp transaction_method migrations after rebase

Main gained migrations dated 20260729-20260730 (already applied to prod)
while this branch carried 20260728 versions, which would have applied
out-of-order on merge. The files have never reached prod, so renaming to
current timestamps is safe and removes any dependence on the integration's
out-of-order handling. All code/doc references updated; the pg test reads
the backfill by its new filename.

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

* chore(migrations): bump transaction_method versions past prod's max

Main's newest applied migration is 20260730090000 (future-leaning
timestamp), so the previous 202607300731xx rename still sorted before
prod's tail and risked a silent skip on merge-time apply. Versions are
now 20260730100000/20260730100100, strictly after everything applied to
prod. References updated; full migration stream replays clean.

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

* fix(transactions): final review round: keyboard guard + bank_connection_id feed marker

- TransactionInboxCard: row-level Enter/Space handling now ignores events
  bubbling from nested controls, so keyboard activation of Bokför / the
  overflow menu is no longer cancelled by the (now much more common)
  expandable row.
- Feed predicate parity with isImportedTransaction(): a live
  bank_connection_id marks a feed row even when import_source is unset
  (the oldest PSD2 rows predate that column), in both the ingest
  classifier and every backfill statement: those legacy rows now get
  classified instead of being skipped as user-created.
- pg fixture typing uses the TransactionMethod union.

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

* chore(migrations): re-timestamp transaction_method migrations past prod's 20260807 tail

Prod max applied is 20260807170000 (verified by name via list_migrations);
the 20260730-stamped pair would sort before it. References in code,
tests, and DECISIONS.md updated to the new versions.

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

* fix(migrations): enforce, not assume, original_description preservation in the title strip

The strip UPDATE now fills a NULL original_description from the
pre-strip description in the same statement. Prod has zero such rows
(0/25,566 feed-scope rows, verified read-only), and 20260605120000's
backfill plus ingest make the NULL case unreachable on any DB that
replayed history, but the migration should not depend on that history
to avoid losing the only copy of a bank string.

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

* docs: record the compliance-review triage of the backfill's booked-row title strip

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

---------

Co-authored-by: Jakob Wennberg <jakob.wennberg@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
2026-08-08 11:58:51 +02:00

261 lines
11 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import { getAllTransactionsWithRaw, convertTransaction, getAccountBalance } from './api-client'
import { uploadDocument } from '@/lib/core/documents/document-service'
import { ingestTransactions as defaultIngest } from '@/lib/transactions/ingest'
import { buildStableExternalIds, FALLBACK_DESCRIPTION } from '@/lib/transactions/external-id'
import type { RawTransaction, IngestResult, IngestOptions } from '@/types'
import type { StoredAccount, TransactionsFetchStrategy } from '../types'
/** Ingest function signature: matches lib/transactions/ingest */
export type IngestFn = (
supabase: SupabaseClient,
companyId: string,
userId: string,
raw: RawTransaction[],
options?: IngestOptions
) => Promise<IngestResult>
export interface SyncOptions {
/** Skip auto-categorization during ingestion (e.g. SIE overlap) */
skipAutoCategorization?: boolean
/** Only INSERT + dedup, no matching/categorization (viewer imports) */
rawInsertOnly?: boolean
/**
* Fetch strategy passed to Enable Banking. 'longest' instructs the upstream
* to fetch the deepest available history (slower); omit for incremental syncs.
*/
strategy?: TransactionsFetchStrategy
}
/**
* How long a stored account balance stays fresh before a sync refreshes it.
* PSD2 unattended consents allow only 4 balance calls per account per day
* (observed: 429 "Consent daily limit 4 is exceeded"), while transaction
* fetches are budgeted separately. 12h keeps at most 2 balance calls per day
* regardless of how many manual "Synka nu" clicks or cron runs happen.
*/
const BALANCE_MAX_AGE_MS = 12 * 60 * 60 * 1000
export interface SyncResult {
imported: number
duplicates: number
errors: number
/** Earliest booking date the ASPSP returned. Undefined when no transactions came back. */
returnedMinBookingDate?: string
/** Latest booking date the ASPSP returned. Undefined when no transactions came back. */
returnedMaxBookingDate?: string
}
/**
* Sync transactions for a single bank account via Enable Banking PSD2.
*
* Fetches transactions from the Enable Banking API, converts to RawTransaction
* format, and delegates to the shared ingestion pipeline. Raw API responses
* are archived as räkenskapsinformation per BFL 7 kap.
*
* @param ingest - Optional ingest function override (defaults to core ingestTransactions).
* When called from an extension handler with ctx.services.ingestTransactions,
* pass that function to avoid direct @/lib imports.
*/
export async function syncAccountTransactions(
supabase: SupabaseClient,
companyId: string,
userId: string,
connectionId: string,
account: StoredAccount,
fromDate: string,
toDate: string,
ingest: IngestFn = defaultIngest,
syncOptions?: SyncOptions
): Promise<SyncResult> {
console.log('[enable-banking] syncAccountTransactions starting', {
connectionId,
accountUid: account.uid,
accountIban: account.iban,
fromDate,
toDate,
strategy: syncOptions?.strategy,
})
const { transactions, rawPages } = await getAllTransactionsWithRaw(
account.uid,
fromDate,
toDate,
syncOptions?.strategy,
)
// Log the actual date range returned so we can compare against the requested
// window. Helps diagnose when an ASPSP truncates history below what we asked for.
let minBookingDate: string | undefined
let maxBookingDate: string | undefined
for (const tx of transactions) {
const d = tx.booking_date || tx.value_date
if (!d) continue
if (!minBookingDate || d < minBookingDate) minBookingDate = d
if (!maxBookingDate || d > maxBookingDate) maxBookingDate = d
}
console.log('[enable-banking] Fetched transactions from API', {
connectionId,
accountUid: account.uid,
transactionCount: transactions.length,
rawPageCount: rawPages.length,
requestedFromDate: fromDate,
requestedToDate: toDate,
returnedMinBookingDate: minBookingDate,
returnedMaxBookingDate: maxBookingDate,
strategy: syncOptions?.strategy,
})
const bankTransactions = transactions.map(tx => convertTransaction(tx, account.currency))
// Only ingest BOOKED transactions: those the ASPSP returned with a real
// booking_date. Pending entries are intentionally skipped: a pending row is
// unstable across syncs (a later "synka nu" returns the same transaction
// either still pending or finally booked, often with a *different* effective
// date). Because BOTH the dedup external_id and the content-dedup key are
// date-derived, that drift mints a brand-new id and re-imports a transaction
// that already exists. Observed in production as the same amount+description
// landing twice with different dates: the bank's value_date in one sync, its
// booking_date in another. Gating the import set on a stable booking_date
// removes the drift at the source, and leaves booked rows' ids byte-identical
// (so the existing rows are NOT re-orphaned).
//
// booking_date is read from the RAW transaction (transactions[i]), index-
// aligned with bankTransactions: convertTransaction's booking_date already
// falls back to value_date/today, so it cannot tell booked from pending.
const bookedEntries = bankTransactions.flatMap((tx, i) => {
const bookingDate = transactions[i]?.booking_date
return typeof bookingDate === 'string' && bookingDate.trim() !== ''
? [{ tx, bookingDate: bookingDate.trim() }]
: []
})
const skippedPending = bankTransactions.length - bookedEntries.length
if (skippedPending > 0) {
console.log('[enable-banking] Skipped pending transactions (no booking_date)', {
connectionId,
accountUid: account.uid,
skippedPending,
total: bankTransactions.length,
})
}
// Derive a stable, content-based external_id per booked transaction. We
// deliberately do NOT key off the bank's transaction id (entry_reference/
// transaction_id): many Swedish ASPSPs regenerate those across requests, so a
// repeat "synka nu" produced a fresh id and re-imported transactions the user
// had already booked. buildStableExternalIds derives the id from (account,
// booking_date, amount) plus an occurrence index, so re-syncs collide on
// (company_id, external_id) and dedupe while genuinely identical transactions
// are still kept apart. Normalize the IBAN (strip whitespace, uppercase) so
// formatting variants from the ASPSP ("SE45 5000 …" vs "SE455000…") don't
// change the scope and orphan every prior external_id. Falls back to the
// provider account uid.
const accountScope = account.iban?.replace(/\s+/g, '').toUpperCase() || account.uid
const externalIds = buildStableExternalIds(
'eb',
accountScope,
bookedEntries.map(({ tx, bookingDate }) => ({ date: bookingDate, amount: tx.amount }))
)
// Convert Enable Banking format to generic RawTransaction. counterparty
// identification: prefer IBAN (international, normalized) over BBAN/BG
// numbers: the own-account detector matches on IBAN first, falling back
// to counterparty_account for Swedish domestic transfers.
const rawTransactions: RawTransaction[] = bookedEntries.map(({ tx, bookingDate }, i) => {
const cpAccount = tx.counterparty_account ?? null
const looksLikeIban = cpAccount && /^[A-Z]{2}\d/.test(cpAccount.replace(/\s+/g, ''))
return {
// The booked date is both the stable dedup anchor (see bookedEntries) and
// the accounting-correct ledger date; keep it identical to the value the
// external_id was derived from.
date: bookingDate,
// tx.description is already non-empty (convertTransaction guarantees a
// label); the trailing fallbacks are defensive. Ingest re-normalizes.
description: tx.description || tx.counterparty_name || FALLBACK_DESCRIPTION,
amount: tx.amount,
currency: tx.currency || account.currency,
external_id: externalIds[i],
mcc_code: tx.merchant_category_code ? parseInt(tx.merchant_category_code, 10) : null,
merchant_name: tx.counterparty_name || null,
reference: tx.reference || null,
bank_connection_id: connectionId,
import_source: 'enable_banking',
counterparty_iban: looksLikeIban ? cpAccount!.replace(/\s+/g, '') : null,
counterparty_account: !looksLikeIban ? cpAccount : null,
// Verbatim transaction-type codes: the ingest boundary classifies them
// into transaction_method and persists them as evidence columns.
bank_transaction_code: tx.bank_transaction_code || null,
proprietary_bank_transaction_code: tx.proprietary_bank_transaction_code || null,
}
})
const ingestOptions: IngestOptions = {}
if (syncOptions?.skipAutoCategorization) ingestOptions.skipAutoCategorization = true
if (syncOptions?.rawInsertOnly) ingestOptions.rawInsertOnly = true
// Per-account ledger routing: the mapping engine consumes settlementAccount
// for the bank-side leg, falling back to '1930' when unset.
if (account.ledger_account) ingestOptions.settlementAccount = account.ledger_account
const ingestResult = await ingest(supabase, companyId, userId, rawTransactions, ingestOptions)
console.log('[enable-banking] Ingest result', {
connectionId,
accountUid: account.uid,
imported: ingestResult.imported,
duplicates: ingestResult.duplicates,
errors: ingestResult.errors,
})
// Archive raw PSD2 API responses as räkenskapsinformation (BFL 7 kap)
for (let i = 0; i < rawPages.length; i++) {
try {
const fileName = `psd2-response_${connectionId}_${account.uid}_${new Date().toISOString().replace(/[:.]/g, '-')}_p${i + 1}.json`
const buffer = new TextEncoder().encode(rawPages[i]).buffer as ArrayBuffer
await uploadDocument(supabase, userId, companyId,
{ name: fileName, buffer, type: 'application/json' },
{ upload_source: 'api' }
)
} catch (archiveError) {
console.error(`[enable-banking] Failed to archive raw response page ${i + 1}:`, archiveError)
// Archival failure must not fail the sync
}
}
// Update account balance, but only when the stored one has gone stale:
// every skipped call preserves the account's scarce daily BALANCES quota
// (see BALANCE_MAX_AGE_MS). balance_updated_at is written ONLY on a
// successful refresh below, so a stale/missing/invalid timestamp always
// falls through to a refresh attempt (NaN and Infinity both fail the
// freshness comparison). A FUTURE timestamp (clock skew, bad data) yields a
// negative age; treat it as stale too, or refreshes would be suppressed
// until the wall clock catches up.
const balanceAgeMs = account.balance_updated_at
? Date.now() - new Date(account.balance_updated_at).getTime()
: Number.POSITIVE_INFINITY
const balanceIsFresh = balanceAgeMs >= 0 && balanceAgeMs < BALANCE_MAX_AGE_MS
if (balanceIsFresh) {
console.log('[enable-banking] Skipping balance refresh (stored balance is fresh)', {
connectionId,
accountUid: account.uid,
balanceUpdatedAt: account.balance_updated_at,
})
} else {
try {
const balance = await getAccountBalance(account.uid)
account.balance = balance.amount
account.balance_updated_at = new Date().toISOString()
} catch {
// Keep previous balance, don't update timestamp
}
}
return {
imported: ingestResult.imported,
duplicates: ingestResult.duplicates,
errors: ingestResult.errors,
returnedMinBookingDate: minBookingDate,
returnedMaxBookingDate: maxBookingDate,
}
}