Housing Application Domain Application CRUD Status Archive and Read Model APIs

frontend/app/api/applications/route.ts, frontend/app/api/applications/[id]/route.ts, frontend/app/api/applications/[id]/archive/route.ts, frontend/app/api/applications/[id]/status/route.ts, frontend/app/api/applications/read-model/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/lib/server/applications.ts, frontend/app/api/applications/common.ts

Overview

This feature exposes the housing application domain through Next.js API route handlers and a server-side read-model facade. It supports applicant list retrieval, single-record lookup, create, delete-all, archive, and review-status updates, then reshapes the data into dashboard-friendly rows for downstream views.

The /applicants experience uses these routes to load the grid, refresh a single applicant, archive records, and change review status. The dashboard layer consumes the read-model route through frontend/lib/server/applications.ts to produce summary KPIs and table rows without reimplementing application filtering or status normalization.

A filesystem-backed fallback store is built into the proxy layer. When backend calls fail or the backend cannot resolve a string reference id, the routes merge remote records with stored records, or fall back to stored mutation paths where the code explicitly supports it.

Architecture Overview

flowchart TB
    subgraph PresentationLayer [Presentation Layer]
        ApplicantsPage[Applicants page]
        AppRoutes[Application route handlers]
        ReadModelRoute[Read model route]
        VersionedRoutes[Versioned aliases]
    end

    subgraph BusinessLayer [Business Layer]
        ServerReadModel[Server read model facade]
    end

    subgraph DataAccessLayer [Data Access Layer]
        CommonHelpers[Application proxy helpers]
        LocalStore[Stored applications]
    end

    subgraph BackendLayer [Backend API]
        BackendList[Application list and detail]
        BackendMutations[Archive and status mutations]
    end

    ApplicantsPage -->|list and refresh| VersionedRoutes
    ApplicantsPage -->|archive and status| VersionedRoutes
    ServerReadModel -->|read model fetch| ReadModelRoute
    ReadModelRoute -->|json list| VersionedRoutes

    AppRoutes --> CommonHelpers
    ReadModelRoute --> CommonHelpers
    VersionedRoutes --> CommonHelpers

    CommonHelpers --> LocalStore
    CommonHelpers --> BackendList
    CommonHelpers --> BackendMutations

Component Structure

Presentation Layer

Application Collection Route

frontend/app/api/applications/route.ts

This route is the main collection endpoint for applicant records. GET merges remote and locally stored applications, POST creates a new application with backend-first then local-fallback behavior, and DELETE clears both the backend dataset and the stored local dataset when possible.

Public methods

Method Description
GET Returns applicant records as HTML or JSON depending on the request format preference.
POST Validates and submits a new application, then falls back to local persistence if backend submission fails.
DELETE Deletes all applications and writes the deleted-all marker used by later list requests.

List Applications

{
    "title": "List Applications",
    "description": "Returns applicant records as JSON by default, or renders an HTML table when format=html or the request prefers text/html. The handler merges remotely fetched applications with stored fallback applications unless the deleted-all marker suppresses both sources.",
    "method": "GET",
    "baseUrl": "<FrontendAppBaseUrl>",
    "endpoint": "/api/applications",
    "headers": [],
    "queryParams": [
        {
            "key": "format",
            "value": "json",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"id\": 1024,\n        \"identifier\": \"app-1024\",\n        \"email\": \"[email protected]\",\n        \"phone\": \"+1-512-555-0148\",\n        \"country\": \"SE\",\n        \"employment_status\": \"employed\",\n        \"financing_consent\": \"yes\",\n        \"full_name\": \"Maya Rosen\",\n        \"date_of_birth\": \"1990-04-16\",\n        \"profession\": \"Product Manager\",\n        \"current_employer\": \"Northwind Labs\",\n        \"job_title\": \"Senior Product Manager\",\n        \"industry\": \"Technology\",\n        \"website\": \"https://maya-rosen.example\",\n        \"linkedin\": \"https://www.linkedin.com/in/mayarosen\",\n        \"agree_policy\": true,\n        \"receive_updates\": false,\n        \"skipped_connect_accounts\": false,\n        \"connected_accounts\": {\n            \"checking\": [],\n            \"savings\": []\n        },\n        \"created_at\": \"2026-03-30T12:00:00Z\",\n        \"updated_at\": \"2026-03-30T12:18:00Z\",\n        \"review_status\": \"in_review\",\n        \"archived\": false,\n        \"credit_score\": 742,\n        \"metadata\": {\n            \"risk_score\": 742,\n            \"application_source\": \"web\"\n        }\n    }\n]"
        }
    }
}

