Open Banking and Financial Data Domain

Overview

This domain covers the applicant-facing account-linking experience for Dwilar’s e-housing flow. The UI selects a provider based on country and query parameters, then routes the user into either a Plaid flow or a Salt Edge flow to connect personal, business, or investment accounts.

The same domain also exposes backend financial-data endpoints through Next.js route proxies. Those proxies let the UI fetch Salt Edge customer data, connection lists, and applicant coverage results through same-origin routes while preserving the backend service boundary.

At the UX level, the feature does four things for applicants:

  • chooses the correct provider experience for the applicant’s country
  • launches Plaid Link or the Salt Edge widget
  • restores and persists connected-account state across redirects
  • exposes coverage and connection details back to the UI for review and underwriting

Architecture Overview

flowchart TD
    subgraph PresentationLayer[Presentation Layer]
        Router[Connect Accounts Router]
        PlaidPage[Plaid Connect Accounts Page]
        SaltPage[Salt Edge Connect Accounts Page]
        Layout[Connect Accounts Layout]
        PlaidButton[Plaid Link Button]
    end

    subgraph FrontendRoutes[Frontend API Route Proxies]
        SaltCustomerProxy[Salt Edge v6 Customer Proxy]
        SaltSessionProxy[Salt Edge v6 Connect Session Proxy]
        SaltConnectionsProxy[Salt Edge Customer Connections Proxy]
        SaltConnectionProxy[Salt Edge Connection Proxy]
        CoverageProxy[Applicant Account Coverage Proxy]
    end

    subgraph BackendServices[Backend Services]
        SaltEdgeAPI[Salt Edge Interface]
        CoverageAPI[Account Coverage API]
        PlaidAPI[Plaid Token and Balance APIs]
        SaltCache[Salt Edge Customer Cache]
    end

    subgraph ExternalProviders[External Providers]
        PlaidLink[Plaid Link]
        SaltEdgeWidget[Salt Edge Widget]
    end

    Router --> PlaidPage
    Router --> SaltPage
    PlaidPage --> Layout
    SaltPage --> Layout
    PlaidPage --> PlaidButton
    PlaidButton --> PlaidAPI
    PlaidButton --> PlaidLink
    SaltPage --> SaltCustomerProxy
    SaltPage --> SaltSessionProxy
    SaltPage --> SaltConnectionsProxy
    SaltPage --> SaltConnectionProxy
    SaltCustomerProxy --> SaltEdgeAPI
    SaltSessionProxy --> SaltEdgeAPI
    SaltConnectionsProxy --> SaltEdgeAPI
    SaltConnectionProxy --> SaltEdgeAPI
    SaltEdgeAPI --> SaltCache
    SaltPage --> SaltEdgeWidget
    CoverageProxy --> CoverageAPI

Component Structure

Provider Selection and Country Routing

[!NOTE] frontend/app/application/connect-accounts/pagePlaid.tsx shows credit-report help text that says Max file size: 15 MB, but the validation logic uses CREDIT_REPORT_MAX_SIZE_BYTES = 25 * 1024 * 1024 and the error copy also says 25 MB. The displayed limit and enforced limit do not match.

frontend/app/application/connect-accounts/providers.ts

frontend/app/application/connect-accounts/page.tsx

The provider configuration file centralizes country-specific open-banking choices and institution suggestions. The router page normalizes the country query parameter, defaults it to us, and chooses the Plaid or Salt Edge page dynamically.

Data Types

Type Properties
Bank id: string, name: string, description: string, defaultAccount: string, connectUrl?: string
ProviderDetail provider: Provider, providerName: string, connectUrl: string, personal: Bank[], investment: Bank[]
CountryOverride provider: Provider, providerName?: string, connectUrl?: string, personal?: Bank[], investment?: Bank[]
OpenBankingProviderOption id: OpenBankingProviderId, name: string, summary: string, coverage: string, compliance: string, dataHandling: string

Enumerations and unions

  • Provider: plaid, saltedge
  • AccountType: personal, investment
  • OpenBankingProviderId: saltedge

Configuration tables

Constant Responsibility
PROVIDER_DETAILS Defines provider display names, connect URLs, and sample institutions for each provider.
COUNTRY_BANK_CONFIG Overrides provider choice and institution suggestions for specific countries.
OPEN_BANKING_PROVIDERS Declares the visible open-banking option set; the shown snippet contains saltedge.
PLAID_COUNTRIES Marks countries that should route to Plaid in the router page.

Key functions

Function Description
getCountryBankConfig Returns provider metadata and institution suggestions for a country and account type, using country overrides first and provider defaults second.
normalizeCountryKey Normalizes country query values to us, ca, or a lowercase fallback key.
ConnectAccountsRouter Chooses between Plaid and Salt Edge pages after reading country and provider query parameters.

Routing behavior

  • country=usa, u.s., united states, and united states of america normalize to us
  • country=canada and country=ca normalize to ca
  • the router inserts country=us into the URL if the query parameter is missing
  • provider=plaid forces the Plaid page even when the country would otherwise route to Salt Edge
  • PLAID_COUNTRIES also routes to Plaid when the country key is in the set

Connect Accounts Router

frontend/app/application/connect-accounts/page.tsx

This page is a thin route selector. It keeps the URL normalized, shows a loading spinner until search parameters are available, and then renders the provider-specific page with SSR disabled for both client flows.

