Architecture and Repository Orientation - Clean-architecture backend layering and data flow

Overview

The backend is organized as a clean-architecture stack: backend/src/interface/ owns FastAPI routing and request validation, backend/src/usecase/ contains orchestration and domain-facing logic, backend/src/services/ wraps direct ORM workflows, and backend/src/models/ exposes model helpers and aliases. backend/src/main.py assembles the application by registering middleware, exception handlers, router modules, and schema bootstrap on startup.

For request handling, the interface layer normalizes input, resolves a per-request SQLAlchemy session, and hands control to a use case or repository boundary. Persistence is performed through SQLAlchemy-backed repositories and service-layer Session access, while tests and scripts reuse the same metadata and repository entry points to validate schema behavior, deletion flows, and authentication wiring.

Architecture Overview

flowchart TB
    subgraph Bootstrap[FastAPI Bootstrap]
        MainPy[backend src main.py]
        App[FastAPI app]
        Middleware[CORSMiddleware and attach_region_headers]
        Handlers[Validation auth and region handlers]
        SchemaBoot[ensure_database_schema]
    end

    subgraph InterfaceLayer[Interface Layer]
        HttpEndpoints[http_endpoints router]
        OpenBankingEndpoints[open_banking_endpoints router]
        LitaEndpoints[lita_endpoints router]
    end

    subgraph BusinessLayer[Business Layer]
        HousingUseCase[submit_housing_application]
        AccountDetection[infer_account_coverage]
        OpenBankingUseCase[register_consent]
        CustomerServiceNode[CustomerService]
        ApplicantServiceNode[ApplicantService]
    end

    subgraph DataLayer[Persistence and Infrastructure]
        HousingRepo[SQLAlchemyHousingApplicationRepository]
        ConsentRepo[SQLOpenBankingConsentRepository]
        UserRepo[SQLAlchemyUserRepository]
        DbEngine[engine and Base metadata]
        PlaidGateway[PlaidKycGateway]
    end

    subgraph OpsAndTests[Operations and Tests]
        ClearScript[clear_housing_applications script]
        Fixtures[conftest fixtures]
        RepoTests[test_schema_migrations and repository tests]
    end

    MainPy --> App
    MainPy --> Middleware
    MainPy --> Handlers
    MainPy --> SchemaBoot

    HttpEndpoints --> HousingUseCase
    HttpEndpoints --> AccountDetection
    HttpEndpoints --> HousingRepo
    HttpEndpoints --> ConsentRepo

    OpenBankingEndpoints --> ConsentRepo
    LitaEndpoints --> UserRepo

    HousingUseCase --> HousingRepo
    AccountDetection --> PlaidGateway
    OpenBankingUseCase --> ConsentRepo
    CustomerServiceNode --> UserRepo
    ApplicantServiceNode --> UserRepo
    ApplicantServiceNode --> ConsentRepo

    ClearScript --> HousingRepo
    Fixtures --> DbEngine
    RepoTests --> DbEngine

Repository Orientation

Directory or File Role in the backend
backend/src/main.py FastAPI bootstrap, middleware, router registration, startup schema creation, and global exception handlers
backend/src/interface/ HTTP request handlers, dependency factories, and request or response schemas
backend/src/usecase/ Business orchestration and domain-facing logic that sits between HTTP handlers and persistence or external gateways
backend/src/models/ API key helpers plus model alias modules that re-export ORM models
backend/src/services/ ORM-backed service classes that perform customer and applicant data access directly through a SQLAlchemy session
backend/src/scripts/ Maintenance commands that operate on repositories without going through HTTP
backend/tests/ SQLite-backed test fixtures, repository regression tests, and endpoint tests

FastAPI Bootstrap and Middleware

backend/src/main.py

Functions and application hooks

Function or Hook Responsibility
ensure_database_schema Imports src.infra.mysql.models to register SQLAlchemy metadata, creates tables on engine, and runs the schema helpers ensure_application_archived_column, ensure_application_review_status_column, and ensure_user_role_columns
health_check Returns the health payload {"status": "ok"}
attach_region_headers Resolves country and locale from the request and appends X-App-Country and X-App-Locale to the response if absent
validation_exception_handler Logs RequestValidationError and returns a 422 JSON payload with detail
auth_exception_handler Logs AuthError and returns 401 JSON with detail, error_code, and WWW-Authenticate: Bearer