Create Application

{
    "title": "Create Application",
    "description": "Validates a new applicant payload, tries one or more backend API base URLs, and falls back to local file persistence when backend submission is unavailable. A successful backend write clears the deleted-all marker.",
    "method": "POST",
    "baseUrl": "<FrontendAppBaseUrl>",
    "endpoint": "/api/applications",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "raw",
    "requestBody": "{\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1-512-555-0148\",\n    \"country\": \"SE\",\n    \"employment_status\": \"employed\",\n    \"financing_consent\": \"yes\",\n    \"full_name\": \"Maya Rosen\",\n    \"date_of_birth\": \"1990-04-16\",\n    \"profession\": \"Product Manager\",\n    \"current_employer\": \"Northwind Labs\",\n    \"job_title\": \"Senior Product Manager\",\n    \"industry\": \"Technology\",\n    \"website\": \"https://maya-rosen.example\",\n    \"linkedin\": \"https://www.linkedin.com/in/mayarosen\",\n    \"agree_policy\": true,\n    \"receive_updates\": false,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": {\n        \"checking\": [],\n        \"savings\": []\n    },\n    \"metadata\": {\n        \"application_source\": \"web\",\n        \"risk_score\": 742\n    },\n    \"created_at\": \"2026-03-30T12:00:00Z\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Local fallback success",
            "body": "{\n    \"id\": 1025,\n    \"created_at\": \"2026-03-30T12:00:00Z\",\n    \"persisted\": \"local_fallback\",\n    \"detail\": \"Backend persistence is currently unavailable. Saved locally so submission can continue.\"\n}"
        }
    }
}

Delete All Applications

{
    "title": "Delete All Applications",
    "description": "Deletes the full application collection. If an auth token is present it forwards the request to the backend delete endpoint, then clears the local stored dataset and writes the deleted-all marker.",
    "method": "DELETE",
    "baseUrl": "<FrontendAppBaseUrl>",
    "endpoint": "/api/applications",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"deleted\": 12\n}"
        }
    }
}

Application Detail Route

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

This route resolves a single application by id. It validates the path parameter with zod, reads the current headers, optionally forwards a bearer token, and then tries backend detail lookup before merging backend list data with stored fallback records.

Public methods

Method Description
collectApplicationIdentifiers Builds the identifier set used to match backend and stored application records.
GET Fetches one application by id and falls back to stored records when the backend cannot resolve the id.

Get Application

{
    "title": "Get Application",
    "description": "Fetches a single application record by id. Backend 404 and 422 responses are treated as fallback signals, so the route searches backend list data and stored local records for matching numeric ids, explicit identifiers, and identifier-like metadata values.",
    "method": "GET",
    "baseUrl": "<FrontendAppBaseUrl>",
    "endpoint": "/api/applications/{id}",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "app-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\": \"SE\",\n    \"employment_status\": \"employed\",\n    \"financing_consent\": \"yes\",\n    \"full_name\": \"Maya Rosen\",\n    \"date_of_birth\": \"1990-04-16\",\n    \"profession\": \"Product Manager\",\n    \"current_employer\": \"Northwind Labs\",\n    \"job_title\": \"Senior Product Manager\",\n    \"industry\": \"Technology\",\n    \"website\": \"https://maya-rosen.example\",\n    \"linkedin\": \"https://www.linkedin.com/in/mayarosen\",\n    \"agree_policy\": true,\n    \"receive_updates\": false,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": {\n        \"checking\": [],\n        \"savings\": []\n    },\n    \"created_at\": \"2026-03-30T12:00:00Z\",\n    \"updated_at\": \"2026-03-30T12:18:00Z\",\n    \"review_status\": \"in_review\",\n    \"archived\": false,\n    \"credit_score\": 742,\n    \"metadata\": {\n        \"risk_score\": 742,\n        \"application_source\": \"web\"\n    }\n}"
        }
    }
}