Key behavior

  • loads search parameters through useSearchParams
  • normalizes the country query value using normalizeCountryKey
  • computes usePlaid from PLAID_COUNTRIES and provider === "plaid"
  • updates the URL with router.replace when country is absent
  • dynamically imports the Plaid and Salt Edge pages with ssr: false

Plaid Connect Accounts Page

frontend/app/application/connect-accounts/pagePlaid.tsx

The Plaid page manages the applicant’s connected accounts, Plaid OAuth resume state, credit-report upload, and local persistence of account results. It also exposes a country-aware account card layout and an “add another country” flow.

Data types

Type Properties
ConnectedAccount id: string, name: string, type: AccountCategory, accessToken?: string, `status?: "active" \
PlaidOnSuccessAccountMetadata `id?: string \
PlaidOnSuccessMetadata `institution?: { name?: string \
ConnectedAccountSummary id: string, name: string

Local state and refs

State or ref Responsibility
connectingStates Tracks per-category connect progress for personal, business, and investments.
plaidError Stores the current Plaid connection error message.
connectedAccounts Holds the rendered account list for each category.
creditReportFileName Stores the selected credit report filename.
creditReportUploadError Stores validation feedback for credit-report upload.
addCountryOpen Controls the “Add Another Country” modal.
creditReportInputRef Hidden file input used to start the credit-report chooser.

Key constants and helpers

Function or constant Description
CONNECTED_ACCOUNTS_STORAGE_KEY LocalStorage key for persisted connected-account data.
CONNECTED_ACCOUNTS_VERSION_KEY LocalStorage key for the account-storage schema version.
CONNECTED_ACCOUNTS_STORAGE_VERSION Current account-storage version, set to "7".
PLAID_OAUTH_TOKEN_KEY LocalStorage key for the Plaid OAuth link token.
PLAID_OAUTH_ACCOUNT_TYPE_KEY LocalStorage key for the account type being resumed after OAuth.
CREDIT_REPORT_ACCEPTED_TYPES Acceptable MIME types for credit-report uploads.
CREDIT_REPORT_ACCEPTED_EXTENSIONS Acceptable file extensions for credit-report uploads.
CREDIT_REPORT_MAX_SIZE_BYTES Maximum upload size accepted by validation.
DEMO_ACCOUNT_KEYWORDS Keywords used to filter demo or placeholder accounts.
buildFallbackAccounts Creates fallback account objects when Plaid balances cannot be fetched.
upsertResolvedAccounts Replaces accounts for the same connection and inserts new resolved accounts without duplicates.
cleanConnectedAccounts Removes demo and placeholder accounts from the persisted and rendered lists.
formatConnectedAccountName Formats account labels and appends the last four digits when available.
handlePlaidSuccess Exchanges Plaid results into connected-account state and hydrates balances.
handlePlaidExit Converts Plaid exit results into a user-facing error state.
handlePlaidEvent Logs Plaid events to the console.
removeAccount Removes one rendered account from the selected category.
buildUrlWithParams Preserves email, country, and showBusiness when navigating to the next application step.

Flow and storage behavior

  • on mount, email is copied into localStorage
  • persisted account state is restored only when CONNECTED_ACCOUNTS_VERSION_KEY matches CONNECTED_ACCOUNTS_STORAGE_VERSION
  • invalid or empty persisted state is cleared from localStorage
  • creditReportFileName only updates after file type and size pass validation
  • AddCountryModal rewrites the current URL with a new country value

UI states

State Trigger
Loading File upload in progress, Plaid token fetch in progress, or initial connection hydration.
Connected One or more valid connected accounts exist for the selected category.
Empty No connected accounts are present and the user has not uploaded a credit report.
Error Plaid exit or exchange failure, invalid credit report upload, or token fetch failure.

[!NOTE] The file upload copy and the runtime validation disagree on the maximum credit-report size. The UI says 15 MB, but validation allows 25 MB.

frontend/app/application/PlaidLinkButton.tsx

This component launches Plaid Link, resumes OAuth redirects, and hands successful connection results back to the Plaid page. It is the only component in this section that talks directly to the Plaid token API.

Data types

Type Properties
PlaidLinkButtonProps `displayVariant?: "default" \

Local state and constants

State or constant Responsibility
linkToken Stores the current Plaid Link token.
error Stores fetch or launch errors.
receivedRedirectUri Holds the OAuth redirect URI when resuming a Plaid OAuth flow.
PLAID_OAUTH_TOKEN_KEY Persists the link token during OAuth redirects.
PLAID_OAUTH_ACCOUNT_TYPE_KEY Persists the account type during OAuth redirects.

Key functions

Function Description
fetchLinkToken Requests a Plaid link token from the backend and persists it for OAuth resume.
handleReconnect Clears the current error and re-fetches a fresh link token.
handleClick Opens Plaid Link if a token is already present or starts token retrieval.

Connection behavior

  • on mount, the component checks for oauth_state_id in the URL
  • if the stored token and stored account type match the current category, the flow resumes automatically
  • the stored token and account type are cleared after success or exit
  • getConfiguredBackendApiUrl() is used to resolve the backend base URL before requesting the token
  • the toggle variant renders a compact switch instead of the primary button

