User Dashboard and Analytics Domain

Overview

This domain assembles the applicant-facing and reviewer-facing dashboard experiences around a shared application record. In frontend/app/applicants/page.tsx, the list view loads application records, normalizes names and identifiers, computes or resolves credit score and affluence summaries, and then renders a sortable, searchable applicant table with archive and status actions. The page also keeps the list fresh through a Server-Sent Events stream and a 30-second fallback refresh loop.

The analytics side is composed in frontend/app/applications/page.tsx and frontend/lib/server/applications.ts. The page itself is a thin shell that mounts KPI and table widgets behind Suspense, while the server helper fetches the /applications/read-model feed and turns it into dashboard totals and row data. Financial insight composition is layered through frontend/lib/financial-insights.ts, frontend/lib/affluence-scoring.ts, frontend/lib/affluence-display.ts, and the wiki/profile fallback data in frontend/lib/client-wiki-data.ts.

Architecture Overview

flowchart TB
  subgraph PresentationLayer [Presentation Layer]
    ApplicantsLayout[Applicants Layout]
    ApplicantsLoading[Applicants Loading]
    ApplicantsPage[Applicants Page]
    ApplicationsPage[Applications Page]
  end

  subgraph BusinessLayer [Business Layer]
    TransformApplications[transformApplications]
    BuildAffluenceSummary[buildAffluenceSummary]
    ExtractAffluenceSummary[extractAffluenceSummary]
    ToApplicationDetail[toApplicationDetail]
    AggregateKpis[getDashboardKpis]
    GetApplicationsPage[getApplicationsPage]
    FormatStars[formatAffluenceStars]
    ResolvePriorityBadge[resolvePriorityBadgeClassName]
  end

  subgraph DataLayer [Data Access Layer]
    ReadModelService[applications read model]
    ApplicantApi[applications API routes]
    ApplicantStream[applications stream]
    WikiProfiles[client wiki data]
    LocalStorage[Browser storage]
  end

  subgraph ExternalSystems [External Systems]
    BackendApi[Backend API]
  end

  ApplicantsLayout --> ApplicantsPage
  ApplicantsLoading --> ApplicantsPage
  ApplicationsPage --> AggregateKpis
  ApplicationsPage --> GetApplicationsPage

  ApplicantsPage --> TransformApplications
  ApplicantsPage --> BuildAffluenceSummary
  ApplicantsPage --> ExtractAffluenceSummary
  ApplicantsPage --> FormatStars
  ApplicantsPage --> ResolvePriorityBadge
  ApplicantsPage --> LocalStorage
  ApplicantsPage --> ApplicantApi
  ApplicantsPage --> ApplicantStream
  ApplicantsPage --> WikiProfiles
  TransformApplications --> BackendApi
  ApplicantApi --> BackendApi
  ApplicantStream --> BackendApi

  AggregateKpis --> ReadModelService
  GetApplicationsPage --> ReadModelService
  ReadModelService --> BackendApi
  ToApplicationDetail --> BackendApi

Presentation Layer

Applicants Layout

frontend/app/applicants/layout.tsx

ApplicantsLayout is the route wrapper for the applicant list area. It only sets the page metadata title and passes children through unchanged.

Component Props

Property Type Description
children React.ReactNode Nested route content rendered inside the applicants section.

Responsibilities

  • Sets metadata.title.absolute to Applicants.
  • Keeps the route shell free of additional layout logic.

Applicants Loading

frontend/app/applicants/loading.tsx

ApplicantsLoading renders the skeleton state for the applicants route while the client page is loading data.

Component Props

Property Type Description
children — This component takes no props.

Responsibilities

  • Renders a main shell with three animated placeholder blocks.
  • Matches the applicants page framing so loading transitions stay visually stable.

Applicants Page

frontend/app/applicants/page.tsx

ApplicantsPage is the main reviewer-facing list view. It loads applicant records, enriches them with display-ready fields, and exposes status update, archive, delete, search, pagination, and dashboard prefetch actions.

State and Derived Data