Application assembly

  • ALLOWED_ORIGINS is loaded from ALLOWED_ORIGINS or defaults to http://localhost:3000.
  • CORSMiddleware is added with credentials enabled and wildcard methods and headers.
  • Routers are included from:
    • src.interface.http_endpoints
    • src.interface.http_credit_report
    • src.interface.auth_endpoints
    • src.interface.saltedge_endpoints
    • src.interface.equifax_endpoints
    • src.interface.transunion_batch_endpoints
    • src.interface.japan_credit_endpoints
    • src.interface.open_banking_endpoints
    • src.interface.lita_endpoints
    • src.interface.test_router
    • src.interface.applicants_endpoints
    • src.interface.billing_endpoints
    • src.interface.credit_upload_endpoints

Request Flow and Persistence Boundaries

Interface to use case boundary

Handler or Helper Boundary behavior
create_application Normalizes request fields, builds a SQLAlchemyHousingApplicationRepository, calls submit_housing_application, syncs Plaid consents, provisions credentials, and publishes application_created
get_application_endpoint Resolves the application through get_housing_application and maps it to a response model with metadata enrichment
archive_application_endpoint Uses archive_housing_application through a repository boundary and converts failures into HTTP errors
decide_application_endpoint Updates review_status through SQLAlchemyHousingApplicationRepository.update_review_status
delete_housing_applications_endpoint Deletes all housing applications through delete_all on the repository
get_application_payment_history Loads the application and consent tokens, then delegates to get_payment_history
get_application_account_coverage Reads the application, instantiates PlaidKycGateway, and delegates to infer_account_coverage
ocr_residence_permit Validates the upload or URL, calls Google Document AI, and maps the extracted document data into a response object

Persistence patterns visible in the code

  • HTTP handlers create repository objects from the request-scoped SQLAlchemy session returned by get_db.
  • open_banking_endpoints.py exposes repository factory helpers for dependency injection.
  • usecase/account_detection.py accepts a gateway object rather than a session, which keeps the Plaid comparison logic separated from persistence concerns.
  • services/customer_service.py and services/applicant_service.py are service-layer wrappers that still operate directly on ORM models through a Session.
  • backend/src/scripts/clear_housing_applications.py bypasses HTTP and uses the same repository pattern for bulk deletion.

Interface Layer and HTTP Endpoints

Interface dependency factories

backend/src/interface/open_banking_endpoints.py

backend/src/interface/lita_endpoints.py

Function Returns Responsibility
get_housing_repository SQLAlchemyHousingApplicationRepository Creates a housing application repository from the injected SQLAlchemy session
get_repository SQLOpenBankingConsentRepository Creates an open banking consent repository from the injected SQLAlchemy session
get_repository LitaRepository Creates the Lita repository from the injected SQLAlchemy session

HTTP handler dependencies

Handler Dependencies visible in code
create_application Depends(get_db)
get_application_endpoint Depends(get_db), Depends(_APPLICATION_DETAIL_USER_DEPENDENCY)
get_application_payment_history Depends(get_db), Depends(_APPLICATION_DETAIL_USER_DEPENDENCY)
get_application_account_coverage Depends(get_db)
archive_application_endpoint Depends(get_db), Depends(get_current_user), _ensure_authorised_role
decide_application_endpoint Depends(get_db), Depends(get_current_user), _ensure_authorised_role
delete_housing_applications_endpoint Depends(get_db), Depends(get_current_user), _ensure_authorised_role
ocr_residence_permit UploadFile or file_url form input

Support functions in the HTTP endpoint module

Function Responsibility
_load_housing_applications Reads housing applications through SQLAlchemyHousingApplicationRepository, optionally filters by phone or residence permit number, and maps records to ApplicationResponse
_load_phone_applications Reads phone applications through SQLAlchemyPhoneApplicationRepository and maps them to PhoneApplicationResponse

Create Housing Application

Create Housing Application

backend/src/interface/http_endpoints.py

This handler validates the applicant payload before it touches persistence. It normalizes the free-text fields, merges metadata and identifier into the connected_accounts payload, persists through SQLAlchemyHousingApplicationRepository, then syncs open banking consents and provisions credentials. If the save succeeds and the application has both id and created_at, it publishes an application_created event with login_credentials.temporary_password excluded.