Salt Edge Connect Accounts Page

frontend/app/application/connect-accounts/pageSalt.tsx

This page manages the Salt Edge onboarding flow, including customer creation, connect-session creation, redirect handling, connection hydration, category overrides, and account persistence. It also keeps the applicant’s draft application context in localStorage so the application can continue after the external widget returns.

Data types

Type Properties
AccountCategory personal, business, investments
ConnectedAccount id: string, name: string, type: string, mask?: string, connectionName?: string, institutionName?: string
SaltEdgeAccountRecord id?: unknown, name?: unknown, nature?: unknown, type?: unknown, extra?: unknown

Local state and refs

State or ref Responsibility
redirectingStates Tracks pending Salt Edge connection requests per account category.
error Stores Salt Edge connection or hydration errors.
isProcessingConnection Prevents duplicate redirect processing.
customerId Stores the current Salt Edge customer id.
categoryOverrides Stores per-connection category overrides loaded from localStorage.
overridesLoaded Gates writes to category override storage until the initial load finishes.
connectedAccounts Stores connected account summaries by category.
creditReportFileName Holds the selected credit-report filename.
creditReportUploadError Holds validation errors for credit-report uploads.
addCountryOpen Controls the modal that adds a new country.
processedConnections Prevents the same Salt Edge connection id from being processed more than once.
categoryOverridesRef Keeps the latest overrides available inside async callbacks.
creditReportInputRef Hidden file input for credit-report selection.

Key constants and helpers

Function or constant Description
SALTEDGE_CLIENTS_URL External Salt Edge client page used for one redirect path.
SALTEDGE_CUSTOMER_STORAGE_KEY LocalStorage key for the Salt Edge customer id.
CATEGORY_OVERRIDE_STORAGE_KEY LocalStorage key for category override mappings.
CONNECTED_ACCOUNTS_STORAGE_KEY LocalStorage key for persisted account groups.
CONNECTED_ACCOUNTS_VERSION_KEY LocalStorage key for the account-storage schema version.
CONNECTED_ACCOUNTS_STORAGE_VERSION Current account-storage version, set to "7".
CREDIT_REPORT_ACCEPTED_TYPES Acceptable MIME types for credit-report uploads.
CREDIT_REPORT_ACCEPTED_EXTENSIONS Acceptable file extensions for credit-report uploads.
CREDIT_REPORT_MAX_SIZE_BYTES Maximum upload size accepted by validation.
DEMO_ACCOUNT_KEYWORDS Used when cleaning connected-account records.
buildApiCandidates Expands a relative path into same-origin, relative, and backend-base candidates.
fetchApiWithFallback Tries each candidate URL in order until a non-404 response arrives.
cleanupReturnParams Removes Salt Edge redirect markers from the current URL.
fetchAllConnections Loads all Salt Edge connections for a customer and groups them by category.
handleSaltEdgeReturn Reads the returned connection, applies category overrides, and rehydrates all accounts.
startSaltEdgeConnect Creates or reuses a customer, requests a connect session, and redirects to Salt Edge.
startOpenBankingConnect Chooses the redirect path for personal accounts when the EU flow is already complete.
buildUrlWithParams Preserves email, country, and showBusiness in internal navigation.
cleanConnectedAccounts Removes demo and placeholder accounts before persistence or render.
buildConnectionDisplayName Converts Salt Edge connection data into a readable label.
toConnectionAccountLabel Formats the per-account label shown in the UI.
formatAccountDescriptor Normalizes account descriptors such as checking, savings, credit, loan, and investment.

Flow and storage behavior

  • the component restores email, customerId, connected accounts, and category overrides from localStorage
  • when the stored account schema version changes, it clears account and Salt Edge storage
  • savedCustomerId is read before storage reset logic so the redirect can survive a first-time Salt Edge return
  • fetchAllConnections groups accounts into personal, business, and investments
  • if no valid accounts remain after cleanup, the saved connection data is cleared
  • handleSaltEdgeReturn removes connection_id, shared, saltedge_redirect, and category from the URL after processing
  • startSaltEdgeConnect stores userFormData with email, nationality, and businessOwnership
  • unsupported-country responses redirect to /dashboard?manual_credit_upload=true

UI states

State Trigger
Loading Initial redirect hydration, connection processing, or missing search parameters.
Connected One or more accounts are restored or fetched successfully.
Empty No cleaned accounts remain after hydration or storage reset.
Error Customer creation, session creation, redirect handling, or account retrieval fails.

Connect Accounts Layout

frontend/app/application/connect-accounts/components/ConnectAccountsLayout.tsx

This shared layout frames both provider flows with the same application navigation. It provides the fixed footer, the back action, the next-step action, and the optional “Connect Later” path.

Observed props

Prop Type Description
backUrl string Target for the back navigation link.
continueUrl string Target for the next-step link.
continueDisabled boolean Disables the next-step link when the user has not connected the required accounts.
connectLaterUrl `string \ undefined`
children ReactNode Page-specific content rendered inside the shared layout.

Key behavior

  • renders a fixed footer with the navigation actions
  • prevents “Next” navigation when continueDisabled is true
  • exposes the “Connect Later” link only when connectLaterUrl is present

API Integration

Frontend API Route Proxies

These Next.js routes expose Salt Edge and applicant coverage endpoints to the UI under same-origin paths.

