Housing Application Domain - Operational Scripts, Fixtures, and Test Coverage

Overview

This section covers the operational tooling and tests that keep housing application data healthy across local development, CI, and manual troubleshooting. The main lifecycle here is simple: seed a realistic application record, verify how the backend stores and lists it, and wipe the table when a test run or local experiment needs a clean slate.

The repository also supports a local fallback path for stored application data. When backend-backed lookups are unavailable, frontend-facing routes can hydrate application records from persisted JSON snapshots, which makes local debugging possible even when the API or database is not fully online.

Architecture Overview

flowchart TD
    subgraph Scripts[Operational Scripts]
        Seed[create_test_application main]
        Clear[clear_housing_applications main]
    end

    subgraph Tests[Validation Suite]
        RepoTests[test_housing_application_repository]
        ApiTests[test_application_endpoint]
        PhoneTests[test_phone_application_endpoint]
        ApplicantTests[test_applicants]
    end

    subgraph Backend[Backend Application Data]
        Repo[SQLAlchemyHousingApplicationRepository]
        UseCases[housing_application use cases]
        AppTable[applications table]
        ApplicantService[ApplicantService]
        ApplicantTable[applicants table]
        ConsentTable[consent grants table]
        CustomerTable[customers table]
    end

    subgraph Fallback[Local Fallback Data]
        JsonLive[data applications json]
        JsonSample[data applications sample]
        StoredRoute[applicants transactions fallback route]
    end

    Seed -->|POST create and GET detail| Repo
    Clear -->|delete_all| Repo
    RepoTests --> Repo
    ApiTests --> Repo
    ApplicantTests --> ApplicantService
    ApplicantTests --> ApplicantTable
    ApplicantTests --> ConsentTable
    ApplicantTests --> CustomerTable
    UseCases --> Repo
    Repo --> AppTable
    StoredRoute --> JsonLive
    JsonSample --> JsonLive
    StoredRoute -->|hydrate stored applications| JsonLive

Operational Scripts

Test Application Seeder

backend/src/scripts/create_test_application.py

This script creates a test housing application through the API and prints the resulting application ID, credit score, login credentials, and detail URL. It is meant for quick manual seeding against a running backend.

Public methods

Method Description
main Parses CLI arguments, posts a test application, fetches the created record, and prints a compact JSON summary.
_default_payload Builds the request payload used when no custom input is supplied.
_build_headers Adds Content-Type: application/json and optional bearer auth.
_request_json Sends an HTTP request and decodes the JSON response or raises a runtime error.

Operational inputs

Input Source Purpose
--base-url CLI flag or APPLICATIONS_API_BASE_URL Points the script at the API host.
--email CLI flag Seeds the applicant email.
--full-name CLI flag Seeds the applicant name.
APPLICATIONS_API_TOKEN Environment variable Adds a bearer token when the target API requires one.

Create Housing Application

{
    "title": "Create Housing Application",
    "description": "Creates a housing application record and returns the created application payload, credentials, and scoring fields",
    "method": "POST",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/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\": \"Test Applicant\",\n    \"agree_policy\": true,\n    \"receive_updates\": false,\n    \"connected_accounts\": {\n        \"personal\": [\n            {\n                \"id\": \"acc_1\",\n                \"name\": \"Primary checking\"\n            }\n        ]\n    }\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Created",
            "body": "{\n    \"id\": 123,\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\": \"Test Applicant\",\n    \"agree_policy\": true,\n    \"receive_updates\": false,\n    \"connected_accounts\": {\n        \"personal\": [\n            {\n                \"id\": \"acc_1\",\n                \"name\": \"Primary checking\"\n            }\n        ]\n    },\n    \"created_at\": \"2024-01-01T00:00:00Z\",\n    \"archived\": false,\n    \"review_status\": \"pending\",\n    \"identifier\": \"dashboard-profile-1\",\n    \"metadata\": {\n        \"profile_name\": \"Dashboard Profile\",\n        \"credit_score\": 742,\n        \"credit_score_scale\": \"300-850\"\n    },\n    \"credit_score\": 742,\n    \"login_credentials\": {\n        \"role\": \"applicant\",\n        \"application_id\": 123,\n        \"username\": \"LITA123456\",\n        \"temporary_password\": \"TempPass!234\"\n    }\n}"
        }
    }
}

Get Created Housing Application