Application Archive Route

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

This route requires authentication, resolves numeric ids when possible, and archives the application in both backend and local store paths. When the request id is not numeric, it first looks up backend applications and tries to translate the requested string id or identifier into a numeric backend id before archiving.

Public methods

Method Description
POST Archives an application and removes the matching stored record when one is found.

Archive Application

{
    "title": "Archive Application",
    "description": "Archives one application. Authentication is required. If the path id is not numeric, the route first scans backend application records for a matching id or identifier, then archives the resolved numeric id and removes the matching local stored record.",
    "method": "POST",
    "baseUrl": "<FrontendAppBaseUrl>",
    "endpoint": "/api/applications/{id}/archive",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "app-1024",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Archived",
            "body": "{\n    \"archived\": true\n}"
        }
    }
}

Application Status Route

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

This route validates the path parameter and a strict review-status payload, then updates the application review state. It requires authentication before any update is attempted, writes through to the backend when a numeric id is available, and mirrors the change into stored records.

Public methods

Method Description
PATCH Updates review_status for the matching application and synchronizes stored fallback records.

Update Application Status

{
    "title": "Update Application Status",
    "description": "Updates the review status for one application. Authentication is required and the payload must contain one of in_review, approved, denied, or hold. Numeric ids are pushed to the backend first, then the local stored record is updated when a matching id or identifier is found.",
    "method": "PATCH",
    "baseUrl": "<FrontendAppBaseUrl>",
    "endpoint": "/api/applications/{id}/status",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "1024",
            "required": true
        }
    ],
    "bodyType": "raw",
    "requestBody": "{\n    \"status\": \"approved\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Updated",
            "body": "{\n    \"id\": \"1024\",\n    \"status\": \"approved\",\n    \"updated\": true\n}"
        }
    }
}

Application Read Model Route

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

This route materializes dashboard rows from the application list endpoint. It calls the versioned list API using the frontend app URL, maps each record into a normalized row, and returns a JSON array that downstream dashboard code can reduce into KPIs.

Public methods

Method Description
GET Builds dashboard-ready application rows from the application list endpoint.

Get Application Read Model

{
    "title": "Get Application Read Model",
    "description": "Materializes dashboard-ready rows from the application list endpoint. The route fetches JSON from the versioned list API, normalizes status and risk score fields, and returns rows with applicationId, applicantName, reviewerName, riskScore, documentState, and lastEventAt.",
    "method": "GET",
    "baseUrl": "<FrontendAppBaseUrl>",
    "endpoint": "/api/applications/read-model",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"applicationId\": \"1024\",\n        \"applicantName\": \"Maya Rosen\",\n        \"status\": \"in_review\",\n        \"reviewerName\": null,\n        \"riskScore\": 742,\n        \"documentState\": null,\n        \"lastEventAt\": \"2026-03-30T12:18:00Z\"\n    }\n]"
        }
    }
}

Versioned API Aliases

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

These files re-export the unversioned handlers and expose the same behavior under /api/v1/.... The /applicants page uses the versioned paths, while the dashboard server facade uses the read-model route.

List Applications via Versioned Alias

