Application Management Domain

platform/deployment/prod/initdb/1_create_database.sql, backend/src/interface/http_endpoints.py, backend/src/interface/schemas.py, backend/src/usecase/housing_application.py, backend/src/usecase/phone_application.py, backend/tests/interface/test_application_endpoint.py, backend/tests/interface/test_phone_application_endpoint.py

Overview

This domain persists two related but distinct record types: full housing applications and lightweight phone leads. Housing applications capture the full submission payload used by the backend to create applicant records, provision login credentials, track archive and review state, and carry structured account data in connected_accounts. Phone leads are a smaller persistence path that stores only a phone number, structured account payload, and creation time.

The backend tests show that these records are not write-only blobs. Housing applications are read back as API objects, deduplicated by the persisted identity used by the repository, filtered by archived, and updated through review and archive endpoints. Phone leads are also round-tripped directly through API responses, with the list endpoint returning the newest rows first.

Architecture Overview

flowchart TB
    subgraph HTTPAPI[HTTP API Layer]
        AppEndpoints[backend src interface http_endpoints]
        PhoneEndpoints[backend src interface http_endpoints]
    end

    subgraph BusinessLayer[Business Layer]
        SubmitHousing[submit_housing_application]
        SearchHousing[search_housing_applications_by_phone]
        SubmitPhone[submit_phone_application]
    end

    subgraph DataAccessLayer[Data Access Layer]
        HousingRepo[SQLAlchemyHousingApplicationRepository]
        PhoneRepo[SQLAlchemyPhoneApplicationRepository]
    end

    subgraph Persistence[MySQL Persistence]
        Applications[(applications)]
        PhoneApplications[(phone_applications)]
    end

    AppEndpoints --> SubmitHousing
    AppEndpoints --> SearchHousing
    AppEndpoints --> HousingRepo
    PhoneEndpoints --> SubmitPhone
    PhoneEndpoints --> PhoneRepo

    SubmitHousing --> HousingRepo
    SearchHousing --> HousingRepo
    SubmitPhone --> PhoneRepo

    HousingRepo --> Applications
    PhoneRepo --> PhoneApplications

Persistence Model

Housing Applications table

platform/deployment/prod/initdb/1_create_database.sql

The applications table is the persisted backing store for full housing submissions. Backend behavior and tests show that a row contains the full application payload plus operational fields used by the application lifecycle.

Column Type Description
id int Primary key used by /api/v1/applications/{application_id} and update endpoints.
email string Applicant email address. Required on create.
phone string Applicant phone number. Used for search and duplicate identity behavior.
country string Application country field submitted by the client.
property_type string Housing property type from the submission.
purchase_intent string Application intent value.
budget_range string Applicant budget range.
savings string Declared savings value.
income string Declared income value.
income_currency string Currency for the income field.
employment_status string Employment status from the submission.
financing_consent string Financing consent value from the submission.
full_name string Applicant full name. Required on create.
agree_policy boolean Privacy policy consent flag. Required to be true on create.
receive_updates boolean Optional updates consent flag. Defaults to False in the request model.
skipped_connect_accounts boolean Flag captured by the request model and persisted with the application.
connected_accounts string / structured payload Serialized structured account data used by the backend to carry linked-account information, embedded metadata, and identifier data.
created_at datetime Creation timestamp. Used by list and detail responses.
archived boolean Application archive flag used by list filtering and archive behavior. Tests prove this column must exist in production and legacy schemas.
review_status string Review lifecycle state updated by the decision endpoint. Tests show pending, approved, and denied.

The tests also prove a uniqueness rule on the housing application identity: duplicate submits with the same full_name and phone update the existing row instead of creating a new one.

Phone Applications table

platform/deployment/prod/initdb/1_create_database.sql

The phone_applications table stores the phone lead path. It is intentionally smaller than applications and only carries the data needed to persist and list a phone lead.

Column Type Description
id int Primary key returned by /api/phone-applications.
phone string Phone number supplied by the client.
connected_accounts string / structured payload Structured payload echoed back in responses.
created_at datetime Creation timestamp used to return the newest phone leads first.

Connected Accounts and Embedded Metadata

The housing create handler does more than pass through connected_accounts:

  1. It copies the incoming request.connected_accounts.
  2. If request.metadata is a dict, it stores a deep copy inside the payload under the internal metadata key used by the backend.
  3. If request.identifier is present and non-blank, it stores that value under the internal identifier key.
  4. It persists the enriched payload through submit_housing_application.
  5. Response serialization removes the internal storage keys from connected_accounts and exposes metadata and identifier as top-level response fields.