{
    "title": "Get Created Housing Application",
    "description": "Fetches the detail view for the application created by the seeding script",
    "method": "GET",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/v1/applications/{application_id}",
    "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": "Success",
            "body": "{\n    \"id\": 123,\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\": \"Test Applicant\",\n    \"agree_policy\": true,\n    \"receive_updates\": false,\n    \"connected_accounts\": {\n        \"personal\": [\n            {\n                \"id\": \"acc_1\",\n                \"name\": \"Primary checking\"\n            }\n        ]\n    },\n    \"created_at\": \"2024-01-01T00:00:00Z\",\n    \"archived\": false,\n    \"review_status\": \"pending\",\n    \"identifier\": \"dashboard-profile-1\",\n    \"metadata\": {\n        \"profile_name\": \"Dashboard Profile\",\n        \"credit_score\": 742,\n        \"credit_score_scale\": \"300-850\"\n    },\n    \"credit_score\": 742\n}"
        }
    }
}

Clear Housing Applications

[!NOTE] create_test_application.py does not calculate credit score locally. It reads the score returned by the create response and then re-fetches the detail record to print the canonical score field.

backend/src/scripts/clear_housing_applications.py

This script deletes every housing application stored in the configured database. It is the fastest way to reset the applications table during local troubleshooting or test cleanup.

Public methods

Method Description
main Parses CLI arguments, enforces confirmation, deletes all application rows, and prints the deletion count.
_build_argument_parser Builds the --yes flag parser used to bypass the interactive prompt.
_confirm_deletion Prompts for the exact word delete before removing records.

Execution behavior

Step Behavior
Confirmation If --yes is omitted, the script requires interactive confirmation.
Abort path Any non-matching response returns exit code 1 and prints Aborted. No records were deleted.
Delete path The script opens SessionLocal, instantiates SQLAlchemyHousingApplicationRepository, calls delete_all(), closes the session, and returns 0.

Delete All Housing Applications

{
    "title": "Delete All Housing Applications",
    "description": "Deletes every housing application row from the configured database",
    "method": "DELETE",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/v1/applications",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Deleted rows",
            "body": "{\n    \"deleted\": 2\n}"
        }
    }
}

Fixture Files

Stored Application Snapshot

[!IMPORTANT] This maintenance path is the direct counterpart to the repository-level delete_all() test coverage. It removes all application rows from the database-backed table, not just the current user’s data.

data/applications.json

This file is the working JSON snapshot used by the local fallback path for stored application records.

Sample Stored Application Snapshot

data/applications.sample.json

This file is the template snapshot for local setup and manual resets. Engineers can copy it into the working JSON file when they need a known-good starting point for fallback-driven development.

Where the JSON fallback is used

The frontend-facing applicant transaction route hydrates stored application records when direct backend lookup and backend listing are not sufficient. That makes the JSON snapshot a practical fallback source for local development and troubleshooting when the API or database is not reachable.

Get Applicant Transactions with Stored Fallback

{
    "title": "Get Applicant Transactions with Stored Fallback",
    "description": "Returns transaction history for an applicant by merging backend records with stored application snapshots when needed",
    "method": "GET",
    "baseUrl": "<FrontendOriginUrl>",
    "endpoint": "/api/v1/applicants/{id}/transactions",
    "headers": [
        {
            "key": "Accept",
            "value": "application/json",
            "required": false
        },
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": false
        }
    ],
    "queryParams": [
        {
            "key": "start_date",
            "value": "2024-01-01",
            "required": false
        },
        {
            "key": "end_date",
            "value": "2024-12-31",
            "required": false
        }
    ],
    "pathParams": [
        {
            "key": "id",
            "value": "123",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Transaction list",
            "body": "{\n    \"applicant_id\": 123,\n    \"start_date\": \"2024-01-01\",\n    \"end_date\": \"2024-12-31\",\n    \"transactions\": [\n        {\n            \"amount\": 1550,\n            \"date\": \"2024-01-01\",\n            \"currency_code\": \"USD\",\n            \"status\": \"posted\",\n            \"account_name\": \"Everyday Checking\",\n            \"connection_name\": \"Bank of Test\",\n            \"description\": \"ABC PROPERTY MGMT\",\n            \"categories\": [\n                \"housing\",\n                \"rent\"\n            ],\n            \"provider\": \"plaid\",\n            \"metadata\": {\n                \"amount\": 1550,\n                \"date\": \"2024-01-01\",\n                \"description\": \"ABC PROPERTY MGMT\"\n            }\n        }\n    ]\n}"
        }
    }
}