{
    "title": "List Applications via Versioned Alias",
    "description": "Re-export of the collection list handler under the versioned API path. The behavior matches the unversioned application list route, including remote plus stored record merging and optional HTML rendering.",
    "method": "GET",
    "baseUrl": "<FrontendAppBaseUrl>",
    "endpoint": "/api/v1/applications",
    "headers": [],
    "queryParams": [
        {
            "key": "format",
            "value": "json",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"id\": 2048,\n        \"identifier\": \"app-2048\",\n        \"email\": \"[email protected]\",\n        \"phone\": \"+46-8-555-0199\",\n        \"country\": \"SE\",\n        \"employment_status\": \"contract\",\n        \"financing_consent\": \"yes\",\n        \"full_name\": \"Diego Ahn\",\n        \"date_of_birth\": \"1988-02-09\",\n        \"profession\": \"Data Analyst\",\n        \"current_employer\": \"Atlas Analytics\",\n        \"job_title\": \"Lead Analyst\",\n        \"industry\": \"Analytics\",\n        \"website\": \"https://diego-ahn.example\",\n        \"linkedin\": \"https://www.linkedin.com/in/diegoahn\",\n        \"agree_policy\": true,\n        \"receive_updates\": true,\n        \"skipped_connect_accounts\": false,\n        \"connected_accounts\": {\n            \"checking\": [],\n            \"savings\": []\n        },\n        \"created_at\": \"2026-03-30T12:00:00Z\",\n        \"updated_at\": \"2026-03-30T12:18:00Z\",\n        \"review_status\": \"approved\",\n        \"archived\": false,\n        \"credit_score\": 781,\n        \"metadata\": {\n            \"risk_score\": 781,\n            \"application_source\": \"referral\"\n        }\n    }\n]"
        }
    }
}

Get Application via Versioned Alias

{
    "title": "Get Application via Versioned Alias",
    "description": "Re-export of the single-application lookup handler under the versioned API path. It keeps the same backend-first plus stored-record fallback logic and the same identifier resolution behavior.",
    "method": "GET",
    "baseUrl": "<FrontendAppBaseUrl>",
    "endpoint": "/api/v1/applications/{id}",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "2048",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"id\": 2048,\n    \"identifier\": \"app-2048\",\n    \"email\": \"[email protected]\",\n    \"phone\": \"+46-8-555-0199\",\n    \"country\": \"SE\",\n    \"employment_status\": \"contract\",\n    \"financing_consent\": \"yes\",\n    \"full_name\": \"Diego Ahn\",\n    \"date_of_birth\": \"1988-02-09\",\n    \"profession\": \"Data Analyst\",\n    \"current_employer\": \"Atlas Analytics\",\n    \"job_title\": \"Lead Analyst\",\n    \"industry\": \"Analytics\",\n    \"website\": \"https://diego-ahn.example\",\n    \"linkedin\": \"https://www.linkedin.com/in/diegoahn\",\n    \"agree_policy\": true,\n    \"receive_updates\": true,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": {\n        \"checking\": [],\n        \"savings\": []\n    },\n    \"created_at\": \"2026-03-30T12:00:00Z\",\n    \"updated_at\": \"2026-03-30T12:18:00Z\",\n    \"review_status\": \"approved\",\n    \"archived\": false,\n    \"credit_score\": 781,\n    \"metadata\": {\n        \"risk_score\": 781,\n        \"application_source\": \"referral\"\n    }\n}"
        }
    }
}

Archive Application via Versioned Alias

{
    "title": "Archive Application via Versioned Alias",
    "description": "Re-export of the archive handler under the versioned API path. Authentication is required and string identifiers are translated to numeric ids when possible before archiving.",
    "method": "POST",
    "baseUrl": "<FrontendAppBaseUrl>",
    "endpoint": "/api/v1/applications/{id}/archive",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "2048",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Archived",
            "body": "{\n    \"archived\": true\n}"
        }
    }
}

Update Application Status via Versioned Alias

{
    "title": "Update Application Status via Versioned Alias",
    "description": "Re-export of the status update handler under the versioned API path. Authentication is required and the route accepts only the four review status values.",
    "method": "PATCH",
    "baseUrl": "<FrontendAppBaseUrl>",
    "endpoint": "/api/v1/applications/{id}/status",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "2048",
            "required": true
        }
    ],
    "bodyType": "raw",
    "requestBody": "{\n    \"status\": \"denied\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Updated",
            "body": "{\n    \"id\": \"2048\",\n    \"status\": \"denied\",\n    \"updated\": true\n}"
        }
    }
}

Get Application Read Model via Versioned Alias