State / Value Type Description
applicants Applicant[] Enriched applicant rows rendered in the table.
isLoading boolean Controls the main loading card and empty/error state gating.
error `string \ null`
statusMessage `string \ null`
query string Search filter text.
sort SortKey Current sort selector state.
isDeleting boolean Disables the bulk delete action while it is running.
archivingIds Set<string> Tracks rows currently being archived.
statusUpdatingIds Set<string> Tracks rows currently being status-updated.
prefetchedDashboardIds Set<string> Avoids repeated dashboard prefetches for the same applicant.
currentPage number Current pagination page.
totalApplicants number Total loaded applicant count before filtering.
visibleApplicants number Filtered count after search and sort.
paginatedApplicants Applicant[] Current page slice.
summaryText string User-facing count summary shown under the title.

Applicant Model

Property Type Description
id string Resolved primary identifier used for selection, archive, and updates.
numericId `number \ null`
firstName string First-name portion used in the client-name column.
secondName string Optional secondary name used beside firstName.
fullName string Normalized display name.
submittedAt string Submission timestamp shown in the table and used in search.
email string Searchable email address.
phone string Searchable phone number.
residencePermitNumber string Uppercased permit number extracted from metadata.
country string Applicant country.
propertyType string Applicant property preference.
budgetRange string Applicant budget range.
savings string Savings field forwarded from the backend record.
income string Income field forwarded from the backend record.
incomeCurrency string Currency used with income and scoring helpers.
status `"in_review" \ "approved" \
creditScore `number \ undefined`
affluence `AffluenceScoreSummary \ null`

Public and Internal Methods

Method Description
loadApplicants Fetches the applicant collection, applies local storage filters, and transforms raw records into Applicant[].
loadSingleApplicant Refreshes a single applicant by ID and merges the result into the current list.
transformApplications Maps backend application records into the display model used by the table.
handleSelectApplicant Stores the selected applicant in localStorage and navigates to /dashboard?id=....
handlePrefetchApplicantDashboard Prefetches the dashboard route for the hovered applicant once per ID.
updateApplicantStatus Optimistically updates the row, calls the status endpoint, and rolls back on failure.
handleDeleteAllApplicants Deletes the current applicant set through the bulk delete endpoint and refreshes the list.
handleArchiveApplicant Archives one applicant, updates local storage markers, and removes the row from the table.
handleCreditScoreSortToggle Switches between ascending and descending credit-score sorts.
handleStatusSortToggle Switches between ascending and descending status sorts.

Applicant Status Model

Status Label Styling Intent
approved Approved Positive green badge.
hold Hold – Not connected Amber warning badge.
in_review In-Review Neutral violet badge.
denied Denied Red rejection badge.

Record Transformation Flow

transformApplications is the core record assembly path:

  1. Filters out archived and explicitly suppressed records.
  2. Resolves the stable identifier with resolveApplicationId.
  3. Pulls any stored name override from browser storage.
  4. Splits the backend full_name into first and second parts.
  5. Computes the score in priority order:
    • application.credit_score
    • metadata score from extractCreditRiskAttributes(application.metadata)
    • computed score from computeCreditScore(...)
  6. Resolves affluence in priority order:
    • extractAffluenceSummary(application.metadata)
    • getClientWikiProfile(...).affluence
    • buildAffluenceSummary(application)
  7. Extracts and normalizes the residence permit number from metadata.
  8. Derives the review status with determineStatus(application).

UI States

  • Loading: a dashed card with Loading applicants….
  • Error: a rose banner with the error message from fetch or validation failures.
  • Empty: a dashed empty state when search returns no rows.
  • Populated: a table with pagination, sorting, hover prefetch, and row actions.

Applications Overview Page

frontend/app/applications/page.tsx

ApplicationsPage is the entry shell for the analytics dashboard. It does not fetch data itself; it mounts KPI and table subtrees inside Suspense boundaries and provides skeleton fallbacks while those subtrees resolve.

Component Props

Property Type Description
children — This component takes no props.

Responsibilities

  • Renders the page title and short subtitle.
  • Loads DashboardKpis behind DashboardKpisSkeleton.
  • Loads ApplicationsTable behind ApplicationsTableSkeleton.

Business Layer

Financial Insights

frontend/lib/financial-insights.ts

This module normalizes application records for dashboard and financial-insight views. The visible toApplicationDetail implementation copies the original application, normalizes connected_accounts, and resolves income_history for downstream cash-flow and payment-analysis components.

Public API

Method Description
toApplicationDetail Converts a backend application into the normalized ApplicationDetail shape used by dashboards and insight cards.
aggregateAnnualCashFlowTotals Aggregates yearly cash-flow totals from normalized application or transaction data.
convertCurrencyAmount Converts an amount into a target currency for display and comparisons.
generateDemoPaymentDataFromIncomeHistory Builds demo payment-history data from income history records.
resolveCashInflowAmount Chooses the cash inflow amount used in insight composition.
formatCurrencyWithFallback Formats currency values while preserving a fallback when currency data is incomplete.

toApplicationDetail Enrichment

  • Spreads the original BackendApplication.
  • Normalizes connected_accounts through normalizeConnectedAccounts.
  • Resolves income_history through resolveIncomeHistory.

Affluence Scoring

frontend/lib/affluence-scoring.ts

buildAffluenceSummary composes a star-based affluence result from the application metadata, connected accounts, and optional research profile data. The function assembles independent category scores, applies scenario weights, and then adjusts the composite score with VIP uplift and risk-cap rules before rounding to half-star precision.

Public API

Method Description
buildAffluenceSummary Produces the full AffluenceScoreSummary for an application.
extractAffluenceSummary Reads an affluence summary from application metadata when one is already present.

Composition Rules

  • Normalizes application metadata before scoring.
  • Builds category inputs for:
    • company prestige
    • active income
    • declared income
    • placeholder modules for restricted or unavailable categories
  • Chooses the scenario and corresponding weights.
  • Computes the base score from weighted category stars.
  • Applies VIP uplift when detected.
  • Caps the final score when a risk cap is active.
  • Produces a composite explanation and data-quality score.

Affluence Display Helpers

frontend/lib/affluence-display.ts

These helpers convert affluence summaries into table-friendly labels and class names.

Public API

Method Description
formatAffluenceStars Converts a star value into the display label shown beside the star icon.
resolvePriorityBadgeClassName Returns the CSS class name used for the priority badge.

Local Wiki Profile Data

frontend/lib/client-wiki-data.ts

This file provides localized profile data used as a fallback when a backend application does not already carry an affluence summary. The visible entry shows how the profile record carries both scoring detail and narrative metadata.

Observed Profile Fields

Property Type Description
relationshipCapital object Localized relationship-capital subscore with stars, label, explanation, data quality, and metrics.
composite object Final affluence score with stars, label, explanation, data quality, metrics, weights, scenario, uplift flags, and final values.
priority object Priority level, display label, explanation, and recommended action.
dataQuality number Overall data-quality score for the profile.
scenario string Scenario label such as selfDeclared.
sources string[] Narrative source list for the profile.
connections string[] Localized connection or affiliation strings.

Relationship Between Profile Data and Applicant Rows

ApplicantsPage resolves affluence in this order:

  1. Metadata summary from extractAffluenceSummary.
  2. Wiki/profile fallback from getClientWikiProfile(...).affluence.
  3. Synthetic score from buildAffluenceSummary(application).

Application Types

frontend/lib/application-types.ts

This type layer supplies the backend application contracts consumed by the applicants list and the dashboard service. The imported names show that the domain relies on typed application payloads plus income-history support models.

Observed Type Usage

Type Description
BackendApplication Raw application DTO consumed by list loading, status updates, and financial-insight normalization.
IncomeHistoryProfile Income-history profile used by financial-insights normalization.
IncomeHistoryAnnualSummaryEntry Annual income-history summary row.
IncomeHistoryMonthlyBreakdownEntry Monthly income-history summary row.
IncomeHistorySourceEntry Source-level income-history record.

Data Access Layer

Dashboard Read Model Service

frontend/lib/server/applications.ts

This server-only helper fetches the applications read model and serves two consumers: dashboard KPI aggregation and the applications table. It builds its base URL from environment variables and fetches /applications/read-model with different cache policies depending on the caller.

Public API

Method Description
getDashboardKpis Fetches the read model and reduces it into total, approved, in-review, and denied counters.
getApplicationsPage Fetches the full read model for tabular dashboard rendering.

Read Model Types

Property Type Description
applicationId string Application identifier in the read model.
applicantName string Display name for the applicant.
status string Review status used by the KPI reducer.
reviewerName `string \ null`
riskScore `number \ null`
documentState `string \ null`
lastEventAt string Last activity timestamp.

KPI Model

Property Type Description
total number Total rows counted from the read model.
approved number Rows whose status normalizes to approved.
inReview number Rows whose status normalizes to anything other than approved or denied.
denied number Rows whose status normalizes to denied.

Caching Behavior

Method Cache Policy Purpose
getDashboardKpis next.revalidate = 30, tag dashboard-kpis Keeps KPI totals fresh while allowing short-lived reuse.
getApplicationsPage cache: "no-store" Always fetches the latest read model for the table.

Realtime Applicant Event Stream

frontend/app/applicants/page.tsx

The applicants page opens an EventSource connection to /api/v1/applications/stream after the reviewer and token checks pass. The stream is used to refresh the list with minimal churn.

Connection Lifecycle

  • Starts only when the browser environment exists, the user is a reviewer, and a token is available.
  • Resolves the backend base URL with resolveBackendApiUrl().
  • Creates new EventSource(${baseUrl}/api/v1/applications/stream).
  • On message:
    • empty payload triggers a full reload
    • heartbeat and ping messages are ignored
    • payloads with an application ID trigger loadSingleApplicant
    • JSON parse failures fall back to loadApplicants
  • On error:
    • the stream is closed
    • reconnect is scheduled after 5000 ms
  • A separate fallback interval calls loadApplicants({ suppressLoading: true }) every 30000 ms.

Stream Payload Fields

Property Type Description
type `string \ undefined`
event `string \ undefined`
application_id `string \ number \
applicationId `string \ number \
id `string \ number \

