Banking and Financial Data Domain Coverage Analysis Silent Refresh and Repatriation Risk Workflows

Overview

This backend slice covers three closely related banking-data workflows used by the housing application flow:

  1. Server-side account coverage analysis compares what the applicant reported in connected_accounts with what Plaid detects for the same access token.
  2. Consent-scoped refresh re-pulls balances and transactions while consent is still active, either manually by an operator or automatically when a consent is due.
  3. Repatriation-risk analysis uses refreshed transaction payloads plus the applicant’s declared country to flag home-country spending patterns as an underwriting signal.

The business purpose is to surface hidden or stale financial signals without depending on client-side honesty or manual review. Coverage analysis detects omitted accounts, refresh workflows keep financial evidence current within consent boundaries, and repatriation-risk scoring turns country-specific spending patterns into a structured result that operators can use in review or underwriting.

Architecture Overview

flowchart TB
    subgraph PresentationLayer [Presentation Layer]
        CoverageEndpoint[get_application_account_coverage]
        OpenBankingEndpoints[open_banking_endpoints]
    end

    subgraph BusinessLayer [Business Layer]
        InferCoverage[infer_account_coverage]
        RegisterConsent[register_consent]
        SyncPlaidConsents[sync_application_plaid_consents]
        TriggerRefresh[trigger_refresh]
        RefreshApplicationConsents[refresh_application_consents]
        AutoRefreshDueConsents[auto_refresh_due_consents]
        DetectRepatriationRisk[detect_repatriation_risk]
    end

    subgraph DataAccessLayer [Data Access Layer]
        HousingRepo[SQLAlchemyHousingApplicationRepository]
        ConsentRepo[SQLOpenBankingConsentRepository]
        PlaidGateway[PlaidKycGateway]
        BankGateway[BankGateway]
        TransactionsGateway[TransactionsGateway]
    end

    CoverageEndpoint --> HousingRepo
    CoverageEndpoint --> InferCoverage
    InferCoverage --> PlaidGateway

    OpenBankingEndpoints --> SyncPlaidConsents
    OpenBankingEndpoints --> TriggerRefresh
    OpenBankingEndpoints --> RefreshApplicationConsents
    OpenBankingEndpoints --> AutoRefreshDueConsents
    OpenBankingEndpoints --> DetectRepatriationRisk

    SyncPlaidConsents --> ConsentRepo
    TriggerRefresh --> ConsentRepo
    TriggerRefresh --> BankGateway
    TriggerRefresh --> TransactionsGateway
    RefreshApplicationConsents --> ConsentRepo
    RefreshApplicationConsents --> BankGateway
    RefreshApplicationConsents --> TransactionsGateway
    AutoRefreshDueConsents --> ConsentRepo
    AutoRefreshDueConsents --> BankGateway
    AutoRefreshDueConsents --> TransactionsGateway
    DetectRepatriationRisk --> HousingRepo
    DetectRepatriationRisk --> RefreshApplicationConsents

Component Structure

1. Presentation Layer

get_application_account_coverage

backend/src/interface/http_endpoints.py

This route validates the applicant identifier, loads the housing application from the database, and computes coverage against Plaid-detected accounts. It returns a structured response that shows whether the submitted account list appears complete.

Method Description
get_application_account_coverage Loads the application, runs server-side coverage inference, and returns AccountCoverageResponse.

Injected dependencies

Type Description
Session SQLAlchemy session used to build SQLAlchemyHousingApplicationRepository.
SQLAlchemyHousingApplicationRepository Loads the housing application by application_id.
PlaidKycGateway Fetches detected account lists from Plaid for each submitted access token.

Execution path

  1. FastAPI validates application_id with Path(..., ge=1).
  2. The handler builds SQLAlchemyHousingApplicationRepository(db).
  3. get_housing_application loads the application.
  4. PlaidKycGateway is created.
  5. infer_account_coverage compares submitted account IDs with detected Plaid account IDs.
  6. AccountCoverageResponse is returned.