{
    "title": "Get Application Read Model via Versioned Alias",
    "description": "Re-export of the read-model route under the versioned API path. The response is the same dashboard-ready row set used by the server-only dashboard facade.",
    "method": "GET",
    "baseUrl": "<FrontendAppBaseUrl>",
    "endpoint": "/api/v1/applications/read-model",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"applicationId\": \"2048\",\n        \"applicantName\": \"Diego Ahn\",\n        \"status\": \"approved\",\n        \"reviewerName\": null,\n        \"riskScore\": 781,\n        \"documentState\": null,\n        \"lastEventAt\": \"2026-03-30T12:18:00Z\"\n    }\n]"
        }
    }
}

Business Layer

Server Application Read Model Facade

frontend/lib/server/applications.ts

This server-only module turns the read-model route into dashboard-ready aggregates. getDashboardKpis loads the read-model rows and reduces them into count totals, while getApplicationsPage returns the row set directly for server-rendered lists.

Public methods

Method Description
getDashboardKpis Fetches the read-model rows and reduces them into total, approved, in-review, and denied counts.
getApplicationsPage Fetches the read-model rows without cache revalidation and returns the full list.

Properties

Property Type Description
ApplicationReadModelRow.applicationId string Stable row identifier used by dashboard views.
ApplicationReadModelRow.applicantName string Display name chosen from the application record.
ApplicationReadModelRow.status string Normalized review status used for dashboard grouping.
ApplicationReadModelRow.reviewerName `string \ null`
ApplicationReadModelRow.riskScore `number \ null`
ApplicationReadModelRow.documentState `string \ null`
ApplicationReadModelRow.lastEventAt string Latest available application timestamp used for dashboard freshness.
DashboardKpis.total number Total read-model rows returned by the facade.
DashboardKpis.approved number Rows whose normalized status is approved.
DashboardKpis.inReview number Rows whose normalized status is neither approved nor denied.
DashboardKpis.denied number Rows whose normalized status is denied.

Data Access Layer

Application Proxy and Storage Helpers

frontend/app/api/applications/common.ts

This module is the shared transport and fallback layer for the application API routes. It resolves backend base URLs, extracts bearer tokens, fetches backend list and detail data, mutates backend records, and reads or writes the local stored application file used for fallback persistence.

Public methods

Method Description
buildErrorResponse Returns a JSON error response with the supplied message and status.
extractAuthToken Reads a bearer token from the incoming headers.
resolveBackendApiUrlCandidates Builds the ordered backend URL candidate list from environment variables and request origin data.
resolveRequestOriginCandidate Derives the request origin used to avoid proxying back into the frontend origin.
fetchApplicationsFromBackend Loads the backend application collection across candidate URLs.
fetchBackendApplicationById Loads one backend application by id across candidate URLs.
readStoredApplications Reads the persisted local application list from the filesystem store.
writeStoredApplications Writes the persisted local application list to the filesystem store.
hydrateStoredApplications Normalizes stored records before they are merged into runtime application objects.
deleteApplicationsInBackend Deletes the backend application collection and returns the deleted count.
archiveApplicationInBackend Sends the backend archive mutation for one numeric application id.
updateApplicationReviewStatusInBackend Sends the backend status mutation for one numeric application id.

Stored application behavior

  • hydrateStoredApplications adds archived: false when the field is missing and preserves metadata.
  • deleteApplicationsInBackend, archiveApplicationInBackend, and updateApplicationReviewStatusInBackend all use resolveBackendApiUrlCandidates and resolveRequestOriginCandidate before they attempt network requests.
  • The mutation helpers retry across candidate base URLs and continue on endpoint-missing and retryable network failures.

Identifier Resolution and Fallback Lookup

[!NOTE] DELETE /api/applications writes the deleted-all marker after clearing the local store, and GET /api/applications checks that marker through hasDeletedAllMarker() before it loads remote or stored applications. That means the collection list can stay empty until a successful create clears the marker again.

The routing code resolves application ids from more than one field so downstream views can survive backend and local identifier mismatches.

  • collectApplicationIdentifiers adds variants from application.id, an explicit identifier, and metadata keys that indicate identifiers.
  • GET /api/applications/[id] treats backend 404 and 422 as fallback signals and searches stored records after a backend miss.
  • POST /api/applications/[id]/archive translates a string reference id into a numeric backend id by scanning backend application records when needed.
  • PATCH /api/applications/[id]/status updates stored records by matching either raw id values or identifier values.