Proxy Salt Edge Customer Creation

{
    "title": "Proxy Salt Edge Customer Creation",
    "description": "Forwards a Salt Edge customer creation request to the backend v6 customer endpoint",
    "method": "POST",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/saltedge/v6/customer",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Customer created or reused",
            "body": "{\n    \"customer_id\": \"cust_123456\"\n}"
        }
    }
}

Proxy Salt Edge Connect Session Creation

{
    "title": "Proxy Salt Edge Connect Session Creation",
    "description": "Forwards a Salt Edge connect-session request to the backend v6 connect-session endpoint",
    "method": "POST",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/saltedge/v6/connect-session",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"customer_id\": \"cust_123456\",\n    \"return_to\": \"https://app.dwilar.local/application/connect-accounts?saltedge_redirect=true&category=personal\",\n    \"consent_scopes\": [\n        \"accounts\",\n        \"transactions\",\n        \"holder_info\"\n    ],\n    \"categorization\": \"personal\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Connect session created",
            "body": "{\n    \"connect_url\": \"https://www.saltedge.com/connect/session_abc123\",\n    \"expires_at\": \"2026-03-31T12:00:00Z\"\n}"
        }
    }
}

Proxy Salt Edge Customer Connections

{
    "title": "Proxy Salt Edge Customer Connections",
    "description": "Forwards a Salt Edge customer connections request for a specific customer id",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/saltedge/customer/{customerId}/connections",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "customerId",
            "value": "cust_123456",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Connections returned",
            "body": "{\n    \"connections\": [\n        {\n            \"id\": \"conn_123\",\n            \"provider_name\": \"HSBC\",\n            \"categorization\": \"personal\",\n            \"accounts\": [\n                {\n                    \"id\": \"acc_123\",\n                    \"name\": \"Current Account\",\n                    \"nature\": \"checking\",\n                    \"type\": \"bank\",\n                    \"extra\": {\n                        \"account_type\": \"checking\"\n                    }\n                }\n            ]\n        }\n    ]\n}"
        }
    }
}

Proxy Salt Edge Connection Detail

{
    "title": "Proxy Salt Edge Connection Detail",
    "description": "Forwards a Salt Edge connection lookup for a specific connection id",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/saltedge/connection/{connectionId}",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "connectionId",
            "value": "conn_123",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Connection returned",
            "body": "{\n    \"id\": \"conn_123\",\n    \"customer_id\": \"cust_123456\",\n    \"provider_name\": \"HSBC\",\n    \"categorization\": \"personal\",\n    \"status\": \"active\",\n    \"accounts\": [\n        {\n            \"id\": \"acc_123\",\n            \"name\": \"Current Account\",\n            \"nature\": \"checking\",\n            \"type\": \"bank\",\n            \"extra\": {\n                \"account_type\": \"checking\"\n            }\n        }\n    ]\n}"
        }
    }
}

Fetch Applicant Account Coverage

{
    "title": "Fetch Applicant Account Coverage",
    "description": "Forwards the applicant coverage request to the backend and returns the coverage summary used by the UI",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/v1/applicants/{id}/account-coverage",
    "headers": [
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "123",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Coverage result",
            "body": "{\n    \"application_id\": 123,\n    \"status\": \"incomplete\",\n    \"reported_accounts\": 2,\n    \"detected_accounts\": 3,\n    \"missing_accounts\": 1,\n    \"coverage_ratio\": 0.67,\n    \"details\": [\n        {\n            \"connection_name\": \"Example Bank\",\n            \"institution_name\": \"Example Bank\",\n            \"reported_accounts\": 2,\n            \"detected_accounts\": 3,\n            \"missing_accounts\": 1,\n            \"status\": \"incomplete\"\n        }\n    ],\n    \"errors\": []\n}"
        }
    }
}

Plaid Backend Calls Used by the UI

The Plaid flow talks directly to backend endpoints from frontend/app/application/PlaidLinkButton.tsx and frontend/app/application/connect-accounts/pagePlaid.tsx.

{
    "title": "Create Plaid Link Token",
    "description": "Fetches a new Plaid link token for the current applicant connection flow",
    "method": "GET",
    "baseUrl": "<BackendApiUrl>",
    "endpoint": "/api/plaid/create_link_token",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Link token returned",
            "body": "{\n    \"link_token\": \"link-sandbox-123\"\n}"
        }
    }
}

Exchange Plaid Public Token

{
    "title": "Exchange Plaid Public Token",
    "description": "Exchanges a Plaid public token for an access token and item id",
    "method": "POST",
    "baseUrl": "<BackendApiUrl>",
    "endpoint": "/api/test/exchange_token",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"public_token\": \"public-sandbox-123\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Token exchange succeeded",
            "body": "{\n    \"item_id\": \"item_123\",\n    \"access_token\": \"access-sandbox-123\"\n}"
        }
    }
}

Fetch Plaid Account Balances