The tests confirm this behavior by asserting that:

  • metadata and identifier survive round-trip responses.
  • The response connected_accounts does not leak the internal storage keys.
  • The housing application list can still render a valid created_at string even when the persisted row has a missing timestamp value.

For phone leads, connected_accounts is passed through directly and returned in the response body after cleanup by _clean_response_connected_accounts.

Production Schema Sensitivity

Backend Behavior

Housing application write path

Note: The application write paths depend on schema fields that were added after the earliest applications table layout. backend/src/main.py calls ensure_application_archived_column(engine) and ensure_application_review_status_column(engine) during startup, and backend/tests/test_schema_migrations.py proves the repository can upgrade a legacy applications table that is missing archived. A production database left behind on an older schema can therefore break or mis-state housing application writes, archive transitions, and review updates until the schema is brought forward.

create_application in backend/src/interface/http_endpoints.py performs request validation before any persistence happens:

  • email must be non-empty after trimming.
  • full_name must be non-empty after trimming.
  • agree_policy must be True.

After validation, it creates a SQLAlchemyHousingApplicationRepository and calls submit_housing_application, which constructs a HousingApplication with:

  • id=None
  • created_at=None
  • archived=False
  • review_status="pending"

That means the application row is created in a known initial lifecycle state. The handler then tries to sync Plaid consents through sync_application_plaid_consents; any failure there is logged and does not cancel the housing application create.

The endpoint tests prove the following write-path behavior:

  • Success returns 201.
  • Missing email or full name returns 400.
  • Missing consent returns 400.
  • Duplicate submit with the same full_name and phone updates the existing record id.
  • The create response includes login credentials for the applicant.
  • archived is False and review_status is pending on new submissions.

Housing application read and state transition paths

The repository and endpoint tests demonstrate the read and lifecycle behavior around the same applications table:

  • GET /api/v1/applications returns recent applications first.
  • Archived housing applications are excluded from the listing.
  • Filtering by phone is supported and returns the matching row(s).
  • GET /api/v1/applications/{application_id} returns a single persisted application.
  • POST /api/v1/applications/{application_id}/archive mutates the archive state and removes the application from subsequent listings.
  • POST /api/v1/applications/{application_id}/decision updates review_status.
  • DELETE /api/v1/applications removes all housing application rows.

The tests also prove two compatibility behaviors:

  • Listing tolerates a missing created_at field on legacy rows.
  • Listing can fall back when the review_status column is unavailable and still serializes pending.

Phone lead write path

create_phone_application validates and persists the smaller phone lead record:

  • phone is trimmed.
  • Empty phone values return 400.
  • A phone value with fewer than 7 digits returns 400.

On success, the handler creates a PhoneApplication through submit_phone_application and returns the persisted row as a PhoneApplicationResponse. The test suite proves that the response includes the trimmed phone value, the original connected_accounts payload, an integer id, and a string created_at.

Phone lead list path

list_phone_applications_endpoint uses a bounded limit query parameter and returns a list[PhoneApplicationResponse]. The test suite confirms that the newest phone lead appears first in the returned list.

Data Models

ApplicationCreateRequest

backend/src/interface/schemas.py

Property Type Description
email str Required applicant email. Must be non-empty.
phone str Required applicant phone number. Must be non-empty.
country str Required country field.
property_type str Required property type.
purchase_intent str Required purchase intent.
budget_range str Required budget range.
savings str Required savings value.
income str Required income value.
income_currency str Required income currency.
employment_status str Required employment status.
financing_consent str Required financing consent value.
full_name str Required applicant name. Must be non-empty.
agree_policy bool Required privacy consent flag.
receive_updates bool Optional update consent flag. Defaults to False.
skipped_connect_accounts bool Optional connect-accounts skip flag. Defaults to False.
connected_accounts Dict[str, Any] Structured connected-account payload. Defaults to an empty dict.
metadata Optional[Dict[str, Any]] Optional application metadata embedded into connected_accounts during persistence.
identifier Optional[str] Optional external identifier embedded into connected_accounts during persistence.

ApplicationResponse

backend/src/interface/schemas.py

