Architecture and Repository Orientation

Overview

This repository is organized as a monorepo with distinct runtime boundaries for the housing application experience, consented financial-data services, and deployment assets. The user-facing flow starts in frontend/, which is a Next.js application with API-route proxies and browser-state persistence. The core housing intake and third-party integration flow lives in backend/, which is a FastAPI application organized into interface, use-case, and infrastructure modules.

The repo also contains separate service boundaries for the US consent and data stack in services/us-api/ and services/us-data-gateway/, plus platform assets under platform/, operational documentation under documents/, shared automation under scripts/, schema assets under db/, and durable session memory under workspace/. The result is a codebase where runtime services, deployment instructions, and memory-oriented repo maps are intentionally separated rather than blended into one application tree.

Architecture Overview

flowchart LR
    User[Browser User]

    subgraph FrontendApp [frontend]
        NextApp[Next.js app]
        Pages[Application pages]
        ApiRoutes[API route proxies]
        BrowserState[Local storage state]
        NextApp --> Pages
        NextApp --> ApiRoutes
        Pages --> BrowserState
    end

    subgraph BackendApp [backend]
        FastAPIApp[FastAPI backend]
        Interface[Interface routes]
        UseCases[Use case layer]
        Infra[Infrastructure layer]
        FastAPIApp --> Interface
        Interface --> UseCases
        UseCases --> Infra
    end

    subgraph PlatformLayer [platform]
        HousingLabelService[housing label service]
        DeploymentAssets[Deployment and database assets]
    end

    subgraph ServicesLayer [services]
        USAPI[us-api]
        USGateway[us-data-gateway]
    end

    subgraph DocsLayer [documents and workspace]
        Docs[documents]
        Memory[workspace]
    end

    User --> NextApp
    ApiRoutes --> FastAPIApp
    ApiRoutes --> BackendSaltEdge[Backend Salt Edge routes]
    FastAPIApp --> BackendSaltEdge
    FastAPIApp --> TransUnion[TransUnion batch routes]
    USAPI --- USGateway
    DeploymentAssets --- FastAPIApp
    Docs --- Memory

Repository Boundaries

Top-level area Boundary role What belongs here
backend/ Primary FastAPI application Applicant intake routes, Salt Edge integration, TransUnion batch ingestion, customer service helpers, use-case code, and infra adapters
frontend/ Next.js application User application flow, API-route proxies, browser state, region detection, connect-accounts provider configuration
platform/ Platform/runtime assets The housing label service, deployment manifests, local and prod compose assets, database scripting helpers
services/ Standalone supporting services us-api, us-data-gateway, and the other service boundaries listed in workspace/REPO_MAP.md
documents/ Operational and product documentation Development setup, deployment process, architecture notes, and service-specific guidance
scripts/ Automation and utility scripts Smoke tests, environment helpers, Vertex AI helpers, and local verification scripts
db/ Schema and SQL infrastructure Database migration assets and SQL-related runtime setup
workspace/ Persistent repo memory Repo map, decisions, patterns, debugging notes, changelog, TODOs, and session constraints

Service Map

Service or boundary Directory Runtime shape Responsibility
Housing application backend backend/ FastAPI Applicant intake, connect-account flows, account coverage inference, TransUnion batch processing, and customer API key management
Browser application frontend/ Next.js User onboarding UI, route-level proxying, request-origin handling, and browser-local persistence
Housing label service platform/housing-label-service/ Platform service Separate platform-side service boundary documented in its own README
US consent and analytics API services/us-api/ TypeScript service Consent, token, data, feature, decision, webhook, and analytics surfaces for the US stack
US data gateway services/us-data-gateway/ Go service Consent-scoped retrieval of accounts, balances, transactions, sync deltas, and income
Deployment layer platform/ Compose and scripts Local and prod deployment topology, database application scripts, and runtime packaging
Operational docs documents/ Markdown Development, deployment, and feature-specific guidance
Repo memory workspace/ Markdown memory Canonical repo map, decisions, patterns, debugging records, changelog, and active TODOs

FastAPI Backend Boundary

[!NOTE] documents/deployment.md opens by describing the frontend as “React with Vite”, but the actual repository tree and the later deployment steps point to the Next.js frontend/ app and its API-route proxy model. The current code layout in frontend/ is the authoritative topology for runtime behavior.

backend/ and backend/src/

The FastAPI backend is the main housing-intake service in this repository. The visible code covers Salt Edge account-linking flows, customer access-key management, account coverage inference, and TransUnion batch ingestion. The backend boundary is layered: interface modules expose HTTP routes, use-case modules implement business logic, and infra modules back repositories and external API integrations.

Core backend modules

File Responsibility
backend/src/interface/saltedge_endpoints.py HTTP routes for Salt Edge connect URLs, customer and connection lookups, and v6 onboarding flows
backend/src/interface/transunion_batch_endpoints.py HTTP route for batch credit-file ingestion
backend/src/usecase/account_detection.py Account coverage inference over connected account payloads
backend/src/usecase/transunion_batch.py Parse, persist, and summarize batch credit rows
backend/src/services/customer_service.py Customer creation, authentication, API key rotation, and deactivation
backend/src/models/customer.py API key generation, hashing, and verification helpers
backend/src/scripts/create_test_application.py Local API smoke helper that posts an application and then fetches its detail record