API Integration

Get Applicant List from Backend API

Load Applicants from Backend API

{
    "title": "Load Applicants from Backend API",
    "description": "Fetches the full applicant collection from the backend API when a reviewer token is available",
    "method": "GET",
    "baseUrl": "<BackendApiUrl>",
    "endpoint": "/api/v1/applications",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"id\": \"123\",\n        \"identifier\": \"APP-123\",\n        \"full_name\": \"John Smith\",\n        \"created_at\": \"2026-03-15T09:45:00.000Z\",\n        \"email\": \"[email protected]\",\n        \"phone\": \"+44 20 5555 0101\",\n        \"country\": \"GB\",\n        \"property_type\": \"Apartment\",\n        \"budget_range\": \"250000-350000\",\n        \"savings\": \"42000\",\n        \"income\": \"88000\",\n        \"income_currency\": \"GBP\",\n        \"credit_score\": 742,\n        \"review_status\": \"in_review\",\n        \"metadata\": {\n            \"residence_permit_number\": \"rp-88991\",\n            \"source\": \"web-intake\"\n        },\n        \"connected_accounts\": {\n            \"personal\": [\n                {\n                    \"name\": \"Main current account\"\n                }\n            ],\n            \"business\": [],\n            \"investments\": []\n        }\n    }\n]"
        }
    }
}

