Application Management Domain API

Overview

This domain exposes the application lifecycle through Next.js route handlers under frontend/app/api/applications/ and the mirrored compatibility routes under frontend/app/api/v1/applications/. The collection endpoints support listing, creating, and deleting applications; the item endpoints support lookup, archive, and review-status updates; the projection endpoint reshapes raw application records into dashboard rows; and the verification/provisioning endpoints handle passcode confirmation and account onboarding flow control.

The implementation is hybrid by design. Some handlers proxy backend functionality directly, some add request shaping and local persistence fallback, and some are frontend-only orchestration endpoints such as run-check and the read-model projection. The result is a single application-management surface that can keep working when the backend is unavailable, while still preferring backend state whenever an authenticated backend call succeeds.

Architecture Overview

flowchart TB
    Client[Client or Server Consumer]

    subgraph AppRoutes[Next.js Application Routes]
        Collection[Application collection handlers]
        ItemLookup[Application item lookup]
        ItemMutation[Archive and status handlers]
        ReadModel[Read model projection]
        VerifyPasscode[Verify passcode handler]
        ProvisionAccount[Provision account handler]
        RunCheck[Run check handler]
        V1Compat[V1 compatibility re exports]
    end

    subgraph Shared[Shared Application Helpers]
        Common[common ts]
    end

    subgraph Data[Data and External Systems]
        BackendApi[Backend application API]
        SaltEdge[Salt Edge customers API]
        LocalStore[Local application store]
        JobQueue[Worker queue]
    end

    subgraph ServerConsumers[Server Read Model Consumers]
        Dashboard[Dashboard KPI consumer]
        PageData[Applications page consumer]
    end

    Client --> Collection
    Client --> ItemLookup
    Client --> ItemMutation
    Client --> ReadModel
    Client --> VerifyPasscode
    Client --> ProvisionAccount
    Client --> RunCheck

    Collection --> Common
    ItemLookup --> Common
    ItemMutation --> Common
    VerifyPasscode --> Common
    ReadModel --> Collection
    V1Compat --> Collection
    V1Compat --> ItemLookup
    V1Compat --> ItemMutation
    V1Compat --> ReadModel
    V1Compat --> VerifyPasscode
    V1Compat --> ProvisionAccount

    Common --> BackendApi
    Common --> SaltEdge
    Common --> LocalStore

    RunCheck --> JobQueue

    Dashboard --> ReadModel
    PageData --> ReadModel

Shared Application Proxy and Storage Helpers

frontend/app/api/applications/common.ts

This module contains the shared backend proxying, auth extraction, URL resolution, and local-store helper functions used by the application routes. It is the main reason the application surface can fall back to stored records when the backend or a backend endpoint is unavailable.

Public Functions

Method Description
buildErrorResponse Returns a JSON error envelope with a detail message and HTTP status.
extractAuthToken Reads a bearer token from Authorization or the auth cookie.
resolveBackendApiUrlCandidates Builds a candidate list of backend URLs from environment values, Docker-friendly fallbacks, and the current request origin.
resolveRequestOriginCandidate Resolves the request origin so the route can avoid proxying back into the frontend origin.
fetchApplicationsFromBackend Fetches and paginates Salt Edge customer data, maps it into application records, deduplicates by id, and returns the merged application list.
fetchBackendApplicationById Fetches one application record from the backend application API by id.
deleteApplicationsInBackend Sends a backend delete request for the full application collection and returns the deleted count when available.
archiveApplicationInBackend Sends the backend archive request for one numeric application id.
updateApplicationReviewStatusInBackend Sends the backend review-status update for one numeric application id.
hydrateStoredApplications Normalizes locally stored application records before they are merged into responses.
readStoredApplications Reads the fallback application store from the resolved local data file.
writeStoredApplications Persists the fallback application store to the resolved local data file.
hasDeletedAllMarker Checks whether the collection delete marker is present.
clearDeletedAllMarker Removes the collection delete marker.
writeDeletedAllMarker Writes the collection delete marker after a local collection delete.

Data Flow and Retry Behavior

  • resolveBackendApiUrlCandidates builds a candidate list from:
    • BACKEND_API_URL
    • API_BASE_URL
    • NEXT_PUBLIC_BACKEND_API_URL
    • VITE_BACKEND_API_URL
    • Docker and localhost fallbacks
    • the current request origin
  • extractAuthToken supports both bearer auth and the auth cookie, which lets the same route work from browser sessions and server-side calls.
  • fetchApplicationsFromBackend uses the backend /api/saltedge/customers list API, paginates through results, maps each customer into an application object, and stops when it reaches the pagination limit or detects a repeated cursor.
  • fetchBackendApplicationById, archiveApplicationInBackend, deleteApplicationsInBackend, and updateApplicationReviewStatusInBackend all retry across candidate base URLs and skip over missing endpoints or retryable network failures.
  • The local-store helpers are used as write-through fallback state and as the source of the deleted-all marker that suppresses stale list results.