{
    "title": "Fetch Plaid Account Balances",
    "description": "Returns account records and balances for a Plaid access token",
    "method": "GET",
    "baseUrl": "<BackendApiUrl>",
    "endpoint": "/api/test/accounts/balances",
    "headers": [],
    "queryParams": [
        {
            "key": "access_token",
            "value": "access-sandbox-123",
            "required": true
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Account balances returned",
            "body": "[\n    {\n        \"account_id\": \"acc_123\",\n        \"name\": \"Checking\",\n        \"subtype\": \"checking\",\n        \"balances\": {\n            \"available\": 1200,\n            \"current\": 1500,\n            \"iso_currency_code\": \"USD\",\n            \"unofficial_currency_code\": null\n        }\n    }\n]"
        }
    }
}

Backend Salt Edge Interface

backend/src/interface/saltedge_endpoints.py

This module owns the Salt Edge backend routes and the in-memory customer cache used by list_saltedge_customers. The authenticated endpoints depend on get_current_user_email; the unauthenticated v6 onboarding endpoints do not.

Route handler methods

Method Description
get_saltedge_connect_url Generates a Salt Edge connect URL for the authenticated user and returns the widget URL payload.
list_saltedge_customers Returns the cached or freshly fetched Salt Edge customer list.
list_saltedge_connections Returns connections for a customer_id query value.
list_saltedge_accounts Returns accounts for a customer_id and connection_id query pair.
initiate_enduser_saltedge_connection Generates a Salt Edge connect URL from an email supplied in the request body.
create_or_get_saltedge_v6_customer Creates or reuses a Salt Edge customer for the v6 onboarding flow.
create_saltedge_v6_connect_session Creates a v6 Salt Edge connect session and returns the widget URL.
get_connections_for_customer Returns all connections for a customer with their accounts attached.
get_saltedge_connection Returns a single connection with customer id, status, and accounts.

Data models

Type Properties
SaltEdgeCustomerData customer_id: string, identifier: string, created_at: string
SaltEdgeCustomerListResponse data: SaltEdgeCustomerData[]
SaltEdgeConnectionData id: string, provider_name: string
SaltEdgeConnectionListResponse data: SaltEdgeConnectionData[]
SaltEdgeAccountData id: string, connection_id: string, name: string, nature: string, balance: float, currency_code: string, extra: Dict[str, Any], created_at: string, updated_at: string
SaltEdgeAccountListResponse data: SaltEdgeAccountData[]
SaltEdgeInitiateEnduserConnectionRequest email: string, return_to?: string
SaltEdgeV6CustomerRequest email: string
SaltEdgeV6CustomerResponse customer_id: string
SaltEdgeV6ConnectSessionRequest customer_id: string, return_to: string, consent_scopes: string[], categorization: string
SaltEdgeV6ConnectSessionResponse connect_url: string, expires_at?: string
SaltEdgeConnectionWithAccountsData id: string, provider_name?: string, categorization?: string, accounts: Dict[str, Any][]
SaltEdgeConnectionsForCustomerResponse connections: SaltEdgeConnectionWithAccountsData[]
SaltEdgeSingleConnectionResponse id: string, customer_id?: string, provider_name?: string, categorization?: string, status?: string, accounts: Dict[str, Any][]

Salt Edge connect URL

{
    "title": "Generate Salt Edge Connect URL",
    "description": "Generates a connect URL for the authenticated user and a requested return_to location",
    "method": "POST",
    "baseUrl": "<BackendApiUrl>",
    "endpoint": "/api/saltedge/connect-url",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"return_to\": \"https://app.dwilar.local/application/review\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Connect URL returned",
            "body": "{\n    \"connect_url\": \"https://www.saltedge.com/connect/session_abc123\",\n    \"expires_at\": \"2026-03-31T12:00:00Z\",\n    \"customer_id\": \"cust_123456\"\n}"
        }
    }
}

Salt Edge customers

{
    "title": "List Salt Edge Customers",
    "description": "Returns the cached Salt Edge customer list for the authenticated user",
    "method": "GET",
    "baseUrl": "<BackendApiUrl>",
    "endpoint": "/api/saltedge/customers",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Customer list returned",
            "body": "{\n    \"data\": [\n        {\n            \"customer_id\": \"cust_123456\",\n            \"identifier\": \"[email protected]\",\n            \"created_at\": \"2026-03-31T12:00:00Z\"\n        }\n    ]\n}"
        }
    }
}

Salt Edge connections by customer

{
    "title": "List Salt Edge Connections",
    "description": "Returns the connection list for a customer id",
    "method": "GET",
    "baseUrl": "<BackendApiUrl>",
    "endpoint": "/api/saltedge/connections",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "customer_id",
            "value": "cust_123456",
            "required": true
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Connection list returned",
            "body": "{\n    \"data\": [\n        {\n            \"id\": \"conn_123\",\n            \"provider_name\": \"HSBC\"\n        }\n    ]\n}"
        }
    }
}

Salt Edge accounts by customer and connection

{
    "title": "List Salt Edge Accounts",
    "description": "Returns the accounts for a customer and connection pair",
    "method": "GET",
    "baseUrl": "<BackendApiUrl>",
    "endpoint": "/api/saltedge/accounts",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "customer_id",
            "value": "cust_123456",
            "required": true
        },
        {
            "key": "connection_id",
            "value": "conn_123",
            "required": true
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Account list returned",
            "body": "{\n    \"data\": [\n        {\n            \"id\": \"acc_123\",\n            \"connection_id\": \"conn_123\",\n            \"name\": \"Current Account\",\n            \"nature\": \"checking\",\n            \"balance\": 1234.56,\n            \"currency_code\": \"USD\",\n            \"extra\": {\n                \"account_type\": \"checking\"\n            },\n            \"created_at\": \"2026-03-31T12:00:00Z\",\n            \"updated_at\": \"2026-03-31T12:00:00Z\"\n        }\n    ]\n}"
        }
    }
}