Get Applicant List from Next.js Proxy

Load Applicants from Local Proxy

{
    "title": "Load Applicants from Local Proxy",
    "description": "Fetches applicants from the local Next.js API route when the backend API is unavailable",
    "method": "GET",
    "baseUrl": "<NextJsAppBaseUrl>",
    "endpoint": "/api/v1/applications?format=json",
    "headers": [
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "format",
            "value": "json",
            "required": true
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"id\": \"123\",\n        \"identifier\": \"APP-123\",\n        \"full_name\": \"John Smith\",\n        \"created_at\": \"2026-03-15T09:45:00.000Z\",\n        \"email\": \"[email protected]\",\n        \"phone\": \"+44 20 5555 0101\",\n        \"country\": \"GB\",\n        \"property_type\": \"Apartment\",\n        \"budget_range\": \"250000-350000\",\n        \"savings\": \"42000\",\n        \"income\": \"88000\",\n        \"income_currency\": \"GBP\",\n        \"credit_score\": 742,\n        \"review_status\": \"in_review\",\n        \"metadata\": {\n            \"residence_permit_number\": \"rp-88991\",\n            \"source\": \"web-intake\"\n        },\n        \"connected_accounts\": {\n            \"personal\": [\n                {\n                    \"name\": \"Main current account\"\n                }\n            ],\n            \"business\": [],\n            \"investments\": []\n        }\n    }\n]"
        }
    }
}

