Architecture and Repository Orientation
Overview
This backend is organized around a clean-architecture split: backend/src/main.py assembles the FastAPI application, backend/src/interface/*.py owns HTTP transport concerns, backend/src/usecase/*.py holds orchestration and business rules, backend/src/models/*.py and backend/src/services/*.py provide supporting identity and CRUD helpers, and backend/src/infra/* is where persistence and external integrations are wired in.
The important boundary for new engineers is simple: routing, request validation, and response shaping stop in src/interface, while multi-step orchestration starts in src/usecase or in the supporting services under src/services. The interface layer is responsible for turning HTTP inputs into validated parameters, selecting repositories or gateways, and mapping outcomes to HTTP responses; it does not own the business workflow itself.
Architecture Overview
flowchart TB
subgraph CompositionRoot [FastAPI Composition Root]
MainPy[src main py]
Middleware[CORS and region middleware]
Handlers[Validation and auth handlers]
Routers[Router registration]
end
subgraph InterfaceLayer [HTTP Interface Layer]
HttpEndpoints[src interface http_endpoints py]
OpenBankingEndpoints[src interface open_banking_endpoints py]
LitaEndpoints[src interface lita_endpoints py]
SaltEdgeEndpoints[src interface saltedge_endpoints py]
TransUnionEndpoints[src interface transunion_batch_endpoints py]
JapanCreditEndpoints[src interface japan_credit_endpoints py]
end
subgraph BusinessLayer [Business Layer]
HousingApplicationUC[src usecase housing_application py]
OpenBankingUC[src usecase open_banking py]
HousingDetectionUC[src usecase housing_detection py]
TransUnionUC[src usecase transunion_batch py]
ResearchUC[src usecase research py]
SaltEdgeUC[src usecase saltedge_usecase py]
end
subgraph SupportLayer [Support Layer]
CustomerService[src services customer_service py]
ApplicantService[src services applicant_service py]
CustomerHelpers[src models customer py]
ApplicantAlias[src models applicant py]
SessionAlias[src models session py]
end
subgraph InfraLayer [Infrastructure Layer]
MySQL[src infra mysql]
ExternalAPIs[src infra external_apis]
EventStream[application_events stream]
SaltEdgeCache[Salt Edge customer cache]
end
MainPy --> Routers
MainPy --> Middleware
MainPy --> Handlers
Routers --> HttpEndpoints
Routers --> OpenBankingEndpoints
Routers --> LitaEndpoints
Routers --> SaltEdgeEndpoints
Routers --> TransUnionEndpoints
Routers --> JapanCreditEndpoints
HttpEndpoints --> HousingApplicationUC
HttpEndpoints --> HousingDetectionUC
HttpEndpoints --> EventStream
HttpEndpoints --> MySQL
HttpEndpoints --> ExternalAPIs
OpenBankingEndpoints --> OpenBankingUC
OpenBankingEndpoints --> MySQL
OpenBankingEndpoints --> ExternalAPIs
TransUnionEndpoints --> TransUnionUC
ResearchUC --> ExternalAPIs
SaltEdgeUC --> ExternalAPIs
CustomerService --> MySQL
ApplicantService --> MySQL
CustomerHelpers --> MySQL
ApplicantAlias --> MySQL
SessionAlias --> MySQL
Request Flow Through the Composition Root
backend/src/main.py is the composition root. It creates the FastAPI app, installs CORSMiddleware, registers every router family, and adds the request/response middleware that sets X-App-Country and X-App-Locale after the downstream handler completes.
The global exception handlers also live here. Validation errors become 422 JSON responses, and AuthError becomes a 401 response with WWW-Authenticate: Bearer. Database schema bootstrapping is handled centrally through ensure_database_schema(), which imports the SQLAlchemy model metadata and applies the schema helper functions before the app starts serving traffic.
backend/src/main.py
Module-level values:
| Value | Type | Description |
|---|---|---|
app |
FastAPI |
FastAPI application instance and composition root. |
ALLOWED_ORIGINS |
list[str] |
Comma-separated CORS allowlist from ALLOWED_ORIGINS. |
Public callables:
| Callable | Description |
|---|---|
health_check |
Returns the service health payload. |
ensure_database_schema |
Creates SQLAlchemy tables and applies schema helpers for archived, review status, and user role columns. |
validation_exception_handler |
Maps RequestValidationError to a 422 JSON response and logs the error. |
auth_exception_handler |
Maps AuthError to a 401 JSON response and sets the bearer auth challenge header. |
attach_region_headers |
Adds X-App-Country and X-App-Locale to outgoing responses. |
Health Check
{
"title": "Health Check",
"description": "Returns the backend health probe payload",
"method": "GET",
"baseUrl": "<BackendApiBaseUrl>",
"endpoint": "/health",
"headers": [],
"queryParams": [],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Service is healthy",
"body": "{\n \"status\": \"ok\"\n}"
}
}
}
Interface Layer
The interface modules stop at HTTP concerns: path parsing, validation, dependency injection, and response mapping. When the handler needs persistence or external data, it instantiates a repository or gateway and delegates orchestration to a use case.
backend/src/interface/http_endpoints.py
This module is the main housing-application adapter. It handles application submission, listing, single-record reads, archive and delete flows, decision updates, account-coverage calculation, document OCR, and the application event stream.
Public and route-level callables:
| Handler | Description |
|---|---|
create_application |
Validates application input, merges metadata into the connected-accounts payload, persists the application, syncs Plaid consents, provisions credentials, and publishes an application event. |
list_housing_applications_endpoint |
Returns applications as JSON or HTML depending on Accept; also filters by phone and residence permit number. |
stream_housing_application_events |
Exposes the application_events.stream() SSE stream. |
get_application_endpoint |
Loads one housing application and converts it to an API response. |
get_application_score |
Thin wrapper that delegates to get_application_credit_score. |
get_application_payment_history |
Loads Plaid access tokens from open-banking consents and delegates to get_payment_history. |
get_application_account_coverage |
Computes connected-account coverage using PlaidKycGateway. |
decide_application_endpoint |
Updates review status after passing role authorization. |
delete_housing_applications_endpoint |
Deletes every housing application and returns the deleted count. |
archive_application_endpoint |
Archives a single housing application. |
ocr_residence_permit |
Runs Document AI OCR for file upload or file URL input. |
create_phone_application |
Validates phone input and persists a phone application. |
_load_housing_applications |
Shared loader for list routes, with phone and residence-permit filtering. |
_phone_application_to_response |
Converts the phone application entity into the API response shape. |
Create Housing Application
create_application performs more than simple persistence. It normalizes the request fields, rejects missing email or full name, enforces privacy-policy consent, merges metadata into the connected_accounts payload, and then calls submit_housing_application() with the cleaned values.
After the application is persisted, the handler tries to synchronize open-banking consents, provision applicant credentials, and send credentials by email. Those side effects are logged defensively; the request still succeeds if the secondary steps fail. The final response is built through _application_to_response(), and the event payload published to application_events excludes the temporary password.
List Housing Applications
list_housing_applications_endpoint reads the Accept header and serves HTML when the client asks for text/html without explicitly asking for JSON. Otherwise it returns the application list as JSON. It also supports phone and residence_permit_number filtering, with search_housing_applications_by_phone() used when phone is present.
Application Event Stream
Note:
list_housing_applications_endpointonly forwardslimitto_load_housing_applicationswhen the query parameter is present. Whenlimitis omitted, the handler passesNone, so the default value in the signature is not the value used for loading.
stream_housing_application_events returns the shared application event stream directly. The matching write path is create_application, which publishes application_created events after the response object is built.
sequenceDiagram
participant Client as Client
participant API as FastAPI app
participant Create as create_application
participant Repo as SQLAlchemyHousingApplicationRepository
participant OpenBankingRepo as SQLOpenBankingConsentRepository
participant Credentials as applicant credentials
participant Bus as application_events
participant Stream as stream_housing_application_events
Client->>API: POST api v1 applications
API->>Create: validate request and inject db
Create->>Repo: submit_housing_application
Create->>OpenBankingRepo: sync_application_plaid_consents
Create->>Credentials: _provision_applicant_credentials
Create->>Bus: publish application_created
Create-->>API: ApplicationResponse
API-->>Client: 201 response
Client->>API: GET api v1 applications stream
API->>Stream: return application_events.stream
Bus-->>Client: application_created event
Create Housing Application
{
"title": "Create Housing Application",
"description": "Validates and persists a new housing application, then triggers consent sync, credential provisioning, and application event publication",
"method": "POST",
"baseUrl": "<BackendApiBaseUrl>",
"endpoint": "/api/v1/applications",
"headers": [
{
"key": "Content-Type",
"value": "application/json",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "json",
"requestBody": "{\n \"email\": \"[email protected]\",\n \"phone\": \"+1-512-555-0147\",\n \"country\": \"US\",\n \"property_type\": \"condo\",\n \"purchase_intent\": \"primary_residence\",\n \"budget_range\": \"400000-500000\",\n \"savings\": \"85000\",\n \"income\": \"120000\",\n \"income_currency\": \"USD\",\n \"employment_status\": \"full_time\",\n \"financing_consent\": \"yes\",\n \"full_name\": \"Jane Doe\",\n \"agree_policy\": true,\n \"receive_updates\": false,\n \"skipped_connect_accounts\": false,\n \"connected_accounts\": {\n \"plaid\": []\n },\n \"metadata\": {\n \"source\": \"web\"\n },\n \"identifier\": \"applicant-001\"\n}",
"formData": [],
"rawBody": "",
"responses": {
"201": {
"description": "Application created",
"body": "{\n \"id\": 123,\n \"identifier\": \"applicant-001\",\n \"email\": \"[email protected]\",\n \"phone\": \"+1-512-555-0147\",\n \"full_name\": \"Jane Doe\",\n \"country\": \"US\",\n \"property_type\": \"condo\",\n \"purchase_intent\": \"primary_residence\",\n \"budget_range\": \"400000-500000\",\n \"savings\": \"85000\",\n \"income\": \"120000\",\n \"income_currency\": \"USD\",\n \"employment_status\": \"full_time\",\n \"financing_consent\": \"yes\",\n \"agree_policy\": true,\n \"receive_updates\": false,\n \"skipped_connect_accounts\": false,\n \"connected_accounts\": {\n \"plaid\": []\n },\n \"metadata\": {\n \"source\": \"web\"\n },\n \"created_at\": \"2026-04-26T12:00:00Z\",\n \"archived\": false,\n \"review_status\": \"pending\"\n}"
}
}
}
List Housing Applications
{
"title": "List Housing Applications",
"description": "Returns housing applications as JSON or HTML. HTML is served when the client prefers text/html and does not explicitly ask for application/json.",
"method": "GET",
"baseUrl": "<BackendApiBaseUrl>",
"endpoint": "/api/v1/applications",
"headers": [],
"queryParams": [
{
"key": "limit",
"value": "50",
"required": false
},
{
"key": "phone",
"value": "+1-512-555-0147",
"required": false
},
{
"key": "residence_permit_number",
"value": "AB12345678CD",
"required": false
}
],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Application list",
"body": "[\n {\n \"id\": 123,\n \"identifier\": \"applicant-001\",\n \"email\": \"[email protected]\",\n \"phone\": \"+1-512-555-0147\",\n \"full_name\": \"Jane Doe\",\n \"country\": \"US\",\n \"property_type\": \"condo\",\n \"purchase_intent\": \"primary_residence\",\n \"budget_range\": \"400000-500000\",\n \"savings\": \"85000\",\n \"income\": \"120000\",\n \"income_currency\": \"USD\",\n \"employment_status\": \"full_time\",\n \"financing_consent\": \"yes\",\n \"agree_policy\": true,\n \"receive_updates\": false,\n \"skipped_connect_accounts\": false,\n \"connected_accounts\": {\n \"plaid\": []\n },\n \"metadata\": {\n \"source\": \"web\"\n },\n \"created_at\": \"2026-04-26T12:00:00Z\",\n \"archived\": false,\n \"review_status\": \"pending\"\n }\n]"
}
}
}
Application Event Stream
{
"title": "Application Event Stream",
"description": "Returns the shared Server-Sent Events stream used for housing application updates",
"method": "GET",
"baseUrl": "<BackendApiBaseUrl>",
"endpoint": "/api/v1/applications/stream",
"headers": [],
"queryParams": [],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Event stream",
"body": "{\n \"type\": \"application_created\",\n \"application\": {\n \"id\": 123,\n \"email\": \"[email protected]\",\n \"full_name\": \"Jane Doe\",\n \"created_at\": \"2026-04-26T12:00:00Z\"\n }\n}"
}
}
}
Get Housing Application
{
"title": "Get Housing Application",
"description": "Returns one persisted housing application",
"method": "GET",
"baseUrl": "<BackendApiBaseUrl>",
"endpoint": "/api/v1/applications/{application_id}",
"headers": [],
"queryParams": [],
"pathParams": [
{
"key": "application_id",
"value": "123",
"required": true
}
],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Application found",
"body": "{\n \"id\": 123,\n \"identifier\": \"applicant-001\",\n \"email\": \"[email protected]\",\n \"phone\": \"+1-512-555-0147\",\n \"full_name\": \"Jane Doe\",\n \"country\": \"US\",\n \"property_type\": \"condo\",\n \"purchase_intent\": \"primary_residence\",\n \"budget_range\": \"400000-500000\",\n \"savings\": \"85000\",\n \"income\": \"120000\",\n \"income_currency\": \"USD\",\n \"employment_status\": \"full_time\",\n \"financing_consent\": \"yes\",\n \"agree_policy\": true,\n \"receive_updates\": false,\n \"skipped_connect_accounts\": false,\n \"connected_accounts\": {\n \"plaid\": []\n },\n \"metadata\": {\n \"source\": \"web\"\n },\n \"created_at\": \"2026-04-26T12:00:00Z\",\n \"archived\": false,\n \"review_status\": \"pending\"\n}"
}
}
}
Archive Housing Application
{
"title": "Archive Housing Application",
"description": "Archives one housing application after role authorization",
"method": "POST",
"baseUrl": "<BackendApiBaseUrl>",
"endpoint": "/api/v1/applications/{application_id}/archive",
"headers": [
{
"key": "Authorization",
"value": "Bearer <token>",
"required": true
}
],
"queryParams": [],
"pathParams": [
{
"key": "application_id",
"value": "123",
"required": true
}
],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Application archived",
"body": "{\n \"archived\": true\n}"
}
}
}
Delete Housing Applications
{
"title": "Delete Housing Applications",
"description": "Deletes every housing application after role authorization",
"method": "DELETE",
"baseUrl": "<BackendApiBaseUrl>",
"endpoint": "/api/v1/applications",
"headers": [
{
"key": "Authorization",
"value": "Bearer <token>",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Applications deleted",
"body": "{\n \"deleted\": 2\n}"
}
}
}
Update Application Decision
{
"title": "Update Application Decision",
"description": "Lowercases the submitted status, applies the review-status update, and returns the updated application",
"method": "POST",
"baseUrl": "<BackendApiBaseUrl>",
"endpoint": "/api/v1/applications/{application_id}/decision",
"headers": [
{
"key": "Authorization",
"value": "Bearer <token>",
"required": true
},
{
"key": "Content-Type",
"value": "application/json",
"required": true
}
],
"queryParams": [],
"pathParams": [
{
"key": "application_id",
"value": "123",
"required": true
}
],
"bodyType": "json",
"requestBody": "{\n \"status\": \"approved\"\n}",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Decision applied",
"body": "{\n \"id\": 123,\n \"identifier\": \"applicant-001\",\n \"email\": \"[email protected]\",\n \"phone\": \"+1-512-555-0147\",\n \"full_name\": \"Jane Doe\",\n \"country\": \"US\",\n \"property_type\": \"condo\",\n \"purchase_intent\": \"primary_residence\",\n \"budget_range\": \"400000-500000\",\n \"savings\": \"85000\",\n \"income\": \"120000\",\n \"income_currency\": \"USD\",\n \"employment_status\": \"full_time\",\n \"financing_consent\": \"yes\",\n \"agree_policy\": true,\n \"receive_updates\": false,\n \"skipped_connect_accounts\": false,\n \"connected_accounts\": {\n \"plaid\": []\n },\n \"metadata\": {\n \"source\": \"web\"\n },\n \"created_at\": \"2026-04-26T12:00:00Z\",\n \"archived\": false,\n \"review_status\": \"approved\"\n}"
}
}
}
Get Application Account Coverage
{
"title": "Get Application Account Coverage",
"description": "Loads the stored connected_accounts payload and computes account coverage using PlaidKycGateway",
"method": "GET",
"baseUrl": "<BackendApiBaseUrl>",
"endpoint": "/api/v1/applicants/{application_id}/account-coverage",
"headers": [],
"queryParams": [],
"pathParams": [
{
"key": "application_id",
"value": "123",
"required": true
}
],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Coverage result",
"body": "{\n \"application_id\": 123,\n \"status\": \"complete\",\n \"reported_accounts\": 3,\n \"detected_accounts\": 3,\n \"missing_accounts\": 0,\n \"coverage_ratio\": 1,\n \"details\": {\n \"plaid\": {\n \"matched\": 3,\n \"missing\": 0\n }\n },\n \"errors\": []\n}"
}
}
}
Residence Permit OCR
{
"title": "Residence Permit OCR",
"description": "Accepts a file upload or file_url, sends the content to Document AI, and returns extracted residence-permit fields",
"method": "POST",
"baseUrl": "<BackendApiBaseUrl>",
"endpoint": "/api/v1/application/residence-permit/ocr",
"headers": [],
"queryParams": [],
"pathParams": [],
"bodyType": "form-data",
"requestBody": "{\n \"file_url\": \"https://cdn.example.com/residence-permit.pdf\",\n \"file\": \"<binary>\"\n}",
"formData": [
{
"key": "file_url",
"value": "https://cdn.example.com/residence-permit.pdf",
"required": false
},
{
"key": "file",
"value": "<binary>",
"required": false
}
],
"rawBody": "",
"responses": {
"200": {
"description": "OCR result",
"body": "{\n \"residence_permit_number\": \"AB12345678CD\",\n \"residence_card_number\": \"AB12345678CD\",\n \"full_name\": \"TURNER ELIZABETH\",\n \"date_of_birth\": \"1985\\u5e7412\\u670831\\u65e5\",\n \"nationality\": \"\\u7c73\\u56fd\",\n \"address\": \"\\u6771\\u4eac\\u90fd\\u5343\\u4ee3\\u7530\\u533a\",\n \"status_of_residence\": \"\\u7559\\u5b66\",\n \"period_of_stay\": \"4\\u5e743\\u6708\",\n \"expiry_date\": \"2023/07/01\",\n \"extracted_text\": \"full OCR text output\",\n \"pages\": [\n {\n \"page_number\": 1,\n \"languages\": [\n \"ja\"\n ]\n }\n ]\n}"
}
}
}
backend/src/interface/open_banking_endpoints.py
This module wires the open-banking request path to repositories, gateway dependencies, and response DTOs. The visible handler logic normalizes domain errors into HTTP statuses, maps gateway payloads into response models, and uses a TransactionsGateway protocol for transaction fetches.
Public callables and contracts:
| Callable | Description |
|---|---|
get_housing_repository |
Injects SQLAlchemyHousingApplicationRepository from the request database session. |
get_repository |
Injects SQLOpenBankingConsentRepository from the request database session. |
refresh_application |
Refreshes consents with refresh_application_consents and maps each result item into RefreshResponse. |
TransactionsGateway.fetch_transactions |
Fetches transactions for an access token and date range. |
Transactions Gateway
| Method | Description |
|---|---|
fetch_transactions |
Fetches transaction data for an access token, start date, and end date. |
Open Banking Request DTOs
ApplicationRefreshRequest
| Property | Type | Description |
|---|---|---|
lookback_days |
int |
Lookback window for refresh requests, default 90, constrained to 1..365. |
RefreshRequest
| Property | Type | Description |
|---|---|---|
consent_reference |
str |
Consent reference to refresh. |
lookback_days |
int |
Lookback window for the refresh, default 90, constrained to 1..365. |
CreateConsentRequest
| Property | Type | Description |
|---|---|---|
consent_reference |
str |
Consent identifier. |
customer_reference |
str |
Customer identifier. |
customer_name |
Optional[str] |
Optional customer display name. |
scopes |
List[str] |
Requested scopes, defaulting to balances:read and transactions:read. |
expires_at |
datetime |
Consent expiry timestamp. |
allowed_operator_ids |
List[str] |
Operators allowed to act on the consent. |
metadata |
Optional[Dict[str, Any]] |
Arbitrary consent metadata. |
auto_refresh_enabled |
bool |
Enables automatic refresh, default True. |
auto_refresh_interval_minutes |
int |
Refresh cadence in minutes, default 720. |
application_id |
Optional[int] |
Optional housing application link. |
RefreshResponse
| Property | Type | Description |
|---|---|---|
consent_reference |
str |
Consent identifier. |
status |
str |
Refresh status. |
refreshed_at |
datetime |
Refresh timestamp. |
balances |
Dict[str, Any] |
Refreshed balances payload. |
transactions |
Dict[str, Any] |
Refreshed transactions payload. |
error_message |
Optional[str] |
Error text when a refresh fails. |
RepatriationRiskRequest
| Property | Type | Description |
|---|---|---|
lookback_days |
int |
Transaction lookback window, default 90, constrained to 1..365. |
min_home_country_transactions |
int |
Minimum home-country transactions, default 3, constrained to 1..100. |
min_home_country_share |
float |
Minimum home-country share, default 0.2, constrained to 0.0..1.0. |
RepatriationRiskResponse
| Property | Type | Description |
|---|---|---|
application_id |
int |
Housing application identifier. |
home_country_code |
str |
Home-country ISO code. |
lookback_days |
int |
Lookback window used for the calculation. |
flagged |
bool |
Whether the applicant is flagged. |
home_country_transactions |
int |
Count of home-country transactions. |
total_transactions |
int |
Total transactions reviewed. |
home_country_share |
float |
Share of home-country transactions. |
reasons |
List[str] |
Human-readable flagging reasons. |
refreshed_at |
datetime |
Timestamp of the evaluation. |
latest_home_country_activity |
Optional[datetime] |
Most recent home-country transaction timestamp. |
Repatriation Risk
{
"title": "Calculate Repatriation Risk",
"description": "Evaluates home-country transaction concentration for an application using open-banking data",
"method": "POST",
"baseUrl": "<BackendApiBaseUrl>",
"endpoint": "/open-banking/applications/{application_id}/repatriation-risk",
"headers": [
{
"key": "Content-Type",
"value": "application/json",
"required": true
}
],
"queryParams": [],
"pathParams": [
{
"key": "application_id",
"value": "123",
"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": "Risk evaluation",
"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.6666666667,\n \"reasons\": [\n \"Home-country share exceeds threshold\"\n ],\n \"refreshed_at\": \"2026-04-26T12:00:00Z\",\n \"latest_home_country_activity\": \"2026-04-25T08:00:00Z\"\n}"
}
}
}
Refresh Application
refresh_application is the visible orchestration function in this module. It sends the lookback window and gateway dependencies to refresh_application_consents, translates OpenBankingConsentNotFound into 404, OpenBankingConsentNotAuthorised into 403, and OpenBankingRefreshFailed into 502, then normalizes each returned dict into a RefreshResponse object.
backend/src/interface/lita_endpoints.py
This module defines the Lita API DTOs that sit beside the router family under /api/lita/v1. The visible classes describe score requests, score responses, snapshots, and consent payloads.
ScoreRequest
| Property | Type | Description |
|---|---|---|
version |
str |
Scoring protocol version. |
request_id |
str |
Request correlation identifier. |
applicant |
Applicant |
Applicant payload. |
context |
ScoreContext |
Scoring context. |
features |
Dict[str, Any] |
Feature map passed into the model. |
ScoreResponse
| Property | Type | Description |
|---|---|---|
version |
str |
Scoring protocol version. |
request_id |
str |
Request correlation identifier. |
score |
int |
Computed score. |
decision |
str |
Decision string. |
approved_limit |
int |
Approved limit. |
model |
ModelMetadata |
Model metadata. |
reasons |
List[ReasonCode] |
Reason codes. |
SnapshotRequest
| Property | Type | Description |
|---|---|---|
version |
str |
Snapshot version, default 1.1. |
payload |
Dict[str, Any] |
Snapshot payload. |
ConsentRequest
| Property | Type | Description |
|---|---|---|
consent_reference |
str |
Consent identifier. |
customer_reference |
str |
Customer identifier. |
applicant_reference |
Optional[str] |
Optional applicant identifier. |
country |
Optional[str] |
Optional country code. |
product_type |
Optional[str] |
Optional product label. |
data_categories |
List[str] |
Requested data categories. |
refresh_permissions |
List[str] |
Allowed refresh permissions. |
expires_at |
datetime |
Consent expiry time. |
refresh_allowed |
bool |
Whether refresh is allowed. |
ConsentResponse
| Property | Type | Description |
|---|---|---|
consent_reference |
str |
Consent identifier. |
customer_reference |
str |
Customer identifier. |
applicant_reference |
Optional[str] |
Optional applicant identifier. |
country |
Optional[str] |
Optional country code. |
product_type |
Optional[str] |
Optional product label. |
data_categories |
List[str] |
Granted data categories. |
refresh_permissions |
List[str] |
Granted refresh permissions. |
expires_at |
datetime |
Consent expiry time. |
refresh_allowed |
bool |
Whether refresh is allowed. |
revoked_at |
Optional[datetime] |
Revocation timestamp. |
created_at |
Optional[datetime] |
Creation timestamp. |
updated_at |
Optional[datetime] |
Update timestamp. |
backend/src/interface/saltedge_endpoints.py
This module exposes a request-scoped cache for Salt Edge customer data and uses an asyncio.Lock to prevent concurrent refreshes from stampeding the upstream API.
| Value | Type | Description |
|---|---|---|
_customer_cache |
Dict[str, Any] |
Shared cache object with data and expires. |
_customer_cache_lock |
asyncio.Lock |
Serializes cache refreshes. |
CUSTOMER_CACHE_TTL_SECONDS |
int |
Cache lifetime in seconds, set to 60. |
The cache is explicitly described as a way to reduce Salt Edge API calls. The visible contract is one shared payload, one expiry timestamp, and one lock; the source snippet does not show per-key partitioning.
Business Layer
Business logic lives in backend/src/usecase/*.py. These functions and small orchestration types translate repository records into application behavior, apply business rules, and build derived summaries.
backend/src/usecase/housing_application.py
This module exposes the housing-application read use case.
| Callable | Description |
|---|---|
get_housing_application |
Returns one housing application by id from the repository. |
backend/src/usecase/housing_detection.py
This module detects recurring housing payments in transaction sets and mutates matching transactions in place. The detector is threshold-driven and only promotes transactions that satisfy the series rules or a direct keyword match.
Visible constants:
| Constant | Type | Description |
|---|---|---|
MONTH_GAP_LOWER_BOUND |
int |
Lower bound for recurring month gaps, 25. |
MONTH_GAP_UPPER_BOUND |
int |
Upper bound for recurring month gaps, 35. |
MIN_UNIQUE_MONTHS |
int |
Minimum unique months needed for series evaluation, 2. |
MIN_AVERAGE_AMOUNT |
float |
Minimum average amount for a series, 200.0. |
MIN_CURRENCY_RATIO |
float |
Minimum dominant-currency ratio, 0.6. |
DIRECT_MATCH_MIN_AMOUNT |
float |
Minimum amount for direct keyword matches, 150.0. |
HOUSING_KEYWORDS |
tuple[str, ...] |
rent, rental, landlord, lease, lease payment, mortgage, home loan, property mgmt, property management, estate mgmt, estate management, hoa, housing, apartment, tenant pay, tenant, rentals. |
Public callables:
| Callable | Description |
|---|---|
annotate_housing_transactions |
Annotates matching transactions with housing categories and housing_detection metadata. |
annotate_housing_transactions() has two paths:
- recurring series detection, which calculates average amount, coefficient of variation, coverage, month gaps, and dominant currency;
- direct keyword match, which tags a transaction immediately when the descriptor or categories clearly indicate rent or mortgage activity.
The function writes categories and metadata["housing_detection"] in place, so downstream consumers see the enriched transaction objects without needing a second pass.
backend/src/usecase/transunion_batch.py
This module parses TransUnion batch lines, persists them through a repository, and builds a summary from the processed records. The flow is explicitly stateful: ingestion starts at received, moves to processing, and ends at completed.
ProcessTransUnionBatchResult
| Property | Type | Description |
|---|---|---|
ingestion |
TransUnionBatchIngestion |
Persisted ingestion record. |
summary |
Dict[str, object] |
Summary payload built from the processed rows. |
sanitized_rows |
List[Dict[str, object]] |
Redacted row view returned to callers. |
issues |
List[TransUnionBatchRowIssue] |
Parsing or row-level issues. |
Public callables:
| Callable | Description |
|---|---|
process_transunion_batch |
Creates the ingestion, parses rows, stores processed records and issues, then finalizes the summary. |
The summary builder emits dataSource: transunion_batch and totalRows, and it adds credit metrics when VantageScore or TruVision values are present. Sanitized rows preserve creditAsOfDate, sequenceNumber, and metrics while masking permId and consumerId down to the last four alphanumeric characters.
backend/src/usecase/research.py
ResearchService is an Exa-backed service. The constructor reads EXA_API_KEY from the environment and instantiates Exa; if the key is missing, initialization fails immediately with ValueError("EXA_API_KEY not configured").
Public callables:
| Callable | Description |
|---|---|
ResearchService.__init__ |
Validates EXA_API_KEY and initializes the Exa client. |
The helper methods in the class handle formatting, normalization, canonical-key generation, and identity-context assembly. They are private helpers, so the visible public surface is just the constructor and the Exa dependency.
backend/src/usecase/saltedge_usecase.py
This module contains the Salt Edge orchestration helpers used by the interface layer.
Public callables:
| Callable | Description |
|---|---|
get_or_create_saltedge_customer |
Creates a Salt Edge customer for a local identifier and returns the remote customer id when available. |
generate_saltedge_connect_url |
Creates a Salt Edge connect session and returns the connect URL, expiry, and customer id when present. |
get_or_create_saltedge_customer() attempts saltedge_client.create_customer(identifier=user_identifier) and returns customer_id if the call succeeds. If the upstream call fails, the helper prints the error and returns None.
generate_saltedge_connect_url() requests a connect session with the fixed consent scopes accounts, transactions, and holder_info. When Salt Edge returns connect_url, the helper surfaces that URL alongside expires_at and any customer_id value in the response.
backend/src/usecase/open_banking.py
The visible contract in this module is the TransactionsGateway protocol.
| Type | Description |
|---|---|
TransactionsGateway |
Protocol used by open-banking refresh orchestration. |
Public callables:
| Callable | Description |
|---|---|
TransactionsGateway.fetch_transactions |
Fetches transactions for a given access token and date window. |
The interface layer injects this protocol into the refresh path, and the tests provide a stub implementation with the same method name and argument shape.
Supporting Services and Model Helpers
The service layer wraps SQLAlchemy persistence and authentication mechanics. The models package then exposes the shared customer helpers used across tests and services.
backend/src/services/customer_service.py
CustomerService owns customer creation, authentication, API-key rotation, and deactivation.
Constructor dependencies:
| Type | Description |
|---|---|
Session |
SQLAlchemy session used for customer queries and commits. |
Public methods:
| Method | Description |
|---|---|
create_customer |
Creates a new customer and returns the customer id plus plaintext API key. |
authenticate |
Returns the active customer that matches the supplied plaintext API key. |
rotate_api_key |
Generates a new API key, stores its hash, and returns the plaintext key. |
deactivate_customer |
Marks a customer as inactive. |
authenticate() hashes the incoming key, looks up the active customer by api_key_hash, and then verifies the hash with verify_api_key(). This means the method is defensive both at query time and at compare time. The service also uses API_KEY_PREFIX_LENGTH when persisting the visible prefix.
backend/src/services/applicant_service.py
ApplicantService owns applicant reads and writes for a given SQLAlchemy session.
Constructor dependencies:
| Type | Description |
|---|---|
Session |
SQLAlchemy session used for applicant and consent-grant queries. |
Public methods:
| Method | Description |
|---|---|
list_applicants |
Returns all applicants for a customer. |
get_applicant |
Returns one applicant by customer and applicant id. |
create_applicant |
Creates an applicant, optionally validating an active consent grant first. |
create_applicant() validates consent_grant_id by querying ConsentGrantModel for a matching grant that belongs to the same customer, is active, and is not revoked. If the grant is missing or inactive, the method raises ValueError("Consent grant is invalid or inactive").
backend/src/models/customer.py
This module provides the customer API-key helpers and re-exports the SQLAlchemy customer model.
Module-level values and functions:
| Name | Type | Description |
|---|---|---|
API_KEY_PREFIX_LENGTH |
int |
Prefix length stored for visible API-key identification. |
CustomerModel |
model alias | Re-export of the SQLAlchemy customer model. |
generate_api_key |
function | Generates a sk_live_ API key with a 32-character token suffix. |
hash_api_key |
function | SHA-256 hashes an API key. |
verify_api_key |
function | Constant-time comparison against a stored hash. |
Customer Helpers
| Callable | Description |
|---|---|
generate_api_key |
Returns a sk_live_... key using secrets.token_urlsafe(32). |
hash_api_key |
Hashes a plaintext API key with SHA-256. |
verify_api_key |
Compares a plaintext key to a stored hash using secrets.compare_digest. |
backend/src/models/applicant.py
This module is an alias export.
| Name | Type | Description |
|---|---|---|
ApplicantModel |
model alias | Re-export of the SQLAlchemy applicant model. |
backend/src/models/session.py
This module is an alias export.
| Name | Type | Description |
|---|---|---|
CustomerSessionModel |
model alias | Re-export of the SQLAlchemy customer-session model. |
State Management
The backend uses persisted state and evented state rather than in-memory UI state.
| State | Where it lives | Behavior in code |
|---|---|---|
| Application archive state | Housing application records | archive_application_endpoint archives a record, and list flows filter archived entries out. |
| Review status | Housing application records | decide_application_endpoint lowercases the submitted status and persists the review-status update. |
| Event stream state | application_events |
create_application publishes application_created, and stream_housing_application_events exposes the SSE stream. |
| Ingestion lifecycle | TransUnion batch ingestion | process_transunion_batch moves through received, processing, and completed. |
| Consent validity | Consent grant and open-banking consent records | ApplicantService.create_applicant requires an active, non-revoked consent grant when consent_grant_id is provided. |
| Customer auth state | Customer records | CustomerService.authenticate only returns active customers. |
| Salt Edge cache state | _customer_cache |
A single cached payload is shared across requests with a 60-second TTL and a lock. |
Error Handling
The backend centralizes generic request errors in src.main and then uses HTTP exceptions inside handlers for business and integration errors.
| Pattern | Behavior |
|---|---|
| Validation errors | RequestValidationError becomes a 422 JSON response with detail and logged request context. |
| Auth errors | AuthError becomes a 401 JSON response with WWW-Authenticate: Bearer. |
| Missing records | Many handlers raise 404 when a repository lookup returns None. |
| Input errors | Business validation failures become 400, usually from ValueError. |
| External service failures | Document AI failures become 502 or 500 depending on the failure class; open-banking refresh failures map to 502. |
| Best-effort side effects | Credential sync, email delivery, and open-banking consent sync inside create_application are logged on failure but do not abort the response. |
ocr_residence_permit() is the strongest example of layered error translation: it checks request inputs first, then validates the Document AI environment, then guards the import, then maps GoogleAPICallError and RetryError to 502, and finally surfaces unexpected exceptions as 500.
Testing Considerations
The tests mirror the architecture layers: interface tests exercise HTTP handlers with TestClient and dependency overrides, service tests hit the customer API-key helpers, and repository tests verify persistence behavior.
| Test file | Coverage |
|---|---|
backend/tests/test_applicants.py |
Applicant filtering by customer and API-key-based auth behavior on the applicants route. |
backend/tests/test_auth.py |
Customer API-key generation, hashing, authentication, and service behavior. |
backend/tests/interface/test_application_endpoint.py |
Application creation, listing, archive behavior, HTML list rendering, created_at fallback, and archived exclusion from listings. |
backend/tests/interface/test_open_banking_endpoints.py |
Open-banking consent flow and repatriation-risk calculation using stubbed gateways. |
backend/tests/infra/test_housing_application_repository.py |
Repository behavior for housing applications. |
backend/tests/interface/test_auth_endpoints.py |
Register/login/profile round-trip for auth endpoints. |
The tests also show the dependency-injection pattern used throughout the interface layer:
get_dbis overridden with an in-memory session.- gateway dependencies are swapped with stubs such as
StubBankGatewayandStubTransactionsGateway. TestClientis used against the FastAPI app, so the request path exercises routing, validation, and response mapping together.
Key Classes Reference
| Class | Responsibility |
|---|---|
main.py |
FastAPI composition root, middleware, exception handling, schema bootstrap. |
http_endpoints.py |
Housing application HTTP adapter, OCR, archive, delete, and event stream entry points. |
open_banking_endpoints.py |
Open-banking request orchestration and response mapping. |
lita_endpoints.py |
Lita scoring and consent DTO definitions. |
saltedge_endpoints.py |
Salt Edge customer cache and request support. |
housing_application.py |
Housing application read use case. |
housing_detection.py |
Recurring housing payment detector. |
transunion_batch.py |
TransUnion batch ingestion and summarization. |
research.py |
Exa-backed research service bootstrap. |
saltedge_usecase.py |
Salt Edge customer and connect-session helpers. |
customer_service.py |
Customer creation, auth, key rotation, and deactivation. |
applicant_service.py |
Applicant reads and writes with consent-grant validation. |
customer.py |
API-key generation, hashing, and verification helpers. |
applicant.py |
Applicant model alias export. |
session.py |
Customer session model alias export. |