Backend component structure

Customer Service

backend/src/services/customer_service.py

CustomerService manages customer records and API keys against a SQLAlchemy Session. It creates hashed API keys, authenticates a plaintext key, rotates keys, and soft-deactivates customers.

Property Type Description
db Session SQLAlchemy session used for customer CRUD and auth operations
Method Description
create_customer Creates a customer record and returns the customer ID plus plaintext API key
authenticate Verifies a plaintext API key and returns the matching customer when active
rotate_api_key Generates a new API key for an existing customer
deactivate_customer Marks a customer inactive

Account Coverage Result

backend/src/usecase/account_detection.py

AccountCoverageResult is the result object for coverage inference across connected accounts and provider-reported balances.

Property Type Description
status str Coverage state such as unknown, incomplete, or complete
reported_accounts int Number of account identifiers reported by the application payload
detected_accounts int Number of account identifiers returned by the gateway
missing_accounts int Number of detected accounts not present in the submitted payload
coverage_ratio Optional[float] Ratio derived from reported versus detected accounts
details list[dict[str, Any]] Per-connection coverage details
errors list[str] Error strings captured while querying the gateway
Method Description
_normalise_string Trims a string to a non-empty value
_iter_connected_account_records Iterates nested connected-account records
_collect_plaid_entries Groups Plaid records by access token
infer_account_coverage Compares submitted account IDs with provider-reported balances

TransUnion Batch Result

backend/src/usecase/transunion_batch.py

ProcessTransUnionBatchResult is the aggregate returned after batch ingestion, including the persisted ingestion record, a summary payload, sanitized rows, and row-level issues.

Property Type Description
ingestion TransUnionBatchIngestion Persisted ingestion record
summary Dict[str, object] Summary metrics derived from processed rows
sanitized_rows List[Dict[str, object]] Sanitized representation of successfully parsed rows
issues List[TransUnionBatchRowIssue] Row-level parse or validation issues
Method Description
_mask_identifier Masks identifiers for returned rows
_build_sanitized_row Converts a TransUnionBatchRecord into a redacted result row
_extract_metric_value Extracts scalar values from nested metric objects
_build_summary Computes summary stats for processed rows
process_transunion_batch Parses rows, persists them, and returns the final result

Salt Edge Schemas

backend/src/interface/saltedge_endpoints.py

Model Property Type Description
SaltEdgeCustomerData customer_id str Salt Edge customer identifier
identifier str Customer identifier value sent to Salt Edge
created_at str Creation timestamp
SaltEdgeCustomerListResponse data List[SaltEdgeCustomerData] Customer list payload
SaltEdgeConnectionData id str Connection identifier
provider_name str Provider name
SaltEdgeConnectionListResponse data List[SaltEdgeConnectionData] Connection list payload
SaltEdgeAccountData id str Account identifier
connection_id str Parent connection identifier
name str Account display name
nature str Account nature
balance float Account balance
currency_code str Currency code
extra Dict[str, Any] Provider-provided extra data
created_at str Creation timestamp
updated_at str Update timestamp
SaltEdgeAccountListResponse data List[SaltEdgeAccountData] Account list payload
SaltEdgeInitiateEnduserConnectionRequest email str User email used to start the connection
return_to Optional[str] Optional return URL
SaltEdgeV6CustomerRequest email str Customer email
SaltEdgeV6CustomerResponse customer_id str Created or existing customer identifier
SaltEdgeV6ConnectSessionRequest customer_id str Customer identifier
return_to str Widget redirect URL
consent_scopes List[str] Scopes requested for the session
categorization str Session categorization
SaltEdgeV6ConnectSessionResponse connect_url str Widget URL
expires_at Optional[str] Optional expiration timestamp
SaltEdgeConnectionWithAccountsData id str Connection identifier
provider_name Optional[str] Provider name
categorization Optional[str] Connection categorization
accounts List[Dict[str, Any]] Embedded account payloads
SaltEdgeConnectionsForCustomerResponse connections List[SaltEdgeConnectionWithAccountsData] Customer connection aggregate
SaltEdgeSingleConnectionResponse id str Connection identifier
customer_id Optional[str] Parent customer identifier
provider_name Optional[str] Provider name
categorization Optional[str] Connection categorization
status Optional[str] Connection status
accounts List[Dict[str, Any]] Embedded accounts

Backend flow: Salt Edge connection and lookup

sequenceDiagram
    participant User as User
    participant Frontend as Next.js page
    participant Backend as FastAPI route
    participant Client as SaltEdgeClient
    participant Provider as Salt Edge

    User->>Frontend: Start connect accounts
    Frontend->>Backend: POST connect session or customer request
    Backend->>Client: create customer or create connect session
    Client->>Provider: API call
    Provider-->>Client: customer id or connect url
    Client-->>Backend: Response payload
    Backend-->>Frontend: JSON response
    Frontend-->>User: Stores customer or opens connect flow

Backend HTTP surfaces

List Salt Edge Customers

{
    "title": "List Salt Edge Customers",
    "description": "Returns cached Salt Edge customers for the current authenticated user",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/saltedge/customers",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"data\": [\n        {\n            \"customer_id\": \"cust_123\",\n            \"identifier\": \"[email protected]\",\n            \"created_at\": \"2024-10-01T00:00:00Z\"\n        }\n    ]\n}"
        }
    }
}