sync_application_consents

[!NOTE] The route rejects invalid IDs twice: FastAPI enforces ge=1, and get_housing_application raises ValueError for non-positive IDs before the repository lookup.

backend/src/interface/open_banking_endpoints.py

This route synchronizes Plaid-linked consents from the stored housing application into the consent repository. It only returns consents the current operator is allowed to view.

Method Description
sync_application_consents Loads the application, creates or updates consent records from connected_accounts, and returns serialized consents.

Injected dependencies

Type Description
SQLOpenBankingConsentRepository Stores and retrieves consent records.
SQLAlchemyHousingApplicationRepository Loads the housing application.
str current_user_email used to filter consent visibility.

Execution path

  1. The application is loaded with get_housing_application.
  2. sync_application_plaid_consents creates or updates consent records from Plaid-linked accounts.
  3. repository.list_by_application_id(application_id) reloads the stored consents.
  4. Each consent is checked with consent.ensure_operator_allowed(current_user_email).
  5. Visible consents are serialized and returned.

list_application_consents

backend/src/interface/open_banking_endpoints.py

This route returns the consents already stored for an application, filtered by operator visibility.

Method Description
list_application_consents Lists consents for an application after operator authorization filtering.

Injected dependencies

Type Description
SQLOpenBankingConsentRepository Consent lookup by application ID.
str current_user_email used to authorize access.

manual_refresh

backend/src/interface/open_banking_endpoints.py

This route triggers a consent-scoped refresh for a single consent reference. It is the operator-driven path that pulls fresh balances and transactions while the consent remains active.

Method Description
manual_refresh Triggers a refresh for one consent reference and returns a RefreshResponse.

Injected dependencies

Type Description
SQLOpenBankingConsentRepository Loads and updates the consent record.
BankGateway Fetches balances.
TransactionsGateway Fetches transactions.
str current_user_email used as the operator identity.

auto_refresh

backend/src/interface/open_banking_endpoints.py

This route triggers the scheduled refresh path for all due consents. It does not take an application ID because it scans the active consent set.

Method Description
auto_refresh Refreshes due consents and returns a list of AutoRefreshResponse.

Injected dependencies

Type Description
SQLOpenBankingConsentRepository Finds due active consents.
BankGateway Fetches balances.
TransactionsGateway Fetches transactions.

refresh_application

backend/src/interface/open_banking_endpoints.py

This route refreshes every consent attached to an application that the current operator is allowed to access. It is the application-scoped refresh entry point used by the repatriation-risk flow.

Method Description
refresh_application Refreshes all accessible consents for an application and returns a list of RefreshResponse.

Injected dependencies

Type Description
SQLOpenBankingConsentRepository Loads the consent set for the application.
BankGateway Fetches balances.
TransactionsGateway Fetches transactions.
str current_user_email used for consent authorization.

repatriation_risk

backend/src/interface/open_banking_endpoints.py

This route refreshes the application’s accessible consents, filters successful refreshes, and runs the repatriation-risk heuristic against the applicant’s declared country. The response exposes a structured underwriting signal with counts, share, and latest activity timing.

Method Description
repatriation_risk Refreshes active consents and returns a RepatriationRiskResponse.

Injected dependencies

Type Description
SQLOpenBankingConsentRepository Loads consent records for the application.
SQLAlchemyHousingApplicationRepository Loads the housing application and declared country.
BankGateway Fetches balances during refresh.
TransactionsGateway Fetches transactions during refresh.
str current_user_email used to authorize consent access.

2. Business Layer

infer_account_coverage

backend/src/usecase/account_detection.py

This function parses the applicant’s stored connected_accounts, groups Plaid entries by access token, and compares submitted account IDs with the accounts Plaid detects for that token.

Method Description
infer_account_coverage Computes coverage status, totals, per-connection details, and errors.

Public properties