Property Type Description
email str Persisted applicant email.
phone str Persisted applicant phone.
country str Persisted country field.
property_type str Persisted property type.
purchase_intent str Persisted purchase intent.
budget_range str Persisted budget range.
savings str Persisted savings value.
income str Persisted income value.
income_currency str Persisted income currency.
employment_status str Persisted employment status.
financing_consent str Persisted financing consent value.
full_name str Persisted applicant name.
agree_policy bool Persisted privacy consent flag.
receive_updates bool Persisted update consent flag.
skipped_connect_accounts bool Persisted connect-accounts skip flag.
connected_accounts Dict[str, Any] Cleaned connected-account payload returned to the client.
id int Persisted application id.
created_at datetime Persisted creation time.
archived bool Archive state exposed to the client.
metadata Optional[Dict[str, Any]] Optional top-level application metadata.
identifier Optional[str] Optional top-level application identifier.
review_status str Current review state.
login_credentials Optional[UserCredentialsResponse] Applicant credentials returned by create responses.
credit_score Optional[int] Optional credit score field exposed by the response model.

ApplicationDecisionRequest

backend/src/interface/schemas.py

Property Type Description
status Literal["approved", "denied", "pending"] Review status written by the decision endpoint.

DeleteApplicationsResponse

backend/src/interface/schemas.py

Property Type Description
deleted int Number of housing application rows deleted by the bulk delete endpoint.

PhoneApplicationCreateRequest

backend/src/interface/schemas.py

Property Type Description
phone str Required phone number. Must be non-empty.
connected_accounts Dict[str, Any] Structured payload stored with the phone lead. Defaults to an empty dict.

PhoneApplicationResponse

backend/src/interface/schemas.py

Property Type Description
id int Persisted phone lead id.
phone str Persisted phone number.
connected_accounts Dict[str, Any] Persisted structured payload returned to the client.
created_at datetime Persisted creation time.

API Integration

Submit Housing Application

{
    "title": "Submit Housing Application",
    "description": "Creates or updates a housing application record, stores connected account data, and returns the persisted applicant payload with login credentials",
    "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                \"provider\": \"plaid\"\n            }\n        ]\n    },\n    \"metadata\": {\n        \"profile_name\": \"Dashboard Profile\",\n        \"credit_score\": 742,\n        \"credit_score_scale\": \"300-850\"\n    },\n    \"identifier\": \"dashboard-profile-1\"\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                \"provider\": \"plaid\"\n            }\n        ]\n    },\n    \"id\": 101,\n    \"created_at\": \"2026-04-26T10:15:30Z\",\n    \"archived\": false,\n    \"metadata\": {\n        \"profile_name\": \"Dashboard Profile\",\n        \"credit_score\": 742,\n        \"credit_score_scale\": \"300-850\"\n    },\n    \"identifier\": \"dashboard-profile-1\",\n    \"review_status\": \"pending\",\n    \"login_credentials\": {\n        \"role\": \"applicant\",\n        \"application_id\": 101,\n        \"username\": \"LITA123456\",\n        \"temporary_password\": \"TempPass!234\"\n    },\n    \"credit_score\": null\n}"
        }
    }
}

List Housing Applications

{
    "title": "List Housing Applications",
    "description": "Returns recent housing applications, filtered by phone when supplied, with archived records excluded from the listing",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applications",
    "headers": [],
    "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": "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                    \"provider\": \"plaid\"\n                }\n            ]\n        },\n        \"id\": 102,\n        \"created_at\": \"2026-04-26T10:16:30Z\",\n        \"archived\": false,\n        \"metadata\": {\n            \"profile_name\": \"Dashboard Profile\",\n            \"credit_score\": 742,\n            \"credit_score_scale\": \"300-850\"\n        },\n        \"identifier\": \"dashboard-profile-1\",\n        \"review_status\": \"pending\",\n        \"login_credentials\": null,\n        \"credit_score\": 742\n    }\n]"
        }
    }
}

Get Housing Application

{
    "title": "Get Housing Application",
    "description": "Fetches a single housing application by id and returns the persisted record as an application response",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applications/{application_id}",
    "headers": [],
    "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                \"provider\": \"plaid\"\n            }\n        ]\n    },\n    \"id\": 101,\n    \"created_at\": \"2026-04-26T10:15:30Z\",\n    \"archived\": false,\n    \"metadata\": {\n        \"profile_name\": \"Dashboard Profile\",\n        \"credit_score\": 742,\n        \"credit_score_scale\": \"300-850\"\n    },\n    \"identifier\": \"dashboard-profile-1\",\n    \"review_status\": \"pending\",\n    \"login_credentials\": null,\n    \"credit_score\": null\n}"
        }
    }
}

Archive Housing Application

{
    "title": "Archive Housing Application",
    "description": "Archives a housing application and removes it from subsequent list responses",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applications/{application_id}/archive",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "application_id",
            "value": "101",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Archived",
            "body": "{\n    \"archived\": true\n}"
        }
    }
}

