Application Management Domain

Overview

This domain covers the housing application and phone application flows that feed Lita’s backend persistence layer. The housing application path normalizes request payloads, creates a HousingApplication domain object, persists it, and then enriches the saved record with consent syncing, applicant credentials, and metadata extraction before returning an API response.

The phone application path is smaller and focused on creating and listing lightweight phone-only records. Alongside the HTTP handlers, this section also includes two operational scripts: one for seeding a test application through the public API and one for clearing all housing applications directly from the database.

Architecture Overview

flowchart TB
    subgraph HttpInterface[HTTP Interface]
        AppEndpoints[Housing and Phone Application Endpoints]
        AppSchemas[Request and Response Schemas]
        EventStream[Application Events Stream]
    end

    subgraph UseCaseLayer[Use Case Layer]
        HousingUseCases[Housing Application Use Cases]
        PhoneUseCases[Phone Application Use Cases]
    end

    subgraph PersistenceLayer[Persistence Layer]
        HousingRepo[SQLAlchemy Housing Application Repository]
        PhoneRepo[SQLAlchemy Phone Application Repository]
        OpenBankingRepo[SQL Open Banking Consent Repository]
        SessionLocalDb[SQLAlchemy SessionLocal]
        MySqlDb[(MySQL Database)]
    end

    subgraph Operations[Operational Scripts]
        SeedScript[create_test_application.py]
        ClearScript[clear_housing_applications.py]
    end

    AppEndpoints --> AppSchemas
    AppEndpoints --> HousingUseCases
    AppEndpoints --> PhoneUseCases
    HousingUseCases --> HousingRepo
    PhoneUseCases --> PhoneRepo
    HousingRepo --> MySqlDb
    PhoneRepo --> MySqlDb
    OpenBankingRepo --> MySqlDb
    ClearScript --> SessionLocalDb
    SessionLocalDb --> MySqlDb
    SeedScript --> AppEndpoints
    AppEndpoints --> EventStream

Domain Schemas

Application Create Request

backend/src/interface/schemas.py

Property Type Description
email str Applicant email address.
phone str Applicant phone number.
country str Applicant country.
property_type str Target property type.
purchase_intent str Intended purchase or rental intent.
budget_range str Budget range supplied by the applicant.
savings str Applicant savings value.
income str Applicant income value.
income_currency str Currency code for income.
employment_status str Employment status string.
financing_consent str Financing consent value.
full_name str Applicant full name.
agree_policy bool Privacy policy consent flag.
receive_updates bool Marketing or progress update opt-in.
skipped_connect_accounts bool Indicates whether account connection was skipped.
connected_accounts Dict[str, Any] Connected account payload stored with the application.
metadata Optional[Dict[str, Any]] Extra metadata attached to the application request.
identifier Optional[str] Optional external identifier attached to the request.

Application Response

backend/src/interface/schemas.py

ApplicationResponse inherits all fields from ApplicationCreateRequest and adds persistence and review fields.

Property Type Description
email str Applicant email address.
phone str Applicant phone number.
country str Applicant country.
property_type str Target property type.
purchase_intent str Intended purchase or rental intent.
budget_range str Budget range supplied by the applicant.
savings str Applicant savings value.
income str Applicant income value.
income_currency str Currency code for income.
employment_status str Employment status string.
financing_consent str Financing consent value.
full_name str Applicant full name.
agree_policy bool Privacy policy consent flag.
receive_updates bool Marketing or progress update opt-in.
skipped_connect_accounts bool Indicates whether account connection was skipped.
connected_accounts Dict[str, Any] Connected account payload returned with the application.
metadata Optional[Dict[str, Any]] Enrichment metadata returned in the API response.
identifier Optional[str] External identifier returned in the API response.
id int Persistent application identifier.
created_at datetime Creation timestamp.
archived bool Archive flag returned by persistence.
review_status str Review state stored on the application.
login_credentials Optional[UserCredentialsResponse] Provisioned applicant credentials when available.
credit_score Optional[int] Credit score attached to the response when available.