List Salt Edge Connections

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

List Salt Edge Accounts

{
    "title": "List Salt Edge Accounts",
    "description": "Returns accounts for a specific customer and connection",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/saltedge/accounts",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "customer_id",
            "value": "cust_123",
            "required": true
        },
        {
            "key": "connection_id",
            "value": "conn_123",
            "required": true
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"data\": [\n        {\n            \"id\": \"acc_123\",\n            \"connection_id\": \"conn_123\",\n            \"name\": \"Checking\",\n            \"nature\": \"checking\",\n            \"balance\": 1500,\n            \"currency_code\": \"USD\",\n            \"extra\": [],\n            \"created_at\": \"2024-10-01T00:00:00Z\",\n            \"updated_at\": \"2024-10-02T00:00:00Z\"\n        }\n    ]\n}"
        }
    }
}

Initiate Salt Edge End User Connection

{
    "title": "Initiate Salt Edge End User Connection",
    "description": "Starts a Salt Edge connect flow using the provided email and return URL",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "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\": \"http://localhost:3000/application/review\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"connect_url\": \"https://connect.saltedge.com/session/abc123\",\n    \"expires_at\": \"2024-10-01T00:10:00Z\",\n    \"customer_id\": \"cust_123\"\n}"
        }
    }
}

Create or Get Salt Edge Customer

{
    "title": "Create or Get Salt Edge Customer",
    "description": "Creates a Salt Edge customer by email or returns an existing customer identifier",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "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": "Success",
            "body": "{\n    \"customer_id\": \"cust_123\"\n}"
        }
    }
}

Create Salt Edge Connect Session

{
    "title": "Create Salt Edge Connect Session",
    "description": "Creates a Salt Edge connect session and returns the widget URL",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/saltedge/v6/connect-session",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"customer_id\": \"cust_123\",\n    \"return_to\": \"http://localhost:3000/application/review\",\n    \"consent_scopes\": [\n        \"accounts\",\n        \"transactions\",\n        \"holder_info\"\n    ],\n    \"categorization\": \"personal\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"connect_url\": \"https://connect.saltedge.com/session/abc123\",\n    \"expires_at\": \"2024-10-01T00:10:00Z\"\n}"
        }
    }
}

Get Salt Edge Connections for Customer

{
    "title": "Get Salt Edge Connections for Customer",
    "description": "Returns customer connections enriched with account lists",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/saltedge/customer/{customer_id}/connections",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "customer_id",
            "value": "cust_123",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"connections\": [\n        {\n            \"id\": \"conn_123\",\n            \"provider_name\": \"Salt Edge\",\n            \"categorization\": \"personal\",\n            \"accounts\": [\n                {\n                    \"id\": \"acc_123\",\n                    \"name\": \"Checking\"\n                }\n            ]\n        }\n    ]\n}"
        }
    }
}

Get Salt Edge Connection

{
    "title": "Get Salt Edge Connection",
    "description": "Returns a single Salt Edge connection with its customer and accounts",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/saltedge/connection/{connection_id}",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "connection_id",
            "value": "conn_123",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"id\": \"conn_123\",\n    \"customer_id\": \"cust_123\",\n    \"provider_name\": \"Salt Edge\",\n    \"categorization\": \"personal\",\n    \"status\": \"active\",\n    \"accounts\": [\n        {\n            \"id\": \"acc_123\",\n            \"name\": \"Checking\"\n        }\n    ]\n}"
        }
    }
}

Applicant Account Coverage

{
    "title": "Applicant Account Coverage",
    "description": "Returns coverage statistics for a specific applicant identifier",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/v1/applicants/{id}/account-coverage",
    "headers": [
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "1",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\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}"
        }
    }
}

Applicant Transactions

{
    "title": "Applicant Transactions",
    "description": "Returns normalized transactions for a specific applicant and optional date window",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/v1/applicants/{id}/transactions",
    "headers": [
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "start_date",
            "value": "2024-10-01",
            "required": false
        },
        {
            "key": "end_date",
            "value": "2024-10-31",
            "required": false
        }
    ],
    "pathParams": [
        {
            "key": "id",
            "value": "1",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"applicant_id\": \"1\",\n    \"start_date\": \"2024-10-01\",\n    \"end_date\": \"2024-10-31\",\n    \"transactions\": [\n        {\n            \"amount\": -1200,\n            \"date\": \"2024-10-01\",\n            \"currency_code\": \"USD\",\n            \"status\": \"posted\",\n            \"account_name\": \"Checking\",\n            \"connection_name\": \"Example Bank\",\n            \"description\": \"Rent\",\n            \"categories\": [\n                \"RENT\"\n            ],\n            \"provider\": \"plaid\",\n            \"metadata\": {\n                \"amount\": -1200,\n                \"date\": \"2024-10-01\",\n                \"currency_code\": \"USD\",\n                \"status\": \"posted\",\n                \"account_name\": \"Checking\",\n                \"connection_name\": \"Example Bank\",\n                \"description\": \"Rent\",\n                \"categories\": [\n                    \"RENT\"\n                ],\n                \"provider\": \"plaid\"\n            }\n        }\n    ]\n}"
        }
    }
}

Salt Edge customer cache

The backend keeps a module-level cache for /api/saltedge/customers. It is guarded by an asyncio.Lock, stored in _customer_cache, and expires after CUSTOMER_CACHE_TTL_SECONDS = 60.