Salt Edge v6 customer

{
    "title": "Create Salt Edge v6 Customer",
    "description": "Creates or reuses a Salt Edge customer for the onboarding flow",
    "method": "POST",
    "baseUrl": "<BackendApiUrl>",
    "endpoint": "/api/saltedge/v6/customer",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Customer id returned",
            "body": "{\n    \"customer_id\": \"cust_123456\"\n}"
        }
    }
}

Salt Edge v6 connect session

{
    "title": "Create Salt Edge v6 Connect Session",
    "description": "Creates a Salt Edge widget session for the applicant",
    "method": "POST",
    "baseUrl": "<BackendApiUrl>",
    "endpoint": "/api/saltedge/v6/connect-session",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"customer_id\": \"cust_123456\",\n    \"return_to\": \"https://app.dwilar.local/application/connect-accounts?saltedge_redirect=true&category=personal\",\n    \"consent_scopes\": [\n        \"accounts\",\n        \"transactions\",\n        \"holder_info\"\n    ],\n    \"categorization\": \"personal\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Widget URL returned",
            "body": "{\n    \"connect_url\": \"https://www.saltedge.com/connect/session_abc123\",\n    \"expires_at\": \"2026-03-31T12:00:00Z\"\n}"
        }
    }
}

Salt Edge customer connections by id

{
    "title": "Get Connections for Customer",
    "description": "Returns all Salt Edge connections for a customer with account data attached",
    "method": "GET",
    "baseUrl": "<BackendApiUrl>",
    "endpoint": "/api/saltedge/customer/{customerId}/connections",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "customerId",
            "value": "cust_123456",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Connections returned",
            "body": "{\n    \"connections\": [\n        {\n            \"id\": \"conn_123\",\n            \"provider_name\": \"HSBC\",\n            \"categorization\": \"personal\",\n            \"accounts\": [\n                {\n                    \"id\": \"acc_123\",\n                    \"name\": \"Current Account\",\n                    \"nature\": \"checking\",\n                    \"type\": \"bank\",\n                    \"extra\": {\n                        \"account_type\": \"checking\"\n                    }\n                }\n            ]\n        }\n    ]\n}"
        }
    }
}

Salt Edge connection by id

{
    "title": "Get Salt Edge Connection",
    "description": "Returns a single Salt Edge connection and its accounts",
    "method": "GET",
    "baseUrl": "<BackendApiUrl>",
    "endpoint": "/api/saltedge/connection/{connectionId}",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "connectionId",
            "value": "conn_123",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Connection returned",
            "body": "{\n    \"id\": \"conn_123\",\n    \"customer_id\": \"cust_123456\",\n    \"provider_name\": \"HSBC\",\n    \"categorization\": \"personal\",\n    \"status\": \"active\",\n    \"accounts\": [\n        {\n            \"id\": \"acc_123\",\n            \"name\": \"Current Account\",\n            \"nature\": \"checking\",\n            \"type\": \"bank\",\n            \"extra\": {\n                \"account_type\": \"checking\"\n            }\n        }\n    ]\n}"
        }
    }
}

Salt Edge end user connection

{
    "title": "Initiate Salt Edge End User Connection",
    "description": "Creates a Salt Edge connect URL from the supplied email and optional return_to",
    "method": "POST",
    "baseUrl": "<BackendApiUrl>",
    "endpoint": "/api/saltedge/initiate-enduser-connection",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\",\n    \"return_to\": \"https://app.dwilar.local/application/review\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Connect URL returned",
            "body": "{\n    \"connect_url\": \"https://www.saltedge.com/connect/session_abc123\",\n    \"expires_at\": \"2026-03-31T12:00:00Z\",\n    \"customer_id\": \"cust_123456\"\n}"
        }
    }
}

Account Coverage Inference

backend/src/usecase/account_detection.py

This use case compares the connected accounts stored on an application with the accounts Plaid reports for each access token. It groups records by token, fetches balances from the Plaid gateway, and returns a coverage summary that drives the applicant coverage response.

Data model

Type Properties
AccountCoverageResult status: string, reported_accounts: int, detected_accounts: int, missing_accounts: int, coverage_ratio?: float, details: list[dict[str, Any]], errors: list[str]

Key functions

Function Description
infer_account_coverage Aggregates Plaid-connection coverage by comparing reported account ids with detected account ids.
_collect_plaid_entries Collects Plaid records from connected_accounts and groups them by access token.
_iter_connected_account_records Yields account records from either a list or a keyed mapping.
_normalise_string Trims and validates string-like input values.

Coverage status rules

  • unknown: no Plaid entries were available or no accounts were detected
  • incomplete: at least one detected account is missing from the reported list
  • complete: all detected accounts were reported

Salt Edge Customer Cache

backend/src/interface/saltedge_endpoints.py

The customer-list endpoint uses a module-level cache to reduce Salt Edge API calls. The cache is guarded by an asyncio.Lock and expires after 60 seconds.

Cache structure

