# Feature: Bank Sync > Last updated: 2026-11-26 (explain restricted-mode empty authorized Enable Banking sessions with `ENABLE_BANKING_NO_ACCOUNTS`) > **Status (1.3.0).** Enable Banking is the only provider. The Powens adapter of > the Java backend was experimental and untested, and was not carried over to the > Rust backend: the `POWENS_*` variables are ignored. Sections below referring to > Powens describe that earlier design, which is no longer in the code. ## Context Picsou syncs bank accounts from Enable Banking's ~29-country EEA coverage — bank search and connection are not restricted to France (see [Country selection](#country-selection)), though France remains the default/primary market. In 1.0.0 the active provider is Enable Banking (PSD2, open banking). A second provider — Powens / Budget Insight (screen scraping) — is implemented behind `BankConnectorPort` but disabled because it has not been tested against a real Powens tenant. The scheduler runs daily auto-sync at 08:00 by default (configurable on the admin page to 1 to 4 distinct local times in `APP_TIMEZONE`, capped at 4 scheduled runs per local day to stay within the PSD2 unattended access quota) for all linked requisitions. ## How it works ### Provider architecture Both providers implement the `BankConnectorPort` interface: `initiateConnection`, `exchangeCode`, `fetchBalances`, `searchInstitutions`, `listCountries`, and (since 1.1.0) `fetchTransactions`. The service layer (`SyncService`) never imports adapters directly -- it depends only on the port. ### Transaction ingestion (1.1.0) Since 1.1.0 the sync also ingests **transactions**, not just balances. After upserting balances, `SyncService` calls `BankConnectorPort.fetchTransactions(sessionId, externalAccountId, from)` for each Enable Banking account (`GET /accounts/{id}/transactions`, mapping creditor/debtor → `counterparty`, remittance → `description`). Transactions are deduplicated by `(account, externalId)`, persisted with `isManual=false`, then categorized by `CategorizationService.apply`. Ingestion is incremental on `lastSyncedAt`; the first attach pulls the maximum available window (≈90 days). This feeds the entire Budget module — see [budget.md](./budget.md). `BankTransactionImportService` also stores SimpleFIN's transactions, which arrive with the balances (`importProvided`); see [simplefin-sync.md](./simplefin-sync.md). For both providers it clips description and category to their column widths, skips an amount that does not fit `numeric(20,8)`, and hashes an external id longer than 255 characters into an `fp:` key. The fingerprint rounds the amount to 8 decimals before hashing, so it matches the stored value. Rows on an investment-typed account (PEA, compte-titres, brokerage...) are stored budget-neutral for both providers, so they stay out of budgets and cashflow; rows stored before an account was retyped keep their status. **Enable Banking** (`EnableBankingBankConnector`): Uses the PSD2 Bank Account Data API. Auth is JWT-based (RS256 signed with an RSA private key). Sessions are created via OAuth redirect. After the user authorizes, Enable Banking populates the `session.accounts` list **asynchronously** — some ASPSPs take seconds, others hours (Boursorama). The adapter polls `GET /sessions/{id}` up to 8 times with 2-second delays (≤ 16 s total, configurable via `app.enablebanking.session-poll-attempts` / `session-poll-delay-ms`). If the session still has no accounts, it returns an empty list rather than throwing — the requisition is marked **FAILED** (preserving the session id) so the scheduler can retry the next day without going back through OAuth. **Powens** (`PowensBankConnector`) — ⚠ experimental in the Java backend, removed with it in 1.3.0. Used screen scraping via the Budget Insight API. Auth is an OAuth webview that handles bank selection and credential entry. The OAuth code is exchanged for a permanent access token. Gated behind `@ConditionalOnExpression` (so it only registers when `POWENS_CLIENT_ID` is set), but `@Primary` was removed for 1.0.0, so Enable Banking remains injected even when the bean is registered. ### Account-matching resilience (Enable Banking 0.16.4) Enable Banking 0.16.4 (released 2026-05-30) changed the account identification hash for ASPSPs that do not expose a per-account currency (e.g. Boursorama) — the account `uid` is now derived from the account number alone, breaking the uid-based match used by the previous upsert logic. Picsou now handles this with a two-pronged strategy: 1. **Uid-first account matching.** `SyncService.upsertAccount()` matches an incoming account against stored accounts by **uid and member** first, falling back to **IBAN, currency, and member** only when the current uid has no active match and the member has not deleted that uid. A deleted uid wins over an active IBAN match. Deleting a legacy Enable Banking row without an IBAN stops its balance updates and transaction imports even when another connector's row has the incoming IBAN and currency. A rotated uid without a deletion record can still recover through the IBAN fallback. This preserves a legacy Enable Banking row without an IBAN when a Revolut sidecar row already has the incoming IBAN and currency. Updates write the incoming IBAN only if no other active or soft-deleted account for that member has the same IBAN and currency. A deleted sidecar still reserves that key because an explicit Revolut reconnect restores its original row. Both rows keep their identities and history; the sidecar's IBAN lookup remains unambiguous after reconnect and on later syncs. Different currency subaccounts can share an IBAN, so IBAN alone does not identify an account. On a successful IBAN and currency match, the stored `uid` is refreshed in place. A missing currency defaults to `EUR` before matching, account creation, and updates. The soft-delete guard uses the same IBAN, currency, and member key alongside the exact uid check. Deleting one currency subaccount does not block another currency sharing its IBAN. Each account keeps its native balance; its snapshot is converted to EUR using that account's currency. When the guard skips a deleted account, the INFO log contains only the IBAN's `LogSanitizer.fingerprint` value so logs can be correlated without exposing the IBAN. Updates reconcile the stored currency with the incoming balance currency before saving and converting the snapshot. This repairs legacy accounts found by uid whose currency was misparsed before IBANs were imported. Their original rows remain separate on later syncs, and the current day's snapshot is corrected using the reconciled currency. Historical snapshots remain unchanged because the provider supplies only the current balance. Revolut discovery, persistence, and IBAN-based deletion checks use the same currency-aware identity when matching accounts previously imported by Enable Banking. - New column: `account.iban VARCHAR(34)`, added by `V46__account_iban.sql`. 2. **Per-account failure isolation in `fetchBalances()`.** Previously, a single failing account would surface an exception that zeroed the entire balance batch. Expected per-account failures are now caught: a `SyncException` (every provider-call failure, such as the 404 after a uid rotation, is mapped to it) and a `NumberFormatException` from a malformed balance amount. The adapter logs the error and skips that account, letting the rest of the batch succeed. Any other exception is a bug and propagates, so the scheduled resync marks the requisition `FAILED` instead of saving a partial result. When every account fails, the first failure is rethrown instead: that is a bank- or consent-level outage (5xx, 429, expired consent), and an empty list would read upstream as "accounts still linking". 3. **Missing currency tolerance.** Some ASPSPs omit the per-account currency field. The adapter now defaults to `EUR` rather than throwing, matching the most common case for French current accounts. ### Enable Banking account details and balance selection `GET /accounts/{uid}/details` returns a flat `AccountResource`, as described in the [Enable Banking API reference](https://enablebanking.com/docs/api/reference/#accountresource). The adapter reads the IBAN from `account_id.iban`. The display name is the first nonblank value in `details`, `product`, and `name`, with `Account` as the fallback. `name` identifies the holder, so it is less useful than the account description. A card (`cash_account_type = CARD`) whose `details` is a known technical token (Boursorama: `immediat_debit`, `delayed_debit`) is the exception: its order is `name`, `product`, with `Card` as the fallback, because `name` is then the label the holder sees, which also tells apart two cards of one joint account (#664). Any other card keeps the usual order, where `details` describes the card better than the holder's name. On a card, a currency of `XXX` (ISO 4217 "no currency", sent by Boursorama) counts as absent. A card's balance is what it owes, stored negative as on the BPCE and La Banque Postale cards. Only an account-scoped balance list can say what a card owes: in the fallback (shared-list) path a `CARD` resource is imported as before, as `CHECKING`. "Available" balances (`ITAV`, `CLAV`, `OPAV`, `FWAV`: credit left, not an amount owed) are left out before the usual selection. A card left with no other balance, or whose selected balance is positive, is still synced as a card with its transactions, but with `AccountData.balance` null: `upsertAccount` leaves the stored balance and currency as they are and writes no snapshot (a new card starts at 0; a `CHECKING` account holding a positive balance is not turned into a card until a readable balance arrives, since that figure is credit left, not owed). Whatever the path, an account already stored as a card never takes a positive balance, and a tie between owed balances counts as unreadable. Nothing is stored with a guessed sign. A malformed or ambiguous balance list still skips the card, as it skips any account. The usual priority applies (`CLBD` before `XPCD`); Boursorama's cards send `OTHR` and `XPCD` only. After balance selection, the adapter truncates the display name to 100 characters to fit `account.name`. Balance matching always uses the full account description, so descriptions that share the first 100 characters remain distinct matching keys. Existing-account names remain unchanged on sync to preserve user edits, with one exception: a card whose stored name is still exactly the one the earlier order produced (`AccountData.legacyName`, e.g. `delayed_debit`) takes the card name, since the user never chose it. An existing generic `Account` label can be renamed in the account form. Balances and IBANs refresh through the usual upsert path, including currency-aware IBAN matching after a uid rotation. Some ASPSPs, including the Qonto response shape reported in issue #317, return the organization's balances for every account uid. The adapter fetches each session account's details before collecting balance candidates, then selects balances after all requests finish. Each endpoint is called at most once per uid to respect Enable Banking's daily call limits. Successfully fetched details retain their label claims even if the balance request fails. The same session response supplies the ASPSP name. Enable Banking documents the balance endpoint as account-scoped and uses `Booked balance` as an example generic label. A named ASPSP other than Qonto follows that contract unless its response names a sibling with a different account description. Accounts can share their own description, such as two `LIVRET A` accounts. That shared label alone does not override established account scope; each endpoint keeps its own balance. Balance labels can describe types, such as `Solde comptable` for `CLBD` and `Solde instantane` for `ITAV`; they need not match each other or the account description. Those responses rank balances independently, so generic labels can overlap across accounts, including independent zero balances. Qonto is treated as shared regardless of country. Missing or blank ASPSP metadata leaves scope unproven. Without a unique description match, a distinct sibling's description keeps the shared-response safeguards, even for another named ASPSP. For shared or unproven responses, the adapter trims descriptions and counts them without case sensitivity. A matching `details` description establishes ownership only when every session account's details were fetched successfully and the description is unique. Unavailable or null sibling details cannot make a shared description appear unique. A description shared by several session accounts cannot establish ownership, even when their IBANs differ. Holder and product names are not matching keys because several accounts can share them. For shared or unproven responses, attribution follows these rules: - **Own label.** When an account's `details` label is unique in the session and some entries carry that name, only those entries are candidates. - **No own label.** When the label is blank or matches no entry, entries named after another session account's label are dropped. An unlabelled account can only take an entry that no sibling can claim. If none remains, the account is skipped. - **Shared label.** When two accounts have the same label, neither can tell which entries are its own, so entries with that name and those named after other siblings are dropped. Both accounts are skipped unless an unattributed entry remains. Within the candidates, the adapter prefers the following [ISO balance types](https://enablebanking.com/docs/api/reference/#balancestatus) in order: 1. `CLBD`, closing booked. 2. `XPCD`, expected. 3. `ITBD`, interim booked. 4. `ITAV`, interim available. 5. `CLAV`, closing available. Other or missing types have lower priority. For shared or unproven responses, when the description is missing, shared, or matches no balance, fallback first excludes entries claimed by any session description. This includes entries with a shared description and claims from accounts whose balance request fails. If no entry remains, that account fails with a `SyncException`. Before selecting any fallback, the adapter compares its remaining labels with every other account that also needs fallback. Overlapping labels make every contender ambiguous, regardless of response size, balance types, currencies, or amounts. A shared list can contain only one normalized label, so that shape alone cannot establish account ownership. The provider's [`HalBalances`](https://enablebanking.com/docs/api/reference/#halbalances) and [`BalanceResource`](https://enablebanking.com/docs/api/reference/#balanceresource) schemas supply no account identifier to resolve the overlap. Generic responses with overlapping labels therefore fail closed for Qonto or an unknown ASPSP. A description match with complete sibling details still syncs, including genuine zeros, and does not compete for fallback. Established account-scoped responses also do not compete for fallback. Every response retains its label claims until selection finishes. A later failure caused by inconsistent labels, tied preferred types, or an invalid amount cannot grant ownership to a sibling. Selection is independent of session order and changes in amounts between requests. Shared fallback also requires complete session ownership information. Unavailable or null sibling details prevent both description matching and fallback for shared or unproven responses. A missing or structurally invalid sibling balance response prevents fallback, but its successfully fetched description still claims its entries. Such a balance failure does not block another account's unique description match. Established account-scoped responses can still sync after a sibling request fails. Shared or unproven fallback then requires a single entry or remaining labels that are all the same after trimming and case normalization. Null and blank labels form one unnamed group. This preserves generic-label fallback, such as repeated `Booked balance` labels, and wholly unnamed responses when their candidates do not compete across scopes. Distinct labels require established account scope or a positive account-description match before type ranking. A unique best type cannot establish account ownership for shared or unknown responses. With only one linked uid, no sibling descriptions are available to identify another account's entries in an organization-wide list. A previously unknown ASPSP that violates the account endpoint contract with a shared response cannot be distinguished from an ordinary account-scoped response using labels or amounts alone. Without an account identifier on balance entries, non-overlapping fallback labels also cannot prove ownership of balances belonging to accounts outside the linked session. Several entries at the best priority are ambiguous and cause a `SyncException`, even when their names match. The adapter never adds balances together or chooses an arbitrary entry from a tie. An absent balance, null entry, or missing selected amount also fails explicitly. A malformed numeric amount follows the existing per-account failure path. These failures leave that account unchanged, allow other accounts to sync, and propagate when every account fails. A genuine zero remains a valid balance. The `BalanceResource` schema has no flag indicating whether an individual balance includes a credit limit. The account-level `credit_limit` cannot identify which tied entry excludes it, so it does not provide a safe tie-break. Unlisted types such as `OPBD` and `PRCD` retain equal priority and also fail closed when tied. Residual limit: sibling labels only exist for accounts linked in the same session. For Qonto or an unknown ASPSP, a single linked uid still rejects distinct unclaimed labels, but cannot detect a shared list whose entries all have the same generic label. A named account-scoped provider ranks its response by type unless a distinct sibling claim contradicts that scope. The selected amount supplies the currency. If it omits the currency, the adapter uses the account-details currency, then `EUR`. `EnableBankingAccountDataTest` serves synthetic responses over loopback HTTP and calls `fetchBalances` through the production WebClient and JSON decoder. It covers shared balance lists, flat details, type priorities, ordinary single-account and multi-account responses with distinct balance-type labels, named-bank accounts sharing their own description, named-bank responses containing distinct sibling claims, unmatched lists with different balance types, missing or unmatched descriptions with only sibling-claimed balances, unclaimed fallback, duplicate session descriptions with different balance types, competing fallback assignments with changing amounts, shared lists with one generic label, overlapping generic nonzero and zero balances for account-scoped providers, conservative handling of missing ASPSP metadata, independent empty accounts with unique description matches, failed sibling details with a shared description, oversized display names, full-description matching before truncation, ambiguous or missing data, and per-account failure isolation for details and balance requests. It also checks that a three-account shared-list sync makes exactly one details request and one balance request per uid. `EnableBankingBankConnectorTest` verifies that an earlier request failure remains the reported error after a later amount-conversion failure, and that unexpected exceptions propagate from either stage. `SyncServiceCurrencyMatchTest` persists accounts and snapshots through real repositories against an isolated H2 database. Synthetic EUR and GBP accounts sharing one IBAN stay separate across repeated syncs and uid rotation. Snapshot conversion uses a fixed synthetic FX rate. Currency-specific soft deletion and the missing-currency EUR default are also covered. The legacy-upgrade regression starts with two EUR accounts without IBANs and same-day EUR 100 snapshots. Two successive syncs preserve their ids, reconcile the GBP account's currency and shared IBAN, and replace its snapshot with EUR 240 for a GBP 200 balance at a fixed 1.20 rate. Another upgrade regression starts with a legacy Enable Banking row without an IBAN alongside a Revolut sidecar row with that IBAN and currency. Repeated Enable Banking syncs preserve both uids and update only the legacy row, for both matching and differing provider names. A following Revolut discovery and sync still finds and updates only the sidecar row. A deleted sidecar row with the same member, IBAN, and currency blocks IBAN backfill onto the active legacy row. Regressions exercise both a direct Revolut reconnect with explicit credentials and voluntary discovery confirmation after repeated Enable Banking syncs. Each reconnect restores the sidecar's original row and updates its balance and snapshot; the legacy row keeps its uid, balance, and snapshot on the following Enable Banking sync. A deleted row in another currency or belonging to another member does not block backfill. Deleting the legacy Enable Banking row instead leaves the surviving Revolut or Boursorama row's uid, connection, balance, sync timestamp, and snapshots unchanged on repeated syncs, and prevents Enable Banking transaction imports. A deleted uid belonging to another member does not block IBAN recovery for the current member. Live bank behavior remains unverified. ### Country selection Bank search is not restricted to France — `GET /api/sync/institutions?query=...&country=CC` accepts any ISO 3166-1 alpha-2 code, and `GET /api/sync/countries` lists what the active provider actually supports. It has its **own** rate-limit bucket, separate from `POST /api/sync/initiate`'s (`SyncController.checkSyncRateLimit` keys buckets by `ip + endpoint name`) — sharing one bucket would let a passive, auto-fetched read (the picker populating on every "Add Account" open) exhaust the budget meant for an explicit user action like connecting a bank. The frontend's `BankCountrySelect` (`frontend/src/components/shared/BankCountrySelect.tsx`) populates its options live from that endpoint rather than a hardcoded list, so it never drifts from real coverage; it snaps back to the first available option if the current selection isn't in the loaded list (e.g. a provider without France coverage), and a visible error — while staying functional on the France-only fallback — is shown whenever it's genuinely stuck there (in bank search, `InstitutionSearch` passes `silentFallback` to the select and renders that error full-width below the search row, since the narrow select column wrapped it): the request failed, *or* it succeeded but came back empty (both cases are indistinguishable from "no other countries exist" without an explicit message). That error is intentionally **not** shown just because a background refetch failed while good data from a prior fetch is still being rendered — the message would then be false ("showing France only" while the full list is on screen). `BankConnectorPort.DEFAULT_COUNTRY` ("FR") is the single named fallback used by the controller's `@RequestParam defaultValue` and by every caller that needs a concrete country — previously this was scattered across independent `"FR"` string literals, one of which could silently mis-resolve a bank with a blank country field. `BankConnectorPort.parseInstitutionId()` is the shared, provider-agnostic parser used by `SyncService.parseCountry` (which backs logo backfill). It reads the **country as the second segment** of the id, which is the position it occupies in both the current `name::country::psuType` form and the legacy `name::country` one (see [PSU types](#psu-types-retail-vs-business-banks)) — reading the *last* segment instead would silently return `"business"` as the country for every three-segment id. It returns a blank name/country (rather than throwing) for a `null` input. Callers decide their own fallback for a blank/absent country: `parseCountry` returns `null`, so an unknown-country logo lookup searches unfiltered across all countries rather than narrowing to France and possibly missing the real institution, while `EnableBankingBankConnector.initiateConnection` needs a concrete value to send upstream and therefore uses its own PSU-aware `parseInstitutionId`, which falls back to `DEFAULT_COUNTRY`. `SyncController.InitiateRequest`'s fields are `@NotBlank`-validated (422 on a missing `institutionId`/`institutionName`), so the parser's null-safety is defense in depth, not the primary guard. When Enable Banking is not configured, `/countries` and `/institutions` fail with the `ENABLE_BANKING_NOT_CONFIGURED` error code (`EnableBankingBankConnector.ERROR_CODE_NOT_CONFIGURED`). `InstitutionSearch` then shows one configuration notice instead of the countries fallback error and the raw search error: an admin gets a Configure link to Administration > Banks & integrations, a member is told to ask the administrator. Older servers that send no code are recognised by the detail text. `EnableBankingBankConnector.listCountries()` never caches a null/empty result from `GET /application` for the full 6h TTL — a transient blip serves (and keeps) the last good cached value instead, matching the same "don't negative-cache" principle used elsewhere in this file. `EnableBankingBankConnector.listCountries()` calls Enable Banking's `GET /application`, which returns the countries this specific application is registered/active for — a small, near-static payload, and more correct than deriving coverage from the full ASPSP catalog (which could list countries this particular app isn't licensed for). The result is cached in-memory for 6 hours (`CachedCountries`, a single-record TTL cache in the same spirit as `PriceService.CachedPrice`, though simpler — no invalidation hook, since app-country coverage essentially never changes at runtime). `PowensBankConnector.listCountries()` fetches its `/connectors` catalog uncached (Powens is disabled by default in 1.0.0; revisit if it's ever re-enabled). **Aside, found and fixed while building this:** `EnableBankingBankConnector`'s `WebClient` used the default 256 KB in-memory buffer limit, which `searchInstitutions()` could already exceed on a single large country (Germany alone is ~1.4 MB across ~1100 institutions) — a latent bug independent of the country picker. Both Enable Banking's and Powens' `WebClient`s now raise this to 8 MB. ### PSU types (retail vs business banks) Enable Banking partitions its ASPSP catalog by **PSU type** — `personal` for retail customers, `business` for professionals. `GET /aspsps` takes it as an optional filter and returns each ASPSP's own `psu_types` array; `POST /auth` takes it as a required field that decides which login page the bank presents. Picsou originally hardcoded `personal` in both places, which made every business-oriented institution invisible in the bank picker — a user with a Swan.io account searched "Swan", got nothing, and had no way to tell that from a misconfiguration. Swan, like other BaaS providers, is published under `business` only. The catalog is now fetched **unfiltered** and `EnableBankingBankConnector` resolves one PSU type per ASPSP (`resolvePsuType`): `personal` whenever the bank offers it — so every retail bank behaves exactly as before — otherwise the bank's first declared type, passed through verbatim rather than coerced to `business`, so an unrecognised provider value can't turn into an `/auth` the API rejects. The resolved type is carried on `InstitutionData.psuType`, surfaced in both bank pickers as a **Pro** badge, and echoed back on `/auth`. The badge is keyed on `business` exactly, not on "not `personal`": the pass-through above means an unrecognised value can reach the picker, and it is not evidence that the bank is a professional one — so it renders unbadged. **Institution id format.** The id is an opaque round-trip token the client never parses, so the PSU type rides along inside it rather than as a second field the client would have to remember to send back: ``` "Swan::FR::business" name::country::psuType (current) "BoursoBank::FR" name::country (written before this change) ``` `parseInstitutionId` and `SyncService.findInstitution` both accept the legacy two-segment form — existing requisitions predate business support and are therefore `personal`. `findInstitution` gained a middle matching tier (name+country, ignoring the PSU segment) so those rows keep their country preference instead of degrading to a bare name match. ### Requisition lifecycle **Consent length (#909).** `/auth` asks `access.valid_until` from the bank's catalog entry (`maximum_consent_validity` in `GET /aspsps`, seconds): the bank's own maximum less 10 minutes, capped at 180 days (EBA RTS 2022/2360 lets account information run 180 days without a new strong authentication). Without a usable maximum, or when the catalog cannot be read, it asks 90 days as before. The same lookup gives the logo at `initiate` and the length at `reconnect`. 1. **CREATED** -- `SyncService.initiateConnection()` calls the port and stores a `Requisition` with `authLink`. 2. **LINKED** -- `SyncService.completeConnection()` exchanges the OAuth callback code, fetches balances, upserts at least one account, and marks the requisition as LINKED. Immediately after a successful exchange, `RequisitionLifecycleWriter` commits the `session_id` and clears the spent OAuth nonce in an independent `REQUIRES_NEW` transaction. A later fetch or account-upsert rollback therefore cannot restore the stale authorization id. 3. **FAILED** -- If the code exchange, balance fetch, or account upsert fails, or if Enable Banking returns zero accounts after polling, the requisition is marked FAILED (preserving the session id when the code was already exchanged) so `retrySync()` can retry later. When the session is `AUTHORIZED` with zero accounts after the polling window (`SESSION_ATTEMPTS = 3`), on completion or on retry of a non-`LINKED` requisition, the requisition is instead marked `FAILED` with `error_code = 'ENABLE_BANKING_NO_ACCOUNTS'` (`V158__requisition_error_code.sql` / SQLite `V5__requisition_error_code.sql`), and the endpoint answers HTTP 422 with that typed error code. Automatic retries skip it until the user reconnects. 4. **Reconnect** -- `POST /api/sync/{id}/reconnect` (`SyncService.reconnect()`) re-initiates the OAuth flow **on the existing requisition** for the cases a retry can never fix: a failed code exchange (the stored id is an authorization id, not a session), an expired/revoked PSD2 consent (up to 180 days, see below), or an `ENABLE_BANKING_NO_ACCOUNTS` connection after linking accounts in the Enable Banking Control Panel. Status returns to CREATED with a fresh `authLink` and `error_code` is cleared; accounts survive because `upsertAccount` matches on `externalAccountId`. **Refused for LINKED requisitions** — overwriting a working session id with an unconsumed authorization id would break scheduled syncs if the user abandons the new OAuth flow. Exposed in the UI as a "Reconnect to bank" button on FAILED and `ENABLE_BANKING_NO_ACCOUNTS` connections (`BankSyncTab` and `SyncAllModal`). Rate-limited like `/initiate` (it triggers an outbound EB `/auth` call), on its own `ip + endpoint` bucket — as is `/complete`, whose `exchangeCode` + `fetchBalances` also hit the provider. Every public method of `EnableBankingBankConnector` maps **all** provider failures (HTTP errors, timeouts, connection errors) to `SyncException`, keeping the external-error contract stable. `completeConnection()` additionally catches arbitrary runtime failures from account persistence, marks the requisition retryable through the independent lifecycle writer, and lets its main transaction roll back partial account/snapshot work. ### Automatic retry of FAILED sessions `SchedulerService.dailyBankSync()` calls `retry_failed_reporting(memberId)` (after `resync_all_reporting`) for every member. It finds all retryable FAILED requisitions — excluding those with `error_code = 'ENABLE_BANKING_NO_ACCOUNTS'`, since an authorized session that shares no accounts cannot succeed on retry until the member acts in the Enable Banking Control Panel (or re-consents) and reconnects — and calls `retry_sync()` for each. If accounts are now populated, the requisition transitions to LINKED (clearing `error_code`) and accounts are upserted. If a previously pending session is now `AUTHORIZED` with zero accounts, `retry_sync()` persists `error_code = 'ENABLE_BANKING_NO_ACCOUNTS'` so background retries stop from that point on. Enable Banking sessions are valid for the consent length asked at `/auth` (`valid_until`), so there is ample time for banks that take hours to asynchronously populate accounts while still pending (observed: Boursorama ~4 h+). An already-`LINKED` requisition keeps `LINKED` on a transient empty resync. ### Reporting a broken bank connector When a sidecar connector (`SidecarSessionPanel`, `BpceSessionPanel`, `BoursoPanel`, `FortuneoPanel`, `LbpPanel`, `BnpPanel`, `DegiroPanel`, `TradeRepublicTab`/`TradeRepublicLogin`, `RevolutTab`/`RevolutWizard`) or Enable Banking (`BankSyncTab`, `BankWizard`) displays a connector/server sync failure (excluding local client-side validation or CSV import errors), a **Report this problem** action (`ReportConnectorIssueButton`) lets the user file a GitHub issue with one click and no telemetry server. - Before opening GitHub, a dialog shows the exact `title` and `body` text that will be prefilled. Picsou sends nothing itself; the primary action is a plain `target="_blank"` link to `https://github.com/Cloeille/picsou-finance/issues/new` with `title` and `body` query parameters (no `.github/ISSUE_TEMPLATE` exists on `release/1.4.0`). - Only four strictly allowlisted technical fields are included (`frontend/src/lib/connector-report.ts`): the canonical connector id (e.g. `bourso`, `enable-banking`), the typed error code (from the `SidecarErrorCode` / typed connector code allowlist, falling back to `UNKNOWN` or `SYNC_FAILED`), the frontend build version (`APP_VERSION`), and the runtime (`desktop` or `web`). Any free-text bank error message, account name, institution name, amount, IBAN, or username is excluded. - The action is hidden in demo mode. ### Account type detection The connector reports the type in `AccountData.type`. Enable Banking maps the ISO 20022 `cash_account_type` `CARD` to `CREDIT_CARD` and `SVGS` to `SAVINGS` (a passbook; Wise sends it for each jar), both case-insensitive. Every other value (`CACC`, `LOAN`, `TRAS`…), a missing one and every Powens account stay `CHECKING`. `SVGS` is read on every balance path, the fallback (shared-list) one included: unlike a card's, a savings account's balance needs no sign convention. There is no `detectType()`: the dual-bank-providers ADR describes an earlier intent. A card's nature comes from its `details` token, case-insensitive: `immediat_debit` is `IMMEDIATE_DEBIT`, `delayed_debit` is `DEFERRED_DEBIT`, anything else leaves it unknown. Enable Banking has no standard field for it. On an existing account, `SyncService.refreshCardIdentity()` turns a still-`CHECKING` account into a card when the bank says `CARD` and fills in an unknown card nature. A type other than `CHECKING` and a known nature are never changed; `CHECKING` cannot be told apart from the old default, so a card the user set back to it by hand is upgraded again. Accounts are never turned back from a card into `CHECKING`. `SyncService.refreshSavingsType()` (`refresh_savings_type`) does the same for savings: a still-`CHECKING` account the bank declares `SVGS` becomes `SAVINGS`, any other stored type is the user's choice and is kept, and a savings account set back to `CHECKING` by hand is upgraded again. An account the bank stops declaring `SVGS` is never turned back into `CHECKING`. Known gaps: - **A Wise jar invested in stocks is typed `SAVINGS`.** Enable Banking sends it as `SVGS` with its market value and nothing that tells it from a cash jar, so it lands in the safety net. Only the Wise API says a jar is invested (#685). - **A bank that sends `SVGS` for a current account** gets it typed `SAVINGS`, and it stays so on every sync even after the user sets it back to `CHECKING`; its debits then leave the expense analysis, which reads `CHECKING` accounts only. Setting another type (e.g. `OTHER`) sticks. Known gaps (#664 follow-ups): - **Immediate-debit purchases count twice in the budget.** Boursorama lists each purchase both on the immediate-debit card and on the current account (observed: 177 of 178 rows). This predates #664; typing the account as a card does not change it (#667). - **Deferred-debit cards** have no `paymentDueAmount` / `paymentDueDate`, no link to their current account and no settlement tagging: Enable Banking says neither which account a card is debited from nor when (#668). The card's balance is its `XPCD` balance (the real-time amount still owed). - **A card never stores or matches an IBAN**: a card may carry its current account's IBAN, and matching on it would turn that account into the card, while storing it would leave two accounts sharing `(iban, currency)` and break the current account's own uid-rotation fallback. An IBAN stored before the card was recognised is cleared on its next sync. A rotated card uid therefore creates a second card. This predates #664 (the rows were `CHECKING` without an IBAN too). ### Key files - `backend-rs/src/sync/enable_banking/connector.rs` -- PSD2 adapter (RSA JWT, async account linking) - `backend-rs/src/admin/mod.rs` (`EnableBankingCallLog`) -- In-memory log of raw Enable Banking responses, read by the admin page (see [admin-page.md](./admin-page.md#enable-banking-call-log)) - `PowensBankConnector.java` -- Scraping adapter (experimental, OAuth webview; `@Primary` removed in 1.0.0) - `backend-rs/src/sync/enable_banking/entries.rs` -- Port interface with `AccountData`, `InstitutionData` records, `DEFAULT_COUNTRY`, and the shared `parseInstitutionId()` static parser - `backend-rs/src/sync/enable_banking/` -- Orchestration: initiate, complete, retry, resync, type detection - `RequisitionLifecycleWriter.java` -- Independent transaction checkpoints for consumed OAuth sessions and retryable failures - `backend-rs/src/sync/enable_banking/` -- REST endpoints under `/api/sync/` - `backend-rs/src/sync/enable_banking/requisitions.rs` -- Tracks connection lifecycle (CREATED/LINKED/FAILED) - `frontend/src/components/shared/BankCountrySelect.tsx` -- Country picker, populated from `GET /api/sync/countries` ### Flow ``` User initiates connection | v SyncController.initiate() --> SyncService --> BankConnectorPort.initiateConnection() | | | Enable Banking: POST /auth (RSA JWT) | Powens: build webview URL | v User authorizes in browser --> redirect to /sync/callback?code=xxx&state=yyy | (frontend POSTs code + state to /api/sync/complete; | the requisition is resolved by its stored state nonce; | http::finish_login_completions runs it as its own task, | so it ends even when the phone's browser drops it, #920) | v SyncController.complete() --> SyncService.completeConnection() | | | v | BankConnectorPort.exchangeCode() --> session_id | | | v | RequisitionLifecycleWriter.checkpointSession() | | (REQUIRES_NEW commit) | v | BankConnectorPort.fetchBalances(session_id) | | | v | upsertAccount() with detectType() | | | v | AccountService.upsertSnapshot() | v SchedulerService.dailyBankSync() --> SyncService.resyncAll() (LINKED only) --> SyncService.retryAllFailed() (FAILED: retry until LINKED or 90d expiry) ``` ## Technical choices | Choice | Why | Rejected alternative | |--------|-----|----------------------| | Dual providers with `@Primary` | PSD2 can't access LEP/PEA/livrets; scraping covers all French account types | Single provider only | | `@ConditionalOnExpression` for Powens | No-code activation: set env var, adapter appears; unset, it disappears | Feature toggles, profiles | | Keyword-based type detection | Banks rarely expose a standardized type field; product name is the most reliable signal | Hardcoded institution-to-type mapping | | Async polling for Enable Banking accounts | EB links accounts asynchronously after OAuth; polling (3 x 1.5 s) handles the delay | Webhook (EB does not provide one) | | Permanent access token for Powens | Powens tokens do not expire; stored directly as the requisition ID | Refresh token rotation (not needed) | | Independent requisition lifecycle checkpoint | OAuth codes are single-use; the exchanged session id and FAILED status must survive rollback of account/snapshot writes | `saveAndFlush` in the outer transaction (flushes SQL but still rolls back with that transaction) | | PSU type encoded in the composite institution id | The id is already an opaque token the client round-trips untouched, so no new request field, no DTO change — and legacy two-segment ids stay parseable | A separate `psuType` field on `POST /sync/initiate` (one more thing the client must send back, plus a nullable column on `requisition`) | | One PSU type resolved per bank, `personal` preferred | A personal-finance app should not ask retail users to pick a login flavour; only business-only banks need the other one | A Particulier/Pro toggle in the search UI | ## Enable Banking onboarding caveats The setup wizard follows Enable Banking's browser-generated PEM path. Registration guidance covers all required application fields, Production mode, and **Activate by linking accounts** before the credentials form. **Request activation** is the commercial path. The Application ID is the downloaded PEM filename without `.pem`. Import that application's private key instead of generating an unrelated server key. See [setup-wizard.md](./setup-wizard.md). In restricted mode, the application can access only accounts linked to it in the Enable Banking Control Panel. Link another bank's accounts there before adding that bank in Picsou. If a bank is authorized before its accounts are linked there (or if no account was selected on the bank's consent screen), Enable Banking returns an `AUTHORIZED` session with `accounts: []`: after polling, Picsou marks the requisition with `error_code = 'ENABLE_BANKING_NO_ACCOUNTS'`, stops background retries, explains the likely cause in `BankSyncTab` and `SyncAllModal` (with a direct Reconnect action and typed error code for the broken-connector report button), and reminds members of per-bank linking in `InstitutionSearch` and Admin → Integrations → Enable Banking. The setup test checks application credentials and connectivity. It does not create a bank connection or import accounts into Picsou. Two pitfalls cost real users a lot of time during 1.0.0 testing — both are surfaced in the wizard now (`EBStep1Explain`, `EBStep2Credentials`): - **PRODUCTION vs SANDBOX**: The Enable Banking developer dashboard defaults to SANDBOX, which only exposes fictitious test banks. A user who creates a SANDBOX application will reach the bank picker, see a list of unfamiliar test banks, and never find their real one. The wizard now shows a warning encart on step 1 and forces the user to tick a "my application is in PRODUCTION mode" checkbox before submitting credentials on step 3. - **PSD2 scope is cash accounts**: PSD2 standardises consent for payment accounts (`CACC`). A bank may also share savings accounts (`SVGS`, such as a passbook), which are imported too (their type: see [account type detection](#account-type-detection)); whether it does depends on the bank. PEA, Assurance Vie and other investment products are out of scope — Enable Banking has no API for them. This is a permanent product limitation, not a Picsou bug. Users should be directed to the dedicated integrations (Trade Republic, BoursoBank sidecar, Finary) or manual entry. The wizard surfaces this on step 1, and `BankSyncTab` repeats the note above the connection list: current accounts, and savings accounts when the bank shares them. ## Enable Banking configuration: the configured pieces Enable Banking needs the following, stored/loaded in **two different places** — a distinction that has confused operators: | Piece | Stored in | Set via | | --- | --- | --- | | Application ID | DB (`app_setting`) or `ENABLEBANKING_APPLICATION_ID` | Setup wizard / Admin → Integrations | | Redirect URI | DB (`app_setting`) or `ENABLEBANKING_REDIRECT_URI` | Setup wizard / Admin → Integrations | | **RSA private key** | **Filesystem** (`/data/keys/enablebanking-private.pem` in Docker, `backend/.local/keys/enablebanking-private.pem` in dev), or `ENABLEBANKING_PRIVATE_KEY_PATH` / inline `ENABLEBANKING_PRIVATE_KEY` | Setup wizard keypair step / **Admin → Integrations keypair panel** | **Application ID == Key ID.** Per Enable Banking's [quick-start spec](https://enablebanking.com/docs/api/quick-start/) the JWT header `kid` *is* the application's ID and the private key file is named `.pem` — so the "Key ID" is never a distinct value. Picsou therefore collects **only the Application ID** (in both the wizard and the admin page) and derives the Key ID from it: `EnableBankingConfigProvider.keyId()` returns an explicitly-configured value if present (legacy `ENABLEBANKING_KEY_ID` env / `key-id` DB row, kept for backward compatibility), otherwise falls back to `applicationId()`. `SetupService.writeEnableBankingConfig(applicationId, redirectUri)` writes the `key-id` row in lock-step with `application-id` so a later app-id change can't be shadowed by a stale DB key-id (which, being DB-first in `resolve()`, would otherwise win). `EnableBankingConfigProvider.isConfigured()` requires app id + key id + redirect URI + a parseable private key; `isConfiguredLenient()` / `privateKeyPresent()` are cheap, **non-parsing** checks used by status surfaces and the admin integration toggle (so a malformed key reports as "present" rather than 500-ing the page — the parse error surfaces at real use in `privateKey()`). Because the text fields (Application ID + Redirect URI) live in Postgres while the key is a file, they can be "saved" while the key is absent — e.g. configuring via the Admin page, abandoning the wizard after the credentials step, or losing the `/data/keys` volume while the DB survives. Symptom: institution search / sync fails with a `SyncException` (HTTP 502). **Recovery / management:** - The **Admin → Integrations → Enable Banking** section shows a readiness banner naming every missing piece (incl. the private key) and provides a keypair panel to **generate** (idempotent — never invalidates an already-uploaded public key) or **import** a `.pem`. Endpoints: `POST /api/admin/settings/enablebanking/keypair` and `/keypair/import` (mirror the wizard's but without the setup-complete guard, so they work post-setup). `GET /api/admin/settings` returns `enableBanking.privateKeyPresent`. - Connector errors are **field-specific**: `EnableBankingBankConnector` names the single missing piece (e.g. *"Enable Banking private key is missing on the server…"*) instead of a blanket "not configured", so the operator knows exactly what to fix. ## Gotchas / Pitfalls - **Powens is gone in 1.3.0**: the adapter existed only in the Java backend. Setting `POWENS_CLIENT_ID` does nothing. - **Enable Banking RSA key**: The private key must be PKCS8 PEM format. The `ENABLEBANKING_PRIVATE_KEY` env var can contain literal `\n` characters -- both formats are handled in `parsePem()`. The key lives on disk, **not** in the DB — see "Enable Banking configuration" above; setting only the text fields (Application ID + Redirect URI) leaves searches failing until a key is generated/imported. - **Local dev key path**: the `dev` Spring profile stores the generated key under `backend/.local/keys/enablebanking-private.pem` so bare-metal macOS/Linux runs do not try to create Docker's `/data/keys` directory at filesystem root. - **The callback URI must be HTTPS — a plain-HTTP deployment cannot sync banks.** Enable Banking rejects `http://` redirect URLs for PRODUCTION applications, and PRODUCTION is the only mode that lists real banks (see the SANDBOX pitfall above), so there is no HTTP escape hatch. Docker deployments must therefore terminate TLS: add `tls` to `COMPOSE_PROFILES` for the bundled Caddy proxy (see [docker-deployment.md](./docker-deployment.md)) or use an existing reverse proxy. Note that Enable Banking never *fetches* the callback URL — the redirect is browser-side only (`window.location.href = authLink`, then the SPA POSTs the `code`) — so a certificate from Caddy's internal CA works fine on a LAN, as long as the family's browsers trust its root. - **Enable Banking redirect URI must be registered**: `ENABLEBANKING_REDIRECT_URI` defaults to `https://localhost:5173/sync/callback` for local development, matching Vite's HTTPS dev server. In production, set it to the public frontend callback URL (for example `https://picsou.example.com/sync/callback`). The exact same URL must be registered in the Enable Banking developer portal under the application's Redirect URIs. A mismatch causes a `REDIRECT_URI_NOT_ALLOWED` 400 error at auth initiation — it surfaces in the Add Account modal bank wizard. - **ALREADY_AUTHORIZED**: If the OAuth code is reused (e.g. browser back button), `SyncService.completeConnection()` catches the error and falls back to refreshing the latest linked session **of the same institution** instead of failing (a replayed Revolut callback must not resync BNP). - **OAuth `state` correlation**: each initiation stores a random single-use nonce on the requisition; the callback resolves the requisition by it (member derived from the row — this is what makes admin-impersonated connections complete correctly). See [ADR 2026-07-08](../decisions/2026-07-08-oauth-state-requisition-correlation.md). - **Session identifiers stay out of logs**: Enable Banking session ids are opaque references that still identify a long-lived PSD2 consent. Use the internal requisition id and institution name for log correlation; never print the raw session id. - **One bank-status query key**: bank-sync feature hooks own `syncKeys.banks()`, and every complete/retry/reconnect/delete mutation invalidates it. Components must use those hooks rather than introducing a parallel key such as `['sync', 'connections']`, or another sync surface can remain stale until its polling interval elapses. - **Type upgrade on resync**: an account the bank reports as a card is upgraded from `CHECKING` to `CREDIT_CARD` on the next sync. Manual user changes are preserved (only `CHECKING` is upgraded), so an account the user set back to `CHECKING` by hand is upgraded again. - **Both providers are optional**: The app starts fine without either. No `BankConnectorPort` bean is required at startup. - **Enable Banking uid instability.** EB 0.16.4 changed the account uid derivation for ASPSPs that don't expose per-account currency. Picsou first matches the current uid, then uses currency-aware IBAN matching and uid refresh after a rotation; if neither key matches, it may be treated as a new account after an EB provider upgrade. This is tracked by `V46__account_iban.sql`. - **A business bank in the list can still fail at authorization**: Enable Banking lets an ASPSP declare `required_psu_headers` that must accompany `/auth`. Picsou does not send them, so a business bank may now be *findable* yet fail when connecting. That is a different failure from "the bank isn't listed" — don't re-diagnose the search path for it. This caveat does not exclude all business banks. Restricted-mode account linking also applies to business accounts. - **`IntegrationsHealthService` queries `/aspsps` unfiltered too**, deliberately: it is a JWT/connectivity probe (`toBodilessEntity()`), and leaving a lone `psu_type=personal` there would read as an oversight. - **Bank logos**: `InstitutionData.logoUrl` (Enable Banking only — Powens hardcodes `null`) is captured at connection time and copied onto each `Account`. See [bank-logos.md](./bank-logos.md) for the capture/backfill flow and the account card fallback to `color`. - **Deleting the last account on a requisition deletes the requisition** (see [the account-deletion ADR](../decisions/2026-08-11-account-deletion-removes-its-connection.md)). `upsertAccount` refuses to resurrect a soft-deleted account, so a requisition whose accounts are all deleted can never produce one again — it would sync forever, cost an outbound call per run, and still appear in "Sync accounts" offering to sync something the user removed. `AccountConnectionService` removes it once no live account is left; a requisition backing several accounts survives until the last one goes. The confirmation dialog names the bank first (`GET /accounts/{id}/deletion-impact`), because getting it back means a full OAuth round trip through the bank — unlike a wallet, which is re-added by pasting an address. - **`account.requisition_id` is what makes that possible, and it is nullable on purpose**: every other connector is recognisable from `external_account_id` (`wallet_`, `amundi_`, `tr_`, `bd_`, `ibkr_`, `sfin_`, `wise_jar_`, `degiro-portfolio`), but an Enable Banking account holds the bank's own opaque id and carries no namespace. V76 adds the column and `upsertAccount` sets it on **both** the create and the update path, so rows that predate it link themselves on their next sync. The V76 backfill matches `provider` against `institution_name` and deliberately skips members holding several requisitions for one institution — a name cannot say which one, and those rows keep their connection rather than risk removing the wrong one. Do not read `NULL` as "not a bank account". ## Tests - `SyncServiceCardAccountTest` -- a new card is created as one with its nature and name; an account imported as `CHECKING` becomes a card and loses its technical name; a type, nature or name the user chose is kept - `EnableBankingAccountDataTest` -- card resources (type, nature per `details` token, name order, `legacyName`, `XXX` currency); a current account keeps its type and name order; a whole session shaped like a redacted live Boursorama capture (three current accounts, immediate cards with a lone `OTHR`, a deferred card with `OTHR` and `XPCD`) - `SyncServiceTest` -- unit tests for upsert logic, retry flow, checkpoint ordering on fetch/upsert failures, and logo matching for both the current and the legacy institution id format - `RequisitionLifecycleWriterTest` -- session/nonce transitions and `REQUIRES_NEW` propagation invariant - `AddAccountModal.test.tsx` -- the Pro badge shows for a business-only institution, and not for a retail one nor for an unrecognised PSU type - `EnableBankingConfigProviderTest` -- DB/env resolution precedence, and `keyId()` falling back to the Application ID vs honoring an explicitly-configured value - `EnableBankingBankConnectorTest` -- JWT build / institution search against a mocked provider, plus the pure catalog helpers: `resolvePsuType` (business-only banks, the Swan regression), `toInstitutions` (composite id, de-duplication, country fallback) and `parseInstitutionId` (three-segment, legacy two-segment, unexpected PSU segment) - `BankConnectorPortTest` -- `parseInstitutionId` cases (name+country, three-segment id with a PSU type, blank country segment, no separator, name containing `"::"`, `null` input) - `SyncControllerTest` -- `GET /countries` returns the service result; rate-limit-exceeded returns 429 without calling the service; `/countries` and `/initiate` use independent buckets - `ReportConnectorIssueButton.test.tsx` (frontend) -- prefilled GitHub URL contains only connector id, typed error code, app version, and runtime; free-text bank errors and PII are dropped; dialog shows exact prefilled text with no network calls; hidden in demo mode; wired on sidecar panels and Enable Banking failed rows - `BankCountrySelect.test.tsx` (frontend) -- loading fallback (no error shown), live options with default-country-first ordering, `onChange` on selection, visible error on a failed fetch with no prior data, visible error on an empty-but-successful response, error suppressed when stale-but-real data is still shown during a failed background refetch, snap-to-first-available when the current value isn't in the loaded list - `InstitutionSearch.test.tsx` (frontend) -- the not-configured notice replaces the countries error and the search error (admin link, member wording), and a transient countries error is rendered full-width - `AdminControllerTest` -- `getSettings` reads the resolved provider; `updateEnableBanking` delegates the 2-arg writer - `IntegrationsServiceTest` -- `isEffectivelyEnabled` = stored flag OR detected config (env/DB/session presence) - Manual integration testing against real provider APIs ## Links - Related ADR: [Dual bank providers](../decisions/2026-03-01-dual-bank-providers.md) - Related ADR: [Ports and adapters](../decisions/2026-01-01-ports-and-adapters.md) - Downstream feature: [Budget & Cashflow](./budget.md) (consumes ingested transactions) - Related: [bank-logos.md](./bank-logos.md) — logo capture/backfill and account card rendering