Property Type Description
status str Coverage state: unknown, incomplete, or complete.
reported_accounts int Count of submitted account IDs.
detected_accounts int Count of accounts detected by Plaid across all evaluated tokens.
missing_accounts int Count of detected accounts not present in the submitted set.
coverage_ratio Optional[float] reported_accounts / detected_accounts, or None when detection did not produce a usable denominator.
details list[dict[str, Any]] Per-connection coverage rows.
errors list[str] Error messages captured while evaluating individual Plaid tokens.

Coverage rules

  • unknown: no Plaid entries were collected, or no accounts were detected.
  • incomplete: at least one detected account was missing from the applicant’s submitted list.
  • complete: every detected account was present in the submitted list.

Connection-level detail shape

Each entry in details contains:

Property Type Description
connection_name `str None`
institution_name `str None`
reported_accounts int Number of submitted account IDs for that token.
detected_accounts int Number of Plaid-detected account IDs for that token.
missing_accounts int Number of detected IDs not found in the submitted set.
status str complete, incomplete, or error.

Detection steps

  1. _collect_plaid_entries keeps only provider == "plaid" entries.
  2. Each access token is grouped once, with submitted account IDs deduplicated into a set.
  3. plaid_gateway.get_account_balances(token) retrieves the live account set.
  4. Detected account IDs are compared with the submitted IDs.
  5. Totals and per-connection details are accumulated.

backend/src/usecase/open_banking.py

This function creates a new OpenBankingConsent record with deduplicated scopes and operator IDs.

Method Description
register_consent Creates and persists a consent record through the repository.

sync_application_plaid_consents

backend/src/usecase/open_banking.py

This function turns Plaid-linked records in connected_accounts into durable consent records. It fingerprints each access token, generates a stable consent reference, and stores account metadata for later refresh workflows.

Method Description
sync_application_plaid_consents Creates or updates consent records for Plaid connections on a housing application.

Behavioral details

  • customer_reference is derived from application.email, then application.id, then application.phone.
  • consent_reference uses the token hash suffix:
    • application-{id}-{suffix}
    • application-unknown-{suffix} when the application ID is absent.
  • New records are created with:
    • scopes=("balances:read", "transactions:read")
    • auto_refresh_enabled=True
    • auto_refresh_interval_minutes=720
  • Existing records are updated in place and re-saved.
  • Token attachment is refreshed after consent persistence.

trigger_refresh

backend/src/usecase/open_banking.py

This is the manual refresh primitive used by the operator-facing refresh route and the repatriation-risk workflow. It enforces consent activity before pulling balances and transactions.

Method Description
trigger_refresh Refreshes a single consent reference, persists the result, and records a refresh event.

Behavioral details

  • Loads the consent by consent_reference.
  • Validates that the consent is active, operator-authorized, and has a token.
  • Pulls balances from BankGateway.
  • Pulls transactions from TransactionsGateway or PlaidKycGateway.
  • Updates last_refreshed_at only on success.
  • Saves an OpenBankingRefreshEvent with:
    • trigger_type="manual"
    • triggered_by=operator_id
    • status
    • balances and transactions payloads
    • error message on failure
  • Raises OpenBankingRefreshFailed if the refresh fails.

refresh_application_consents

backend/src/usecase/open_banking.py

This function runs trigger_refresh for every consent that the operator is allowed to access. It is the application-level refresh wrapper used by the repatriation-risk route.

Method Description
refresh_application_consents Refreshes all operator-accessible consents for an application and aggregates their results.

Behavioral details

  • Throws OpenBankingConsentNotFound if the application has no stored consents.
  • Filters consents with consent.ensure_operator_allowed(operator_id).
  • Skips unauthorized consents silently during filtering.
  • Converts per-consent refresh failures into result rows with:
    • status="failed"
    • empty payloads
    • error_message
  • Raises OpenBankingRefreshFailed if every result failed.

auto_refresh_due_consents

backend/src/usecase/open_banking.py

This function handles silent refresh. It scans active consents, keeps only those due for refresh and configured for automation, and pulls balances plus transactions without operator input.