Persistence and State Inputs

  • The fallback store is resolved through DATA_FILE_PATH = resolveDataFilePath().
  • Local records are hydrated before being returned so the frontend sees the same shape whether the record came from the backend or the fallback store.
  • The delete marker is part of collection-level state management, not the application record itself.

Request and Response Shapes

Application Payload

Used by POST /api/applications.

Property Type Description
id `number \ string`
email string Applicant email address.
phone string Applicant phone number.
country string Applicant country code or name.
employment_status string Employment status text.
financing_consent string Financing consent flag as text.
full_name string Applicant full name.
date_of_birth string Optional date of birth string.
profession string Optional profession.
current_employer string Optional current employer.
job_title string Optional job title.
industry string Optional industry.
website string Optional personal or company website.
linkedin string Optional LinkedIn URL.
agree_policy boolean Policy consent flag.
receive_updates boolean Marketing or update consent flag.
skipped_connect_accounts boolean Optional flag for skipped account linking.
connected_accounts Record<string, unknown[]> Optional connected-account data.
metadata Record<string, unknown> Optional free-form metadata.
created_at string Optional creation timestamp.

Backend Application Record

Used by GET /api/applications, GET /api/applications/[id], and the mirrored v1 routes.

Property Type Description
id `number \ string`
identifier string Optional alternate identifier used by lookup routes.
email string Applicant email.
phone string Applicant phone.
country string Applicant country.
employment_status string Employment status.
financing_consent string Financing consent text.
full_name string Applicant full name.
date_of_birth string Date of birth string.
profession string Profession string.
current_employer string Current employer string.
job_title string Job title string.
industry string Industry string.
website string Website string.
linkedin string LinkedIn string.
agree_policy boolean Policy consent.
receive_updates boolean Updates consent.
skipped_connect_accounts boolean Account-linking skip flag.
connected_accounts Record<string, unknown[]> Connected account groups.
created_at string Creation timestamp.
metadata Record<string, unknown> Free-form backend metadata.
archived boolean Archive flag used by local hydration and backend records.
review_status string Review state used by archive/status/read-model flows.
credit_score number Optional credit score used by the read-model projection.
updated_at string Optional last update timestamp used by the read-model projection.

Application Read Model Row

Used by GET /api/applications/read-model and frontend/lib/server/applications.ts.

Property Type Description
applicationId string Stable row identifier derived from id or identifier.
applicantName string Display name derived from full_name, email, or a fallback label.
status string Projected review status.
reviewerName null Fixed null in the current projection.
riskScore `number \ null`
documentState null Fixed null in the current projection.
lastEventAt string updated_at, created_at, or the current timestamp fallback.

Status Update Payload

Used by PATCH /api/applications/[id]/status and the mirrored v1 route.

