Housing Application Domain - Application Submission Funnel and Applicant Onboarding Flow

Overview

This flow collects an applicant’s identity, contact details, employment context, and connected financial accounts, then turns that data into a persisted housing application record. The onboarding starts in frontend/app/application/page.tsx, continues through frontend/app/application/employment/page.tsx, is reviewed and submitted from frontend/app/application/review/page.tsx, and ends on frontend/app/application/confirm/page.tsx.

The submission path is split between browser state, frontend API relay routes, and backend persistence. The review step posts to the versioned application API, the backend handler normalizes and stores a HousingApplication, and the frontend read model can later resolve the record by numeric id, generated application reference, or identifier-like metadata.

Architecture Overview

flowchart TD
    subgraph PresentationLayer [Presentation Layer]
        AppPage[Application page]
        PasscodeRoute[Passcode route]
        EmploymentPage[Employment page]
        ReviewPage[Review page]
        ConfirmPage[Confirm page]
        ApplicantsPage[Applicants overview]
    end

    subgraph BusinessLayer [Business Layer]
        CreateApplication[create_application]
        SubmitApplication[submit_housing_application]
    end

    subgraph DataAccessLayer [Data Access Layer]
        AppProxy[Application proxy routes]
        AppByIdProxy[Application lookup route]
        LocalStorage[Browser localStorage]
        StoredJson[Stored application JSON]
        ApplicantStream[EventSource applicant stream]
    end

    subgraph BackendStorage [Backend Storage]
        Repository[SQLAlchemyHousingApplicationRepository]
        Database[Application database]
    end

    AppPage -->|save form data| LocalStorage
    AppPage -->|route to passcode| PasscodeRoute
    PasscodeRoute --> EmploymentPage
    EmploymentPage -->|update userFormData| LocalStorage
    EmploymentPage -->|route to connect accounts| ReviewPage
    ReviewPage -->|POST application| AppProxy
    AppProxy -->|forward payload| CreateApplication
    CreateApplication -->|persist application| SubmitApplication
    SubmitApplication --> Repository
    Repository --> Database
    CreateApplication -->|created response| ReviewPage
    ReviewPage -->|route to confirm| ConfirmPage

    ApplicantsPage -->|load read model| AppProxy
    ApplicantsPage -->|lookup by id or reference| AppByIdProxy
    ApplicantsPage -->|realtime refresh| ApplicantStream
    AppProxy -->|merge fallback data| StoredJson
    AppByIdProxy -->|merge fallback data| StoredJson

Submission Funnel

Form Stages and Route Transitions

Stage File What the user does Data written or carried forward
1. Application details frontend/app/application/page.tsx Enters name, email, country code, phone, and accepts the required agreements Writes userFormData to localStorage, then navigates to /application/passcode?name=...&email=...&phone=...
2. Passcode handoff frontend/app/application/page.tsx and frontend/app/application/employment/page.tsx The funnel routes through the passcode step before employment Query params preserve name, email, and phone
3. Employment frontend/app/application/employment/page.tsx Selects citizenship and employment type Updates userFormData with fullName, email, phone, nationality, businessOwnership, and metadata, then routes to /application/connect-accounts
4. Connected accounts review frontend/app/application/review/page.tsx Confirms linked accounts and reviews the submission summary Reads local storage, requires at least one personal account, generates an application reference, and posts the final payload
5. Confirmation frontend/app/application/confirm/page.tsx Sees the success page after submission Receives reference and submittedAt in the query string

Application Page

[!NOTE] The frontend review payload shown in frontend/app/application/review/page.tsx submits email, phone, country, employment_status, financing_consent, full_name, agree_policy, receive_updates, connected_accounts, created_at, and metadata. The backend use case in backend/src/usecase/housing_application.py persists additional fields such as property_type, purchase_intent, budget_range, savings, income, income_currency, and skipped_connect_accounts. In the traced code, those extra fields are only populated if they are already present on the request object that reaches create_application.

frontend/app/application/page.tsx

This page is the entry point for the onboarding funnel. It gathers the applicant’s name, email, country calling code, and phone number, then blocks continuation until the email is valid and both consent checkboxes are checked.

State fields