Method Description
auto_refresh_due_consents Refreshes due consents and returns a list of successful refresh summaries.

Behavioral details

  • Uses repository.list_active_consents().
  • Filters on:
    • auto_refresh_enabled
    • consent.is_due_for_refresh(at=timestamp)
    • consent.ensure_has_token()
  • Uses PlaidKycGateway() when no transactions_gateway is supplied.
  • Writes last_refreshed_at and persists the consent on success.
  • Records an OpenBankingRefreshEvent for both success and failure.
  • Returns only successful refresh summaries.

detect_repatriation_risk

backend/src/usecase/repatriation_risk.py

This function converts home-country transaction behavior into a binary risk signal plus supporting reasons. It examines recent transaction payloads, compares them with the applicant’s declared country, and returns counts, share, and latest activity timing.

Method Description
detect_repatriation_risk Flags recent home-country activity as a repatriation-risk signal.

Public properties

Property Type Description
home_country_code str Normalized country code derived from the applicant’s declared country.
total_transactions int Total transactions evaluated across the supplied payloads.
home_country_transactions int Transactions matching the home-country heuristic.
home_country_share float Share of home-country transactions over total transactions.
flagged bool True when the heuristic emits one or more reasons.
reasons list[str] Human-readable reason strings.
latest_home_country_activity `datetime None`

Heuristic sources

The function uses both of these matching paths, as evidenced by the endpoint tests and the implementation comments:

  • transaction location country
  • account country on transaction records

3. Data Access Layer

SQLAlchemyHousingApplicationRepository

backend/src/interface/http_endpoints.py and backend/src/interface/open_banking_endpoints.py

This repository is used to load housing applications for account coverage checks and repatriation-risk evaluation.

Method Description
get_housing_application Loads a housing application by ID.

SQLOpenBankingConsentRepository

backend/src/interface/open_banking_endpoints.py and backend/src/usecase/open_banking.py

This repository persists consent state, refresh events, and consent token attachments for manual and silent refresh flows.

Method Description
list_by_application_id Returns all consents attached to an application.
get_by_reference Returns a consent by consent_reference.
create Persists a new consent.
save Updates an existing consent.
record_refresh Persists a refresh event.
list_active_consents Returns active consents for silent refresh evaluation.

BankGateway

backend/src/usecase/open_banking.py

This gateway retrieves balances for consented accounts.

Method Description
get_balances Fetches balance payloads for a stored access token.

TransactionsGateway

backend/src/usecase/open_banking.py

This gateway retrieves transaction payloads for consented accounts.

Method Description
fetch_transactions Fetches transactions for a stored access token and date range.

PlaidKycGateway

backend/src/interface/http_endpoints.py and backend/src/usecase/open_banking.py

This gateway is used in two places in this workflow set:

  • account coverage inference to fetch the full account list for an access token
  • silent refresh fallback when a transactions gateway is not explicitly provided
Method Description
get_account_balances Returns the Plaid-detected accounts used for coverage comparison.
fetch_transactions Returns transactions for the requested date range.

Feature Flows

1. Server-Side Account Coverage Analysis

sequenceDiagram
    participant Client as Client
    participant Handler as get_application_account_coverage
    participant Repo as SQLAlchemyHousingApplicationRepository
    participant UseCase as infer_account_coverage
    participant Plaid as PlaidKycGateway

    Client->>Handler: GET account coverage
    Handler->>Repo: get_housing_application
    Repo-->>Handler: HousingApplication
    Handler->>Plaid: create gateway
    Handler->>UseCase: infer_account_coverage
    UseCase->>Plaid: get_account_balances
    Plaid-->>UseCase: detected accounts
    UseCase-->>Handler: AccountCoverageResult
    Handler-->>Client: AccountCoverageResponse

The handler validates the route parameter, loads the application, and delegates the comparison to infer_account_coverage. The response is built from the inferred totals and connection-level details.