Update Application Review Status

{
    "title": "Update Application Review Status",
    "description": "Updates review_status for a housing application using the decision payload",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applications/{application_id}/decision",
    "headers": [
        {
            "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                \"provider\": \"plaid\"\n            }\n        ]\n    },\n    \"id\": 101,\n    \"created_at\": \"2026-04-26T10:15:30Z\",\n    \"archived\": false,\n    \"metadata\": null,\n    \"identifier\": null,\n    \"review_status\": \"approved\",\n    \"login_credentials\": null,\n    \"credit_score\": null\n}"
        }
    }
}

Delete Housing Applications

{
    "title": "Delete Housing Applications",
    "description": "Deletes all housing application rows and returns the deleted count",
    "method": "DELETE",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/v1/applications",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Deleted",
            "body": "{\n    \"deleted\": 2\n}"
        }
    }
}

Submit Phone Application

{
    "title": "Submit Phone Application",
    "description": "Creates a phone lead record and returns the persisted phone application",
    "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        \"example\": \"data\"\n    }\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Created",
            "body": "{\n    \"id\": 201,\n    \"phone\": \"+1 (555) 123-4567\",\n    \"connected_accounts\": {\n        \"example\": \"data\"\n    },\n    \"created_at\": \"2026-04-26T10:20:00Z\"\n}"
        }
    }
}

List Phone Applications

{
    "title": "List Phone Applications",
    "description": "Returns recent phone lead records in reverse chronological order",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/phone-applications",
    "headers": [],
    "queryParams": [
        {
            "key": "limit",
            "value": "50",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"id\": 202,\n        \"phone\": \"+1 555 123 4501\",\n        \"connected_accounts\": {\n            \"account\": [\n                1\n            ]\n        },\n        \"created_at\": \"2026-04-26T10:21:00Z\"\n    }\n]"
        }
    }
}

Feature Flows

Housing application submission and persistence

sequenceDiagram
    participant User as User
    participant API as create_application
    participant Usecase as submit_housing_application
    participant Repo as SQLAlchemyHousingApplicationRepository
    participant DB as applications table
    participant Sync as sync_application_plaid_consents
    participant UI as API response

    User->>API: POST /api/v1/applications
    API->>API: validate email full_name agree_policy
    API->>API: merge connected_accounts metadata identifier
    API->>Usecase: submit_housing_application
    Usecase->>Repo: create HousingApplication
    Repo->>DB: insert or update applications row
    DB-->>Repo: persisted application
    Repo-->>Usecase: HousingApplication
    Usecase-->>API: HousingApplication
    API->>Sync: sync_application_plaid_consents
    Sync-->>API: optional consent sync result
    API-->>User: ApplicationResponse with login_credentials

Housing application archive and review update

sequenceDiagram
    participant User as User
    participant API as archive_application_endpoint
    participant Guard as _ensure_authorised_role
    participant Repo as SQLAlchemyHousingApplicationRepository
    participant DB as applications table
    participant UI as API response

    User->>API: POST /api/v1/applications/{application_id}/archive
    API->>Guard: check current_user role
    Guard-->>API: allowed
    API->>Repo: archive application_id
    Repo->>DB: update archived state or legacy delete fallback
    DB-->>Repo: mutation result
    Repo-->>API: archived true or false
    API-->>User: {"archived": true}

Phone lead submission and listing

sequenceDiagram
    participant User as User
    participant API as create_phone_application
    participant Usecase as submit_phone_application
    participant Repo as SQLAlchemyPhoneApplicationRepository
    participant DB as phone_applications table
    participant UI as API response

    User->>API: POST /api/phone-applications
    API->>API: trim phone and validate digit count
    API->>Usecase: submit_phone_application
    Usecase->>Repo: create PhoneApplication
    Repo->>DB: insert phone_applications row
    DB-->>Repo: persisted phone lead
    Repo-->>Usecase: PhoneApplication
    Usecase-->>API: PhoneApplication
    API-->>User: PhoneApplicationResponse

    User->>API: GET /api/phone-applications
    API->>Repo: list_phone_applications with limit
    Repo->>DB: select recent phone leads
    DB-->>Repo: ordered rows
    Repo-->>API: phone lead list
    API-->>User: list[PhoneApplicationResponse]

State Management

Housing application lifecycle state

  • archived: drives whether a housing application is excluded from list responses.
  • review_status: starts as pending on create and changes through the decision endpoint to approved or denied.
  • connected_accounts: carries the linked-account payload and embedded metadata that the response layer later cleans.