Property Type Description
status `"in_review" \ "approved" \

Archive Response

Used by POST /api/applications/[id]/archive and the mirrored v1 route.

Property Type Description
archived boolean Indicates the record was archived or removed from the local fallback store.

Delete Applications Response

Used by DELETE /api/applications and the mirrored v1 route.

Property Type Description
deleted number Number of applications removed remotely or from the local fallback store.

Application Creation Fallback Response

Used by the local fallback branch in POST /api/applications.

Property Type Description
id number Locally assigned fallback id.
created_at string Creation timestamp assigned by the route.
persisted string Fixed value local_fallback.
detail string Human-readable explanation of the fallback save path.

Verify Passcode Request

Used by POST /api/applications/verify-passcode and the mirrored v1 route.

Property Type Description
email string Required email address.
fullName string Optional full name override.
passcode string Required 6-digit passcode.
phone string Optional phone number used by the fallback application create.
country string Optional country used by the fallback application create.

Verify Passcode Response

Used by POST /api/applications/verify-passcode and the mirrored v1 route.

Property Type Description
ok boolean Success flag returned on both backend-success and local-fallback success paths.
email string Normalized lowercase email.
message string Success message chosen by the route.
token string Synthetic guest token written into the auth cookie.
user object Session user envelope.

User Envelope

Property Type Description
id number Timestamp-based user id.
username string Local username derived from the email prefix.
email string Normalized lowercase email.
role string admin for configured admin emails, otherwise applicant.
fullName string Resolved full name.
applicationId `number \ string`

Provision Account Payload

Used by POST /api/applications/provision-account and the mirrored v1 route.

Property Type Description
email string Optional email address.
fullName string Optional full name.

Provision Account Response

Declared in frontend/app/api/applications/provision-account/route.ts.

Property Type Description
email string Declared response field.
password `string \ null`
status `"created" \ "exists"`
userId string Declared response field.

Run Check Response

[!NOTE] The provision-account handler returns { "status": "disabled" } with HTTP 200. The declared ProvisionAccountResponse shape is present in the file, but the handler does not emit that declared payload.

Used by POST /api/applications/[id]/run-check.

Property Type Description
ok boolean Indicates the enqueue request succeeded.
status string Fixed processing value.
applicationId string Application id passed into the job payload.
jobId string Queue job id returned by enqueueApplicationJob.

Dashboard KPI Shape

Used by frontend/lib/server/applications.ts.

Property Type Description
total number Total applications counted from the read-model rows.
approved number Count of rows with status normalized to approved.
inReview number Count of rows with any non-approved, non-denied status.
denied number Count of rows with status normalized to denied.

Endpoint Patterns

Pattern Routes Behavior
Raw collection CRUD GET /api/applications, POST /api/applications, DELETE /api/applications List, create, and clear the whole collection. These handlers prefer backend state but fall back to the local store.
Item lookup GET /api/applications/[id] Resolves by id, identifier, and identifier-like metadata fields, then merges backend and stored data before returning a single application.
State transitions POST /api/applications/[id]/archive, PATCH /api/applications/[id]/status Mutate one application record, require auth, and synchronize both backend and local fallback state when possible.
Projection GET /api/applications/read-model Builds dashboard rows from the application list instead of returning raw application objects.
Bootstrap verification POST /api/applications/verify-passcode Verifies a passcode with the backend when possible, then creates local session state and an auth cookie.
Disabled onboarding stub POST /api/applications/provision-account Consumes the request body and returns a disabled acknowledgement.
Job trigger POST /api/applications/[id]/run-check Enqueues a credit-check job instead of proxying backend data directly.

Root Application Collection Endpoints

frontend/app/api/applications/route.ts

This file owns the collection-level handlers and the local deleted-all marker lifecycle. The GET handler can serve HTML or JSON, the POST handler can create remotely or fall back to a local persisted record, and the DELETE handler clears both remote and local application data.

Collection Handlers

Method Description
GET Lists applications, optionally as HTML, and merges backend results with local fallback data.
POST Validates and creates an application, prefers backend persistence, and falls back to a local record when the backend fails.
DELETE Removes all applications remotely when auth is available and always clears the local fallback collection.

List Applications

frontend/app/api/applications/route.ts

{
    "title": "List Applications",
    "description": "Returns the application collection as HTML or JSON. The JSON path merges backend applications from /api/v1/applications with local stored applications and is suppressed when the deleted-all marker is present.",
    "method": "GET",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/applications",
    "headers": [],
    "queryParams": [
        {
            "key": "format",
            "value": "json",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "JSON success response",
            "body": "[\n    {\n        \"id\": 1024,\n        \"identifier\": \"app-1024\",\n        \"email\": \"[email protected]\",\n        \"phone\": \"+1-512-555-0148\",\n        \"country\": \"US\",\n        \"employment_status\": \"employed\",\n        \"financing_consent\": \"yes\",\n        \"full_name\": \"Aya Mendez\",\n        \"date_of_birth\": \"1991-04-12\",\n        \"profession\": \"Architect\",\n        \"current_employer\": \"Mendez Studio\",\n        \"job_title\": \"Lead Architect\",\n        \"industry\": \"Design\",\n        \"website\": \"https://mendezstudio.example\",\n        \"linkedin\": \"https://www.linkedin.com/in/ayamendez\",\n        \"agree_policy\": true,\n        \"receive_updates\": false,\n        \"skipped_connect_accounts\": false,\n        \"connected_accounts\": {\n            \"checking\": []\n        },\n        \"created_at\": \"2026-04-26T12:34:56.000Z\",\n        \"metadata\": {\n            \"risk_score\": 712,\n            \"review_status\": \"in_review\"\n        },\n        \"archived\": false,\n        \"review_status\": \"in_review\",\n        \"credit_score\": 712,\n        \"updated_at\": \"2026-04-26T12:35:10.000Z\"\n    }\n]"
        }
    }
}

Create Application

frontend/app/api/applications/route.ts

{
    "title": "Create Application",
    "description": "Creates an application in the backend when possible, otherwise writes a local fallback record and returns a local persistence envelope. Successful backend writes clear the deleted-all marker.",
    "method": "POST",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/applications",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"id\": \"app-1024\",\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1-512-555-0148\",\n    \"country\": \"US\",\n    \"employment_status\": \"employed\",\n    \"financing_consent\": \"yes\",\n    \"full_name\": \"Aya Mendez\",\n    \"date_of_birth\": \"1991-04-12\",\n    \"profession\": \"Architect\",\n    \"current_employer\": \"Mendez Studio\",\n    \"job_title\": \"Lead Architect\",\n    \"industry\": \"Design\",\n    \"website\": \"https://mendezstudio.example\",\n    \"linkedin\": \"https://www.linkedin.com/in/ayamendez\",\n    \"agree_policy\": true,\n    \"receive_updates\": false,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": {\n        \"checking\": []\n    },\n    \"metadata\": {\n        \"source\": \"web\",\n        \"campaign\": \"spring-intake\"\n    },\n    \"created_at\": \"2026-04-26T12:34:56.000Z\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Backend passthrough success",
            "body": "{\n    \"id\": 1024,\n    \"identifier\": \"app-1024\",\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1-512-555-0148\",\n    \"country\": \"US\",\n    \"employment_status\": \"employed\",\n    \"financing_consent\": \"yes\",\n    \"full_name\": \"Aya Mendez\",\n    \"date_of_birth\": \"1991-04-12\",\n    \"profession\": \"Architect\",\n    \"current_employer\": \"Mendez Studio\",\n    \"job_title\": \"Lead Architect\",\n    \"industry\": \"Design\",\n    \"website\": \"https://mendezstudio.example\",\n    \"linkedin\": \"https://www.linkedin.com/in/ayamendez\",\n    \"agree_policy\": true,\n    \"receive_updates\": false,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": {\n        \"checking\": []\n    },\n    \"created_at\": \"2026-04-26T12:34:56.000Z\",\n    \"metadata\": {\n        \"source\": \"web\",\n        \"campaign\": \"spring-intake\"\n    },\n    \"archived\": false,\n    \"review_status\": \"in_review\",\n    \"credit_score\": 712,\n    \"updated_at\": \"2026-04-26T12:35:10.000Z\"\n}"
        },
        "201": {
            "description": "Local fallback success",
            "body": "{\n    \"id\": 1025,\n    \"created_at\": \"2026-04-26T12:34:56.000Z\",\n    \"persisted\": \"local_fallback\",\n    \"detail\": \"Backend persistence is currently unavailable. Saved locally so submission can continue.\"\n}"
        }
    }
}

Delete Applications

frontend/app/api/applications/route.ts

{
    "title": "Delete Applications",
    "description": "Deletes the collection in the backend when an auth token is available, then clears the local fallback store and writes the deleted-all marker.",
    "method": "DELETE",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/applications",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"deleted\": 3\n}"
        }
    }
}

Application Item Endpoints

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

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

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

These routes work on one application at a time. The lookup route is read-only and identifier-aware. The archive and status routes are write-through mutations that require auth and then synchronize local storage if the backend is unreachable or cannot resolve the record.

Item Handlers

Method Description
GET Resolves one application by id, identifier, or identifier-like metadata.
POST Archives one application and removes the matching local fallback record.
PATCH Updates one application review status and mirrors that change into local storage.

Get Application

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

{
    "title": "Get Application",
    "description": "Returns one application record by matching the requested id against id, identifier, and identifier-like metadata values. The handler prefers backend data and falls back to the merged local and backend application list when the backend cannot resolve the record.",
    "method": "GET",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/applications/{id}",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "1024",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"id\": 1024,\n    \"identifier\": \"app-1024\",\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1-512-555-0148\",\n    \"country\": \"US\",\n    \"employment_status\": \"employed\",\n    \"financing_consent\": \"yes\",\n    \"full_name\": \"Aya Mendez\",\n    \"date_of_birth\": \"1991-04-12\",\n    \"profession\": \"Architect\",\n    \"current_employer\": \"Mendez Studio\",\n    \"job_title\": \"Lead Architect\",\n    \"industry\": \"Design\",\n    \"website\": \"https://mendezstudio.example\",\n    \"linkedin\": \"https://www.linkedin.com/in/ayamendez\",\n    \"agree_policy\": true,\n    \"receive_updates\": false,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": {\n        \"checking\": []\n    },\n    \"created_at\": \"2026-04-26T12:34:56.000Z\",\n    \"metadata\": {\n        \"source\": \"web\",\n        \"review_status\": \"in_review\"\n    },\n    \"archived\": false,\n    \"review_status\": \"in_review\",\n    \"credit_score\": 712,\n    \"updated_at\": \"2026-04-26T12:35:10.000Z\"\n}"
        },
        "400": {
            "description": "Invalid application id",
            "body": "{\n    \"detail\": \"Invalid application id\"\n}"
        },
        "404": {
            "description": "Application not found",
            "body": "{\n    \"detail\": \"Application not found\"\n}"
        }
    }
}

Archive Application

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

{
    "title": "Archive Application",
    "description": "Archives one application after resolving the requested id to a numeric backend id when needed. Auth is required, and the route also removes any matching local fallback record.",
    "method": "POST",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/applications/{id}/archive",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "1024",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"archived\": true\n}"
        },
        "401": {
            "description": "Authentication required",
            "body": "{\n    \"detail\": \"Authentication required\"\n}"
        },
        "404": {
            "description": "Application not found",
            "body": "{\n    \"detail\": \"Application not found.\"\n}"
        }
    }
}

Update Application Status

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

{
    "title": "Update Application Status",
    "description": "Updates the review status for one application. Auth is required, the requested status is validated against the review-status enum, and local fallback data is updated when the backend call fails or the record only exists in local storage.",
    "method": "PATCH",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/applications/{id}/status",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "1024",
            "required": true
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"status\": \"approved\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"id\": \"1024\",\n    \"status\": \"approved\",\n    \"updated\": true\n}"
        },
        "400": {
            "description": "Invalid payload",
            "body": "{\n    \"detail\": \"Invalid review status payload\"\n}"
        },
        "401": {
            "description": "Authentication required",
            "body": "{\n    \"detail\": \"Authentication required\"\n}"
        },
        "404": {
            "description": "Application not found",
            "body": "{\n    \"detail\": \"Application not found\"\n}"
        }
    }
}

Archive and Status Pattern Notes

  • archive is a mutation that removes the record from view and local storage.
  • status is a review-state transition that only updates review_status.
  • Both routes are backend-first when a numeric backend id can be resolved.
  • Both routes write through to the local fallback store so the UI stays consistent when the backend call fails.

Read Model Projection

frontend/app/api/applications/read-model/route.ts

The read-model route is not raw CRUD. It fetches the application list from /api/v1/applications?format=json, then projects each application into a dashboard-friendly row with a normalized status, computed risk score, and a stable display id.

Projection Rules

  • status comes from review_status:
    • approved
    • denied
    • hold
    • in_review for everything else
  • riskScore comes from credit_score, then metadata.risk_score, then null.
  • lastEventAt uses updated_at, then created_at, then the current time.
  • reviewerName and documentState are fixed null values in the current projection.

Read Model

frontend/app/api/applications/read-model/route.ts

{
    "title": "Get Application Read Model",
    "description": "Projects the application list into dashboard rows. The handler fetches the list from /api/v1/applications?format=json, normalizes status and risk score fields, and emits a read-model array instead of raw application objects.",
    "method": "GET",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/applications/read-model",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"applicationId\": \"1024\",\n        \"applicantName\": \"Aya Mendez\",\n        \"status\": \"in_review\",\n        \"reviewerName\": null,\n        \"riskScore\": 712,\n        \"documentState\": null,\n        \"lastEventAt\": \"2026-04-26T12:35:10.000Z\"\n    }\n]"
        },
        "502": {
            "description": "Read-model source unavailable",
            "body": "{\n    \"detail\": \"Failed to load applications\"\n}"
        }
    }
}

Server Read Model Consumers

frontend/lib/server/applications.ts

These functions consume the read-model route from server code.

Method Description
getDashboardKpis Fetches the read model with a 30-second revalidation window and reduces it into KPI totals.
getApplicationsPage Fetches the read model with no-store so the page sees the current projection immediately.

Read Model Consumer Flow

sequenceDiagram
    participant S as Server Consumer
    participant A as Read Model Route
    participant L as List Route
    participant B as Backend List
    participant R as Result

    S->>A: GET read model
    A->>L: GET applications list
    L->>B: GET backend list or stored data
    B-->>L: application list
    L-->>A: raw application array
    A-->>S: projected rows

Dashboard KPI Caching

Method Cache strategy Cache key or scope
getDashboardKpis revalidate: 30 dashboard-kpis tag
getApplicationsPage no-store No cached page result

Passcode Verification and Provisioning

frontend/app/api/applications/verify-passcode/route.ts

frontend/app/api/applications/provision-account/route.ts

These handlers are not raw CRUD. verify-passcode is a hybrid bootstrap endpoint that requires auth, normalizes user input, forwards to the backend when possible, and then issues a local session cookie. provision-account is an explicit disabled stub that accepts a request body and returns a stable acknowledgement.

Verification and Provisioning Handlers

Method Description
POST Verifies a passcode, creates a session token, and falls back to local application creation when backend verification succeeds or is unavailable.
POST Consumes the body and returns a disabled acknowledgement for account provisioning.

Verify Passcode

frontend/app/api/applications/verify-passcode/route.ts

{
    "title": "Verify Passcode",
    "description": "Normalizes the email, validates the 6-digit passcode, forwards the request to the backend verify-passcode endpoint, and then issues a local auth cookie and session payload. When the backend verification path is unavailable, the route still creates a local application record and returns a success envelope.",
    "method": "POST",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/applications/verify-passcode",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\",\n    \"fullName\": \"Aya Mendez\",\n    \"passcode\": \"123456\",\n    \"phone\": \"+1-512-555-0148\",\n    \"country\": \"US\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Verification success",
            "body": "{\n    \"ok\": true,\n    \"email\": \"[email protected]\",\n    \"message\": \"Verification successful\",\n    \"token\": \"guest-token-1714134896000\",\n    \"user\": {\n        \"id\": 1714134896000,\n        \"username\": \"aya.mendez\",\n        \"email\": \"[email protected]\",\n        \"role\": \"applicant\",\n        \"fullName\": \"Aya Mendez\",\n        \"applicationId\": 1024\n    }\n}"
        },
        "400": {
            "description": "Validation failure",
            "body": "{\n    \"error\": \"Valid 6-digit passcode is required\"\n}"
        },
        "401": {
            "description": "Authentication required",
            "body": "{\n    \"detail\": \"Authentication required\"\n}"
        }
    }
}

Provision Account

frontend/app/api/applications/provision-account/route.ts

{
    "title": "Provision Account",
    "description": "Consumes the request body and returns a disabled acknowledgement instead of creating an account. The route is intentionally silent and does not proxy backend provisioning.",
    "method": "POST",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/applications/provision-account",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\",\n    \"fullName\": \"Aya Mendez\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Disabled acknowledgement",
            "body": "{\n    \"status\": \"disabled\"\n}"
        }
    }
}

Run Check Trigger

frontend/app/api/applications/[id]/run-check/route.ts

This handler is frontend-only orchestration. It does not proxy backend application data; instead it validates the id and enqueues a run-credit-check job through enqueueApplicationJob.

Run Check Handler

Method Description
POST Enqueues a credit-check job for the requested application id and returns a processing envelope with the queue job id.

Run Check

frontend/app/api/applications/[id]/run-check/route.ts

{
    "title": "Run Check",
    "description": "Validates the application id and enqueues a run-credit-check job through the worker queue. This route is a frontend orchestration endpoint and does not proxy backend application data directly.",
    "method": "POST",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/applications/{id}/run-check",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "1024",
            "required": true
        }
    ],
    "bodyType": "json",
    "requestBody": "[]",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Queue accepted",
            "body": "{\n    \"ok\": true,\n    \"status\": \"processing\",\n    \"applicationId\": \"1024\",\n    \"jobId\": \"job_01HRY6P4R6Q2M0F0Z8Q1M9\"\n}"
        },
        "400": {
            "description": "Invalid application id",
            "body": "{\n    \"detail\": \"Invalid application id\"\n}"
        }
    }
}

v1 Compatibility Routes

frontend/app/api/v1/applications/route.ts

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

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

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

frontend/app/api/v1/applications/read-model/route.ts

frontend/app/api/v1/applications/provision-account/route.ts

frontend/app/api/v1/applications/verify-passcode/route.ts

The v1 tree is a thin alias layer. Each file re-exports the root handler without adding new request shaping or response logic, so the runtime behavior is the same and only the URL path changes.

List Applications v1

frontend/app/api/v1/applications/route.ts

{
    "title": "List Applications v1",
    "description": "Compatibility alias for /api/applications. It returns the same application list and HTML view behavior as the root route.",
    "method": "GET",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/v1/applications",
    "headers": [],
    "queryParams": [
        {
            "key": "format",
            "value": "json",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "JSON success response",
            "body": "[\n    {\n        \"id\": 1024,\n        \"identifier\": \"app-1024\",\n        \"email\": \"[email protected]\",\n        \"phone\": \"+1-512-555-0148\",\n        \"country\": \"US\",\n        \"employment_status\": \"employed\",\n        \"financing_consent\": \"yes\",\n        \"full_name\": \"Aya Mendez\",\n        \"date_of_birth\": \"1991-04-12\",\n        \"profession\": \"Architect\",\n        \"current_employer\": \"Mendez Studio\",\n        \"job_title\": \"Lead Architect\",\n        \"industry\": \"Design\",\n        \"website\": \"https://mendezstudio.example\",\n        \"linkedin\": \"https://www.linkedin.com/in/ayamendez\",\n        \"agree_policy\": true,\n        \"receive_updates\": false,\n        \"skipped_connect_accounts\": false,\n        \"connected_accounts\": {\n            \"checking\": []\n        },\n        \"created_at\": \"2026-04-26T12:34:56.000Z\",\n        \"metadata\": {\n            \"risk_score\": 712,\n            \"review_status\": \"in_review\"\n        },\n        \"archived\": false,\n        \"review_status\": \"in_review\",\n        \"credit_score\": 712,\n        \"updated_at\": \"2026-04-26T12:35:10.000Z\"\n    }\n]"
        }
    }
}

Create Application v1

frontend/app/api/v1/applications/route.ts

{
    "title": "Create Application v1",
    "description": "Compatibility alias for /api/applications POST. It uses the same backend-first create path and the same local fallback envelope.",
    "method": "POST",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/v1/applications",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"id\": \"app-1024\",\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1-512-555-0148\",\n    \"country\": \"US\",\n    \"employment_status\": \"employed\",\n    \"financing_consent\": \"yes\",\n    \"full_name\": \"Aya Mendez\",\n    \"date_of_birth\": \"1991-04-12\",\n    \"profession\": \"Architect\",\n    \"current_employer\": \"Mendez Studio\",\n    \"job_title\": \"Lead Architect\",\n    \"industry\": \"Design\",\n    \"website\": \"https://mendezstudio.example\",\n    \"linkedin\": \"https://www.linkedin.com/in/ayamendez\",\n    \"agree_policy\": true,\n    \"receive_updates\": false,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": {\n        \"checking\": []\n    },\n    \"metadata\": {\n        \"source\": \"web\",\n        \"campaign\": \"spring-intake\"\n    },\n    \"created_at\": \"2026-04-26T12:34:56.000Z\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Backend passthrough success",
            "body": "{\n    \"id\": 1024,\n    \"identifier\": \"app-1024\",\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1-512-555-0148\",\n    \"country\": \"US\",\n    \"employment_status\": \"employed\",\n    \"financing_consent\": \"yes\",\n    \"full_name\": \"Aya Mendez\",\n    \"date_of_birth\": \"1991-04-12\",\n    \"profession\": \"Architect\",\n    \"current_employer\": \"Mendez Studio\",\n    \"job_title\": \"Lead Architect\",\n    \"industry\": \"Design\",\n    \"website\": \"https://mendezstudio.example\",\n    \"linkedin\": \"https://www.linkedin.com/in/ayamendez\",\n    \"agree_policy\": true,\n    \"receive_updates\": false,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": {\n        \"checking\": []\n    },\n    \"created_at\": \"2026-04-26T12:34:56.000Z\",\n    \"metadata\": {\n        \"source\": \"web\",\n        \"campaign\": \"spring-intake\"\n    },\n    \"archived\": false,\n    \"review_status\": \"in_review\",\n    \"credit_score\": 712,\n    \"updated_at\": \"2026-04-26T12:35:10.000Z\"\n}"
        },
        "201": {
            "description": "Local fallback success",
            "body": "{\n    \"id\": 1025,\n    \"created_at\": \"2026-04-26T12:34:56.000Z\",\n    \"persisted\": \"local_fallback\",\n    \"detail\": \"Backend persistence is currently unavailable. Saved locally so submission can continue.\"\n}"
        }
    }
}

Delete Applications v1

frontend/app/api/v1/applications/route.ts

{
    "title": "Delete Applications v1",
    "description": "Compatibility alias for /api/applications DELETE. It clears the backend collection when auth is available and always clears the local fallback store.",
    "method": "DELETE",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/v1/applications",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"deleted\": 3\n}"
        }
    }
}

Get Application v1

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

{
    "title": "Get Application v1",
    "description": "Compatibility alias for /api/applications/[id]. It returns the same lookup result and fallback merge behavior.",
    "method": "GET",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/v1/applications/{id}",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "1024",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"id\": 1024,\n    \"identifier\": \"app-1024\",\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1-512-555-0148\",\n    \"country\": \"US\",\n    \"employment_status\": \"employed\",\n    \"financing_consent\": \"yes\",\n    \"full_name\": \"Aya Mendez\",\n    \"date_of_birth\": \"1991-04-12\",\n    \"profession\": \"Architect\",\n    \"current_employer\": \"Mendez Studio\",\n    \"job_title\": \"Lead Architect\",\n    \"industry\": \"Design\",\n    \"website\": \"https://mendezstudio.example\",\n    \"linkedin\": \"https://www.linkedin.com/in/ayamendez\",\n    \"agree_policy\": true,\n    \"receive_updates\": false,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": {\n        \"checking\": []\n    },\n    \"created_at\": \"2026-04-26T12:34:56.000Z\",\n    \"metadata\": {\n        \"source\": \"web\",\n        \"review_status\": \"in_review\"\n    },\n    \"archived\": false,\n    \"review_status\": \"in_review\",\n    \"credit_score\": 712,\n    \"updated_at\": \"2026-04-26T12:35:10.000Z\"\n}"
        },
        "400": {
            "description": "Invalid application id",
            "body": "{\n    \"detail\": \"Invalid application id\"\n}"
        }
    }
}

Archive Application v1

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

{
    "title": "Archive Application v1",
    "description": "Compatibility alias for /api/applications/[id]/archive. It performs the same auth-required archive and local-store cleanup flow.",
    "method": "POST",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/v1/applications/{id}/archive",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "1024",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"archived\": true\n}"
        },
        "401": {
            "description": "Authentication required",
            "body": "{\n    \"detail\": \"Authentication required\"\n}"
        }
    }
}

Update Application Status v1

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

{
    "title": "Update Application Status v1",
    "description": "Compatibility alias for /api/applications/[id]/status. It validates the same review-status enum and writes through to the same local fallback store.",
    "method": "PATCH",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/v1/applications/{id}/status",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "1024",
            "required": true
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"status\": \"approved\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"id\": \"1024\",\n    \"status\": \"approved\",\n    \"updated\": true\n}"
        }
    }
}

Read Model v1

frontend/app/api/v1/applications/read-model/route.ts

{
    "title": "Get Application Read Model v1",
    "description": "Compatibility alias for /api/applications/read-model. It returns the same projected dashboard rows.",
    "method": "GET",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/v1/applications/read-model",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"applicationId\": \"1024\",\n        \"applicantName\": \"Aya Mendez\",\n        \"status\": \"in_review\",\n        \"reviewerName\": null,\n        \"riskScore\": 712,\n        \"documentState\": null,\n        \"lastEventAt\": \"2026-04-26T12:35:10.000Z\"\n    }\n]"
        }
    }
}

Verify Passcode v1

frontend/app/api/v1/applications/verify-passcode/route.ts

{
    "title": "Verify Passcode v1",
    "description": "Compatibility alias for /api/applications/verify-passcode. It performs the same backend verification, session issuance, and local fallback create flow.",
    "method": "POST",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/v1/applications/verify-passcode",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\",\n    \"fullName\": \"Aya Mendez\",\n    \"passcode\": \"123456\",\n    \"phone\": \"+1-512-555-0148\",\n    \"country\": \"US\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Verification success",
            "body": "{\n    \"ok\": true,\n    \"email\": \"[email protected]\",\n    \"message\": \"Verification successful\",\n    \"token\": \"guest-token-1714134896000\",\n    \"user\": {\n        \"id\": 1714134896000,\n        \"username\": \"aya.mendez\",\n        \"email\": \"[email protected]\",\n        \"role\": \"applicant\",\n        \"fullName\": \"Aya Mendez\",\n        \"applicationId\": 1024\n    }\n}"
        }
    }
}

Provision Account v1

frontend/app/api/v1/applications/provision-account/route.ts

{
    "title": "Provision Account v1",
    "description": "Compatibility alias for /api/applications/provision-account. It returns the same disabled acknowledgement.",
    "method": "POST",
    "baseUrl": "<FrontendApiBaseUrl>",
    "endpoint": "/api/v1/applications/provision-account",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\",\n    \"fullName\": \"Aya Mendez\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Disabled acknowledgement",
            "body": "{\n    \"status\": \"disabled\"\n}"
        }
    }
}

State Management

Local Store and Deleted Marker

  • readStoredApplications and writeStoredApplications maintain the fallback application collection on disk.
  • hasDeletedAllMarker suppresses list results after a full collection delete so stale backend data does not reappear immediately.
  • clearDeletedAllMarker is called after a successful create so newly created records become visible again.
  • writeDeletedAllMarker is called after a local collection delete completes.

Review Status Values

  • in_review
  • approved
  • denied
  • hold

PATCH /api/applications/[id]/status is the only route in this section that writes review_status directly. The read-model route consumes that field and converts it into the dashboard-facing status value.

Integration Points

  • frontend/lib/server/applications.ts consumes GET /api/applications/read-model for dashboard KPIs and the applications page.
  • @/worker/queue is used by POST /api/applications/[id]/run-check to enqueue run-credit-check.
  • The backend application API is used at /api/v1/applications for item lookup, archive, status, and collection delete.
  • The backend list source for collection hydration is /api/saltedge/customers.
  • The local fallback store is the JSON data file resolved by resolveDataFilePath().

Error Handling

  • buildErrorResponse standardizes error envelopes as { detail: string }.
  • GET /api/applications/[id] returns 401 or 403 immediately when backend auth fails, then falls back to local merges for 404, 422, and backend-side missing-record cases.
  • POST /api/applications/[id]/archive and PATCH /api/applications/[id]/status require an auth token before doing any mutation work.
  • POST /api/applications/verify-passcode validates email and passcode before it contacts the backend.
  • POST /api/applications/provision-account intentionally suppresses body validation errors by consuming the request body and returning the disabled response.
  • POST /api/applications/[id]/run-check rejects an empty id with HTTP 400.

Caching Strategy

Method or Route Cache strategy Invalidation or scope
GET /api/applications Backend fetches are cache: "no-store"; local data is read fresh. clearDeletedAllMarker after create; writeDeletedAllMarker after delete.
POST /api/applications Backend fetch is cache: "no-store"; fallback write is immediate. Clears the deleted-all marker on success.
DELETE /api/applications Backend delete uses cache: "no-store". Clears the local store and writes the deleted-all marker.
GET /api/applications/[id] Backend fetches are cache: "no-store". None beyond the current request.
POST /api/applications/[id]/archive Backend archive uses cache: "no-store". Local fallback store is rewritten immediately.
PATCH /api/applications/[id]/status Backend patch uses cache: "no-store". Local fallback store is rewritten immediately.
GET /api/applications/read-model Internal fetch to /api/v1/applications?format=json uses cache: "no-store". Fresh projection per request.
frontend/lib/server/applications.ts:getDashboardKpis revalidate: 30, tag dashboard-kpis Time-based revalidation.
frontend/lib/server/applications.ts:getApplicationsPage no-store None.
POST /api/applications/verify-passcode Backend verification fetch uses cache: "no-store". Session cookie is issued immediately.
POST /api/applications/[id]/run-check Queue submission only; no fetch caching applies. None.

Testing Considerations

  • POST /api/applications should cover both backend success and local fallback creation.
  • GET /api/applications/[id] should cover lookup by numeric id, string id, identifier, and metadata-derived identifiers.
  • POST /api/applications/[id]/archive should cover auth failure, backend archive success, backend not found, and local-only archive cleanup.
  • PATCH /api/applications/[id]/status should cover enum validation, backend write-through, and local-store-only updates.
  • GET /api/applications/read-model should cover status mapping, risk score extraction, and timestamp fallback behavior.
  • POST /api/applications/verify-passcode should cover valid email/passcode, auth failure, backend verification success, backend verification failure with local fallback, and cookie issuance.
  • POST /api/applications/provision-account should return the disabled response regardless of the incoming payload.
  • POST /api/applications/[id]/run-check should reject empty ids and return the queue job envelope on success.

Key Classes Reference

Class Responsibility
route.ts Collection-level application list, create, and delete handlers.
[id]/route.ts Application lookup and identifier matching.
[id]/archive/route.ts Archive mutation and local cleanup for one application.
[id]/status/route.ts Review-status mutation and local synchronization for one application.
read-model/route.ts Dashboard projection built from application records.
verify-passcode/route.ts Passcode verification, session issuance, and local fallback bootstrap.
provision-account/route.ts Disabled account-provision acknowledgement.
[id]/run-check/route.ts Credit-check job enqueue trigger.
common.ts Shared backend URL resolution, backend proxying, and local storage helpers.
applications.ts Server-side consumers of the application read-model.