Database-Backed Repository and Maintenance

Repository behavior covered by tests

backend/tests/infra/test_housing_application_repository.py

The repository tests exercise the database-facing housing application repository directly and confirm the maintenance behavior that the scripts rely on.

Coverage table

Test Verifies
test_get_by_id_returns_application_when_present A created application can be loaded back by ID.
test_get_by_id_returns_none_when_missing A missing ID returns None.
test_delete_all_removes_every_application delete_all() removes every row and leaves list_recent() empty.
test_delete_all_on_empty_table_is_a_noop delete_all() returns 0 on an empty table.

Repository methods used in this section

Method Description
create Inserts a HousingApplication record.
get_by_id Fetches a single application by numeric ID.
list_recent Returns recent applications in newest-first order.
delete_all Removes all application rows.
archive Marks or removes a single application from active listing behavior.

Legacy schema migration coverage

[!NOTE] The repository migration tests prove that legacy tables are upgraded in place. When the archived column is missing, the repository path adds it and preserves existing rows with archived set to false.

backend/tests/test_schema_migrations.py

This file validates the schema repair path that the repository depends on when running against older databases.

Test Verifies
test_ensure_application_archived_column_adds_column_when_missing The archived column is added to a legacy applications table and existing rows remain unarchived.
test_repository_ensures_archived_column_when_missing Constructing the repository against a legacy table also triggers the archived-column repair path.

Application fixture builder used by repository tests

_build_application

backend/tests/infra/test_housing_application_repository.py

Field Type Value pattern
id `int None`
email str user{n}@example.com
phone str +1555000{n}
country str US
property_type str apartment
purchase_intent str rent
budget_range str 1000-1500
savings str 10000
income str 50000
income_currency str USD
employment_status str employed
financing_consent str yes
full_name str Test User {n}
agree_policy bool True
receive_updates bool False
connected_accounts dict[str, object] {}
created_at `datetime None`

Applicant score fixture builder used by use case tests

_build_application

backend/tests/usecase/test_credit_score_runtime.py and backend/tests/usecase/test_credit_scoring.py

Field Type Value pattern
id int 1 by default
email str [email protected]
phone str 1234567890
country str US
property_type str condo
purchase_intent str loan or buy depending on test
budget_range str 250k
savings str 40k
income str 120k
income_currency str USD
employment_status str full-time or contract
financing_consent str yes
full_name str Test Applicant
agree_policy bool True
receive_updates bool False
skipped_connect_accounts bool False
connected_accounts dict[str, object] Empty or Plaid-shaped account data
created_at datetime datetime.now()
archived bool False
review_status str pending

HTTP API Endpoints

Create Application

Backend route used by the seeding script and the interface tests.

Create Housing Application

{
    "title": "Create Housing Application",
    "description": "Creates a housing application and returns the saved record together with login credentials when credential provisioning succeeds",
    "method": "POST",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/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    \"connected_accounts\": {\n        \"personal\": [\n            {\n                \"id\": \"acc_1\",\n                \"name\": \"Primary checking\"\n            }\n        ]\n    }\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Created",
            "body": "{\n    \"id\": 123,\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    \"connected_accounts\": {\n        \"personal\": [\n            {\n                \"id\": \"acc_1\",\n                \"name\": \"Primary checking\"\n            }\n        ]\n    },\n    \"created_at\": \"2024-01-01T00:00:00Z\",\n    \"archived\": false,\n    \"review_status\": \"pending\",\n    \"login_credentials\": {\n        \"role\": \"applicant\",\n        \"application_id\": 123,\n        \"username\": \"LITA123456\",\n        \"temporary_password\": \"TempPass!234\"\n    }\n}"
        },
        "400": {
            "description": "Validation error",
            "body": "{\n    \"detail\": \"Email is required.\"\n}"
        }
    }
}

Get Application

Get Housing Application

{
    "title": "Get Housing Application",
    "description": "Returns a single housing application by ID",
    "method": "GET",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/v1/applications/{application_id}",
    "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": "Success",
            "body": "{\n    \"id\": 123,\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    \"connected_accounts\": {\n        \"personal\": [\n            {\n                \"id\": \"acc_1\",\n                \"name\": \"Primary checking\"\n            }\n        ]\n    },\n    \"created_at\": \"2024-01-01T00:00:00Z\",\n    \"archived\": false,\n    \"review_status\": \"pending\",\n    \"identifier\": \"dashboard-profile-1\",\n    \"metadata\": {\n        \"profile_name\": \"Dashboard Profile\",\n        \"credit_score\": 742,\n        \"credit_score_scale\": \"300-850\"\n    }\n}"
        },
        "404": {
            "description": "Application not found",
            "body": "{\n    \"detail\": \"Application not found.\"\n}"
        }
    }
}