Get Single Applicant

Refresh Applicant

{
    "title": "Refresh Applicant",
    "description": "Fetches one applicant record by ID for realtime row refreshes",
    "method": "GET",
    "baseUrl": "<BackendApiUrl>",
    "endpoint": "/api/v1/applications/{id}",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "123",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"id\": \"123\",\n    \"identifier\": \"APP-123\",\n    \"full_name\": \"John Smith\",\n    \"created_at\": \"2026-03-15T09:45:00.000Z\",\n    \"email\": \"[email protected]\",\n    \"phone\": \"+44 20 5555 0101\",\n    \"country\": \"GB\",\n    \"property_type\": \"Apartment\",\n    \"budget_range\": \"250000-350000\",\n    \"savings\": \"42000\",\n    \"income\": \"88000\",\n    \"income_currency\": \"GBP\",\n    \"credit_score\": 742,\n    \"review_status\": \"in_review\",\n    \"metadata\": {\n        \"residence_permit_number\": \"rp-88991\",\n        \"source\": \"web-intake\"\n    },\n    \"connected_accounts\": {\n        \"personal\": [\n            {\n                \"name\": \"Main current account\"\n            }\n        ],\n        \"business\": [],\n        \"investments\": []\n    }\n}"
        }
    }
}

Update Applicant Status

Update Applicant Status

{
    "title": "Update Applicant Status",
    "description": "Validates the path parameter and status payload, updates the backend when a numeric ID is available, and falls back to local storage persistence",
    "method": "PATCH",
    "baseUrl": "<NextJsAppBaseUrl>",
    "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": "123",
            "required": true
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"status\": \"approved\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"id\": \"123\",\n    \"status\": \"approved\",\n    \"updated\": true\n}"
        },
        "400": {
            "description": "Invalid application id or invalid review status 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 Applicant

Archive Applicant

{
    "title": "Archive Applicant",
    "description": "Archives one applicant and uses a 404 response as a signal to remove the row locally",
    "method": "POST",
    "baseUrl": "<NextJsAppBaseUrl>",
    "endpoint": "/api/v1/applications/{id}/archive",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "123",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[]"
        },
        "404": {
            "description": "Applicant already absent from the backend",
            "body": "{\n    \"detail\": \"Not found\"\n}"
        }
    }
}

Delete All Applicants

Delete All Applicants

{
    "title": "Delete All Applicants",
    "description": "Deletes the current applicant set and reads the deleted count from the JSON response",
    "method": "DELETE",
    "baseUrl": "<NextJsAppBaseUrl>",
    "endpoint": "/api/v1/applications",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"deleted\": 3\n}"
        }
    }
}

Subscribe to Applicant Stream

Subscribe to Applicant Stream

{
    "title": "Subscribe to Applicant Stream",
    "description": "Opens the realtime applicant event stream used to refresh the list and single rows",
    "method": "GET",
    "baseUrl": "<BackendApiUrl>",
    "endpoint": "/api/v1/applications/stream",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Server sent event payload example",
            "body": "{\n    \"type\": \"application.updated\",\n    \"event\": \"application.updated\",\n    \"application_id\": \"123\",\n    \"applicationId\": \"123\",\n    \"id\": \"123\"\n}"
        }
    }
}

Get Application Read Model

Get Application Read Model