Field Type Purpose
resumeLink `string \ null`
name string Applicant name input
selectedCountry Country Country code selection used to build the phone number
email string Applicant email input
phone string Applicant phone input
agreeTerms boolean Terms and Privacy Policy consent
agreeUserAgreement boolean Lita User Agreement consent
fullNumber string Computed dialCode + phone value
isEmailValid boolean Regex validation of the email field
isDisabled boolean Controls the Next button state

Funnel behavior

  • Prefetches passcodePath on mount.
  • Restores a resume link if userFormData or dw_application_connected_accounts already exists in browser storage.
  • Stores { fullName, email, phone } into localStorage under "userFormData" before routing onward.
  • Pushes the applicant to /application/passcode with name, email, and phone query params.

Employment Page

frontend/app/application/employment/page.tsx

This step records the applicant’s citizenship and employment type. It is the first place where the funnel writes the applicant’s nationality and employment selection into the stored form object.

State fields

Field Type Purpose
isCountryOpen boolean Controls the citizenship dropdown
isLoadingCitizenshipOptions boolean Tracks asynchronous citizenship option loading
citizenshipOptions Country[] Dropdown choices loaded for citizenship selection
countrySearch string Search text used to filter citizenship options

Funnel behavior

  • Reads and updates USER_FORM_DATA_STORAGE_KEY.
  • Writes fullName, email, phone, nationality, businessOwnership, and metadata into the stored form record.
  • Preserves phone if it already exists in saved form data.
  • Builds the next route as /application/connect-accounts and carries email, country, and showBusiness in the query string.
  • handleBack routes back to /application/passcode and preserves name, email, and phone.

Review Page

frontend/app/application/review/page.tsx

This page composes the final submission payload and performs the POST call. It also enforces the business rule that at least one personal account must be connected before submission is allowed.

State fields

Field Type Purpose
storedForm `StoredFormData \ null`
submitError `string \ null`
isSubmitting boolean Tracks the submit action
connectedAccounts Record<string, unknown[]> Connected account groups loaded from storage
applicantEmail string Derived email value used in the final payload
applicantCountry string Derived country value used in the final payload
applicantRole string Derived employment label used in the final payload
applicantName string Derived full name used in the final payload
applicantPhone string Derived phone value used in the final payload
residencePermitNumber string Derived residence permit number used in metadata
hasPersonalAccount boolean Submission gate; must be true to proceed

Submission behavior

  • Reads CONNECTED_ACCOUNTS_STORAGE_KEY, CONNECTION_CATEGORY_STORAGE_KEY, and USER_FORM_DATA_STORAGE_KEY.
  • Removes SALTEDGE_CUSTOMER_STORAGE_KEY after a successful submission.
  • Generates a new application reference with generateApplicationReference().
  • Builds submissionPayload with:
    • email
    • phone
    • country
    • employment_status
    • financing_consent
    • full_name
    • agree_policy
    • receive_updates
    • connected_accounts
    • created_at
    • metadata
  • Adds application_reference and residence_permit_number to metadata.
  • Posts to /api/v1/applications.
  • Stores the generated reference in APPLICATION_REFERENCE_STORAGE_KEY.
  • Redirects to /application/confirm with reference, submittedAt, and any preserved query params.

Confirm Page

frontend/app/application/confirm/page.tsx

This page is the terminal success state of the funnel. The visible code renders a confirmation message, summarizes what happens next, and reads the redirect query parameters passed from the review step.

Tracked data passed into the page

Query parameter Purpose
reference Application reference generated during submission
submittedAt ISO timestamp passed from the review step
email Preserved applicant email
country Preserved applicant country
showBusiness Preserved business-owner flag

Passcode Route Transition

frontend/app/application/page.tsx

frontend/app/application/employment/page.tsx

The funnel sends applicants through /application/passcode before employment. The visible code uses that route in two places:

  • ApplicationPage prefetches passcodePath and then navigates to /application/passcode?name=...&email=...&phone=...
  • EmploymentPage uses handleBack to return to /application/passcode with the same identity fields

No OTP handler is shown in the traced files, so the documented behavior is the route transition itself and the data it carries.

Business Layer