{
    "title": "Create Housing Application",
    "description": "Creates a housing application, syncs Plaid consents, and provisions applicant credentials",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applications",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        },
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1 555 010 0200\",\n    \"country\": \"US\",\n    \"property_type\": \"Condo\",\n    \"purchase_intent\": \"buy\",\n    \"budget_range\": \"300000-400000\",\n    \"savings\": \"50000\",\n    \"income\": \"98000\",\n    \"income_currency\": \"USD\",\n    \"employment_status\": \"employed\",\n    \"financing_consent\": \"granted\",\n    \"full_name\": \"Jane Doe\",\n    \"agree_policy\": true,\n    \"receive_updates\": true,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": {\n        \"plaid\": [\n            {\n                \"provider\": \"plaid\",\n                \"access_token\": \"access-sample\",\n                \"connection_name\": \"Example Bank\",\n                \"institution_name\": \"Example Bank\",\n                \"account_id\": \"acc-001\"\n            }\n        ]\n    },\n    \"metadata\": {\n        \"source\": \"web\",\n        \"campaign\": \"spring-intake\"\n    },\n    \"identifier\": \"app-123\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Created",
            "body": "{\n    \"id\": 123,\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1 555 010 0200\",\n    \"country\": \"US\",\n    \"property_type\": \"Condo\",\n    \"purchase_intent\": \"buy\",\n    \"budget_range\": \"300000-400000\",\n    \"savings\": \"50000\",\n    \"income\": \"98000\",\n    \"income_currency\": \"USD\",\n    \"employment_status\": \"employed\",\n    \"financing_consent\": \"granted\",\n    \"full_name\": \"Jane Doe\",\n    \"agree_policy\": true,\n    \"receive_updates\": true,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": {\n        \"plaid\": [\n            {\n                \"provider\": \"plaid\",\n                \"access_token\": \"access-sample\",\n                \"connection_name\": \"Example Bank\",\n                \"institution_name\": \"Example Bank\",\n                \"account_id\": \"acc-001\"\n            }\n        ]\n    },\n    \"metadata\": {\n        \"source\": \"web\",\n        \"campaign\": \"spring-intake\"\n    },\n    \"identifier\": \"app-123\",\n    \"review_status\": \"pending\",\n    \"archived\": false,\n    \"created_at\": \"2026-03-31T12:00:00Z\",\n    \"login_credentials\": {\n        \"username\": \"[email protected]\",\n        \"temporary_password\": \"TempPass!234\"\n    }\n}"
        },
        "400": {
            "description": "Validation or business rule failure",
            "body": "{\n    \"detail\": \"Privacy policy consent is required.\"\n}"
        }
    }
}

List Housing Applications

List Housing Applications

backend/src/interface/http_endpoints.py

The list path returns list[ApplicationResponse] and is backed by _load_housing_applications, which can route through phone search or list-all behavior before response mapping. The tests exercise this endpoint through the authenticated FastAPI client fixture.

{
    "title": "List Housing Applications",
    "description": "Lists housing applications using the repository-backed loader",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applications",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"id\": 123,\n        \"email\": \"[email protected]\",\n        \"phone\": \"+1 555 010 0200\",\n        \"country\": \"US\",\n        \"property_type\": \"Condo\",\n        \"purchase_intent\": \"buy\",\n        \"budget_range\": \"300000-400000\",\n        \"savings\": \"50000\",\n        \"income\": \"98000\",\n        \"income_currency\": \"USD\",\n        \"employment_status\": \"employed\",\n        \"financing_consent\": \"granted\",\n        \"full_name\": \"Jane Doe\",\n        \"agree_policy\": true,\n        \"receive_updates\": true,\n        \"skipped_connect_accounts\": false,\n        \"connected_accounts\": [],\n        \"metadata\": {\n            \"source\": \"web\"\n        },\n        \"identifier\": \"app-123\",\n        \"review_status\": \"pending\",\n        \"archived\": false,\n        \"created_at\": \"2026-03-31T12:00:00Z\"\n    }\n]"
        }
    }
}

Get Housing Application

Get Housing Application

backend/src/interface/http_endpoints.py

The handler resolves the application through get_housing_application, then enriches the response from metadata and returns a single ApplicationResponse. It requires the detail-user dependency before the handler body runs.