sequenceDiagram
    participant Operator as Operator
    participant Handler as manual_refresh
    participant UseCase as trigger_refresh
    participant ConsentRepo as SQLOpenBankingConsentRepository
    participant Bank as BankGateway
    participant Tx as TransactionsGateway

    Operator->>Handler: POST refresh request
    Handler->>UseCase: trigger_refresh
    UseCase->>ConsentRepo: get_by_reference
    UseCase->>UseCase: _ensure_active_consent
    UseCase->>Bank: get_balances
    UseCase->>Tx: fetch_transactions
    UseCase->>ConsentRepo: save
    UseCase->>ConsentRepo: record_refresh
    UseCase-->>Handler: refresh result
    Handler-->>Operator: RefreshResponse

The consent must be active, operator-authorized, and tokenized before the pull runs. If the upstream refresh fails, the handler maps the failure to a 502 response.

3. Silent Refresh for Due Consents

sequenceDiagram
    participant Scheduler as Scheduler
    participant UseCase as auto_refresh_due_consents
    participant ConsentRepo as SQLOpenBankingConsentRepository
    participant Bank as BankGateway
    participant Tx as TransactionsGateway

    Scheduler->>UseCase: run auto refresh
    UseCase->>ConsentRepo: list_active_consents
    loop each due consent
        UseCase->>Bank: get_balances
        UseCase->>Tx: fetch_transactions
        UseCase->>ConsentRepo: save
        UseCase->>ConsentRepo: record_refresh
    end
    UseCase-->>Scheduler: refreshed summaries

This path only processes consent records marked for automation and due for refresh. Consents missing a token are skipped, and the function continues scanning the rest of the active set.

4. Repatriation Risk Workflow

sequenceDiagram
    participant Operator as Operator
    participant Handler as repatriation_risk
    participant AppRepo as SQLAlchemyHousingApplicationRepository
    participant ConsentFlow as refresh_application_consents
    participant Refresh as trigger_refresh
    participant Risk as detect_repatriation_risk

    Operator->>Handler: POST repatriation risk request
    Handler->>AppRepo: get_housing_application
    Handler->>ConsentFlow: refresh_application_consents
    ConsentFlow->>Refresh: trigger_refresh
    Refresh->>Refresh: _ensure_active_consent
    Refresh->>ConsentFlow: per consent refresh result
    Handler->>Risk: detect_repatriation_risk
    Risk-->>Handler: RepatriationRiskResult
    Handler-->>Operator: RepatriationRiskResponse

The endpoint refreshes the application’s accessible consents first, then evaluates only successful refresh payloads. This makes the risk signal depend on current consented data rather than stale stored payloads.

State Management

Coverage Status and Error States

AccountCoverageResult uses a compact status model:

  • unknown when no Plaid entries can be evaluated or no accounts are detected
  • incomplete when any detected account is missing from the submitted set
  • complete when every detected account is present

Per-connection rows use:

  • complete
  • incomplete
  • error

Refresh Execution States

Refresh responses use:

  • succeeded
  • failed

Manual refresh failures are surfaced as exceptions and converted into HTTP errors by the route handler. Silent refresh records failures per consent and keeps processing remaining items.

Repatriation Risk States

RepatriationRiskResponse.flagged is the top-level signal. The supporting state is carried in:

  • home_country_transactions
  • total_transactions
  • home_country_share
  • reasons
  • latest_home_country_activity

API Integration

Get Applicant Account Coverage

backend/src/interface/http_endpoints.py

{
    "title": "Get Applicant Account Coverage",
    "description": "Compares the applicant's submitted connected accounts with the full set of Plaid-detected accounts for the same access tokens and returns completeness details.",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applicants/{application_id}/account-coverage",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "name": "application_id",
            "type": "int",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"application_id\": 123,\n    \"status\": \"incomplete\",\n    \"reported_accounts\": 2,\n    \"detected_accounts\": 3,\n    \"missing_accounts\": 1,\n    \"coverage_ratio\": 0.6667,\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}"
        },
        "400": {
            "description": "Invalid application id",
            "body": "{\n    \"detail\": \"Application id must be a positive integer.\"\n}"
        },
        "404": {
            "description": "Application not found",
            "body": "{\n    \"detail\": \"Application not found.\"\n}"
        }
    }
}

