User Dashboard DOMAIN - Applicant listing, reviewer workflows, and dashboard assembly surfaces

Overview

This feature set is the reviewer-facing half of Lita’s housing dashboard. The applicant listing page assembles a live queue of applicants, lets reviewers sort, search, page, approve, deny, archive, or delete records, and links each row into the downstream dashboard detail route. The dashboard page itself is a server-rendered shell that composes KPI and table surfaces from a read model instead of rebuilding those values on the client.

The same domain also includes the public submission path that creates new applications. That path is intentionally different: it posts onboarding data into the applications collection, while the reviewer pages read, enrich, and mutate the aggregated queue. Operational guidance in documents/development.md shows how reviewer and admin roles are enabled locally with environment variables and how to validate the data path when an applicant id does not resolve correctly.

Architecture Overview

flowchart TB
    subgraph PresentationLayer[Presentation Layer]
        ApplicantsPage[Applicants Page]
        ApplicantsLoading[Applicants Loading]
        ApplicationsPage[Applications Page]
        ReviewPage[Public Review Submission]
    end

    subgraph BusinessLayer[Business Layer]
        ServerApplications[Server Applications Helpers]
        AssignReviewerAction[Assign Reviewer Action]
    end

    subgraph DataAccessLayer[Data Access Layer]
        ReviewStatusRoute[Applicant Status Route]
        ApplicationsReadModel[Applications Read Model]
        ApplicationsCollection[Applications Collection]
        LocalApplicationsFile[Local Applications File]
        BackendApplications[Backend Applications API]
    end

    ApplicantsPage -->|GET list and stream| ApplicationsCollection
    ApplicantsPage -->|PATCH status| ReviewStatusRoute
    ApplicantsPage -->|POST archive and DELETE all| ApplicationsCollection
    ApplicantsPage -->|open dashboard| ApplicationsPage
    ReviewPage -->|POST submission| ApplicationsCollection
    ApplicationsPage -->|getDashboardKpis| ServerApplications
    ApplicationsPage -->|getApplicationsPage| ServerApplications
    ServerApplications -->|fetch read model| ApplicationsReadModel
    AssignReviewerAction -->|POST assign reviewer| BackendApplications
    ApplicationsCollection -->|persist submissions| LocalApplicationsFile
    ApplicationsCollection -->|merge remote data| BackendApplications

Component Structure

1. Presentation Layer

Applicants Page

frontend/app/applicants/page.tsx

This is the reviewer queue. It gates access by auth token and reviewer role, loads applicant data, applies search and sorting, paginates results, and exposes row actions for status updates, archiving, and deletion. It also prefetches dashboard detail routes and listens to a live event stream so the list can update without a full reload.

Data sources used by the page

Source When it is used Purpose
resolveBackendApiUrl() plus ${backendApiUrl}/api/v1/applications When a token exists and a backend URL is configured Primary applicant feed from the backend container
/api/v1/applications?format=json Fallback when the backend request fails or is unavailable Local composite feed served by the frontend
${baseUrl}/api/v1/applications/stream When the page is mounted in a browser Live refresh channel for incremental applicant updates
dw_application_applicant_names During transform and row refresh Restores display names saved in browser storage
dw_application_archived_applicant_ids During transform and row refresh Hides archived applicants from the visible queue
data/applications.json Via the local applications route Persistence for local onboarding submissions

Component state

State Type Purpose
applicants Applicant[] Visible applicant rows after transform and filtering
isLoading boolean Controls the skeleton and loading state
error `string \ null`
statusMessage `string \ null`
query string Search input value
sort SortKey Active sort mode
isDeleting boolean Prevents overlapping delete-all requests
archivingIds Set<string> Tracks rows currently being archived
statusUpdatingIds Set<string> Tracks rows currently being updated
prefetchedDashboardIds Set<string> Prevents duplicate dashboard prefetch requests
currentPage number Current pagination page

Applicant data model