{
    "title": "Get Housing Application",
    "description": "Fetches one housing application by application id",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applications/{application_id}",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "application_id",
            "type": "integer",
            "required": true,
            "example": 123
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"id\": 123,\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1 555 010 0200\",\n    \"country\": \"US\",\n    \"property_type\": \"Condo\",\n    \"purchase_intent\": \"buy\",\n    \"budget_range\": \"300000-400000\",\n    \"savings\": \"50000\",\n    \"income\": \"98000\",\n    \"income_currency\": \"USD\",\n    \"employment_status\": \"employed\",\n    \"financing_consent\": \"granted\",\n    \"full_name\": \"Jane Doe\",\n    \"agree_policy\": true,\n    \"receive_updates\": true,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": [],\n    \"metadata\": {\n        \"source\": \"web\"\n    },\n    \"identifier\": \"app-123\",\n    \"review_status\": \"pending\",\n    \"archived\": false,\n    \"created_at\": \"2026-03-31T12:00:00Z\"\n}"
        },
        "404": {
            "description": "Application not found",
            "body": "{\n    \"detail\": \"Application not found.\"\n}"
        }
    }
}

Update Application Decision

Update Application Decision

backend/src/interface/http_endpoints.py

This endpoint lowercases payload.status, updates the review status through SQLAlchemyHousingApplicationRepository.update_review_status, and returns the enriched application response. The path is protected by user resolution and role authorization before the repository call runs.

{
    "title": "Update Application Decision",
    "description": "Updates review status for a housing 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
        },
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "application_id",
            "type": "integer",
            "required": true,
            "example": 123
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"status\": \"approved\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Updated",
            "body": "{\n    \"id\": 123,\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1 555 010 0200\",\n    \"country\": \"US\",\n    \"property_type\": \"Condo\",\n    \"purchase_intent\": \"buy\",\n    \"budget_range\": \"300000-400000\",\n    \"savings\": \"50000\",\n    \"income\": \"98000\",\n    \"income_currency\": \"USD\",\n    \"employment_status\": \"employed\",\n    \"financing_consent\": \"granted\",\n    \"full_name\": \"Jane Doe\",\n    \"agree_policy\": true,\n    \"receive_updates\": true,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": [],\n    \"metadata\": {\n        \"source\": \"web\"\n    },\n    \"identifier\": \"app-123\",\n    \"review_status\": \"approved\",\n    \"archived\": false,\n    \"created_at\": \"2026-03-31T12:00:00Z\"\n}"
        },
        "404": {
            "description": "Application not found",
            "body": "{\n    \"detail\": \"Application not found.\"\n}"
        }
    }
}

Archive Housing Application

Archive Housing Application

backend/src/interface/http_endpoints.py

This handler calls archive_housing_application and returns ArchiveApplicationResponse(archived=True) when the repository reports success. The log text and HTTP 500 message still say delete even though the operation is an archive update.

{
    "title": "Archive Housing Application",
    "description": "Marks a housing application as archived",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applications/{application_id}/archive",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "application_id",
            "type": "integer",
            "required": true,
            "example": 123
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Archived",
            "body": "{\n    \"archived\": true\n}"
        },
        "404": {
            "description": "Application not found",
            "body": "{\n    \"detail\": \"Application not found.\"\n}"
        }
    }
}

Delete Housing Applications

Delete Housing Applications

[!NOTE] archive_application_endpoint archives the row through archive_housing_application, but its unexpected-error log and 500 response text still say "delete". That mismatch affects observability and client-facing error wording, while the database state change remains an archive.

backend/src/interface/http_endpoints.py

This endpoint deletes all housing applications through the repository and returns the count in DeleteApplicationsResponse. It is guarded by user resolution and role authorization before calling delete_all_housing_applications.

{
    "title": "Delete Housing Applications",
    "description": "Deletes all housing applications from persistence",
    "method": "DELETE",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applications",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Deleted",
            "body": "{\n    \"deleted\": 3\n}"
        }
    }
}

Get Application Account Coverage

Get Application Account Coverage

backend/src/interface/http_endpoints.py

The handler reads the application, instantiates PlaidKycGateway, and passes the stored connected_accounts into infer_account_coverage. The result is a deterministic comparison of reported account ids versus the ids returned by Plaid.