The tests show that this state is persisted, not just derived at response time:

  • archived is False on new application responses.
  • review_status is pending on new application responses.
  • Archive operations remove the application from subsequent list results.
  • Decision operations update the returned review_status immediately.

Error Handling

Housing applications

  • 400 when email is blank.
  • 400 when full_name is blank.
  • 400 when agree_policy is false.
  • 400 when submit_housing_application raises ValueError.
  • 404 when a requested application id is not found.
  • 403 when the decision or archive role guard rejects the current user.
  • 500 is used by the bulk delete path and the phone list path when unexpected repository failures occur.

Phone applications

  • 400 when the phone field is empty after trimming.
  • 400 when the phone contains fewer than 7 digits.
  • 500 when list_phone_applications_endpoint cannot load records.

Persistence compatibility

The tests demonstrate compatibility behavior for older rows and older schemas:

  • Missing created_at does not break housing application listing.
  • Missing archived is upgraded in place by the repository schema helper.
  • Missing review_status falls back to pending in list output.

Dependencies

  • FastAPI request injection via Depends(get_db) and path/query parameter validation.
  • SQLAlchemy sessions for all persistence operations.
  • Pydantic request and response models in backend/src/interface/schemas.py.
  • MySQL schema managed through platform/deployment/prod/initdb/1_create_database.sql.
  • backend/src/main.py schema helpers:
    • ensure_application_archived_column
    • ensure_application_review_status_column
  • backend/tests/test_schema_migrations.py legacy-schema coverage.
  • backend/tests/interface/test_application_endpoint.py and backend/tests/interface/test_phone_application_endpoint.py endpoint coverage.

Testing Considerations

Test Behavior verified Persistence implication
test_submit_application_success Application create returns persisted fields, archived false, review_status pending Housing write path stores the full application row and initial lifecycle state
test_submit_application_requires_email_and_name Blank email or full name returns 400 Validation happens before persistence
test_submit_application_requires_consent Missing consent returns 400 Consent is required for insert
test_submit_application_updates_existing_record Re-submitting the same application updates the existing id The table behaves as a unique business record keyed by full_name and phone
test_submit_application_persists_embedded_dashboard_metadata Metadata and identifier round-trip without leaking internal keys into connected_accounts connected_accounts is the storage carrier for embedded metadata
test_list_applications_returns_recent_records Newest housing application appears first and all items remain unarchived List order and archive filtering come from the persisted table
test_list_applications_handles_missing_created_at Listing still returns a string created_at when a row lacks a timestamp Serializer tolerates legacy rows
test_list_applications_falls_back_without_review_status_column List response still serializes review_status: pending when the column is missing The backend tolerates older schemas
test_archive_application_removes_from_listing Archived application disappears from the list Archive state is enforced at read time
test_archive_application_returns_404_for_missing_record Missing archive target returns 404 Archive path is keyed by persisted id
test_admin_can_update_application_status Decision updates review_status The applications row stores review state
test_applicant_cannot_update_application_status Unauthorized decision returns 403 Review updates are guarded before persistence
test_submit_phone_application_success Phone lead returns id, trimmed phone, connected_accounts, created_at phone_applications round-trips the payload
test_submit_phone_application_invalid_phone Invalid phone returns 400 Phone lead validation happens before persistence
test_list_phone_applications Phone leads list successfully and newest row appears first phone_applications is ordered by recency

Key Classes Reference

Class Responsibility
ApplicationCreateRequest (schemas.py) Validates the housing application submission payload.
ApplicationResponse (schemas.py) Represents the persisted housing application returned by the API.
ApplicationDecisionRequest (schemas.py) Carries the review status used by the decision endpoint.
DeleteApplicationsResponse (schemas.py) Returns the deleted row count for bulk housing application deletes.
PhoneApplicationCreateRequest (schemas.py) Validates the phone lead submission payload.
PhoneApplicationResponse (schemas.py) Represents the persisted phone lead returned by the API.
submit_housing_application (housing_application.py) Creates the HousingApplication aggregate with initial lifecycle state and persists it.
search_housing_applications_by_phone (housing_application.py) Delegates phone-based housing application search to the repository.
submit_phone_application (phone_application.py) Creates and persists a PhoneApplication aggregate.
SQLAlchemyHousingApplicationRepository (housing_application_repository.py) Persists, retrieves, archives, searches, and deletes housing application rows.
SQLAlchemyPhoneApplicationRepository (phone_application_repository.py) Persists and reads phone lead rows.
http_endpoints.py Hosts the HTTP handlers that connect the API surface to the persistence layer.