List Applications

List Housing Applications

{
    "title": "List Housing Applications",
    "description": "Returns recent housing applications in newest-first order and can render HTML when the client requests text/html",
    "method": "GET",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/v1/applications",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "limit",
            "value": "50",
            "required": false
        },
        {
            "key": "phone",
            "value": "5551234567",
            "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\": 124,\n        \"email\": \"[email protected]\",\n        \"phone\": \"+1 555 123 4568\",\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\": \"Second Applicant\",\n        \"agree_policy\": true,\n        \"receive_updates\": false,\n        \"connected_accounts\": [],\n        \"created_at\": \"2024-01-02T00:00:00Z\",\n        \"archived\": false,\n        \"review_status\": \"pending\",\n        \"identifier\": \"cust-123\",\n        \"metadata\": {\n            \"kyc\": {\n                \"provider\": \"saltedge\"\n            }\n        }\n    }\n]"
        }
    }
}

Archive Application

Archive Housing Application

{
    "title": "Archive Housing Application",
    "description": "Archives a housing application so it no longer appears in the active list",
    "method": "POST",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/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": "Archived",
            "body": "{\n    \"archived\": true\n}"
        },
        "404": {
            "description": "Application not found",
            "body": "{\n    \"detail\": \"Application not found.\"\n}"
        }
    }
}

Update Application Decision

Update Housing Application Decision

{
    "title": "Update Housing Application Decision",
    "description": "Updates the review status of a housing application",
    "method": "POST",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/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": "Updated application",
            "body": "{\n    \"id\": 123,\n    \"email\": \"[email protected]\",\n    \"full_name\": \"Jane Doe\",\n    \"review_status\": \"approved\",\n    \"archived\": false\n}"
        },
        "403": {
            "description": "Forbidden",
            "body": "{\n    \"detail\": \"You do not have permission to perform this action.\"\n}"
        }
    }
}

Applicant Transaction Lookup Fallback

Get Applicant Transactions

{
    "title": "Get Applicant Transactions",
    "description": "Returns transaction history for an applicant using backend data first and stored JSON fallback records when needed",
    "method": "GET",
    "baseUrl": "<FrontendOriginUrl>",
    "endpoint": "/api/v1/applicants/{id}/transactions",
    "headers": [
        {
            "key": "Accept",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [
        {
            "key": "start_date",
            "value": "2024-01-01",
            "required": false
        },
        {
            "key": "end_date",
            "value": "2024-12-31",
            "required": false
        }
    ],
    "pathParams": [
        {
            "key": "id",
            "value": "123",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Transaction history",
            "body": "{\n    \"applicant_id\": 123,\n    \"start_date\": \"2024-01-01\",\n    \"end_date\": \"2024-12-31\",\n    \"transactions\": [\n        {\n            \"amount\": 1550,\n            \"date\": \"2024-01-01\",\n            \"currency_code\": \"USD\",\n            \"status\": \"posted\",\n            \"account_name\": \"Everyday Checking\",\n            \"connection_name\": \"Bank of Test\",\n            \"description\": \"ABC PROPERTY MGMT\",\n            \"categories\": [\n                \"housing\",\n                \"rent\"\n            ],\n            \"provider\": \"plaid\",\n            \"metadata\": {\n                \"amount\": 1550,\n                \"date\": \"2024-01-01\",\n                \"description\": \"ABC PROPERTY MGMT\"\n            }\n        }\n    ]\n}"
        },
        "404": {
            "description": "No transaction history",
            "body": "{\n    \"detail\": \"No transaction history is available for this applicant yet. Connect and sync bank accounts first.\"\n}"
        }
    }
}

Phone Application Records

Create Phone Application

{
    "title": "Create Phone Application",
    "description": "Creates a phone application record with connected account metadata",
    "method": "POST",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/phone-applications",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"phone\": \"+1 555 123 4500\",\n    \"connected_accounts\": {\n        \"account\": [\n            0\n        ]\n    }\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Created phone application",
            "body": "{\n    \"phone\": \"+1 555 123 4500\",\n    \"connected_accounts\": {\n        \"account\": [\n            0\n        ]\n    }\n}"
        }
    }
}