{
    "title": "Get Application Account Coverage",
    "description": "Compares submitted connected accounts with Plaid detected accounts",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applicants/{application_id}/account-coverage",
    "headers": [
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "application_id",
            "type": "integer",
            "required": true,
            "example": 123
        }
    ],
    "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.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}"
        },
        "404": {
            "description": "Application not found",
            "body": "{\n    \"detail\": \"Application not found.\"\n}"
        }
    }
}

Get Application Payment History

Get Application Payment History

backend/src/interface/http_endpoints.py

The handler loads the application, queries consent records through SQLOpenBankingConsentRepository.list_by_application_id, extracts Plaid access tokens, and wraps them in PaymentHistoryRequest before calling get_payment_history. It does not transform the downstream result, so the response is the dictionary returned by that use case.

{
    "title": "Get Application Payment History",
    "description": "Returns payment history for the application's linked Plaid access tokens",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applications/{application_id}/payment-history",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [
        {
            "name": "start_date",
            "type": "string",
            "required": false,
            "example": "2025-01-01"
        },
        {
            "name": "end_date",
            "type": "string",
            "required": false,
            "example": "2025-03-31"
        }
    ],
    "pathParams": [
        {
            "name": "application_id",
            "type": "integer",
            "required": true,
            "example": 123
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"application_id\": 123,\n    \"start_date\": \"2025-01-01\",\n    \"end_date\": \"2025-03-31\",\n    \"transactions\": [\n        {\n            \"amount\": 1450.25,\n            \"date\": \"2025-03-01\",\n            \"currency_code\": \"USD\",\n            \"status\": \"posted\",\n            \"account_name\": \"Checking\",\n            \"connection_name\": \"Example Bank\",\n            \"description\": \"Rent payment\",\n            \"categories\": [\n                \"housing\",\n                \"rent\"\n            ],\n            \"provider\": \"plaid\",\n            \"metadata\": {\n                \"access_token\": \"access-sample\"\n            }\n        }\n    ]\n}"
        },
        "404": {
            "description": "Application not found or no history available",
            "body": "{\n    \"detail\": \"No transaction history is available for this applicant yet. Connect and sync bank accounts first.\"\n}"
        }
    }
}

Process Residence Permit OCR

Process Residence Permit OCR

backend/src/interface/http_endpoints.py

This endpoint validates environment variables, rejects unsupported MIME types, accepts either an uploaded file or file_url, and then sends the document to Google Document AI. It extracts page languages and residence-permit fields from the returned document before packaging the OCR result.

{
    "title": "Process Residence Permit OCR",
    "description": "Extracts residence permit fields from an uploaded file or a file URL",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/application/residence-permit/ocr",
    "headers": [
        {
            "key": "Content-Type",
            "value": "multipart/form-data",
            "required": true
        },
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "form-data",
    "requestBody": "{\n    \"file_url\": \"https://example.com/residence-permit.pdf\"\n}",
    "formData": [
        {
            "key": "file",
            "type": "file",
            "required": false,
            "value": "residence_permit.pdf"
        },
        {
            "key": "file_url",
            "type": "text",
            "required": false,
            "value": "https://example.com/residence-permit.pdf"
        }
    ],
    "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-12-31\",\n    \"nationality\": \"US\",\n    \"address\": \"Tokyo, Japan\",\n    \"status_of_residence\": \"Student\",\n    \"period_of_stay\": \"4 years 3 months\",\n    \"expiry_date\": \"2027-07-01\",\n    \"extracted_text\": \"Full OCR text output\",\n    \"pages\": [\n        {\n            \"page_number\": 1,\n            \"languages\": [\n                \"en\",\n                \"ja\"\n            ]\n        }\n    ]\n}"
        },
        "400": {
            "description": "Input validation failure",
            "body": "{\n    \"detail\": \"Either file or file_url is required.\"\n}"
        },
        "502": {
            "description": "Document AI failure",
            "body": "{\n    \"detail\": \"Document AI error: <provider error>\"\n}"
        }
    }
}

Health Check

Health Check

backend/src/main.py

The health endpoint returns a simple status payload and is not wrapped in any request-specific repository or use case flow.

{
    "title": "Health Check",
    "description": "Returns a simple service health status",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/health",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Healthy",
            "body": "{\n    \"status\": \"ok\"\n}"
        }
    }
}

Business Layer

Account Coverage Inference

backend/src/usecase/account_detection.py