Data Models

Application Payload

[!NOTE] PATCH /api/applications/[id]/status only calls the backend mutation when requestedId parses as a positive integer. Unlike the archive route, it does not first scan the backend list to translate a string reference id into a numeric id, so non-numeric references depend on matching stored records.

frontend/app/api/applications/route.ts

This is the request model for POST /api/applications.

Property Type Description
id `number \ string`
email string Applicant email.
phone string Applicant phone number.
country string Applicant country.
employment_status string Applicant employment status.
financing_consent string Financing consent flag as submitted by the client.
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 consent flag.
receive_updates boolean Marketing or updates opt-in flag.
skipped_connect_accounts `boolean \ undefined`
connected_accounts `Record<string, unknown[]> \ undefined`
metadata `Record<string, unknown> \ undefined`
created_at `string \ undefined`

Application Record Fields Used by These APIs

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

These fields are visible in the proxy and fallback logic for application records.

Property Type Description
id `number \ string`
identifier `string \ undefined`
email string Applicant email.
phone string Applicant phone.
country string Applicant country.
employment_status string Employment status.
financing_consent string Financing consent value.
full_name string Applicant display name.
date_of_birth string Date of birth as carried by the record.
profession string Profession.
current_employer string Current employer.
job_title string Job title.
industry string Industry.
website string Website.
linkedin string LinkedIn URL.
agree_policy boolean Policy acceptance flag.
receive_updates boolean Updates opt-in flag.
skipped_connect_accounts boolean Account connection skip flag.
connected_accounts Record<string, unknown[]> Connected account data used by downstream applicant views.
created_at string Creation timestamp.
updated_at `string \ undefined`
review_status `string \ undefined`
archived `boolean \ undefined`
credit_score `number \ undefined`
metadata `Record<string, unknown> \ undefined`

Application Read Model Row

frontend/lib/server/applications.ts, frontend/app/api/applications/read-model/route.ts

This is the dashboard-friendly response model returned by the read-model route and consumed by the server facade.

Property Type Description
applicationId string Stable row id chosen from id, identifier, or a generated fallback.
applicantName string Display name derived from full_name or email.
status string Normalized status: approved, denied, hold, or in_review.
reviewerName `string \ null`
riskScore `number \ null`
documentState `string \ null`
lastEventAt string Most recent event timestamp from updated_at, created_at, or current time fallback.

Dashboard KPIs

frontend/lib/server/applications.ts

Property Type Description
total number Total number of read-model rows.
approved number Count of approved applications.
inReview number Count of rows that are not approved or denied.
denied number Count of denied applications.

Feature Flows

Load Applicants and Refresh Dashboard Read Model

sequenceDiagram
    participant User
    participant ApplicantsPage as Applicants page
    participant VersionedRoute as Versioned application route
    participant CommonHelpers as Application proxy helpers
    participant BackendApi as Backend API
    participant ReadModelFacade as Server read model facade
    participant ReadModelRoute as Read model route

    User->>ApplicantsPage: Open applicants view
    ApplicantsPage->>VersionedRoute: GET applications json
    VersionedRoute->>CommonHelpers: fetchApplicationsFromBackend
    CommonHelpers->>BackendApi: GET applications list
    BackendApi-->>CommonHelpers: Application records
    CommonHelpers-->>VersionedRoute: Remote and stored records
    VersionedRoute-->>ApplicantsPage: JSON list

    ReadModelFacade->>ReadModelRoute: getDashboardKpis
    ReadModelRoute->>VersionedRoute: GET applications json
    VersionedRoute-->>ReadModelRoute: JSON list
    ReadModelRoute-->>ReadModelFacade: Read model rows
    ReadModelFacade-->>User: KPI counts and dashboard rows

Update Application Status