Application Decision Request

backend/src/interface/schemas.py

Property Type Description
status Literal["approved", "denied", "pending"] Review status written back to the application.

Phone Application Create Request

backend/src/interface/schemas.py

Property Type Description
phone str Applicant phone number.
connected_accounts Dict[str, Any] Optional connected account payload for the phone application.

Phone Application Response

backend/src/interface/schemas.py

Property Type Description
id int Persistent phone application identifier.
phone str Stored phone number.
connected_accounts Dict[str, Any] Stored connected account payload.
created_at datetime Creation timestamp.

Use Case Layer

housing_application.py

backend/src/usecase/housing_application.py

The housing use case layer is the mediation point between request payloads and persistence. It converts raw fields into a HousingApplication domain object, enforces positive application IDs where required, and delegates storage operations to HousingApplicationRepository.

Repository dependency

Type Description
HousingApplicationRepository Persistence contract for creating, retrieving, listing, archiving, searching, and deleting housing applications.
Method Description
submit_housing_application Builds a HousingApplication with id=None, created_at=None, archived=False, and review_status="pending", then persists it through repository.create.
search_housing_applications_by_phone Returns housing applications whose phone number matches the supplied query, with an optional limit.
get_housing_application Loads a housing application by ID after validating that the ID is positive.
list_housing_applications Returns recent housing applications in newest-first order, with an optional limit.
archive_housing_application Validates the ID and delegates to repository.archive.
delete_all_housing_applications Deletes every housing application through repository.delete_all and returns the removed row count.

phone_application.py

[!NOTE] submit_housing_application sets review_status to "pending" and archived to False before persistence. The review state is later changed by the decision endpoint, while cleanup uses the separate delete-all path.

backend/src/usecase/phone_application.py

The phone use case layer follows the same pattern as the housing flow, but with a smaller domain object. It creates a PhoneApplication from the request values and delegates persistence and listing to the repository abstraction.

Repository dependency

Type Description
PhoneApplicationRepository Persistence contract for creating and listing phone applications.
Method Description
submit_phone_application Builds a PhoneApplication with id=None and persists it through repository.create.
list_phone_applications Returns recent phone applications in newest-first order, with an optional limit.

HTTP Interface and Event Streaming

HTTP Interface Helpers

backend/src/interface/http_endpoints.py

Function Description
_load_housing_applications Chooses search or listing based on phone, applies residence_permit_number filtering, resolves enrichment metadata, and maps each record to ApplicationResponse.
_phone_application_to_response Converts a persisted phone application into PhoneApplicationResponse and rejects records missing id or created_at.
_load_phone_applications Loads recent phone applications and maps each one to PhoneApplicationResponse.

Application Events Stream

backend/src/interface/http_endpoints.py

The housing application create path publishes an application_created event after the record is saved. The SSE endpoint exposes the same event stream through application_events.stream().

Producer Consumer Payload
create_application application_events.publish {"type": "application_created", "application": {...}}
stream_housing_application_events application_events.stream Server-sent events stream

Create Housing Application

Create Housing Application