List Phone Applications

{
    "title": "List Phone Applications",
    "description": "Returns phone application records in newest-first order",
    "method": "GET",
    "baseUrl": "<ApplicationsApiBaseUrl>",
    "endpoint": "/phone-applications",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Phone application list",
            "body": "[\n    {\n        \"phone\": \"+1 555 123 4501\",\n        \"connected_accounts\": {\n            \"account\": [\n                1\n            ]\n        }\n    },\n    {\n        \"phone\": \"+1 555 123 4500\",\n        \"connected_accounts\": {\n            \"account\": [\n                0\n            ]\n        }\n    }\n]"
        }
    }
}

Feature Flows

Seed a Test Application

sequenceDiagram
    participant Engineer as Engineer
    participant Script as create_test_application main
    participant API as Backend API
    participant Repo as SQLAlchemyHousingApplicationRepository
    participant DB as applications table

    Engineer->>Script: run with base url and optional token
    Script->>API: POST /v1/applications
    API->>Repo: create application
    Repo->>DB: insert row
    DB-->>Repo: created record
    Repo-->>API: HousingApplication
    API-->>Script: created JSON
    Script->>API: GET /v1/applications/id
    API-->>Script: detailed JSON
    Script-->>Engineer: print application_id credit_score login_credentials

Clear All Housing Applications

sequenceDiagram
    participant Engineer as Engineer
    participant Script as clear_housing_applications main
    participant Repo as SQLAlchemyHousingApplicationRepository
    participant DB as applications table

    Engineer->>Script: run clear script
    Script->>Engineer: prompt for delete confirmation
    Engineer->>Script: type delete or pass --yes
    Script->>Repo: delete_all
    Repo->>DB: remove all rows
    DB-->>Repo: deleted count
    Repo-->>Script: deleted count
    Script-->>Engineer: Deleted N housing application(s)

Resolve Applicant Transactions with Stored Fallback

sequenceDiagram
    participant Browser as Browser or Client
    participant Route as /api/v1/applicants/id/transactions
    participant Backend as Backend API
    participant Store as Stored JSON Applications
    participant Response as JSON Result

    Browser->>Route: GET applicant transactions
    Route->>Backend: fetch application by id
    Backend-->>Route: record or error
    Route->>Backend: list backend applications
    Backend-->>Route: list or error
    Route->>Store: read stored applications
    Store-->>Route: hydrated records
    Route->>Route: find matching application and extract transactions
    Route-->>Response: applicant_id dates transactions
    Response-->>Browser: JSON payload

Test Coverage

Interface Tests

[!NOTE] The handler still returns a created application when consent synchronization or credential provisioning fails. Those failures are logged, but they do not block creation. [!NOTE] list_housing_applications_endpoint only applies the configured limit when the limit query parameter is present. If the caller omits the parameter, the code passes limit=None to the loader and returns all records, which is why the unlimited list test expects the full table.

backend/tests/interface/test_application_endpoint.py

This file covers the main application lifecycle exposed through HTTP.

Test Coverage
test_submit_application_success Successful creation returns the persisted fields, id, created_at, archived, and review_status.
test_submit_application_returns_login_credentials Creation includes applicant login credentials.
test_submit_application_requires_email_and_name Blank email or full name returns 400.
test_submit_application_updates_existing_record Re-submitting the same applicant updates the existing row instead of creating a duplicate.
test_submit_application_persists_embedded_dashboard_metadata identifier and metadata survive creation and detail retrieval.
test_get_application_by_id Detail lookup returns the expected record.
test_list_applications_returns_recent_records Listing returns newest-first records.
test_list_applications_returns_all_without_limit Omitting limit returns the full result set.
test_list_applications_handles_missing_created_at A missing created_at still serializes as a non-empty string in the list view.
test_list_applications_includes_metadata_when_available Listed records include merged metadata and identifier values when available.
test_list_applications_renders_html_when_requested Accept: text/html switches the same list route to HTML output.
test_list_applications_falls_back_without_review_status_column Legacy schemas without review_status still list successfully and default to pending.
test_search_applications_by_phone Phone search works with digit-only and partial input.
test_archive_application_removes_from_listing Archived applications disappear from the list.
test_admin_can_update_application_status Admin status updates succeed.
test_applicant_cannot_update_application_status Applicant credentials are rejected with 403.
test_extract_residence_permit_schema_from_document_prefers_form_key_values OCR extraction prefers form-field values when present.