sequenceDiagram
    participant User
    participant ApplicantsPage as Applicants page
    participant StatusRoute as Status route
    participant CommonHelpers as Application proxy helpers
    participant BackendApi as Backend API
    participant LocalStore as Stored applications

    User->>ApplicantsPage: Click status pill
    ApplicantsPage->>StatusRoute: PATCH status payload
    StatusRoute->>CommonHelpers: updateApplicationReviewStatusInBackend
    CommonHelpers->>BackendApi: PATCH application review status
    BackendApi-->>CommonHelpers: Mutation response
    StatusRoute->>LocalStore: Update stored record review_status
    LocalStore-->>StatusRoute: Persisted record
    StatusRoute-->>ApplicantsPage: Updated true
    ApplicantsPage-->>User: UI status updated or rolled back on error

Archive Application with Identifier Fallback

sequenceDiagram
    participant User
    participant ApplicantsPage as Applicants page
    participant ArchiveRoute as Archive route
    participant CommonHelpers as Application proxy helpers
    participant BackendApi as Backend API
    participant LocalStore as Stored applications

    User->>ApplicantsPage: Click archive action
    ApplicantsPage->>ArchiveRoute: POST archive request
    ArchiveRoute->>CommonHelpers: archiveApplicationInBackend
    CommonHelpers->>BackendApi: POST archive
    BackendApi-->>CommonHelpers: Archive response

    alt Requested id is not numeric
        ArchiveRoute->>BackendApi: GET application list
        BackendApi-->>ArchiveRoute: Records with ids and identifiers
    end

    ArchiveRoute->>LocalStore: Remove matching stored record
    LocalStore-->>ArchiveRoute: Persisted remaining records
    ArchiveRoute-->>ApplicantsPage: archived true
    ApplicantsPage-->>User: Row removed from list

Identifier Mismatch Resolution

The lookup code is intentionally permissive so local and backend records can still line up when one side uses a string reference and the other side uses a numeric id.

  • The detail route builds a set of candidate identifiers from the path id.
  • collectApplicationIdentifiers compares against raw id, explicit identifier, and metadata values whose keys indicate identifiers.
  • Archive resolves string ids by searching backend application records before mutating.
  • Status updates search stored records by raw id or identifier when the backend path id is not numeric.

State Management

Review Status and Archive State

  • The review status payload accepts in_review, approved, denied, and hold.
  • frontend/app/api/applications/read-model/route.ts normalizes backend review_status into the read-model status values used by dashboard views.
  • The /applicants page keeps separate local sets for archivingIds and statusUpdatingIds so button states can reflect in-flight mutations.
  • The collection route uses a deleted-all marker to keep list responses empty after a bulk delete until a new application is created.

View State Used by /applicants

  • isLoading drives the list loading state.
  • error captures API and fallback failures.
  • statusMessage displays empty or success messages.
  • archivingIds and statusUpdatingIds prevent repeated actions while a mutation is in flight.
  • prefetchedDashboardIds tracks which applicant dashboard routes have already been prefetched.

Integration Points

  • /applicants page:
    • fetches /api/v1/applications?format=json
    • refreshes a single applicant with /api/v1/applications/{id}
    • archives with /api/v1/applications/{id}/archive
    • updates status with /api/v1/applications/{id}/status
  • Dashboard server views:
    • call getDashboardKpis
    • call getApplicationsPage
    • rely on /applications/read-model for normalized rows
  • Real-time refresh:
    • the applicants page opens EventSource to /api/v1/applications/stream
    • heartbeat and ping messages are ignored
    • non-empty application events refresh one applicant or the full list
  • Shared identifier handling:
    • collectApplicationIdentifiers also supports downstream applicant-transaction style lookups that need the same record matching rules

Real-time Applicant Event Stream

frontend/app/applicants/page.tsx

The applicants page keeps the list synchronized with a server-sent event stream. It reconnects after disconnects, ignores heartbeat and ping events, and falls back to full list reloads when the payload cannot be parsed or does not contain a usable application id.

Connection lifecycle

  • Opens EventSource against ${baseUrl}/api/v1/applications/stream.
  • Uses a 5 second reconnect timer after errors.
  • Falls back to a 30 second polling interval if the stream stays idle.
  • On application-specific events, refreshes one row first and only reloads the full list when needed.