submit_housing_application

backend/src/usecase/housing_application.py

This use case creates a HousingApplication object with the normalized submission values and persists it through the injected repository.

Public methods

Method Description
submit_housing_application Builds a HousingApplication aggregate from the submitted fields and stores it through repository.create

Input fields

Parameter Type Purpose
repository HousingApplicationRepository Persistence boundary used to create the application
email str Applicant email
phone str Applicant phone number
country str Applicant country
property_type str Housing property type
purchase_intent str Intent such as rent or buy
budget_range str Desired budget range
savings str Applicant savings
income str Applicant income
income_currency str Income currency
employment_status str Employment category
financing_consent str Financial data consent flag
full_name str Applicant full name
agree_policy bool Privacy policy acceptance
receive_updates bool Marketing or update consent
skipped_connect_accounts bool Indicates whether the account connection step was skipped
connected_accounts dict[str, object] Connected financial account payload

Persistence behavior

  • Sets id=None.
  • Sets created_at=None.
  • Sets archived=False.
  • Sets review_status="pending".
  • Returns the result of repository.create(application).

create_application

backend/src/interface/http_endpoints.py

This HTTP handler receives the application creation request, validates core consent fields, packages metadata and identifier data into the request payload, and then calls submit_housing_application.

Public methods

Method Description
create_application Validates the request, merges metadata into the connected accounts payload, persists the application, and attempts to sync open-banking consents

Traced validation and persistence path

  1. Normalizes email, full_name, and phone.
  2. Rejects the request with 400 Bad Request if:
    • email is empty
    • full_name is empty
    • agree_policy is false
  3. Copies request.connected_accounts into connected_accounts_payload.
  4. If request.metadata is a dictionary, stores a deep copy under a metadata key in connected_accounts_payload.
  5. If request.identifier is present and non-empty, stores it under a second metadata key in connected_accounts_payload.
  6. Instantiates SQLAlchemyHousingApplicationRepository(db).
  7. Calls submit_housing_application.
  8. Instantiates SQLOpenBankingConsentRepository(db).
  9. Calls sync_application_plaid_consents and logs a warning if that defensive sync fails.

Data Access Layer

Frontend Application Proxy Routes

[!NOTE] create_application stores both metadata and identifier inside the connected_accounts_payload before persistence. That means the application record is written with the normalized top-level fields plus the extra metadata nested into the connected-account structure.

frontend/app/api/applications/route.ts

These routes provide the application list and submission relay used by the funnel and the reviewer dashboard. The GET handler supports HTML and JSON responses, the POST handler forwards application submissions to the backend, and the DELETE handler clears both backend and local fallback storage.

Public methods

Method Description
GET Returns the current application list as HTML or JSON, combining backend records with local fallback storage
POST Validates the payload and forwards it to backend /api/v1/applications across configured base URLs
DELETE Removes all applications from backend and local storage, then marks the local deletion state

GET behavior

  • Reads the request Accept header.
  • Uses ?format=html or ?format=json to override content negotiation.
  • Calls fetchApplicationsFromBackend when remote applications are enabled.
  • Reads stored applications with readStoredApplications().
  • Converts stored rows with hydrateStoredApplications().
  • Returns HTML when requested, otherwise JSON.

POST behavior

  • Parses the incoming JSON body into ApplicationPayload.
  • Calls validatePayload(payload) before forwarding.
  • Resolves backend base URL candidates through resolveBackendApiUrlCandidates.
  • For each candidate base URL:
    • Sends POST ${baseUrl}/api/v1/applications
    • Adds Content-Type: application/json
    • Adds Accept: application/json
    • Adds Authorization: Bearer ... when a token is available
  • Returns the backend response body on success.
  • Returns 500 if no backend base URL is configured.

DELETE behavior

  • Reads the current stored applications to determine the deleted count.
  • Calls deleteApplicationsInBackend when an auth token is available.
  • Writes an empty array through writeStoredApplications([]).
  • Clears and rewrites the deleted-all marker state.

Frontend Application Lookup Route

frontend/app/api/applications/[id]/route.ts

This route resolves a single application by numeric id, generated reference, or identifier-like metadata. It is used by the dashboard and by the read-model refresh logic.