Cache item Type Description
data Any Cached Salt Edge customer list payload
expires number Epoch timestamp when the cache entry expires
Behavior Description
Cache hit Returns cached customer data without calling Salt Edge
Cache miss Fetches from Salt Edge, stores the result, and refreshes the TTL
Locking Prevents concurrent refreshes from racing
sequenceDiagram
    participant User as User
    participant Backend as Salt Edge customers route
    participant Cache as Module cache
    participant Client as SaltEdgeClient
    participant Provider as Salt Edge

    User->>Backend: GET customers
    Backend->>Cache: Check data and expiry
    alt Cache valid
        Cache-->>Backend: Cached payload
        Backend-->>User: JSON response
    else Cache expired
        Backend->>Client: list all customers
        Client->>Provider: Fetch customers
        Provider-->>Client: Customer payload
        Client-->>Backend: Customer list
        Backend->>Cache: Store payload and expiry
        Backend-->>User: JSON response
    end

Repository memory surface

workspace/ is the persistent orientation layer for the repository. The files are operational, not product features, and they are meant to stay current as the repo changes.

File Responsibility
workspace/REPO_MAP.md High-level repository map and update protocol
workspace/PATTERNS.md Recurring architecture and file-structure conventions
workspace/DECISIONS.md Durable technical decisions and trade-offs
workspace/DEBUGGING.md Troubleshooting records and incident notes
workspace/CHANGELOG.md Notable project-level changes
workspace/TODO.md High-signal follow-up tasks
workspace/SOUL.md Session behavior constraints and style rules

Next.js Frontend Boundary

frontend/ and frontend/app/

The frontend is a Next.js application that holds the browser-side onboarding journey and route-level API proxies. It does more than render screens: some routes merge backend data with stored JSON, some proxy directly to backend Salt Edge routes, and the application flow preserves state in localStorage so the user can move through the onboarding steps without losing context.

Frontend module structure