infer_account_coverage is the main business function behind the account coverage endpoint. It gathers Plaid records from connected_accounts, groups them by access token, fetches account balances from the injected gateway, and builds both aggregate totals and per-connection detail rows.

The computed coverage_ratio is reported_total / detected_total when detected accounts exist. The function returns status="unknown" when no Plaid entries are available, status="incomplete" when any detected account is missing from the submitted list, and status="complete" only when every detected account is represented.

Public symbols

Symbol Type Responsibility
AccountCoverageResult dataclass Holds the aggregate coverage result returned to the HTTP layer
infer_account_coverage function Performs the account coverage comparison and result assembly
_collect_plaid_entries function Groups Plaid-connected account records by access token
_iter_connected_account_records function Iterates over list or mapping shaped connected_accounts input
_normalise_string function Trims a string value and returns None for blank input

Account Coverage Result

Property Type Description
status str Coverage status returned to the HTTP layer
reported_accounts int Count of account ids submitted by the applicant
detected_accounts int Count of account ids returned by the gateway
missing_accounts int Count of detected account ids not found in the submission
coverage_ratio Optional[float] Ratio of reported accounts to detected accounts
details list[dict[str, Any]] Per-connection coverage rows
errors list[str] Gateway errors collected while evaluating connections

backend/src/usecase/open_banking.py

register_consent constructs an OpenBankingConsent with deduplicated scopes and allowed_operator_ids, then persists it through the injected repository. The defaults in the signature enable auto-refresh and set the refresh interval to 720 minutes.

Public interface

Symbol Type Responsibility
TransactionsGateway Protocol Abstracts transaction fetches for open banking transaction workflows
register_consent function Builds and stores an OpenBankingConsent record

Transactions Gateway

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

Customer Service

backend/src/services/customer_service.py

CustomerService is a service-layer wrapper around customer CRUD and authentication. It uses the SQLAlchemy session directly and relies on the API-key helpers from src.models.customer.

Constructor dependencies

Type Description
Session SQLAlchemy session used for ORM reads, writes, and commits

Properties

Property Type Description
db Session Injected SQLAlchemy session used by the service methods

Public methods

Method Description
create_customer Generates an API key, stores the hashed form, and returns the new customer id plus plaintext key
authenticate Looks up an active customer by API key and verifies the hash
rotate_api_key Replaces the stored key material for a customer and returns the new plaintext key
deactivate_customer Performs a soft delete by deactivating the customer

Applicant Service

backend/src/services/applicant_service.py

ApplicantService provides direct ORM access for applicant records. It enforces consent-grant validity before creating an applicant, so the service fails early if the linked grant is not active or has been revoked.

Constructor dependencies

Type Description
Session SQLAlchemy session used for ORM reads, writes, refreshes, and commits

Properties

Property Type Description
db Session Injected SQLAlchemy session used by the service methods

Public methods

Method Description
list_applicants Returns all applicants linked to a customer
get_applicant Returns one applicant for a customer when the applicant id matches
create_applicant Validates the optional consent grant, inserts a new applicant, and refreshes the record

Housing Application Use Case Boundary

backend/src/usecase/housing_application.py

This module is the housing-application boundary used by the HTTP handlers for read and write flows. The provided snippet shows the domain and repository imports that the interface layer relies on when loading or persisting application records.

Model Helpers and Alias Modules

Customer Model Helpers

backend/src/models/customer.py

This module exports API-key helpers alongside the customer ORM alias. The helpers are used by CustomerService and by auth-related tests.

Exported symbols

Symbol Type Responsibility
API_KEY_PREFIX_LENGTH int Length used when storing the non-secret prefix of an API key
generate_api_key function Generates a secure key with the sk_live_ prefix
hash_api_key function Hashes an API key with SHA-256
verify_api_key function Compares a plaintext API key against a stored hash using constant-time comparison
CustomerModel re-export ORM model alias imported from src.infra.mysql.models

Applicant and Session Alias Modules

backend/src/models/applicant.py

backend/src/models/session.py

File Export
applicant.py Re-exports ApplicantModel
session.py Re-exports CustomerSessionModel

These modules exist as repository-facing aliases so callers can import the ORM models from the src.models namespace without reaching into the infrastructure package directly.

Persistence and Maintenance Scripts

Clear Housing Applications

backend/src/scripts/clear_housing_applications.py