{
    "title": "Create Housing Application",
    "description": "Creates a housing application, syncs open banking consent, provisions applicant credentials, and publishes an application_created event",
    "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 555 123 4567\",\n    \"country\": \"Japan\",\n    \"property_type\": \"Condo\",\n    \"purchase_intent\": \"buy\",\n    \"budget_range\": \"\\u00a5100\\u2013200M\",\n    \"savings\": \"\\u00a510M\",\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        \"personal\": [\n            {\n                \"id\": \"acc_1\",\n                \"name\": \"Primary checking\"\n            }\n        ]\n    },\n    \"metadata\": {\n        \"source\": \"manual_seed\",\n        \"residence_permit_number\": \"AB12345678CD\"\n    },\n    \"identifier\": \"cust-123\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Created",
            "body": "{\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1 555 123 4567\",\n    \"country\": \"Japan\",\n    \"property_type\": \"Condo\",\n    \"purchase_intent\": \"buy\",\n    \"budget_range\": \"\\u00a5100\\u2013200M\",\n    \"savings\": \"\\u00a510M\",\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        \"personal\": [\n            {\n                \"id\": \"acc_1\",\n                \"name\": \"Primary checking\"\n            },\n            {\n                \"metadata\": {\n                    \"source\": \"manual_seed\",\n                    \"residence_permit_number\": \"AB12345678CD\"\n                }\n            }\n        ]\n    },\n    \"metadata\": {\n        \"source\": \"manual_seed\",\n        \"residence_permit_number\": \"AB12345678CD\"\n    },\n    \"identifier\": \"cust-123\",\n    \"id\": 101,\n    \"created_at\": \"2026-04-26T10:15:00Z\",\n    \"archived\": false,\n    \"review_status\": \"pending\",\n    \"login_credentials\": null,\n    \"credit_score\": 742\n}"
        }
    }
}

The endpoint validates email, full_name, and agree_policy before calling submit_housing_application. It then attempts to sync Plaid consents and provision credentials after the record is created.

List Housing Applications

List Housing Applications

{
    "title": "List Housing Applications",
    "description": "Returns housing applications ordered from newest to oldest, with optional phone search and residence permit filtering",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applications",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "limit",
            "value": "50",
            "required": false
        },
        {
            "key": "phone",
            "value": "+1 555 123 4567",
            "required": false
        },
        {
            "key": "residence_permit_number",
            "value": "AB12345678CD",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"email\": \"[email protected]\",\n        \"phone\": \"+1 555 123 4567\",\n        \"country\": \"Japan\",\n        \"property_type\": \"Condo\",\n        \"purchase_intent\": \"buy\",\n        \"budget_range\": \"\\u00a5100\\u2013200M\",\n        \"savings\": \"\\u00a510M\",\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            \"personal\": [\n                {\n                    \"id\": \"acc_1\",\n                    \"name\": \"Primary checking\"\n                }\n            ]\n        },\n        \"metadata\": {\n            \"source\": \"manual_seed\",\n            \"residence_permit_number\": \"AB12345678CD\"\n        },\n        \"identifier\": \"cust-123\",\n        \"id\": 101,\n        \"created_at\": \"2026-04-26T10:15:00Z\",\n        \"archived\": false,\n        \"review_status\": \"pending\",\n        \"login_credentials\": null,\n        \"credit_score\": 742\n    }\n]"
        }
    }
}

[!NOTE] The housing application is persisted before consent syncing and credential provisioning. Failures in those follow-up steps are logged and do not roll back the create call, so the endpoint can still return a created application.

The handler chooses search_housing_applications_by_phone when phone is present and otherwise calls list_housing_applications. It then filters the loaded results by normalized residence permit number extracted from embedded metadata.

[!NOTE] The route declares a limit default, but the handler only forwards a limit when the query string explicitly contains limit. If the client omits the parameter, the code passes None to the use case and returns the full result set.

The endpoint also changes response shape based on the Accept header: it returns HTML when the client prefers text/html and JSON otherwise.

Stream Housing Application Events

Stream Housing Application Events

{
    "title": "Stream Housing Application Events",
    "description": "Returns the housing application event stream as server-sent events",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applications/stream",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Server-Sent Events stream",
            "body": "{\n    \"type\": \"application_created\",\n    \"application\": {\n        \"email\": \"[email protected]\",\n        \"phone\": \"+1 555 123 4567\",\n        \"country\": \"Japan\",\n        \"property_type\": \"Condo\",\n        \"purchase_intent\": \"buy\",\n        \"budget_range\": \"\\u00a5100\\u2013200M\",\n        \"savings\": \"\\u00a510M\",\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            \"personal\": [\n                {\n                    \"id\": \"acc_1\",\n                    \"name\": \"Primary checking\"\n                }\n            ]\n        },\n        \"metadata\": {\n            \"source\": \"manual_seed\",\n            \"residence_permit_number\": \"AB12345678CD\"\n        },\n        \"identifier\": \"cust-123\",\n        \"id\": 101,\n        \"created_at\": \"2026-04-26T10:15:00Z\",\n        \"archived\": false,\n        \"review_status\": \"pending\",\n        \"login_credentials\": null,\n        \"credit_score\": 742\n    }\n}"
        }
    }
}