File Responsibility
frontend/app/application/employment/page.tsx Employment and citizenship step with lazy country loading and browser-state persistence
frontend/app/application/review/page.tsx Review and submit step with connected-account cleanup, local storage state, and application POST
frontend/app/application/connect-accounts/providers.ts Country and provider configuration for connect-account screens
frontend/app/api/v1/applicants/[id]/account-coverage/route.ts Route proxy to backend applicant coverage data
frontend/app/api/v1/applicants/[id]/transactions/route.ts Route that merges backend and stored application transaction data
frontend/app/api/saltedge/* Route proxies to backend Salt Edge endpoints
frontend/lib/region.ts Country and locale resolution from request metadata

Frontend state management

Employment page state

frontend/app/application/employment/page.tsx

State or cache Type Responsibility
citizenship string Selected country of citizenship
isCountryOpen boolean Dropdown open state
countrySearch string Search filter for citizenship list
employment string Selected employment value
citizenshipOptions CitizenshipOption[] Loaded citizenship options
isLoadingCitizenshipOptions boolean Loading flag while country list imports
citizenshipOptionsCache `CitizenshipOption[] \ null`
citizenshipOptionsPromise `Promise<CitizenshipOption[]> \ null`

Review page state

frontend/app/application/review/page.tsx

State or storage key Type Responsibility
CONNECTED_ACCOUNTS_STORAGE_KEY string Stored connected accounts payload
CONNECTED_ACCOUNTS_VERSION_KEY string Version gate for stored connected accounts
CONNECTED_ACCOUNTS_STORAGE_VERSION string Current connected accounts version
SALTEDGE_CUSTOMER_STORAGE_KEY string Stored Salt Edge customer identifier
CONNECTION_CATEGORY_STORAGE_KEY string Stored connection category overrides
USER_FORM_DATA_STORAGE_KEY string Stored form payload from earlier steps
APPLICATION_REFERENCE_STORAGE_KEY string Generated application reference
connectedAccounts object Personal, business, and investment accounts
storedForm `StoredFormData \ null`
submitError `string \ null`
isSubmitting boolean Submission in-flight flag

Frontend provider configuration

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

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
Function Description
toCountryKey Normalizes country strings to lower-case keys
getInvestmentDescriptionForCountry Returns a country-specific investment description
getCountryBankConfig Resolves the provider, name, connect URL, and bank list for a country and account type
getOpenBankingProvidersForCountry Returns the available open-banking providers
getDefaultOpenBankingProviderForCountry Returns the default provider option
getOpenBankingProviderById Returns a provider by ID

Frontend flow: applicant transactions lookup

sequenceDiagram
    participant User as User
    participant Page as Applicant page
    participant Route as Next.js api route
    participant Backend as FastAPI backend
    participant Storage as Stored applications

    User->>Page: Open transactions view
    Page->>Route: GET applicant transactions
    Route->>Backend: Fetch direct match
    Route->>Backend: Fetch full application list
    Route->>Storage: Read stored applications
    Storage-->>Route: Stored submissions
    Backend-->>Route: Backend applications
    Route-->>Page: Filtered transaction payload
    Page-->>User: Render transactions or error state

Frontend HTTP surfaces

Create or Get Salt Edge Customer Proxy

{
    "title": "Create or Get Salt Edge Customer Proxy",
    "description": "Proxies a customer creation request to the backend Salt Edge route",
    "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": "Success",
            "body": "{\n    \"customer_id\": \"cust_123\"\n}"
        }
    }
}

Create Salt Edge Connect Session Proxy

{
    "title": "Create Salt Edge Connect Session Proxy",
    "description": "Proxies a connect-session request to the backend Salt Edge route",
    "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_123\",\n    \"return_to\": \"http://localhost:3000/application/review\",\n    \"consent_scopes\": [\n        \"accounts\",\n        \"transactions\",\n        \"holder_info\"\n    ],\n    \"categorization\": \"personal\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"connect_url\": \"https://connect.saltedge.com/session/abc123\",\n    \"expires_at\": \"2024-10-01T00:10:00Z\"\n}"
        }
    }
}

Get Salt Edge Customer Connections Proxy

{
    "title": "Get Salt Edge Customer Connections Proxy",
    "description": "Proxies the customer connections route to the backend Salt Edge service",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/saltedge/customer/{customerId}/connections",
    "headers": [
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "customerId",
            "value": "cust_123",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"connections\": [\n        {\n            \"id\": \"conn_123\",\n            \"provider_name\": \"Salt Edge\",\n            \"categorization\": \"personal\",\n            \"accounts\": [\n                {\n                    \"id\": \"acc_123\",\n                    \"name\": \"Checking\"\n                }\n            ]\n        }\n    ]\n}"
        }
    }
}

Get Salt Edge Connection Proxy

{
    "title": "Get Salt Edge Connection Proxy",
    "description": "Proxies the single connection route to the backend Salt Edge service",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/saltedge/connection/{connectionId}",
    "headers": [
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "connectionId",
            "value": "conn_123",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"id\": \"conn_123\",\n    \"customer_id\": \"cust_123\",\n    \"provider_name\": \"Salt Edge\",\n    \"categorization\": \"personal\",\n    \"status\": \"active\",\n    \"accounts\": [\n        {\n            \"id\": \"acc_123\",\n            \"name\": \"Checking\"\n        }\n    ]\n}"
        }
    }
}

Applicant Account Coverage

{
    "title": "Applicant Account Coverage",
    "description": "Proxies applicant coverage lookup to the backend and returns the backend payload",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/v1/applicants/{id}/account-coverage",
    "headers": [
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "1",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\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}"
        }
    }
}

Applicant Transactions

{
    "title": "Applicant Transactions",
    "description": "Returns filtered transactions for an applicant by merging backend results and stored submissions",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/v1/applicants/{id}/transactions",
    "headers": [
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "start_date",
            "value": "2024-10-01",
            "required": false
        },
        {
            "key": "end_date",
            "value": "2024-10-31",
            "required": false
        }
    ],
    "pathParams": [
        {
            "key": "id",
            "value": "1",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"applicant_id\": \"1\",\n    \"start_date\": \"2024-10-01\",\n    \"end_date\": \"2024-10-31\",\n    \"transactions\": [\n        {\n            \"amount\": -1200,\n            \"date\": \"2024-10-01\",\n            \"currency_code\": \"USD\",\n            \"status\": \"posted\",\n            \"account_name\": \"Checking\",\n            \"connection_name\": \"Example Bank\",\n            \"description\": \"Rent\",\n            \"categories\": [\n                \"RENT\"\n            ],\n            \"provider\": \"plaid\",\n            \"metadata\": {\n                \"amount\": -1200,\n                \"date\": \"2024-10-01\",\n                \"currency_code\": \"USD\",\n                \"status\": \"posted\",\n                \"account_name\": \"Checking\",\n                \"connection_name\": \"Example Bank\",\n                \"description\": \"Rent\",\n                \"categories\": [\n                    \"RENT\"\n                ],\n                \"provider\": \"plaid\"\n            }\n        }\n    ]\n}"
        }
    }
}

Frontend route and state notes

frontend/app/api/v1/applicants/[id]/transactions/route.ts is not a pure proxy. It looks up the applicant directly, then lists all backend applications, then merges in stored submissions before filtering transaction history. That means the route behaves as an aggregation and reconciliation layer for browser-side applicant detail views.

frontend/app/application/review/page.tsx also removes demo and placeholder accounts before it accepts or displays connected-account state. It only allows submission when at least one personal account is present.

Platform and Deployment Boundary

platform/ and documents/

The platform layer contains deployment topology, runtime assets, and the housing label service boundary. documents/deployment.md and documents/development.md are the main operational entrypoints in the visible repository context, while workspace/REPO_MAP.md is the long-lived inventory for the repository shape.

Platform and deployment assets

File or directory Responsibility
platform/housing-label-service/README.md Documents the separate housing label service boundary
platform/deployment/local/ Local compose and environment setup
platform/deployment/prod/ Production compose and environment setup
platform/database/apply_schema.sh Applies schema updates to long-lived MySQL data
db/ Migration and SQL infrastructure assets
documents/development.md Local setup and contributor workflow
documents/deployment.md Production deployment, stability checks, and post-deploy verification

Deployment topology

The deployment guide describes a CI/CD path that builds backend and frontend images, pushes them to Artifact Registry, and deploys via docker-compose on a Compute Engine instance behind Fastly and a Google Cloud HTTPS Load Balancer. The same docs also describe a schema application step for production databases so form submissions and batch writes do not fail when tables are missing.

US API Boundary

[!NOTE] The deployment notes include both docker-compose.yml and docker-compose.yaml references, and they mix older Vite wording with Next.js-specific smoke tests. The repository shape should be read from the actual frontend/ implementation and the platform/deployment files rather than from a single paragraph in the deployment guide.

services/us-api/

The US API is a separate TypeScript service for consent-aware data access, scoring, and analytics. Its visible modules show a clean split between route handlers, business services, models, middleware, and test coverage. The service uses Prisma for persistence, reads feature evidence, and can replay decisions through an optional callback URL.

US API core modules

File Responsibility
services/us-api/src/models/types.ts Consent and feature enums used across the service
services/us-api/src/services/consentService.ts Consent creation and revocation
services/us-api/src/services/connectionService.ts Connection readiness and refresh updates
services/us-api/src/services/featureService.ts Cashflow feature computation and evidence storage
services/us-api/src/services/scoringService.ts Decision validation, storage, and replay
services/us-api/src/services/modelGovernanceService.ts Model lineage and governance support
services/us-api/src/routes/internalAnalytics.ts Internal analytics routes for consent events and metrics
services/us-api/src/jobs/featureDriftJob.ts Daily drift check trigger
services/us-api/test/flows.test.ts Route-level behavior tests
services/us-api/test/psuConsentAnalytics.test.ts Analytics and watchdog coverage

US API model and enum surfaces

Data Categories

services/us-api/src/models/types.ts

DataCategoryValues: IDENTITY_BASIC, ACCOUNTS, BALANCES, TRANSACTIONS, INCOME, EMPLOYMENT, CASHFLOW_FEATURES, DEVICE_RISK, WATCHLIST_SCREENING

Connection Statuses

services/us-api/src/models/types.ts

ConnectionStatusValues: ACTIVE, REAUTH_REQUIRED, DEGRADED, DISCONNECTED

Purposes

services/us-api/src/models/types.ts

PurposeValues: RENTAL_SCREENING, LENDING_UNDERWRITING, ACCOUNT_OPENING, INCOME_VERIFICATION, FRAUD_PREVENTION, GENERAL_PERSONAL_FINANCE

Feature Set

services/us-api/src/models/types.ts

FeatureSet: US_CASHFLOW_V1

Decision payload

services/us-api/src/services/scoringService.ts

Property Type Description
applicant_reference `string \ undefined`
purpose string Declared purpose
product_type `string \ undefined`
score `number \ undefined`
decision string Final decision string
approved_limit `number \ undefined`
model object \ undefined
reasons `{ code: string; description?: string }[] \ undefined`
evidence_ref string Evidence snapshot reference
consent_id string Consent identifier
consent_text_version string Consent text version
connection_status string Connection status string
features Record<string, unknown> Feature payload sent to scoring

Deny reasons allowlist

services/us-api/src/services/scoringService.ts

DenyReasonsAllowlist: INSUFFICIENT_INCOME, INCOME_INSTABILITY, RECENT_OVERDRAFTS, LOW_MIN_BALANCE, HIGH_CASHFLOW_VOLATILITY, INSUFFICIENT_HISTORY, UNVERIFIED_ACCOUNT, INCONSISTENT_IDENTITY_SIGNALS, HIGH_RISK_DEVICE_SIGNAL

US API service methods

Method Description
createConsent Creates a consent, writes a consent log entry, and returns the persisted record
revokeConsent Revokes a consent and related tokens
ensureConnectionsReady Checks connection state and raises when re-authentication is required
recordConnectionRefresh Marks matching connections active and refreshes their timestamp
computeCashflow Builds cashflow features from mock provider data and stores an evidence snapshot
fetchEvidence Loads a stored evidence snapshot by ID
validateDecision Enforces deny-reason allowlist rules
storeDecision Persists a decision and records model lineage when model metadata is present
replayDecision Replays a stored decision or forwards a replay request to the configured callback
recordModelLineage Creates model artifact and deployment records when a new lineage item is seen

US API internal analytics route notes

services/us-api/src/routes/internalAnalytics.ts uses requireInternalAuth as a pre-handler on both routes. The event route validates its body with Zod before applying the event, and the metrics route validates query dates and then fans out to daily, funnel, failure, and latency metrics helpers.

Register Analytics Event

{
    "title": "Register Analytics Event",
    "description": "Records a consent analytics event after internal authentication and body validation",
    "method": "POST",
    "baseUrl": "<USApiBaseUrl>",
    "endpoint": "/internal/analytics/events",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"psu_id\": \"psu_123\",\n    \"consent_session_id\": \"session_123\",\n    \"product\": \"rentals\",\n    \"country\": \"US\",\n    \"provider\": \"plaid\",\n    \"institution_id\": \"inst_123\",\n    \"timestamp\": \"2024-10-01T12:00:00Z\",\n    \"failure_reason\": null,\n    \"event_name\": \"consent_created\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"status\": \"ok\"\n}"
        },
        "409": {
            "description": "Dimension mismatch",
            "body": "{\n    \"status\": \"dimension_mismatch\"\n}"
        }
    }
}

US API sequence

sequenceDiagram
    participant Partner as Partner service
    participant Api as US API
    participant Prisma as Prisma
    participant Evidence as Evidence snapshot
    participant Callback as Optional scoring callback

    Partner->>Api: Create consent or replay decision
    Api->>Prisma: Read or write consent and decision records
    Api->>Evidence: Load evidence snapshot
    alt Callback configured
        Api->>Callback: POST replay payload
        Callback-->>Api: Decision response
        Api->>Prisma: Store decision lineage
    end
    Api-->>Partner: Consent or decision response

US Data Gateway Boundary

services/us-data-gateway/

The data gateway is a separate Go service that exposes consent-scoped read APIs for accounts, balances, transactions, transaction sync, and income. It wires together a Postgres pool, Redis client, JWT public key verification, and a provider interface.

Gateway configuration and provider surface

Config

services/us-data-gateway/internal/config/config.go

Property Type Description
Port string HTTP listen port
DatabaseURL string Postgres connection string
RedisURL string Redis connection string
JWTPublicKey string RS256 public key used for token verification
Provider string Provider selector from environment

Provider models

services/us-data-gateway/internal/provider/provider.go

Type Properties
Account AccountToken string, Name string, Type string, Mask string
Balance AccountToken string, Available float64, Current float64, Currency string
Transaction TransactionID string, AccountToken string, Amount float64, Currency string, PostedAt string, MerchantName string, MerchantCategory string
TransactionRemoval TransactionID string
TransactionSync Added []Transaction, Modified []Transaction, Removed []TransactionRemoval, NextCursor string
Income IncomeID string, Amount float64, Currency string, PayDate string
Method Description
FetchAccounts Returns account records for a consent
FetchBalances Returns balance records for a consent
FetchTransactions Returns transactions for a date range
FetchTransactionsSync Returns cursor-based sync changes
FetchIncome Returns income records for a lookback window

Gateway handler

services/us-data-gateway/internal/handlers/handlers.go

Property Type Description
DB *pgxpool.Pool Postgres connection pool
Provider provider.Provider Data provider interface
Auth auth.TokenVerifier JWT and revocation verifier
Method Description
Accounts Returns token-scoped accounts
Balances Returns token-scoped balances
Transactions Returns token-scoped transactions
TransactionsSync Returns cursor-based transaction sync payload
Income Returns income records
authorize Extracts and verifies a bearer token
ensureConsentActive Checks consent state and expiry before data access
writeError Serializes service errors into JSON
writeJSON Writes JSON responses
contains Checks category membership

US data gateway flow

sequenceDiagram
    participant Client as Caller
    participant Gateway as US data gateway
    participant Auth as Token verifier
    participant DB as Postgres
    participant Provider as Mock provider

    Client->>Gateway: GET data endpoint with bearer token
    Gateway->>Auth: Verify token
    Auth-->>Gateway: Claims
    Gateway->>DB: Read consent record
    DB-->>Gateway: Consent row
    Gateway->>Provider: Fetch consent data
    Provider-->>Gateway: Data payload
    Gateway-->>Client: JSON response

US data gateway HTTP surfaces

Get Accounts

{
    "title": "Get Accounts",
    "description": "Returns consent-scoped accounts",
    "method": "GET",
    "baseUrl": "<USDataGatewayBaseUrl>",
    "endpoint": "/api/v1/us/data/accounts",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <ACCESS_TOKEN>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"accounts\": [\n        {\n            \"account_token\": \"acct_tok_1\",\n            \"name\": \"Checking\",\n            \"type\": \"depository\",\n            \"mask\": \"1234\"\n        }\n    ]\n}"
        }
    }
}

Get Balances

{
    "title": "Get Balances",
    "description": "Returns consent-scoped balances",
    "method": "GET",
    "baseUrl": "<USDataGatewayBaseUrl>",
    "endpoint": "/api/v1/us/data/balances",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <ACCESS_TOKEN>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"balances\": [\n        {\n            \"account_token\": \"acct_tok_1\",\n            \"available\": 1200,\n            \"current\": 1500,\n            \"currency\": \"USD\"\n        }\n    ]\n}"
        }
    }
}

Get Transactions

{
    "title": "Get Transactions",
    "description": "Returns consent-scoped transactions with optional date filtering",
    "method": "GET",
    "baseUrl": "<USDataGatewayBaseUrl>",
    "endpoint": "/api/v1/us/data/transactions",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <ACCESS_TOKEN>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "from",
            "value": "2024-10-01",
            "required": false
        },
        {
            "key": "to",
            "value": "2024-10-31",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"transactions\": [\n        {\n            \"transaction_id\": \"txn_1\",\n            \"account_token\": \"acct_tok_1\",\n            \"amount\": 1200,\n            \"currency\": \"USD\",\n            \"posted_at\": \"2024-10-01T00:00:00Z\",\n            \"merchant_name\": \"Rent Co\",\n            \"merchant_category\": \"RENT\"\n        }\n    ]\n}"
        }
    }
}

Get Transactions Sync

{
    "title": "Get Transactions Sync",
    "description": "Returns added, modified, and removed transactions for a cursor",
    "method": "GET",
    "baseUrl": "<USDataGatewayBaseUrl>",
    "endpoint": "/api/v1/us/data/transactions/sync",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <ACCESS_TOKEN>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "cursor",
            "value": "cursor_123",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"added\": [\n        {\n            \"transaction_id\": \"txn_3\",\n            \"account_token\": \"acct_tok_2\",\n            \"amount\": 45,\n            \"currency\": \"USD\",\n            \"posted_at\": \"2024-10-03T00:00:00Z\",\n            \"merchant_name\": \"Coffee\",\n            \"merchant_category\": \"FOOD\"\n        }\n    ],\n    \"modified\": [\n        {\n            \"transaction_id\": \"txn_2\",\n            \"account_token\": \"acct_tok_1\",\n            \"amount\": 90,\n            \"currency\": \"USD\",\n            \"posted_at\": \"2024-10-02T00:00:00Z\",\n            \"merchant_name\": \"Card\",\n            \"merchant_category\": \"DEBT\"\n        }\n    ],\n    \"removed\": [\n        {\n            \"transaction_id\": \"txn_4\"\n        }\n    ],\n    \"next_cursor\": \"cursor_next_1\"\n}"
        }
    }
}

Get Income

{
    "title": "Get Income",
    "description": "Returns income records for a consent and lookback window",
    "method": "GET",
    "baseUrl": "<USDataGatewayBaseUrl>",
    "endpoint": "/api/v1/us/data/income",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <ACCESS_TOKEN>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "lookback_days",
            "value": "180",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"income\": [\n        {\n            \"income_id\": \"inc_1\",\n            \"amount\": 5100,\n            \"currency\": \"USD\",\n            \"pay_date\": \"2024-09-30T00:00:00Z\"\n        }\n    ]\n}"
        }
    }
}

Operational Documentation Boundary

Development guide

[!NOTE] services/us-data-gateway/cmd/us-data-gateway/main.go maps both PROVIDER=mock and the default case to provider.MockProvider{}. In the visible code, the provider selector does not switch to a non-mock implementation.

documents/development.md

This file captures the local developer workflow for the current stack, including Docker Compose startup, environment-file handling, and the reviewer/admin account setup. It also documents the browser-to-backend flow for application submission and the troubleshooting path for applicant lookup and dashboard state.

Deployment guide

documents/deployment.md

This file captures the production deployment shape: GitHub Actions builds images, Artifact Registry stores them, Compute Engine runs the containers, Fastly fronts the load balancer, and schema application is handled explicitly for long-lived databases. The pre-launch stability workflow is also documented here with smoke tests for both backend and frontend.

State and Storage Patterns

Browser local storage

The frontend uses browser storage as a lightweight state bridge across application steps. It keeps user details, connected accounts, Salt Edge customer IDs, and generated references outside component state so users can move backward and forward without losing progress.

Storage key Used by Purpose
userFormData Employment and review pages Shared application metadata across steps
dw_application_connected_accounts Review page Connected-account payload
dw_application_connected_accounts_version Review page Version gate for stored connected accounts
dw_application_saltedge_customer_id Review page Salt Edge customer identifier
dw_application_saltedge_category_overrides Review page Category overrides by connection
dw_application_reference Review page Generated application reference

State transitions

Area Initial state Transition trigger Final state
Employment page Empty citizenship and default employment User selects citizenship and employment Ready to continue
Employment page country list Not loaded Dropdown opens Lazily loaded and cached
Review page accounts Empty account sets Local storage read completes Cleaned account set
Review page submission Not submitting User presses submit Submitting, then success or error
Salt Edge customer cache Empty Customer list request Cached for 60 seconds

Caching and persistence boundaries

Cache or store Scope Invalidation trigger
citizenshipOptionsCache Module-level frontend cache Reload of the page bundle
citizenshipOptionsPromise Module-level frontend promise cache Same as cache
_customer_cache Backend Salt Edge customer list TTL expiry after 60 seconds
Browser local storage User session storage Version mismatch, submit completion, or explicit cleanup

Testing Considerations

Scenario What the code exercises
Salt Edge customer listing Module-level cache hit and refresh logic
Applicant transactions Merge of backend records and stored submissions
Account coverage Coverage ratio, missing accounts, and error capture
Batch ingestion Sanitize, persist, and summarize TransUnion rows
US consent routes Consent creation, revocation, and refresh-limit handling
US gateway auth Bearer token verification and category enforcement
US analytics jobs Event application and timeout watchdog behavior
Frontend onboarding Local storage persistence and form-step transitions

Key Classes Reference

Class Location Responsibility
CustomerService customer_service.py Customer CRUD and API key management
AccountCoverageResult account_detection.py Account coverage inference result
ProcessTransUnionBatchResult transunion_batch.py Batch ingestion outcome
Config config.go Gateway runtime configuration
Handler handlers.go Consent-scoped US data gateway endpoints
Account provider.go Account response model
Balance provider.go Balance response model
Transaction provider.go Transaction response model
TransactionSync provider.go Transaction sync response model
Income provider.go Income response model
SaltEdgeCustomerData saltedge_endpoints.py Salt Edge customer schema
SaltEdgeConnectionData saltedge_endpoints.py Salt Edge connection schema
SaltEdgeAccountData saltedge_endpoints.py Salt Edge account schema
SaltEdgeV6CustomerRequest saltedge_endpoints.py v6 customer request schema
SaltEdgeV6ConnectSessionRequest saltedge_endpoints.py v6 connect-session request schema
Bank providers.ts Connect-account bank config
ProviderDetail providers.ts Provider defaults and bank lists
CountryOverride providers.ts Country-specific provider override
OpenBankingProviderOption providers.ts Provider capability summary