Phone Application Tests

backend/tests/interface/test_phone_application_endpoint.py

Test Coverage
test_list_phone_applications Two posted phone records are returned by the list endpoint, newest first.

Repository Tests

backend/tests/infra/test_housing_application_repository.py

Test Coverage
test_delete_all_removes_every_application delete_all() clears all rows and list_recent() becomes empty.
test_delete_all_on_empty_table_is_a_noop The empty-table delete path returns zero deletions.
test_get_by_id_returns_application_when_present Stored records are retrievable by ID.
test_get_by_id_returns_none_when_missing Missing IDs return None.

Applicant Service Tests

backend/tests/test_applicants.py

These tests validate the separate applicant service and the auth-driven routes it backs.

Test Coverage
test_applicant_filtering_by_customer The customer-scoped applicant list only returns applicants belonging to the authenticated customer.
test_create_applicant_validates_consent Applicant creation succeeds with a valid grant and rejects invalid or inactive consent grants with a 400 message.

Schema Migration Tests

backend/tests/test_schema_migrations.py

Test Coverage
test_ensure_application_archived_column_adds_column_when_missing The archived column is added to legacy tables and existing rows stay unarchived.
test_repository_ensures_archived_column_when_missing Repository initialization repairs older schemas before listing records.

Error Handling

Script-level handling

File Behavior
create_test_application.py Converts HTTPError, URLError, and JSON decode failures into RuntimeError messages that include the method and URL.
clear_housing_applications.py Returns 1 when confirmation is denied or stdin closes before confirmation.

API-level handling

Endpoint Error path
POST /v1/applications Returns 400 when email is missing, full name is missing, or policy consent is false.
GET /v1/applications/{application_id} Returns 400 for invalid IDs and 404 when the row is missing.
GET /v1/applications Returns 500 if the list load fails.
DELETE /v1/applications Returns 500 if the repository delete fails.
POST /v1/applications/{application_id}/archive Returns 400 for invalid IDs, 404 when the record is not found, and 500 for unexpected failures.
POST /v1/applications/{application_id}/decision Returns 403 when the caller does not have the required decision role.
POST /api/v1/applicants Returns 400 when the supplied consent grant is invalid or inactive.
GET /api/v1/applicants/{id}/transactions Returns 400 for malformed IDs or query parameters, and 404 when there is no matching application or transaction history.

Dependencies

Runtime and storage

  • src.infra.mysql.database.SessionLocal
  • src.infra.mysql.database.get_db
  • src.infra.mysql.housing_application_repository.SQLAlchemyHousingApplicationRepository
  • src.infra.mysql.schema.ensure_application_archived_column
  • src.services.applicant_service.ApplicantService
  • src.domain.housing_application.HousingApplication
  • src.domain.housing_application.HousingApplicationRepository

Script and test tooling

  • argparse
  • json
  • urllib.request
  • urllib.error
  • fastapi.testclient.TestClient
  • sqlalchemy
  • sqlite:///:memory:
  • StaticPool

Environment and local configuration

  • APPLICATIONS_API_BASE_URL
  • APPLICATIONS_API_TOKEN
  • DATABASE_URL

Frontend fallback helpers

  • readStoredApplications
  • hydrateStoredApplications
  • fetchApplicationsFromBackend
  • fetchBackendApplicationById
  • extractAuthToken

Testing Considerations

  • Seed paths should verify both the created row and the follow-up detail fetch.
  • Delete paths should be validated against both populated and empty tables.
  • Legacy schema tests should be run against SQLite and a real SQL database path.
  • List tests should cover limit, no limit, phone search, metadata merge, and HTML rendering.
  • Status-change tests should include both admin and applicant credentials.
  • Consent validation should cover valid grants and invalid/inactive grants.
  • Fallback tests should confirm stored JSON records are used when backend lookups do not resolve the transaction history.

Key Classes Reference

Class Responsibility
create_test_application.py Seeds a housing application through the API and prints the created record summary.
clear_housing_applications.py Deletes all housing application rows from the configured database after confirmation.
test_application_endpoint.py Verifies application creation, listing, archive, detail, metadata, and status behavior.
test_phone_application_endpoint.py Verifies phone application create and list behavior.
test_housing_application_repository.py Verifies repository persistence and bulk delete behavior.
test_applicants.py Verifies applicant service filtering and consent-grant validation.
test_schema_migrations.py Verifies repository schema repair for legacy application tables.