This endpoint returns application_events.stream() directly and is used for live housing application updates.

Delete Housing Applications

Delete Housing Applications

{
    "title": "Delete Housing Applications",
    "description": "Deletes every housing application after authorizing the current user role",
    "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": "Success",
            "body": "{\n    \"deleted\": 2\n}"
        }
    }
}

The handler calls _ensure_authorised_role(current_user, _DECISION_ROLES) before it reaches the repository. It then invokes delete_all_housing_applications and returns the removed row count.

Archive Housing Application

Archive Housing Application

{
    "title": "Archive Housing Application",
    "description": "Archives a housing application by ID after authorizing the current user role",
    "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": "101",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"archived\": true\n}"
        }
    }
}

archive_application_endpoint validates the path parameter, authorizes the current user role, delegates to archive_housing_application, and returns 404 when the repository reports no affected record.

Decide Application

Decide Application

{
    "title": "Decide Application",
    "description": "Updates the housing application review status after role authorization",
    "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": "101",
            "required": true
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"status\": \"approved\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1 555 123 4567\",\n    \"country\": \"Japan\",\n    \"property_type\": \"Condo\",\n    \"purchase_intent\": \"buy\",\n    \"budget_range\": \"\\u00a5100\\u2013200M\",\n    \"savings\": \"\\u00a510M\",\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        \"personal\": [\n            {\n                \"id\": \"acc_1\",\n                \"name\": \"Primary checking\"\n            }\n        ]\n    },\n    \"metadata\": {\n        \"source\": \"manual_seed\",\n        \"residence_permit_number\": \"AB12345678CD\"\n    },\n    \"identifier\": \"cust-123\",\n    \"id\": 101,\n    \"created_at\": \"2026-04-26T10:15:00Z\",\n    \"archived\": false,\n    \"review_status\": \"approved\",\n    \"login_credentials\": null,\n    \"credit_score\": 742\n}"
        }
    }
}

The request schema only permits approved, denied, or pending. The handler lowercases the value and writes it through repository.update_review_status.

Get Housing Application

Get Housing Application

{
    "title": "Get Housing Application",
    "description": "Returns a housing application by ID after authorizing the current user dependency",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applications/{application_id}",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "application_id",
            "value": "101",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1 555 123 4567\",\n    \"country\": \"Japan\",\n    \"property_type\": \"Condo\",\n    \"purchase_intent\": \"buy\",\n    \"budget_range\": \"\\u00a5100\\u2013200M\",\n    \"savings\": \"\\u00a510M\",\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        \"personal\": [\n            {\n                \"id\": \"acc_1\",\n                \"name\": \"Primary checking\"\n            }\n        ]\n    },\n    \"metadata\": {\n        \"source\": \"manual_seed\",\n        \"residence_permit_number\": \"AB12345678CD\"\n    },\n    \"identifier\": \"cust-123\",\n    \"id\": 101,\n    \"created_at\": \"2026-04-26T10:15:00Z\",\n    \"archived\": false,\n    \"review_status\": \"pending\",\n    \"login_credentials\": null,\n    \"credit_score\": 742\n}"
        }
    }
}

The handler resolves application metadata and enriches the response before returning it.

Get Application Account Coverage

Get Application Account Coverage