Sync Application Consents

backend/src/interface/open_banking_endpoints.py

{
    "title": "Sync Application Consents",
    "description": "Loads the housing application, materializes Plaid-linked consents from connected accounts, and returns only the consents visible to the current operator.",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/open-banking/applications/{application_id}/consents/sync",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "application_id",
            "type": "int",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"consent_reference\": \"application-123-9f4a1c2d3e5f\",\n        \"customer_reference\": \"[email protected]\",\n        \"customer_name\": \"Jane Doe\",\n        \"scopes\": [\n            \"balances:read\",\n            \"transactions:read\"\n        ],\n        \"expires_at\": \"2026-03-26T12:00:00+00:00\",\n        \"allowed_operator_ids\": [],\n        \"metadata\": {\n            \"application_id\": 123,\n            \"application_email\": \"[email protected]\",\n            \"application_phone\": \"+81 555 000 5678\",\n            \"token_fingerprint\": \"9f4a1c2d3e5f6a7b8c9d0e1f\",\n            \"connection_name\": \"Example Bank\",\n            \"institution_name\": \"Example Bank\",\n            \"account_ids\": [\n                \"acct-1\",\n                \"acct-2\"\n            ]\n        },\n        \"auto_refresh_enabled\": true,\n        \"auto_refresh_interval_minutes\": 720,\n        \"application_id\": 123\n    }\n]"
        },
        "403": {
            "description": "Operator not authorised",
            "body": "{\n    \"detail\": \"You are not authorised to view these consents.\"\n}"
        },
        "404": {
            "description": "Application not found",
            "body": "{\n    \"detail\": \"Application not found\"\n}"
        }
    }
}

List Application Consents

backend/src/interface/open_banking_endpoints.py

{
    "title": "List Application Consents",
    "description": "Returns stored consents for an application after filtering them by operator visibility.",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/open-banking/applications/{application_id}/consents",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "application_id",
            "type": "int",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"consent_reference\": \"application-123-9f4a1c2d3e5f\",\n        \"customer_reference\": \"[email protected]\",\n        \"customer_name\": \"Jane Doe\",\n        \"scopes\": [\n            \"balances:read\",\n            \"transactions:read\"\n        ],\n        \"expires_at\": \"2026-03-26T12:00:00+00:00\",\n        \"allowed_operator_ids\": [],\n        \"metadata\": {\n            \"application_id\": 123,\n            \"application_email\": \"[email protected]\",\n            \"application_phone\": \"+81 555 000 5678\",\n            \"token_fingerprint\": \"9f4a1c2d3e5f6a7b8c9d0e1f\",\n            \"connection_name\": \"Example Bank\",\n            \"institution_name\": \"Example Bank\",\n            \"account_ids\": [\n                \"acct-1\",\n                \"acct-2\"\n            ]\n        },\n        \"auto_refresh_enabled\": true,\n        \"auto_refresh_interval_minutes\": 720,\n        \"application_id\": 123\n    }\n]"
        },
        "403": {
            "description": "Operator not authorised",
            "body": "{\n    \"detail\": \"You are not authorised to view these consents.\"\n}"
        }
    }
}

Manual Refresh

backend/src/interface/open_banking_endpoints.py