Symbol Responsibility
_customer_cache Stores cached response data and the expiry timestamp.
_customer_cache_lock Serializes refreshes when the cache is stale.
CUSTOMER_CACHE_TTL_SECONDS Cache lifetime, set to 60.

Data flow

  1. list_saltedge_customers checks _customer_cache["data"] and _customer_cache["expires"].
  2. If the cache is valid, the endpoint returns SaltEdgeCustomerListResponse(data=_customer_cache["data"]).
  3. If the cache is stale, the endpoint acquires _customer_cache_lock.
  4. The endpoint fetches fresh customer data from SaltEdgeClient.list_all_customers().
  5. The endpoint stores the new data and expires values before returning the response.
sequenceDiagram
    participant C as Caller
    participant E as list_saltedge_customers
    participant M as _customer_cache
    participant L as _customer_cache_lock
    participant S as SaltEdgeClient

    C->>E: GET customers
    E->>M: check data and expires
    alt cache hit
        M-->>E: cached data
        E-->>C: SaltEdgeCustomerListResponse
    else cache miss
        E->>L: acquire
        E->>S: list_all_customers
        S-->>E: customer data
        E->>M: store data and expiry
        E-->>C: SaltEdgeCustomerListResponse
    end

Logging

backend/src/interface/saltedge_endpoints.py

The module-level logger captures cache activity and Salt Edge failures.

Logged events

  • cache hits for list_saltedge_customers
  • cache refreshes after fetching Salt Edge data
  • Salt Edge API errors
  • unexpected errors during customer, connection, account, and connect-session handling

Error reporting behavior

  • several handlers use logger.error(...) for Salt Edge client errors
  • several handlers also use print(...) for unexpected failures
  • API error payloads are surfaced back to the caller using HTTPException

Feature Flows

Provider Routing and Page Selection

sequenceDiagram
    participant U as User
    participant R as Connect Accounts Router
    participant P as Plaid Page
    participant S as Salt Edge Page

    U->>R: Open connect accounts page
    R->>R: normalizeCountryKey
    R->>R: set country to us when missing
    R->>R: choose provider from country and provider query
    alt Plaid selected
        R->>P: Render Plaid flow
    else Salt Edge selected
        R->>S: Render Salt Edge flow
    end

Plaid Connection Flow

sequenceDiagram
    participant U as User
    participant P as Plaid Page
    participant B as Plaid Link Button
    participant A as Backend API
    participant L as Plaid Link

    U->>P: Click Connect
    P->>B: Start connection
    B->>A: GET create_link_token
    A-->>B: link_token
    B->>L: open with token
    L-->>B: public_token and metadata
    B->>A: POST exchange_token
    A-->>B: item_id and access_token
    B->>A: GET balances
    A-->>B: account records
    B->>P: upsertResolvedAccounts
    P-->>U: Render connected accounts

Flow notes

  • if the backend base URL is unavailable, buildFallbackAccounts creates local connection records from Plaid metadata
  • handlePlaidSuccess resolves accounts from balances first and uses fallback accounts only when balance hydration returns nothing
  • handlePlaidExit clears the per-category connect state and surfaces a readable message
  • handlePlaidEvent only logs event data

Salt Edge Connection Flow

sequenceDiagram
    participant U as User
    participant P as Salt Edge Page
    participant X as Frontend Proxy
    participant B as Backend Salt Edge API
    participant W as Salt Edge Widget

    U->>P: Click Connect
    P->>X: POST v6 customer
    X->>B: create customer
    B-->>X: customer_id
    X-->>P: customer_id
    P->>X: POST v6 connect session
    X->>B: create connect session
    B-->>X: connect_url
    X-->>P: connect_url
    P->>W: Redirect browser to connect_url
    W-->>P: Return with connection_id and category
    P->>X: GET connection by id
    X->>B: fetch connection details
    B-->>X: connection data
    X-->>P: connection data
    P->>X: GET customer connections
    X->>B: fetch all connections and accounts
    B-->>X: connections list
    X-->>P: grouped connections
    P-->>U: Render connected accounts

Flow notes

  • fetchApiWithFallback tries same-origin proxy paths before direct backend candidates
  • processedConnections prevents duplicate handling of the same Salt Edge redirect
  • handleSaltEdgeReturn stores the returned customer_id, loads the connection details, and refreshes all connection groups
  • startOpenBankingConnect sends users to SALTEDGE_CLIENTS_URL when the EU personal-account flow is already connected
  • unsupported-country errors redirect the applicant to manual credit upload

Applicant Account Coverage Exposure

sequenceDiagram
    participant U as User
    participant F as UI
    participant R as Coverage Proxy
    participant B as Backend API

    U->>F: Open applicant coverage view
    F->>R: GET account coverage
    R->>R: resolve backend url candidates
    R->>B: GET /api/v1/applicants/id/account-coverage
    B-->>R: coverage response
    R-->>F: JSON payload
    F-->>U: Render coverage summary

State Management

Router State

  • derived from useSearchParams
  • URL normalization adds country=us when missing
  • provider selection is derived, not stored

Plaid Page State

State Description
connectingStates Per-category connection progress flags.
plaidError Current Plaid failure message.
connectedAccounts Account groups persisted to localStorage and rendered in the cards.
creditReportFileName Selected report name shown in the card.
creditReportUploadError Validation error shown under the upload control.
addCountryOpen Country modal visibility.