{
    "title": "Get Application Account Coverage",
    "description": "Infers connected account coverage for a housing application using PlaidKycGateway",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applicants/{application_id}/account-coverage",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "application_id",
            "value": "101",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"application_id\": 101,\n    \"status\": \"complete\",\n    \"reported_accounts\": [\n        \"checking\"\n    ],\n    \"detected_accounts\": [\n        \"checking\"\n    ],\n    \"missing_accounts\": [],\n    \"coverage_ratio\": 1,\n    \"details\": {\n        \"institutions\": [\n            \"Plaid\"\n        ]\n    },\n    \"errors\": []\n}"
        }
    }
}

This endpoint loads the application, builds a PlaidKycGateway, and passes the saved connected_accounts to infer_account_coverage.

Create Phone Application

Create Phone Application

{
    "title": "Create Phone Application",
    "description": "Creates a phone application after validating the phone number format",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/phone-applications",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"phone\": \"+1 555 123 4567\",\n    \"connected_accounts\": {\n        \"account\": [\n            1\n        ]\n    }\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Created",
            "body": "{\n    \"id\": 201,\n    \"phone\": \"+1 555 123 4567\",\n    \"connected_accounts\": {\n        \"account\": [\n            1\n        ]\n    },\n    \"created_at\": \"2026-04-26T10:15:00Z\"\n}"
        }
    }
}

The handler trims the incoming phone number and requires at least seven digits before calling submit_phone_application.

List Phone Applications

List Phone Applications

{
    "title": "List Phone Applications",
    "description": "Returns recent phone applications ordered from newest to oldest",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/phone-applications",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"id\": 201,\n        \"phone\": \"+1 555 123 4567\",\n        \"connected_accounts\": {\n            \"account\": [\n                1\n            ]\n        },\n        \"created_at\": \"2026-04-26T10:15:00Z\"\n    }\n]"
        }
    }
}

The helper path loads recent phone applications and converts each one with _phone_application_to_response, which rejects records missing persistence metadata.

Operational Scripts

create_test_application.py

backend/src/scripts/create_test_application.py

This script seeds a housing application through the API and prints a compact JSON summary of the created application and its detail lookup. It is built around urllib.request, so it does not depend on the FastAPI test client or any ORM session.

Environment variables

Variable Purpose
APPLICATIONS_API_BASE_URL Overrides the default API base URL.
APPLICATIONS_API_TOKEN Optional bearer token added to the request headers.
Function Description
_default_payload Builds the default housing application request body used for the seed call.
_build_headers Adds Content-Type: application/json and optionally an Authorization bearer token.
_request_json Executes an HTTP request and parses the JSON response, raising RuntimeError on transport or decode failures.
main Parses CLI arguments, creates an application, fetches the detail record, and prints the summary JSON.

CLI arguments

  • --base-url: Defaults to http://localhost:8000/api.
  • --email: Defaults to [email protected].
  • --full-name: Defaults to Test Applicant.

Observed flow

  1. Build the default payload.
  2. Send POST {base-url}/v1/applications.
  3. Read id, credit_score, and login_credentials from the create response.
  4. Send GET {base-url}/v1/applications/{id}.
  5. Print application_id, credit_score, login_credentials, and detail_url.
sequenceDiagram
    participant Op as Operator
    participant Script as create_test_application.py
    participant Api as Applications API
    participant Db as Application Storage

    Op->>Script: Run main
    Script->>Api: POST create application
    Api->>Db: Persist housing application
    Db-->>Api: Created record
    Api-->>Script: Create response
    Script->>Api: GET application detail
    Api-->>Script: Detail response
    Script-->>Op: Print summary JSON

clear_housing_applications.py

backend/src/scripts/clear_housing_applications.py

This script deletes every housing application from the configured database. It opens a SQLAlchemy session through SessionLocal, uses SQLAlchemyHousingApplicationRepository.delete_all, and closes the session in a finally block.

Function Description
_build_argument_parser Defines the --yes flag and the destructive-command description.
_confirm_deletion Prompts for the literal word delete and aborts on EOF or any other response.
main Parses CLI arguments, asks for confirmation unless --yes is present, deletes all rows, prints the deletion count, and returns an exit code.