sequenceDiagram
    participant ApplicantsPage as Applicants page
    participant Stream as EventSource stream
    participant Loader as Applicants loader
    participant DetailLoader as Single applicant loader

    ApplicantsPage->>Stream: Open stream
    Stream-->>ApplicantsPage: Heartbeat or ping
    ApplicantsPage-->>ApplicantsPage: Ignore event

    Stream-->>ApplicantsPage: Application event
    ApplicantsPage->>DetailLoader: Refresh one applicant

    Stream-->>ApplicantsPage: Empty or invalid payload
    ApplicantsPage->>Loader: Reload full list

    Stream-->>ApplicantsPage: Error
    ApplicantsPage-->>ApplicantsPage: Close and reconnect

Error Handling

Condition Route or helper behavior
Invalid path id GET, PATCH, and POST archive return 400.
Missing auth token POST archive and PATCH status return 401.
Backend 401 or 403 on detail lookup The error is returned directly from GET /api/applications/{id}.
Backend 404 or 422 on detail lookup The route falls back to stored records.
Backend 404 on archive The route attempts local removal and then returns not found if no record is resolved.
Backend unavailable on read-model fetch The read-model route returns 502.
Status update backend failure The route updates local stored records when possible and returns an error only when both paths fail.

BackendHttpError, ResourceNotFoundError, and EndpointNotFoundError are the key control-flow errors in the proxy layer. They determine when the code retries another base URL, falls back to storage, or returns the upstream error immediately.

Caching Strategy

Method Cache behavior Effect
GET /api/applications cache: "no-store" on backend fetches Always reads the latest backend and stored state.
POST /api/applications cache: "no-store" on backend submission attempts Avoids reusing stale transport responses.
DELETE /api/applications cache: "no-store" on backend deletion Keeps collection deletion immediate.
GET /api/applications/[id] cache: "no-store" on backend fetches Ensures the fallback lookup uses current records.
POST /api/applications/[id]/archive cache: "no-store" on backend archive calls Prevents stale mutation reads.
PATCH /api/applications/[id]/status cache: "no-store" on backend status calls Prevents stale mutation reads.
GET /api/applications/read-model cache: "no-store" for the internal fetch Dashboard rows are rebuilt on each request.
getDashboardKpis next.revalidate: 30, tag dashboard-kpis Allows short-lived dashboard KPI reuse.
getApplicationsPage cache: "no-store" Always returns the current read-model rows.

Dependencies

  • next/headers for request header access and bearer token extraction.
  • next/server for NextRequest and NextResponse.
  • zod for request parameter and status payload validation.
  • node:fs/promises and node:path for filesystem-backed stored application persistence.
  • frontend/app/api/applications/common.ts for backend URL resolution, fallback storage, and mutation transport.
  • frontend/lib/application-types for the application record shape consumed across proxy routes and server helpers.
  • frontend/lib/server/applications.ts for dashboard read-model access.
  • EventSource in frontend/app/applicants/page.tsx for live refresh support.

Testing Considerations

  • Path validation should reject blank or malformed application ids.
  • The status route should reject payloads outside the four accepted statuses.
  • Archive should resolve non-numeric reference ids against backend records before removing local data.
  • Detail lookup should fall back to stored records when the backend returns 404 or 422.
  • Read-model rows should normalize review_status into approved, denied, hold, or in_review.
  • The deleted-all marker should suppress list output until a successful create clears it.
  • Dashboard KPI reduction should count statuses exactly as getDashboardKpis does.

Key Classes Reference

Class Responsibility
route.ts Collection CRUD proxy for listing, creating, and deleting applications.
[id]/route.ts Single-application lookup with backend and stored-record fallback.
[id]/archive/route.ts Application archive mutation and local record removal.
[id]/status/route.ts Application review-status update and stored-record synchronization.
read-model/route.ts Dashboard-ready application row materialization.
common.ts Backend URL resolution, transport helpers, and filesystem fallback store access.
applications.ts Server-side dashboard facade for read-model rows and KPI reduction.
page.tsx /applicants consumer that uses the APIs and live refresh stream.