Salt Edge Page State

State Description
redirectingStates Per-category Salt Edge connection progress flags.
error Connection, customer, or hydration error state.
isProcessingConnection Guards duplicate redirect processing.
customerId Salt Edge customer id used for widget creation and hydration.
categoryOverrides Connection-to-category overrides loaded from storage.
connectedAccounts Rendered account groups persisted to localStorage.
overridesLoaded Ensures override persistence does not run before initial hydration finishes.
creditReportFileName Uploaded credit-report filename.
creditReportUploadError Credit-report validation feedback.
addCountryOpen Country modal visibility.
State Description
linkToken Current Plaid Link token.
error Token fetch or connection error.
receivedRedirectUri OAuth return URI used when resuming a redirect flow.

Persistent Storage

Key Used by Purpose
dw_application_connected_accounts pagePlaid.tsx, pageSalt.tsx Persist connected-account groups.
dw_application_connected_accounts_version pagePlaid.tsx, pageSalt.tsx Track the connected-account schema version.
dw_application_saltedge_customer_id pageSalt.tsx Persist the Salt Edge customer id.
dw_application_category_overrides pageSalt.tsx Persist Salt Edge category overrides.
plaid_oauth_link_token PlaidLinkButton.tsx Resume Plaid OAuth redirect flows.
plaid_oauth_account_type PlaidLinkButton.tsx Resume Plaid OAuth redirect flows for the correct account type.
userFormData pageSalt.tsx Preserve applicant context across the Salt Edge redirect.

Error Handling

Plaid page

  • token fetch failures set plaidError
  • Plaid exit errors use err.display_message when available
  • balance hydration failures fall back to metadata-based account records
  • if fallback account construction also fails, the page surfaces a readable connection error

Salt Edge page

  • customer-creation failures surface as Failed to connect bank account
  • connect-session failures inspect the backend detail payload
  • unsupported_country response codes redirect to manual credit upload
  • malformed localStorage payloads are removed and ignored
  • connection processing errors are logged and rendered in the alert banner

Coverage proxy

  • invalid applicant ids return a 400 error
  • missing backend configuration returns a 500 error
  • backend 404 responses trigger fallback candidate selection
  • other backend failures surface through buildErrorResponse

Caching Strategy

Connection storage and versioning

  • both connect pages persist connected accounts to localStorage
  • storage is versioned with CONNECTED_ACCOUNTS_STORAGE_VERSION = "7"
  • mismatched versions clear stored accounts and related Salt Edge metadata

Salt Edge customer cache

  • list_saltedge_customers caches the response body for 60 seconds
  • the cache is protected by _customer_cache_lock
  • cache state is module-global and reused across requests during the TTL window

Plaid OAuth resume storage

  • Plaid OAuth state is stored in localStorage before opening Plaid Link
  • the token and account type are cleared after success or exit
  • this allows the component to reopen the same Link session after an OAuth redirect

Dependencies

UI and routing

  • next/navigation
  • next/dynamic
  • next/link
  • React hooks: useState, useEffect, useMemo, useCallback, useRef, Suspense
  • lucide-react
  • @/components/ui/button
  • @/components/application/add-country-modal

Plaid integration

  • react-plaid-link
  • backend Plaid token and balance endpoints
  • getConfiguredBackendApiUrl
  • resolveBackendApiUrl

Salt Edge integration

  • frontend proxy routes under /api/saltedge/...
  • backend Salt Edge endpoints in saltedge_endpoints.py
  • get_current_user_email for authenticated backend routes
  • SaltEdgeClient
  • generate_saltedge_connect_url

Coverage exposure

  • frontend coverage proxy under /api/v1/applicants/[id]/account-coverage
  • backend coverage response and inference model from account_detection.py

Testing Considerations

  • verify country normalization for usa, u.s., canada, and default values
  • verify provider=plaid forces the Plaid page
  • verify Plaid OAuth resume logic when oauth_state_id is present
  • verify Plaid balance hydration and fallback account creation
  • verify the Plaid upload validator rejects non-image, non-PDF, and oversized files
  • verify Salt Edge redirect handling with saltedge_redirect, connection_id, and category
  • verify duplicate Salt Edge redirect processing is blocked by processedConnections
  • verify unsupported-country handling routes to manual credit upload
  • verify account storage is cleared when the schema version changes
  • verify the coverage proxy rejects invalid applicant ids and falls back across backend candidates

Key Classes Reference

Class Responsibility
page.tsx Routes applicants to Plaid or Salt Edge based on country and provider parameters.
pagePlaid.tsx Manages Plaid account linking, balance hydration, and connected-account persistence.
pageSalt.tsx Manages Salt Edge customer creation, widget redirects, and connection hydration.
providers.ts Defines country-specific bank suggestions and open-banking provider metadata.
ConnectAccountsLayout.tsx Provides the shared application footer and navigation shell for account connection pages.
PlaidLinkButton.tsx Launches Plaid Link and resumes OAuth redirects.
route.ts Exposes Salt Edge proxy routes to the frontend UI.
route.ts Exposes the applicant account coverage proxy route.
saltedge_endpoints.py Implements backend Salt Edge endpoints and the customer cache.
account_detection.py Computes account coverage from connected accounts and Plaid-detected accounts.