Public methods

Method Description
collectApplicationIdentifiers Builds a set of candidate identifiers from the application id, explicit identifier, and identifier-like metadata fields
GET Loads a single application from backend storage and falls back to locally stored applications when needed

Identifier resolution behavior

  • Adds identifier variants from application.id.
  • Adds identifier variants from application.identifier.
  • Scans application.metadata for keys that indicate identifier-like values.
  • Uses the resulting candidate set to match against records loaded from backend or local storage.

This is the path that makes generated application references searchable after submission, because the review step stores application_reference in metadata and the lookup route can later match it.

Application Data Models

ApplicationPayload

frontend/app/api/applications/route.ts

This is the request shape accepted by the frontend submission proxy.

Property Type Description
id `number \ string \
email string Applicant email
phone string Applicant phone
country string Applicant country
employment_status string Employment category
financing_consent string Financing consent value
full_name string Applicant full name
date_of_birth `string \ undefined`
profession `string \ undefined`
current_employer `string \ undefined`
job_title `string \ undefined`
industry `string \ undefined`
website `string \ undefined`
linkedin `string \ undefined`
agree_policy boolean Policy acceptance
receive_updates boolean Updates opt-in
skipped_connect_accounts `boolean \ undefined`
connected_accounts `Record<string, unknown[]> \ undefined`
metadata `Record<string, unknown> \ undefined`
created_at `string \ undefined`

BackendApplication

frontend/lib/application-types.ts

This is the normalized application shape used by the frontend proxy and read-model code.

Property Type Description
id `number \ string`
identifier `string \ undefined`
email string Applicant email
phone string Applicant phone
country string Applicant country
property_type `string \ undefined`
purchase_intent `string \ undefined`
budget_range `string \ undefined`
savings `string \ undefined`
income `string \ undefined`
income_currency `string \ undefined`
employment_status string Employment category
financing_consent string Financing consent value
full_name string Applicant full name
date_of_birth `string \ undefined`
profession `string \ undefined`
current_employer `string \ undefined`
job_title `string \ undefined`
industry `string \ undefined`
website `string \ undefined`
linkedin `string \ undefined`
agree_policy boolean Policy acceptance
receive_updates boolean Updates opt-in
skipped_connect_accounts `boolean \ undefined`
connected_accounts `Record<string, unknown[]> \ undefined`
created_at string Creation timestamp
metadata `Record<string, unknown> \ undefined`
archived `boolean \ undefined`
review_status `string \ undefined`
credit_score `number \ null \
login_credentials `{ id: number; username: string; email: string; role: string; application_id: number null; temporary_password?: string

ApplicationReadModelRow

frontend/lib/server/applications.ts

Property Type Description
applicationId string Read-model identifier
applicantName string Display name
status string Review state
reviewerName `string \ null`
riskScore `number \ null`
documentState `string \ null`
lastEventAt string Timestamp of the last read-model event

DashboardKpis

frontend/lib/server/applications.ts

Property Type Description
total number Total applications
approved number Approved applications
inReview number Applications under review
denied number Denied applications

Applicants Read Model and Realtime Refresh

frontend/app/applicants/page.tsx

The applicant overview page is the main read-model consumer that verifies submitted applications appear in the dashboard. It loads applications from the API, falls back to local storage when necessary, and listens for live application updates over EventSource.

Presentation model

Property Type Description
id string Resolved route id for the applicant row
numericId `number \ null`
firstName string First name displayed in the table
secondName string Second name displayed in the table
fullName string Normalized display name
submittedAt string Creation timestamp
email string Applicant email
phone string Applicant phone
residencePermitNumber string Normalized permit number from metadata
country string Country display value
propertyType string Property type display value
budgetRange string Budget range display value
savings string Savings display value
income string Income display value
incomeCurrency string Income currency display value
status `"in_review" \ "approved" \
creditScore `number \ undefined`
affluence `AffluenceScoreSummary \ null`

Realtime applicant stream