{
    "title": "Manual Refresh",
    "description": "Refreshes a single consent reference inside an active consent window and persists the resulting balances and transactions.",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/open-banking/refresh",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"consent_reference\": \"consent-123\",\n    \"lookback_days\": 30\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"consent_reference\": \"consent-123\",\n    \"status\": \"succeeded\",\n    \"refreshed_at\": \"2026-03-26T12:00:00+00:00\",\n    \"balances\": {\n        \"acct-1\": {\n            \"current\": 10250.5,\n            \"available\": 9800.25\n        }\n    },\n    \"transactions\": {\n        \"transactions\": [\n            {\n                \"transaction_id\": \"txn-1\",\n                \"date\": \"2026-03-25\",\n                \"amount\": -1200,\n                \"account_id\": \"acct-1\"\n            }\n        ]\n    },\n    \"error_message\": null\n}"
        },
        "400": {
            "description": "Inactive or missing token",
            "body": "{\n    \"detail\": \"Consent consent-123 is no longer active\"\n}"
        },
        "403": {
            "description": "Operator not authorised",
            "body": "{\n    \"detail\": \"Operator [email protected] is not authorised for application 123\"\n}"
        },
        "404": {
            "description": "Consent not found",
            "body": "{\n    \"detail\": \"Consent not found\"\n}"
        },
        "502": {
            "description": "Refresh failed",
            "body": "{\n    \"detail\": \"Refresh failed\"\n}"
        }
    }
}

Refresh Due Consents

backend/src/interface/open_banking_endpoints.py

{
    "title": "Refresh Due Consents",
    "description": "Runs the silent refresh path for active consents that are due for refresh and have automation enabled.",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/open-banking/refresh/auto",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"lookback_days\": 30\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"consent_reference\": \"consent-123\",\n        \"status\": \"succeeded\",\n        \"refreshed_at\": \"2026-03-26T12:00:00+00:00\"\n    }\n]"
        },
        "400": {
            "description": "Missing token",
            "body": "{\n    \"detail\": \"Consent token is missing\"\n}"
        }
    }
}

Refresh Application Consents

backend/src/interface/open_banking_endpoints.py

{
    "title": "Refresh Application Consents",
    "description": "Refreshes every consent attached to an application that the current operator may access, then returns per-consent refresh results.",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/open-banking/applications/{application_id}/refresh",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "application_id",
            "type": "int",
            "required": true
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"lookback_days\": 30\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"consent_reference\": \"consent-123\",\n        \"status\": \"succeeded\",\n        \"refreshed_at\": \"2026-03-26T12:00:00+00:00\",\n        \"balances\": {\n            \"acct-1\": {\n                \"current\": 10250.5\n            }\n        },\n        \"transactions\": {\n            \"transactions\": [\n                {\n                    \"transaction_id\": \"txn-1\",\n                    \"date\": \"2026-03-25\",\n                    \"amount\": -1200\n                }\n            ]\n        },\n        \"error_message\": null\n    }\n]"
        },
        "403": {
            "description": "Operator not authorised",
            "body": "{\n    \"detail\": \"Operator [email protected] is not authorised for application 123\"\n}"
        },
        "404": {
            "description": "Consent not found",
            "body": "{\n    \"detail\": \"No open banking consents registered for application 123\"\n}"
        },
        "502": {
            "description": "Refresh failed",
            "body": "{\n    \"detail\": \"Refresh failed\"\n}"
        }
    }
}

Repatriation Risk

backend/src/interface/open_banking_endpoints.py

{
    "title": "Assess Repatriation Risk",
    "description": "Refreshes the application's accessible consents, evaluates home-country spending, and returns an underwriting signal with reason strings and activity timing.",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/open-banking/applications/{application_id}/repatriation-risk",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "application_id",
            "type": "int",
            "required": true
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"lookback_days\": 30,\n    \"min_home_country_transactions\": 2,\n    \"min_home_country_share\": 0.2\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"application_id\": 123,\n    \"home_country_code\": \"JP\",\n    \"lookback_days\": 30,\n    \"flagged\": true,\n    \"home_country_transactions\": 2,\n    \"total_transactions\": 3,\n    \"home_country_share\": 0.6667,\n    \"reasons\": [\n        \"Home-country transactions represent 67% of recent activity\",\n        \"2 transactions flowed through home-country accounts\",\n        \"2 transactions occurred in home-country locations\"\n    ],\n    \"refreshed_at\": \"2026-03-26T12:00:00+00:00\",\n    \"latest_home_country_activity\": \"2026-03-25T00:00:00+00:00\"\n}"
        },
        "403": {
            "description": "Operator not authorised",
            "body": "{\n    \"detail\": \"Operator [email protected] is not authorised for application 123\"\n}"
        },
        "404": {
            "description": "Application or consent not found",
            "body": "{\n    \"detail\": \"Application not found\"\n}"
        },
        "502": {
            "description": "Refresh failed",
            "body": "{\n    \"detail\": \"Refresh failed\"\n}"
        }
    }
}