CLI behavior

  • Without --yes, the script prompts for confirmation.
  • Typing anything other than delete aborts the run.
  • EOF aborts the run.
  • Success prints Deleted N housing application(s).
  • Abort prints Aborted. No records were deleted. and returns 1.
sequenceDiagram
    participant Op as Operator
    participant Script as clear_housing_applications.py
    participant Repo as SQLAlchemyHousingApplicationRepository
    participant Db as MySQL Database

    Op->>Script: Run main
    Script->>Script: Parse arguments
    Script->>Script: Confirm deletion when needed
    Script->>Repo: delete_all
    Repo->>Db: Delete all housing applications
    Db-->>Repo: Deleted row count
    Repo-->>Script: Count
    Script-->>Op: Print result and exit code

State Management

Housing application review state

  • submit_housing_application initializes review_status to pending.
  • decide_application_endpoint accepts approved, denied, or pending and writes the selected value back to the record.
  • archive_housing_application is exposed separately from review decisions and returns a boolean from the repository.

Housing application archive state

  • New housing applications are created with archived=False.
  • archive_application_endpoint returns archived=True when the repository call succeeds.
  • delete_housing_applications_endpoint clears the table rather than changing individual archive flags.

Phone application state

  • submit_phone_application creates the domain object with id=None.
  • Persistence metadata for list and response conversion depends on id and created_at.
  • Connected account data is stored as a dict and returned as part of the response.

Error Handling

Location Error Path Result
create_application Missing email, missing full name, or agree_policy=False 400 Bad Request
create_application submit_housing_application raises ValueError 400 Bad Request
list_housing_applications_endpoint Any unexpected exception during load or mapping 500 Internal Server Error
delete_housing_applications_endpoint Any unexpected exception during deletion 500 Internal Server Error
archive_application_endpoint Invalid application ID 400 Bad Request
archive_application_endpoint Repository returns false 404 Not Found
archive_application_endpoint Unexpected exception 500 Internal Server Error
create_phone_application Blank phone number or fewer than 7 digits 400 Bad Request
get_housing_application Non-positive application_id ValueError before repository access
get_application_endpoint Application missing 404 Not Found
get_application_account_coverage Application missing 404 Not Found
clear_housing_applications.main User aborts confirmation Exit code 1
_request_json HTTP error, URL error, invalid JSON RuntimeError

Integration Points

  • src.infra.mysql.housing_application_repository.SQLAlchemyHousingApplicationRepository
  • src.infra.mysql.phone_application_repository.SQLAlchemyPhoneApplicationRepository
  • src.infra.mysql.open_banking_consent_repository.SQLOpenBankingConsentRepository
  • src.infra.mysql.database.get_db
  • src.infra.mysql.database.SessionLocal
  • src.infra.external_apis.plaid_client.PlaidKycGateway
  • src.usecase.open_banking.sync_application_plaid_consents
  • _provision_applicant_credentials inside http_endpoints.py
  • application_events.publish and application_events.stream

Testing Considerations

  • Create housing application returns persisted records with review_status="pending".
  • List housing applications returns most recent records first.
  • Phone-based search returns the correct application by normalized phone query.
  • Residence permit filtering is applied after the initial load.
  • Listing remains stable when created_at is missing in storage.
  • Listing falls back to review_status="pending" when schema support is reduced.
  • delete_all returns zero on an empty table and the full count on populated tables.
  • Phone application listing returns newest-first data.
  • Application creation path includes metadata propagation into the response.

Key Classes Reference

Class Responsibility
housing_application.py Housing application creation, lookup, listing, archive, and cleanup use cases.
phone_application.py Phone application creation and listing use cases.
schemas.py Request and response DTOs for housing and phone applications.
http_endpoints.py FastAPI handlers, response mapping, validation, and application event publishing.
create_test_application.py API-driven seed and verification script for a housing application.
clear_housing_applications.py Destructive cleanup script that deletes every housing application from the configured database.