{
    "title": "Get Application Read Model",
    "description": "Returns the dashboard read model used by KPI aggregation and the applications table",
    "method": "GET",
    "baseUrl": "<Resolve Api Url>",
    "endpoint": "/applications/read-model",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"applicationId\": \"123\",\n        \"applicantName\": \"John Smith\",\n        \"status\": \"approved\",\n        \"reviewerName\": \"Ava Brown\",\n        \"riskScore\": 18,\n        \"documentState\": \"complete\",\n        \"lastEventAt\": \"2026-03-15T09:45:00.000Z\"\n    }\n]"
        }
    }
}

Feature Flows

sequenceDiagram
  participant U as Reviewer
  participant V as Applicants Page
  participant A as Auth Hook
  participant L as loadApplicants
  participant B as Backend API
  participant P as Local Proxy
  participant T as transformApplications
  participant W as Wiki Profile Data
  participant UI as Table and Filters

  U->>V: Open applicants route
  V->>A: Read token and user
  A-->>V: token and user role
  V->>V: Redirect if not authorized
  V->>L: Fetch applicants
  L->>B: GET /api/v1/applications
  B-->>L: Application records
  L->>P: Fallback GET /api/v1/applications?format=json
  P-->>L: Application records
  L->>T: Normalize records
  T->>W: Resolve wiki profile fallback
  W-->>T: Profile affluence summary
  T-->>V: Applicant[]
  V-->>UI: Render searchable table

Real Time Refresh and Status Editing

sequenceDiagram
  participant U as Reviewer
  participant V as Applicants Page
  participant S as EventSource
  participant R as loadSingleApplicant
  participant P as PATCH status route
  participant B as Backend API
  participant UI as Table state

  U->>V: Hover or click row
  V-->>UI: Prefetch dashboard or navigate
  V->>S: Open /api/v1/applications/stream
  S-->>V: JSON event payload
  alt payload has application id
    V->>R: Refresh one applicant
    R->>B: GET /api/v1/applications/id
    B-->>R: Updated applicant
    R-->>UI: Merge row
  else heartbeat or ping
    V-->>V: Ignore event
  else parse failure or blank payload
    V->>V: Reload full list
  end

  U->>V: Change status
  V->>P: PATCH /api/v1/applications/id/status
  P->>B: Update review status
  B-->>P: Updated status
  P-->>V: { id, status, updated }
  V-->>UI: Keep optimistic row or roll back on error

Dashboard Assembly

sequenceDiagram
  participant U as User
  participant P as Applications Page
  participant K as getDashboardKpis
  participant T as getApplicationsPage
  participant R as Read Model API
  participant UI as KPI and Table Components

  U->>P: Open applications dashboard
  P->>K: Resolve KPI data
  K->>R: GET /applications/read-model with revalidation
  R-->>K: Read model rows
  K-->>UI: KPI totals
  P->>T: Resolve table data
  T->>R: GET /applications/read-model no-store
  R-->>T: Read model rows
  T-->>UI: Applications table rows

Affluence Resolution

sequenceDiagram
  participant V as Applicants Page
  participant M as Backend metadata
  participant W as Wiki Profile Data
  participant F as buildAffluenceSummary
  participant D as Display Helpers
  participant UI as Affluence Column

  V->>M: Read application.metadata
  V->>V: extractAffluenceSummary
  alt metadata contains summary
    V-->>UI: Use metadata summary
  else metadata missing summary
    V->>W: getClientWikiProfile name
    W-->>V: Profile affluence fallback
    alt profile has affluence
      V-->>UI: Use wiki profile summary
    else no profile summary
      V->>F: buildAffluenceSummary(application)
      F-->>V: Synthetic affluence summary
      V-->>UI: Render computed summary
    end
  end
  V->>D: formatAffluenceStars and resolvePriorityBadgeClassName
  D-->>V: Star label and badge class

State Management

Applicants Page State Pattern

  • useState holds canonical list data, error messaging, search text, sort selection, loading flags, and pagination.
  • useMemo derives the filtered list, total counts, page range, and summary string from the canonical array.
  • useEffect resets pagination to page 1 when the query, sort order, or loaded applicant list changes.
  • useEffect clamps the current page when a filter reduces the number of visible rows.
  • useCallback keeps fetch, refresh, archive, prefetch, and status-update handlers stable across renders.