Error Handling

The workflow uses HTTP exceptions at the route layer and domain exceptions in the usecase layer.

Source Exception or condition HTTP result
get_application_account_coverage Invalid application ID 400 Bad Request
get_application_account_coverage No application found 404 Not Found
sync_application_consents No application found 404 Not Found
sync_application_consents / list_application_consents No accessible consents for operator 403 Forbidden
manual_refresh Consent not found 404 Not Found
manual_refresh Consent inactive 400 Bad Request
manual_refresh Operator not authorised 403 Forbidden
manual_refresh Missing token 400 Bad Request
manual_refresh Refresh failure 502 Bad Gateway
auto_refresh Missing token 400 Bad Request
refresh_application Consent not found 404 Not Found
refresh_application Operator not authorised 403 Forbidden
refresh_application Refresh failure 502 Bad Gateway
repatriation_risk Application not found 404 Not Found
repatriation_risk Consent not found 404 Not Found
repatriation_risk Operator not authorised 403 Forbidden
repatriation_risk Refresh failure 502 Bad Gateway

The usecases also preserve partial results where possible:

  • infer_account_coverage adds per-token error rows and continues evaluating the rest.
  • refresh_application_consents converts per-consent refresh failures into result rows.
  • auto_refresh_due_consents records failed attempts and continues scanning remaining consents.

Dependencies

  • SQLAlchemyHousingApplicationRepository
  • SQLOpenBankingConsentRepository
  • BankGateway
  • TransactionsGateway
  • PlaidKycGateway
  • get_current_user_email
  • OpenBankingConsent, OpenBankingRefreshEvent, and associated consent exceptions from the domain layer
  • datetime, timezone, and timedelta for consent window and refresh timing

Testing Considerations

The visible tests cover the most important branches of this workflow:

  • coverage analysis marks a connection incomplete when Plaid detects more accounts than were submitted
  • coverage analysis marks a connection complete when every detected account is reported
  • refresh flows pull balances and transactions for a stored access token
  • repatriation-risk checks can trigger from:
    • location-based home-country transactions
    • account-based home-country transactions
    • combined count and share thresholds

Useful scenario checks:

  • no Plaid-linked records in connected_accounts returns unknown
  • token present but no detected accounts returns unknown
  • one missing account sets status="incomplete"
  • missing token during auto refresh is skipped
  • inactive consent during manual refresh returns 400
  • repatriation-risk response reflects the maximum refreshed_at across successful consent refreshes

Key Classes Reference

Class Location Responsibility
AccountCoverageResult account_detection.py Holds the inferred coverage totals, status, details, and errors.
RepatriationRiskResult repatriation_risk.py Holds the repatriation-risk signal and supporting reason data.
RepatriationRiskResponse open_banking_endpoints.py Pydantic response model returned by the repatriation-risk endpoint.
http_endpoints.py http_endpoints.py Exposes the applicant account coverage route.
open_banking_endpoints.py open_banking_endpoints.py Exposes consent sync, refresh, auto-refresh, and repatriation-risk routes.
account_detection.py account_detection.py Compares reported accounts to Plaid-detected accounts.
open_banking.py open_banking.py Implements consent registration, manual refresh, silent refresh, and application-level refresh orchestration.
repatriation_risk.py repatriation_risk.py Converts home-country activity into an underwriting signal.