main parses command-line arguments, optionally asks for confirmation, opens a SQLAlchemy session, creates SQLAlchemyHousingApplicationRepository, calls delete_all, and then closes the session. The script is a direct maintenance path for bulk deletion without going through HTTP.

Public methods

Method Description
main Runs the delete-all maintenance command and returns the exit code

Testing and Repository Validation

Test Fixtures and Client Setup

backend/tests/conftest.py

Fixture or Helper Responsibility
test_db Creates all tables on the test engine and drops them after the session finishes
client Overrides get_db, registers an admin account through the auth endpoints, fetches a bearer token, and yields an authenticated TestClient
_create_session Builds a SQLAlchemy session bound to an in-memory SQLite engine
test_db setup Uses the same metadata path exercised by production startup, but against SQLite

The client fixture updates app.dependency_overrides[get_db], registers [email protected], authenticates via /api/auth/token, and injects the resulting bearer token into the test client headers.

Auth Test Double

backend/tests/test_auth.py

MockUserRepository

Property Type Description
users dict In-memory storage for test users keyed by email

Public methods

Method Description
create_user Assigns an id, stamps created_at, stores the user, and returns it
get_user_by_email Returns a user by email from the in-memory store
get_user_by_username Returns a user by username from the in-memory store

Repository Regression Coverage

backend/tests/infra/test_housing_application_repository.py

backend/tests/test_schema_migrations.py

backend/tests/interface/test_application_endpoint.py

Test file What it validates
test_housing_application_repository.py delete_all removes every application and returns the expected count
test_schema_migrations.py SQLAlchemyHousingApplicationRepository.list_recent() triggers archived-column schema repair on a legacy SQLite table
test_application_endpoint.py Archiving an application removes it from subsequent listing responses

Error Handling

The backend uses layered error conversion rather than a single generic catch-all.

  • main.py converts RequestValidationError into a 422 JSON response and logs the invalid request path and errors.
  • main.py converts AuthError into a 401 JSON response with WWW-Authenticate: Bearer.
  • HTTP handlers translate repository and validation issues into 400, 404, 500, or 502 responses depending on the boundary that failed.
  • create_application turns ValueError from the use case into 400 and logs defensive sync or provisioning failures without aborting the request.
  • ocr_residence_permit maps Google API exceptions to 502 and general processing failures to 500.
  • archive_application_endpoint logs unexpected failures and returns 500, but the log and response text still refer to delete even though the code archives the row.
  • CustomerService.authenticate returns None when the API key is missing, inactive, or fails verification, and emits a warning when the stored hash does not match.

Dependencies

  • FastAPI request and middleware stack in backend/src/main.py
  • SQLAlchemy sessions and metadata from src.infra.mysql.database
  • SQLAlchemy repositories:
    • SQLAlchemyHousingApplicationRepository
    • SQLOpenBankingConsentRepository
    • SQLAlchemyPhoneApplicationRepository
    • LitaRepository
  • External gateways and services:
    • PlaidKycGateway
    • PlaidBankGateway
    • BankGateway
    • Google Document AI through google.cloud.documentai
    • google.api_core exception and client option classes
  • Auth and request user resolution through get_current_user, get_current_user_email, and _APPLICATION_DETAIL_USER_DEPENDENCY
  • Logging through the standard library logging module
  • Test infrastructure:
    • pytest
    • TestClient
    • SQLite engines with StaticPool and in-memory sessions

Key Classes Reference

Class Responsibility
main.py Boots the FastAPI app, registers middleware, routes, and startup schema creation
http_endpoints.py Implements housing application intake, review, archive, coverage, payment history, OCR, and deletion handlers
open_banking.py Defines the consent registration use case and transaction gateway protocol
account_detection.py Computes account coverage results from submitted accounts and gateway data
CustomerService Handles customer API key lifecycle and authentication
ApplicantService Handles applicant CRUD and consent-grant validation
customer.py Exposes API-key helpers and the customer model alias
applicant.py Re-exports ApplicantModel
session.py Re-exports CustomerSessionModel
clear_housing_applications.py Provides a direct-delete maintenance command
conftest.py Supplies SQLite-backed test fixtures and authenticated API clients
test_schema_migrations.py Verifies archived-column schema repair behavior
test_housing_application_repository.py Verifies repository bulk-delete behavior