Field Type Behavior
ApplicantStreamEvent.type `string \ undefined`
ApplicantStreamEvent.event `string \ undefined`
ApplicantStreamEvent.application_id `string \ number \
ApplicantStreamEvent.applicationId `string \ number \
ApplicantStreamEvent.id `string \ number \

Stream behavior

  • Opens an EventSource against ${baseUrl}/api/v1/applications/stream.
  • Ignores heartbeat and ping messages.
  • Calls loadSingleApplicant when the stream payload includes an application id.
  • Falls back to a full reload when the payload is blank or cannot be parsed.
  • Closes the stream and reconnects after 5 seconds on errors.
  • Runs a 30-second fallback polling interval via loadApplicants({ suppressLoading: true }).

Frontend Proxy and Read-Model Error Handling

Application submission errors

  • frontend/app/application/review/page.tsx blocks submission until a personal account exists.
  • The submit handler catches network and API errors and surfaces a generic retry message.
  • frontend/app/api/applications/route.ts returns 400 for invalid payloads and 500 when no backend base URL is configured.
  • backend/src/interface/http_endpoints.py returns 400 for missing email, missing full name, or missing policy consent.

Identifier and lookup errors

  • frontend/app/api/applications/[id]/route.ts returns 400 for malformed ids.
  • It returns 401 or 403 immediately when the backend denies access.
  • It falls back to local storage when backend lookup returns 404 or 422.
  • It treats backend 500 responses as fallback candidates for local hydration.

Feature Flows

Full Submission Path

sequenceDiagram
    participant U as Applicant
    participant A as ApplicationPage
    participant E as EmploymentPage
    participant R as ReviewPage
    participant P as Frontend API Proxy
    participant B as create_application
    participant S as submit_housing_application
    participant Q as SQLAlchemyHousingApplicationRepository
    participant D as Database
    participant C as ConfirmPage

    U->>A: Enter name email phone and consents
    A->>A: Save userFormData
    A->>E: Route to passcode then employment
    E->>E: Save nationality and employment data
    E->>R: Route to connect accounts then review
    R->>R: Load form data and connected accounts
    R->>R: Generate application reference
    R->>P: POST /api/v1/applications
    P->>B: Forward JSON payload
    B->>S: Build HousingApplication
    S->>Q: create application
    Q->>D: Insert row
    D-->>Q: Persisted record
    Q-->>S: HousingApplication
    S-->>B: HousingApplication
    B-->>P: Created response
    P-->>R: JSON result
    R->>R: Store application reference
    R->>C: Navigate to confirm

Read Model Lookup and Refresh

sequenceDiagram
    participant V as ApplicantsPage
    participant X as EventSource stream
    participant G as GET application lookup route
    participant L as Local storage fallback
    participant B as Backend application source

    V->>X: Open stream connection
    X-->>V: Message payload
    V->>V: Parse event and resolve application id
    V->>G: Request applicant by id or reference
    G->>B: Fetch backend application
    B-->>G: BackendApplication or not found
    G->>L: Hydrate stored applications when needed
    L-->>G: Stored fallback rows
    G-->>V: Refreshed applicant row

API Integration

Submit Application

POST /api/v1/applications

Submits the final application from the review page and relays it to the backend application service.

{
    "title": "Submit Application",
    "description": "Submits the final housing application from the review step and relays it to backend storage",
    "method": "POST",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/v1/applications",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        },
        {
            "key": "Accept",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"id\": \"app-local-20260331-0001\",\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1 555 010 2048\",\n    \"country\": \"US\",\n    \"employment_status\": \"self_employed\",\n    \"financing_consent\": \"granted\",\n    \"full_name\": \"Ahmed Ali\",\n    \"date_of_birth\": \"1990-06-14\",\n    \"profession\": \"Product Designer\",\n    \"current_employer\": \"Aurora Studio\",\n    \"job_title\": \"Founder\",\n    \"industry\": \"Design\",\n    \"website\": \"https://example.com\",\n    \"linkedin\": \"https://linkedin.com/in/ahmedali\",\n    \"agree_policy\": true,\n    \"receive_updates\": true,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": {\n        \"personal\": [\n            {\n                \"name\": \"Personal Checking\",\n                \"account_id\": \"acc_001\",\n                \"balance\": 12800\n            }\n        ],\n        \"business\": [\n            {\n                \"name\": \"Business Checking\",\n                \"account_id\": \"acc_101\",\n                \"balance\": 45200\n            }\n        ],\n        \"investments\": [\n            {\n                \"name\": \"Retirement Account\",\n                \"account_id\": \"acc_201\",\n                \"balance\": 88000\n            }\n        ]\n    },\n    \"metadata\": {\n        \"application_reference\": \"LITA-20260331-0001\",\n        \"residence_permit_number\": \"RP-774412\",\n        \"country\": \"US\",\n        \"financing_consent\": \"granted\"\n    },\n    \"created_at\": \"2026-03-31T15:04:05.000Z\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Application created and persisted",
            "body": "{\n    \"id\": 1024,\n    \"identifier\": \"app-local-20260331-0001\",\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1 555 010 2048\",\n    \"country\": \"US\",\n    \"property_type\": \"apartment\",\n    \"purchase_intent\": \"buy\",\n    \"budget_range\": \"250000-300000\",\n    \"savings\": \"60000\",\n    \"income\": \"98000\",\n    \"income_currency\": \"USD\",\n    \"employment_status\": \"self_employed\",\n    \"financing_consent\": \"granted\",\n    \"full_name\": \"Ahmed Ali\",\n    \"date_of_birth\": \"1990-06-14\",\n    \"profession\": \"Product Designer\",\n    \"current_employer\": \"Aurora Studio\",\n    \"job_title\": \"Founder\",\n    \"industry\": \"Design\",\n    \"website\": \"https://example.com\",\n    \"linkedin\": \"https://linkedin.com/in/ahmedali\",\n    \"agree_policy\": true,\n    \"receive_updates\": true,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": {\n        \"personal\": [\n            {\n                \"name\": \"Personal Checking\",\n                \"account_id\": \"acc_001\",\n                \"balance\": 12800\n            }\n        ],\n        \"business\": [\n            {\n                \"name\": \"Business Checking\",\n                \"account_id\": \"acc_101\",\n                \"balance\": 45200\n            }\n        ],\n        \"investments\": [\n            {\n                \"name\": \"Retirement Account\",\n                \"account_id\": \"acc_201\",\n                \"balance\": 88000\n            }\n        ]\n    },\n    \"created_at\": \"2026-03-31T15:04:05.000Z\",\n    \"metadata\": {\n        \"application_reference\": \"LITA-20260331-0001\",\n        \"residence_permit_number\": \"RP-774412\",\n        \"country\": \"US\",\n        \"financing_consent\": \"granted\"\n    },\n    \"archived\": false,\n    \"review_status\": \"pending\",\n    \"credit_score\": 742,\n    \"login_credentials\": null\n}"
        }
    }
}

Application List Read Model

GET /api/applications?format=json

Returns the application read model as JSON. The visible route can also return HTML when the browser requests it, but the onboarding and reviewer flows use the JSON variant.

{
    "title": "Get Application List",
    "description": "Returns the merged application list from backend storage and local fallback storage",
    "method": "GET",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/applications",
    "headers": [
        {
            "key": "Accept",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [
        {
            "key": "format",
            "value": "json",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Merged applicant list",
            "body": "[\n    {\n        \"id\": 1024,\n        \"identifier\": \"app-local-20260331-0001\",\n        \"email\": \"[email protected]\",\n        \"phone\": \"+1 555 010 2048\",\n        \"country\": \"US\",\n        \"property_type\": \"apartment\",\n        \"purchase_intent\": \"buy\",\n        \"budget_range\": \"250000-300000\",\n        \"savings\": \"60000\",\n        \"income\": \"98000\",\n        \"income_currency\": \"USD\",\n        \"employment_status\": \"self_employed\",\n        \"financing_consent\": \"granted\",\n        \"full_name\": \"Ahmed Ali\",\n        \"date_of_birth\": \"1990-06-14\",\n        \"profession\": \"Product Designer\",\n        \"current_employer\": \"Aurora Studio\",\n        \"job_title\": \"Founder\",\n        \"industry\": \"Design\",\n        \"website\": \"https://example.com\",\n        \"linkedin\": \"https://linkedin.com/in/ahmedali\",\n        \"agree_policy\": true,\n        \"receive_updates\": true,\n        \"skipped_connect_accounts\": false,\n        \"connected_accounts\": {\n            \"personal\": [\n                {\n                    \"name\": \"Personal Checking\",\n                    \"account_id\": \"acc_001\",\n                    \"balance\": 12800\n                }\n            ],\n            \"business\": [\n                {\n                    \"name\": \"Business Checking\",\n                    \"account_id\": \"acc_101\",\n                    \"balance\": 45200\n                }\n            ],\n            \"investments\": [\n                {\n                    \"name\": \"Retirement Account\",\n                    \"account_id\": \"acc_201\",\n                    \"balance\": 88000\n                }\n            ]\n        },\n        \"created_at\": \"2026-03-31T15:04:05.000Z\",\n        \"metadata\": {\n            \"application_reference\": \"LITA-20260331-0001\",\n            \"residence_permit_number\": \"RP-774412\",\n            \"country\": \"US\",\n            \"financing_consent\": \"granted\"\n        },\n        \"archived\": false,\n        \"review_status\": \"pending\",\n        \"credit_score\": 742,\n        \"login_credentials\": null\n    }\n]"
        }
    }
}

Application Lookup Read Model

GET /api/applications/{id}

Resolves a single application by numeric id, generated application reference, or identifier-like metadata.

{
    "title": "Get Application By Id",
    "description": "Resolves a single application from backend storage or local fallback storage using id, identifier, or reference metadata",
    "method": "GET",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/applications/{id}",
    "headers": [
        {
            "key": "Accept",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "app-local-20260331-0001",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Resolved application record",
            "body": "{\n    \"id\": 1024,\n    \"identifier\": \"app-local-20260331-0001\",\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1 555 010 2048\",\n    \"country\": \"US\",\n    \"property_type\": \"apartment\",\n    \"purchase_intent\": \"buy\",\n    \"budget_range\": \"250000-300000\",\n    \"savings\": \"60000\",\n    \"income\": \"98000\",\n    \"income_currency\": \"USD\",\n    \"employment_status\": \"self_employed\",\n    \"financing_consent\": \"granted\",\n    \"full_name\": \"Ahmed Ali\",\n    \"date_of_birth\": \"1990-06-14\",\n    \"profession\": \"Product Designer\",\n    \"current_employer\": \"Aurora Studio\",\n    \"job_title\": \"Founder\",\n    \"industry\": \"Design\",\n    \"website\": \"https://example.com\",\n    \"linkedin\": \"https://linkedin.com/in/ahmedali\",\n    \"agree_policy\": true,\n    \"receive_updates\": true,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": {\n        \"personal\": [\n            {\n                \"name\": \"Personal Checking\",\n                \"account_id\": \"acc_001\",\n                \"balance\": 12800\n            }\n        ],\n        \"business\": [\n            {\n                \"name\": \"Business Checking\",\n                \"account_id\": \"acc_101\",\n                \"balance\": 45200\n            }\n        ],\n        \"investments\": [\n            {\n                \"name\": \"Retirement Account\",\n                \"account_id\": \"acc_201\",\n                \"balance\": 88000\n            }\n        ]\n    },\n    \"created_at\": \"2026-03-31T15:04:05.000Z\",\n    \"metadata\": {\n        \"application_reference\": \"LITA-20260331-0001\",\n        \"residence_permit_number\": \"RP-774412\",\n        \"country\": \"US\",\n        \"financing_consent\": \"granted\"\n    },\n    \"archived\": false,\n    \"review_status\": \"pending\",\n    \"credit_score\": 742,\n    \"login_credentials\": null\n}"
        }
    }
}

State Management

Browser storage keys

Key Used by Purpose
"userFormData" Application and employment pages Stores the applicant’s partial form data across steps
APPLICATION_REFERENCE_STORAGE_KEY Review page Stores the generated application reference after successful submission
CONNECTED_ACCOUNTS_STORAGE_KEY Review page Stores connected accounts loaded before review
CONNECTION_CATEGORY_STORAGE_KEY Review page Stores the account category state used in the connected-accounts flow
SALTEDGE_CUSTOMER_STORAGE_KEY Review page Cleared after successful submission
APPLICANT_NAMES_STORAGE_KEY Applicants page Stores derived names for previously seen applicants
ARCHIVED_APPLICANT_IDS_STORAGE_KEY Applicants page Stores ids hidden from the reviewer list

Progression rules

  • ApplicationPage requires a valid email and both consents before enabling Next.
  • ReviewPage requires at least one personal account.
  • create_application requires non-empty email, non-empty full_name, and agree_policy=true.
  • ApplicantsPage uses review_status to drive the reviewer status pill and uses connected-account presence to fall back to hold.

Integration Points

  • frontend/app/application/page.tsx persists early applicant identity.
  • frontend/app/application/employment/page.tsx persists citizenship and employment.
  • frontend/app/application/review/page.tsx composes the final submission payload and generates the reference.
  • frontend/app/api/applications/route.ts relays the final payload to backend storage and serves the merged read model.
  • frontend/app/api/applications/[id]/route.ts resolves applications by id or reference for dashboards and follow-up lookup.
  • backend/src/usecase/housing_application.py persists a HousingApplication aggregate.
  • backend/src/interface/http_endpoints.py validates policy consent and synchronizes open-banking consents after creation.
  • frontend/app/applicants/page.tsx verifies that persisted applications show up in the reviewer list and supports live refresh.

Error Handling

Submission and validation

  • ApplicationPage shows inline email validation when the input is non-empty and fails the regex.
  • ReviewPage blocks submit and surfaces Connect at least one personal account before submitting. when no personal account is connected.
  • ReviewPage catches final submission failures and shows Unable to finalise your application. Please try again.
  • create_application returns 400 for missing email, missing full name, or missing policy consent.
  • backend/src/interface/http_endpoints.py wraps submit_housing_application ValueError exceptions in HTTPException with 400 Bad Request.

Proxy and lookup fallbacks

  • frontend/app/api/applications/route.ts falls back to local stored applications when backend listing fails.
  • frontend/app/api/applications/[id]/route.ts falls back to stored applications when backend lookup returns 404, 422, or selected 5xx responses.
  • ApplicantsPage reloads the entire read model when the stream payload cannot be parsed or does not contain a resolvable application id.

Caching Strategy

Browser-side persistence

  • Partial onboarding data is stored in localStorage and reused across page transitions.
  • The review step stores the final application reference after success.
  • The review step clears the saltedge customer marker after successful submission.

Frontend proxy storage

  • The application list route merges backend records with readStoredApplications() results.
  • The delete-all path rewrites the stored list to an empty array and writes the deleted-all marker state.
  • GET requests in the proxy layer use cache: "no-store" for backend and stored reads.
  • The applicants page performs a 30-second fallback refresh in addition to the live stream.

Testing Considerations

  • Verify the application step rejects empty name, invalid email, missing phone, or missing consent.
  • Verify the employment step preserves existing userFormData and routes to /application/connect-accounts with the expected query string.
  • Verify the review step refuses submission without a personal account.
  • Verify the review step writes APPLICATION_REFERENCE_STORAGE_KEY and redirects to /application/confirm.
  • Verify POST /api/v1/applications accepts the final payload and returns a created application response.
  • Verify GET /api/applications?format=json merges backend and local fallback data.
  • Verify GET /api/applications/{id} resolves both numeric ids and generated application references.
  • Verify the reviewer overview updates when a streamed event carries an application id.
  • Verify the backend handler stores review_status="pending" on newly created applications.

Key Classes Reference

Class Responsibility
page.tsx Captures the first application details and launches the passcode handoff
employment/page.tsx Stores citizenship and employment data before account connection
review/page.tsx Generates the application reference and submits the final payload
confirm/page.tsx Shows the post-submission confirmation state
housing_application.py Persists the application aggregate through the repository
http_endpoints.py Validates incoming submissions and synchronizes consent data
route.ts Relays, lists, and clears application records through the frontend proxy
[id]/route.ts Resolves a single application by id or reference
application-types.ts Defines the shared backend application data shape
applications.ts Defines the read-model row and dashboard KPI shapes
applicants/page.tsx Displays the reviewer read model and handles live refresh