Files
accounted/extensions/general/enable-banking/lib/sync.ts
T
Jakob WennbergandClaude Opus 4.7 722b22972d feat(enable-banking): per-account ledger mapping for multicurrency setups (#443) — rebase of #487 (#488)
* feat(enable-banking): per-account ledger mapping for multicurrency setups (#443)

Today every bank account routes to BAS 1930. Multicurrency setups (Wise,
SEB foreign-currency sub-accounts) get pooled into a single SEK ledger
account, making year-end FX revaluation a mess.

This change lets each bank account under a PSD2 consent map to its own BAS
account (SEK→1930, EUR→1932, USD→1933, etc.). The mapping engine already
honors IngestOptions.settlementAccount (lib/bookkeeping/mapping-engine.ts:55-57)
so the wiring is small:

- StoredAccount gains an optional ledger_account field (no migration —
  bank_connections.accounts_data is already JSONB).
- syncAccountTransactions passes account.ledger_account through as
  settlementAccount so the bank-side leg routes to the right BAS account.
- PATCH /accounts accepts account_mappings, validates 4-digit BAS format,
  and verifies each ledger_account exists in chart_of_accounts before
  persisting. Selection edits without account_mappings preserve existing
  values for back-compat.
- AccountPickerDialog shows a per-account "Bokför till konto" combobox
  populated from the company's 19xx accounts, with currency-based
  defaults (SEK→1930, EUR→1932, USD→1933, GBP→1934) and a non-blocking
  warning when two enabled accounts route to the same BAS account with
  different currencies.

Reconciliation still scans 1930 only — foreign-currency accounts skip
auto-matching until follow-up PR 4 (filed in the plan).

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

* fix(enable-banking): address review feedback on PR #487

Two real bugs flagged in review:

1. AccountPickerDialog row wrapped a Radix <Checkbox> (which renders as its
   own <button role="checkbox">) inside <button onClick={toggle}>. Browsers
   silently flatten nested interactive elements, the Checkbox lost its
   onCheckedChange handler, and the toggle interaction was effectively
   broken. Reverted to <label> + <Checkbox onCheckedChange> with the <Select>
   as a sibling outside the label so clicking it doesn't also toggle.

2. BAS_ACCOUNT_PATTERN was /^[0-9]{4}$/ — accepted 3001 (revenue), 2640 (input
   VAT), or any 4-digit account that happens to exist in the chart. Direct
   API calls would bypass the UI's 19% picker filter and silently misroute
   every bank-side journal-entry leg into the wrong BAS class, corrupting both
   the ledger and momsdeklaration. Tightened to /^19[0-9]{2}$/ (kassa/bank only).

Tests updated to assert non-19xx rejection.

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

* fix(enable-banking): validate account_mappings UIDs against accounts_data

A typo'd UID in account_mappings was silently dropped — the entry never
landed in the resulting accounts_data while the response was still 200,
leaving the client to believe the mapping was applied. Mirror the existing
enabled_uids guard: reject unknown UIDs with 400 + unknown_uids in the body.

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

* fix(enable-banking): catch syncPromise rejections to prevent process crash

When the 60s timeout wins the Promise.race, the underlying Promise.all
keeps running. A subsequent bank-API rejection has no registered handler,
which surfaces as an unhandledRejection — Node 22 (the self-hosted Docker
runtime) terminates the process by default on those.

The cron self-heals via initial_sync_completed_at IS NULL, so a no-op
catch is the right policy: drop the late rejection, let the cron retry.

Caught by Greptile review on PR #488.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 16:59:29 +02:00

164 lines
6.1 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 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
}
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))
// Convert Enable Banking format to generic RawTransaction
const rawTransactions: RawTransaction[] = bankTransactions.map((tx) => ({
date: tx.booking_date || tx.date,
description: tx.description || tx.counterparty_name || 'Unknown',
amount: tx.amount,
currency: tx.currency || account.currency,
external_id: `eb_${account.iban || account.uid}_${tx.id}`,
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',
}))
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
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,
}
}