Loading and Transition Rules

  • isLoading is set before fetches unless the caller suppresses the loading transition.
  • Error and status messages are cleared at the beginning of data loads and action handlers.
  • Status changes are applied optimistically before the network call and rolled back if the request fails.
  • Deletions and archives update the local row set immediately after the backend confirms success.

Browser Storage Signals

Storage Key Purpose
selectedApplicantId Stores the applicant selected for dashboard navigation.
selectedApplicantName Stores the selected applicant name for later reuse.
dw_application_applicant_names Stores remembered applicant display names.

Error Handling

ApplicantsPage uses the same pattern across fetches and mutations:

  • extractApiErrorMessage converts backend error payloads into visible messages.
  • Network and parsing failures are normalized into Error instances when possible.
  • AbortError and aborted signals are ignored during load teardown.
  • Status mutation failures restore the previous applicant status before showing the error.
  • Archive failures keep the row visible unless the backend already returned 404, in which case the row is removed locally and the archive markers are still updated.
  • loadSingleApplicant falls back to a full refresh when row refresh fails.

Route Validation and Failure Handling

frontend/app/api/v1/applications/[id]/status/route.ts validates both the path parameter and the JSON body before any persistence step runs.

Failure Handler Response
Invalid id 400 Invalid application id
Invalid payload 400 Invalid review status payload
Missing auth token 401 Authentication required
Backend update failure Backend error status or local fallback handling
No matching application 404 Application not found
Final persistence failure 502 Failed to update application status

Caching Strategy

Area Policy Effect
getDashboardKpis next.revalidate = 30 with tag dashboard-kpis Reuses KPI data briefly while staying fresh.
getApplicationsPage cache: "no-store" Always reads the latest dashboard rows.
loadApplicants cache: "no-store" Prevents stale applicant data in the browser.
loadSingleApplicant cache: "no-store" Keeps row refreshes aligned with the backend state.
EventSource stream Stream connection Pushes updates without polling the read model.
Fallback interval 30000 ms Recovers from missed stream events and stale state.

Integration Points

  • useAuth provides token and user for route gating and authenticated fetches.
  • isReviewerRole controls whether the applicants route is accessible.
  • resolveBackendApiUrl and getConfiguredBackendApiUrl supply backend base URLs.
  • computeCreditScore and extractCreditRiskAttributes enrich applicant rows with score data.
  • extractAffluenceSummary, getClientWikiProfile, and buildAffluenceSummary resolve the affluence display.
  • formatAffluenceStars and resolvePriorityBadgeClassName translate affluence summaries into table labels.
  • Browser localStorage stores selected applicants and remembered names.
  • EventSource keeps the applicant list synchronized with backend application events.

Testing Considerations

  • Reviewer access should redirect unauthorized users away from /applicants.
  • Search should match name parts, email, phone digits, permit number, property type, budget range, and submission date text.
  • Sort toggles should switch both direction and visual indicator state.
  • Status updates should be optimistic and roll back on server rejection.
  • Archive and bulk-delete flows should remove the correct rows and refresh the summary text.
  • SSE messages should refresh one row when an application ID is present and fall back to full reload on invalid payloads.
  • Affluence fallback order should prefer metadata over wiki profile data and computed summaries.

Key Classes Reference

Class Responsibility
layout.tsx Sets the Applicants route metadata title and passes children through.
loading.tsx Renders the applicants loading skeleton.
page.tsx Loads, transforms, filters, sorts, and mutates the applicants table.
page.tsx Mounts the analytics dashboard shell with KPI and table suspense boundaries.
financial-insights.ts Normalizes applications into dashboard-ready financial insight data.
affluence-scoring.ts Builds and extracts affluence summaries for applicant rows.
affluence-display.ts Converts affluence scores into table labels and badge styling.
client-wiki-data.ts Supplies localized wiki/profile fallback data for affluence enrichment.
application-types.ts Defines the application and income-history types used by this domain.
server/applications.ts Fetches the read model and reduces it into dashboard KPIs.