Property Type Description
id string Canonical route and row identifier used for selection and mutations
numericId `number \ null`
firstName string Display first name used in the table
secondName string Optional second name used in the table
fullName string Normalized display name used for search and dashboard routing
submittedAt string Submission timestamp shown in the list
email string Applicant email shown and searchable
phone string Applicant phone shown and searchable
residencePermitNumber string Display and search value from applicant metadata
country string Applicant country shown and searchable
propertyType string Applicant property preference shown and searchable
budgetRange string Applicant budget shown and searchable
savings string Applicant savings value used in score assembly
income string Applicant income value used in score assembly
incomeCurrency string Currency used in score assembly
status `"in_review" \ "approved" \
creditScore `number \ undefined`
affluence `AffluenceScoreSummary \ null`

Stream event model

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

Sort and status values

  • SortDirection: asc, desc, inactive
  • SortKey: submitted-desc, score-desc, score-asc, status-asc, status-desc
  • Applicant["status"]: approved, hold, in_review, denied
  • STATUS_ORDER: approved, hold, in_review, denied
  • STATUS_CONFIG labels: Approved, Hold – Not connected, In-Review, Denied

Internal methods and helpers

Method Description
ApplicantsPage Renders the applicant listing page and wires auth, loading, search, sort, pagination, and row actions
loadApplicants Loads the queue from backend or local applications data and applies transforms
loadSingleApplicant Refreshes one row after a stream event or targeted update
handleSelectApplicant Stores the selected applicant in browser storage and navigates to /dashboard?id=...
handlePrefetchApplicantDashboard Prefetches the dashboard route for the hovered applicant
updateApplicantStatus Optimistically updates a row, then patches the backend status route
handleDeleteAllApplicants Deletes the collection and reloads the queue
handleArchiveApplicant Archives one applicant and removes it from the visible list
determineStatus Maps backend review state and connected-account state into the row status
transformApplications Converts backend application records into display-ready applicant rows
StatusPill Displays the status badge for a row
SortArrows Displays the sort indicator for a sortable header

[!IMPORTANT] frontend/app/applicants/page.tsx renders only for authenticated reviewer accounts. useEffect redirects anonymous users to /login, redirects authenticated non-reviewers to /dashboard, and every mutation path checks isReviewer before sending the request.

UI states

  • Loading: shows the skeleton card until the queue resolves.
  • Defined: shows the table, search, sorting, pagination, and row actions.
  • Empty: shows “No applicants yet.” or “No applicants match your search.” depending on source data and query.
  • Error: shows a banner with the extracted error message from fetch or mutation failures.

Applicants Loading Skeleton

frontend/app/applicants/loading.tsx

This is the route-level loading fallback for the applicant queue. It renders a minimal skeleton shell while the page and its data are being prepared.

Applications Page

frontend/app/applications/page.tsx

This is the server-rendered dashboard shell. It does not assemble the data itself; it wraps DashboardKpis and ApplicationsTable in Suspense so the dashboard can stream its summary and table sections independently.

Method Description
ApplicationsPage Renders the dashboard shell and composes the KPI and table surfaces

Public Application Submission Surface

frontend/app/application/review/page.tsx

This is the client-side submission surface that creates a new application. It collects values from stored form state and connected accounts, builds a submission payload, and posts it to the public applications collection route without attaching a reviewer token.

Submission payload fields

Field Source Description
email storedForm.email or emailQuery Applicant email
phone Stored phone fields or phoneQuery Applicant phone, normalized to an empty string when not provided
country storedForm.nationality or countryQuery Applicant country
employment_status storedForm.businessOwnership or fallback text Applicant role value sent to the submission route
financing_consent Literal granted Consent flag included in the submission
full_name Derived from storedForm Applicant display name
agree_policy Literal true Policy consent flag
receive_updates Literal true Marketing or status-update flag
connected_accounts connectedAccounts Personal, business, and investment accounts selected in the flow
created_at now.toISOString() Submission timestamp
metadata.application_reference generateApplicationReference() Application reference written into metadata
metadata.residence_permit_number Stored permit data Permit number normalized to an empty string when missing

The handler removes APPLICATION_REFERENCE_STORAGE_KEY when the submission succeeds, stores the generated reference in browser storage, and routes to /application/confirm with the generated reference and submission time in the query string.

2. Business Layer

Dashboard Applications Server Helpers

frontend/lib/server/applications.ts

This file is the server-side assembly surface for dashboard data. It fetches the read model from the configured API base, returns the raw row set for the applications page, and reduces the same row set into KPI counts for the dashboard summary.

Types

ApplicationReadModelRow

Property Type Description
applicationId string Identifier for the row
applicantName string Display name used in the dashboard
status string Review status used for KPI grouping
reviewerName `string \ null`
riskScore `number \ null`
documentState `string \ null`
lastEventAt string Timestamp of the latest event

DashboardKpis

Property Type Description
total number Total row count
approved number Count of approved rows
inReview number Count of rows not marked approved or denied
denied number Count of denied rows

Methods

Method Description Returns
getDashboardKpis Fetches the read model and reduces it into dashboard totals Promise<DashboardKpis>
getApplicationsPage Fetches the read model and returns the raw rows for the dashboard table Promise<ApplicationReadModelRow[]>

Caching behavior

Method API endpoint Description Caching
getDashboardKpis GET <ApiUrl>/applications/read-model Loads rows and rolls them up into KPI counts next.revalidate: 30, tag dashboard-kpis
getApplicationsPage GET <ApiUrl>/applications/read-model Loads the raw row set for the table cache: "no-store"

resolveApiUrl reads API_URL, then NEXT_PUBLIC_BACKEND_API_URL, then falls back to http://localhost:3000/api. In local development, that means the server helpers can read the dashboard data from the frontend API namespace when no external API base is configured.

Reviewer Assignment Action

frontend/app/applications/actions.ts

This server action forwards a reviewer assignment to the backend and then invalidates the dashboard KPI tag so the summary can refresh.

Method Description
assignReviewerAction Posts reviewerId to the backend reviewer assignment endpoint and revalidates dashboard-kpis

3. Data Access Layer

Applicant Status Route

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

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

This route handles reviewer status mutations for a single application id. It validates the route params and payload with zod, requires an auth token extracted from the request headers, attempts to update the backend first for numeric ids, and then persists the review status into the local applications store when a matching stored record exists.

Method Description Returns
PATCH Updates one applicant’s review status in the backend and local store NextResponse JSON on success or structured error response on failure

[!IMPORTANT] PATCH /api/v1/applications/{id}/status rejects requests without an auth token before it touches the backend or the local applications file. The client page mirrors that requirement by only sending the request after isReviewer passes and by adding Authorization: Bearer <token> when the token is available.

Route behavior

  • Invalid route params return 400 with “Invalid application id”.
  • Invalid payloads return 400 with “Invalid review status payload”.
  • Missing auth returns 401 with “Authentication required”.
  • Backend errors surface directly when the backend update throws a BackendHttpError.
  • Local write failures fall back to Failed to update application status if the route cannot confirm a successful update.
  • If the backend update succeeds but the local store does not contain a matching record, the route still returns success when the backend path completed.

API Integration

Get Applications Read Model

{
    "title": "Get Applications Read Model",
    "description": "Returns the row set used by getDashboardKpis and getApplicationsPage. The dashboard page consumes the same read model for KPI aggregation and for the applications table.",
    "method": "GET",
    "baseUrl": "<ApiUrl>",
    "endpoint": "/applications/read-model",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"applicationId\": \"LA-10001\",\n        \"applicantName\": \"Jordan Smith\",\n        \"status\": \"in_review\",\n        \"reviewerName\": \"Avery Lee\",\n        \"riskScore\": 72,\n        \"documentState\": \"complete\",\n        \"lastEventAt\": \"2026-04-26T09:15:00.000Z\"\n    }\n]"
        }
    }
}

Update Applicant Review Status

{
    "title": "Update Applicant Review Status",
    "description": "Updates one applicant status after the route validates params, payload, and Authorization headers. The route tries the backend first for numeric ids and then writes to the local application store when a matching stored record exists.",
    "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": "1",
            "required": true
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"status\": \"approved\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"id\": \"1\",\n    \"status\": \"approved\",\n    \"updated\": true\n}"
        },
        "400": {
            "description": "Invalid params or payload",
            "body": "{\n    \"detail\": \"Invalid review status payload\"\n}"
        },
        "401": {
            "description": "Missing auth token",
            "body": "{\n    \"detail\": \"Authentication required\"\n}"
        },
        "404": {
            "description": "Application not found",
            "body": "{\n    \"detail\": \"Application not found\"\n}"
        },
        "502": {
            "description": "Update failed",
            "body": "{\n    \"detail\": \"Failed to update application status\"\n}"
        }
    }
}

Assign Reviewer to Application

{
    "title": "Assign Reviewer to Application",
    "description": "Posts reviewerId to the backend assignment endpoint and revalidates the dashboard KPI tag after a successful response.",
    "method": "POST",
    "baseUrl": "<ApiUrl>",
    "endpoint": "/api/v1/applications/{applicationId}/assign-reviewer",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "applicationId",
            "value": "LA-10001",
            "required": true
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"reviewerId\": \"reviewer-42\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[]"
        }
    }
}

Feature Flows

1. Reviewer Loads the Applicant Queue

sequenceDiagram
    participant U as Reviewer
    participant P as ApplicantsPage
    participant A as AuthHook
    participant B as BackendApi
    participant L as LocalApplicationsRoute
    participant S as EventStream

    U->>P: open applicants page
    P->>A: useAuth
    A-->>P: token and user role

    alt missing token
        P-->>U: redirect to login
    else non reviewer
        P-->>U: redirect to dashboard
    else reviewer
        P->>B: GET applications
        alt backend unavailable
            B-->>P: error
            P->>L: GET applications local
            L-->>P: merged applicant list
        else backend available
            B-->>P: applicant list
        end

        P->>S: open stream
        S-->>P: applicant event
        P->>P: refresh one row or reload list
        P-->>U: render table
    end

The list page resolves candidate rows from the backend first when possible, then falls back to the local applications route. Search, sort, and pagination all run on the transformed list in the browser. The live stream patches individual applicants when an event includes an application id, and falls back to a full refresh on malformed payloads or stream errors.

2. Reviewer Updates or Archives a Row

sequenceDiagram
    participant U as Reviewer
    participant P as ApplicantsPage
    participant R as ReviewStatusRoute
    participant B as BackendApi
    participant F as LocalApplicationsFile

    U->>P: choose approve deny or archive
    P->>P: optimistic row update or local hide

    alt status change
        P->>R: PATCH status
        R->>B: update backend status
        R->>F: persist local status when matched
        R-->>P: updated row
    else archive row
        P->>R: POST archive
        R->>B: archive backend record
        R->>F: update local archive state
        R-->>P: archived row or not found
    else delete all rows
        P->>R: DELETE collection
        R->>B: delete backend records
        R->>F: clear local store
        R-->>P: delete count
    end

    P-->>U: rollback on error or confirm success

Status updates are optimistic in the UI and revert if the mutation fails. Archiving also writes the applicant id into browser storage so the row stays hidden across refreshes. When the archive endpoint returns 404, the client treats the row as already archived and removes it locally anyway.

3. Dashboard Assembly on the Server

sequenceDiagram
    participant B as Browser
    participant P as ApplicationsPage
    participant S as ServerApplications
    participant R as ReadModelEndpoint

    B->>P: request dashboard page
    P->>S: getDashboardKpis
    P->>S: getApplicationsPage

    S->>R: GET read model
    R-->>S: rows

    S->>S: aggregate KPI counts
    S-->>P: KPI data and row list
    P-->>B: render Suspense sections

The dashboard page is intentionally thin. It delegates the read-model fetch to server helpers, which means the KPI summary and table receive the same underlying rows but different transformations. getDashboardKpis reduces the rows into totals, while getApplicationsPage exposes the rows directly.

4. Public Submission Becomes Visible to Reviewers

sequenceDiagram
    participant U as Applicant
    participant R as PublicReviewPage
    participant A as ApplicationsCollection
    participant F as LocalApplicationsFile
    participant Q as ApplicantsPage

    U->>R: submit application
    R->>A: POST application payload
    A->>F: append submission
    A-->>R: generated identifier and timestamp
    R-->>U: redirect to confirmation

    Q->>A: later GET applications
    A-->>Q: combined applicant list
    Q-->>U: reviewer sees new row

The public submission path is write-oriented. It gathers form data and connected accounts, then posts a creation payload to the applications collection route. The reviewer queue later reads the resulting record through the same collection surface or the backend feed, so submitted applicants appear in the dashboard without needing a separate review-only write path.

State Management

Applicants Queue State

  • query drives text filtering over names, email, phone digits, residence permit number, property type, budget range, and submission time.
  • sort selects one of five sort modes, including date, score, and status ordering.
  • currentPage resets when the query, sort, or underlying applicant set changes.
  • archivingIds, statusUpdatingIds, and isDeleting prevent overlapping mutations for the same operation.
  • prefetchedDashboardIds prevents duplicate router prefetch requests.

Status and list transforms

  • determineStatus reads review_status and the presence of connected accounts.
  • Approved and denied rows are honored directly from review_status.
  • Rows without connected accounts become hold.
  • All other rows become in_review.

Browser storage keys

Key Purpose
dw_application_applicant_names Restores applicant name formatting across reloads
dw_application_archived_applicant_ids Persists hidden row ids across reloads
selectedApplicantId Saves the row selected for dashboard navigation
selectedApplicantName Saves the selected applicant name for later dashboard context
dw_application_reference Stores the generated application reference after public submission

Reviewer Access and Role Unlocking

The reviewer queue is unlocked by both auth state and role state.

  • useAuth() supplies token and user.
  • isReviewerRole(user?.role) decides whether the applicant list is visible and whether mutation actions are allowed.
  • Anonymous users are redirected to /login.
  • Authenticated non-reviewers are redirected to /dashboard.
  • frontend/app/applicants/page.tsx blocks loadApplicants, handleDeleteAllApplicants, handleArchiveApplicant, and updateApplicantStatus when the reviewer role is missing.
  • frontend/app/api/applications/[id]/status/route.ts also rejects requests without an auth token.

Reviewer Account Guidance

documents/development.md

The local setup guidance assigns dashboard roles through environment variables before the stack starts.

  • ADMIN_EMAILS promotes accounts into admin role.
  • REALTOR_EMAILS promotes accounts into reviewer role.
  • Both variables accept a comma-separated list of addresses.

The same document also gives a practical checklist for application id issues:

  • compare the ids returned by GET /api/v1/applications
  • verify the detail route for the selected id
  • inspect data/applications.json
  • confirm BACKEND_API_URL
  • watch frontend logs while reproducing the click

That guidance is tied directly to the applicant queue, because the list page uses the application collection route, local persistence, and the backend URL configuration together.

Caching Strategy

Server-side dashboard reads

  • getDashboardKpis uses next.revalidate: 30.
  • getDashboardKpis tags the response with dashboard-kpis.
  • assignReviewerAction calls revalidateTag("dashboard-kpis") after a successful reviewer assignment.
  • getApplicationsPage uses cache: "no-store" so the table view always reads fresh rows.

Browser-driven reviewer queue

  • The applicants page uses cache: "no-store" for fetches.
  • The page also sets a 30-second fallback interval that reloads the queue even when the event stream is quiet.
  • The event stream path gives incremental updates, while the fallback interval guarantees periodic full refreshes.

Local application persistence

  • The review submission flow and the local dashboard route both rely on the applications data file.
  • APPLICATIONS_DATA_FILE changes the file path used by the submission store.
  • The development docs call out persistent volumes for that file so reviewer-visible submissions survive container restarts.

Error Handling

Applicants page

  • Load failures surface through setError and the red banner.
  • Parse failures on stream payloads fall back to a full list reload.
  • Stream disconnects close the event source and schedule a reconnect.
  • Status mutation failures restore the previous status in the list.
  • Archive and delete failures show an error message and leave the page state consistent.

Status route

  • Invalid route params return 400.
  • Invalid payloads return 400.
  • Missing auth returns 401.
  • Backend failures can still fall back to the local store when the record exists there.
  • Unmatched ids return 404 or 502 depending on which path failed to complete.

Public submission

  • Submission failures show the generic finalization error and keep the user on the review flow.
  • The route only stores the generated reference after a successful response.
  • The confirmation redirect is built only after the submission completes.

Integration Points

  • useAuth() and isReviewerRole control visibility and mutation access.
  • resolveBackendApiUrl() decides whether the reviewer list reads the backend directly.
  • EventSource listens to ${baseUrl}/api/v1/applications/stream.
  • revalidateTag("dashboard-kpis") ties the reviewer assignment mutation back to the dashboard summary cache.
  • API_URL and NEXT_PUBLIC_BACKEND_API_URL drive the server dashboard helpers and reviewer assignment action.
  • BACKEND_API_URL, ENABLE_REMOTE_APPLICATIONS, ADMIN_EMAILS, and REALTOR_EMAILS shape local dashboard behavior in development.

Testing Considerations

The documentation in documents/development.md gives the most direct verification commands for this section:

curl -s http://localhost:3000/api/v1/applications | jq 'map({id, identifier, full_name})'
curl -s -w '\nHTTP %{http_code}\n' http://localhost:3000/api/v1/applications/1 | jq .
cat data/applications.json | jq '.'
docker compose -f platform/deployment/local/docker-compose.yml exec frontend env | grep BACKEND_API_URL
docker compose -f platform/deployment/local/docker-compose.yml logs frontend -f | grep -i application

Use those checks when the queue shows an invalid id, when the backend feed is empty, or when the local fallback data does not match the clicked applicant.

Key Classes Reference

Class Responsibility
page.tsx Reviewer applicant queue with auth gating, live refresh, filtering, sorting, pagination, and row actions
loading.tsx Skeleton fallback for the applicant queue route
page.tsx Server dashboard shell that composes KPI and table surfaces
applications.ts Server-side read-model helper that returns dashboard KPIs and row data
actions.ts Reviewer assignment mutation that revalidates dashboard KPI cache
route.ts Applicant status mutation route with backend sync and local persistence
page.tsx Public application review submission surface that posts new applications
development.md Reviewer and admin environment guidance plus troubleshooting commands