User Dashboard and Analytics Domain

Overview

This domain exposes the dashboard-facing API surfaces that let the frontend route users into mission control, retrieve payment history, inspect applicant transaction histories, and verify account coverage against connected financial accounts. It also includes the shared transaction and account-normalization models that power these views.

The implementation is split between thin Next.js App Router endpoints and shared domain utilities. The route handlers validate request shape, resolve backend base URLs, and proxy or aggregate data from backend services and stored application snapshots before returning JSON to the client.

Architecture Overview

flowchart TB
    subgraph PresentationLayer[Frontend App Router Routes]
        MissionControlRoute[dashboard mission control route]
        PaymentsHistoryRoute[payments history route]
        AccountCoverageRoute[v1 applicant account coverage route]
        TransactionsRoute[v1 applicant transactions route]
    end

    subgraph SharedDomain[Shared Domain Utilities]
        CollectIds[collectApplicationIdentifiers]
        FinancialInsights[financial-insights.ts]
        AccountDetection[infer_account_coverage]
    end

    subgraph DataAccessLayer[Backend and Local Data Sources]
        BackendApi[Backend API]
        StoredApplications[Stored application records]
        PlaidGateway[Plaid gateway]
    end

    MissionControlRoute -->|redirect| MissionControlPage[mission control page]
    PaymentsHistoryRoute -->|validate and proxy| BackendApi
    AccountCoverageRoute -->|resolve candidate URLs| BackendApi
    TransactionsRoute -->|direct lookup and fallback merge| BackendApi
    TransactionsRoute -->|read and hydrate| StoredApplications
    TransactionsRoute --> CollectIds
    FinancialInsights -->|normalize and summarise| TransactionsRoute
    AccountDetection -->|compare coverage| PlaidGateway

Component Structure

1. Presentation Layer

Mission Control Redirect Route

frontend/app/api/dashboard/mission-control/route.ts

This endpoint is a redirect shim. It does not assemble dashboard metrics; it immediately redirects the browser to /mission-control.

Public methods

Method Description
GET Redirects the request to /mission-control using NextResponse.redirect

Payments History Route

frontend/app/api/payments/history/route.ts

This route validates a payment-history request body, resolves the backend API base URL, forwards the payload to the backend /api/payments/history endpoint, and returns the backend JSON response to the caller. It also normalizes a backend 204 response into an empty transaction-history object.

Request model: requestSchema

Property Type Description
plaid_access_tokens string[] Plaid access tokens to include in the request body
saltedge_accounts saltedgeAccountSchema[] Salt Edge account descriptors to include in the request body
start_date `string \ undefined`
end_date `string \ undefined`

Nested model: saltedgeAccountSchema

Property Type Description
customer_id string Salt Edge customer identifier
account_id string Salt Edge account identifier
connection_id `string \ undefined`
account_name `string \ undefined`
connection_name `string \ undefined`
currency_code `string \ undefined`

Public methods

Method Description
POST Validates the JSON payload, resolves a backend base URL, proxies the request, and returns the backend response

Applicant Account Coverage Route

frontend/app/api/v1/applicants/[id]/account-coverage/route.ts

This route validates the applicant id, resolves backend URL candidates, and forwards a GET request to each backend candidate at /api/v1/applicants/{id}/account-coverage until one returns a non-404 response. It sends only Accept: application/json to the backend and returns the backend JSON payload directly.

Public methods

Method Description
GET Resolves backend URL candidates, queries account coverage, and returns the first successful backend JSON payload

Applicant Transaction History Route

frontend/app/api/v1/applicants/[id]/transactions/route.ts

This route resolves the applicant by id, gathers transactions from multiple sources inside the application record, filters the results by the optional date range, and returns the applicant’s transaction history. It combines direct backend lookup, backend list lookup, and locally stored application snapshots before it selects a match.

Public methods

Method Description
GET Resolves the applicant, extracts and filters transaction history, and returns the matching transaction list

Application Identifier Resolution

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

This helper is used by the transaction-history endpoint to match applicants across direct ids, explicit identifiers, and identifier-like metadata fields.

Public methods

Method Description
collectApplicationIdentifiers Builds a Set<string> of identifier variants from application.id, identifier, and metadata keys that indicate identifiers

2. Business Layer

Financial Insights Utilities

frontend/lib/financial-insights.ts

These utilities normalize account and transaction structures into shapes that the dashboard can consume. The file includes the transaction summary model used by the payments and applicant-history endpoints, plus the account model used when normalizing connected accounts.

Interfaces

PaymentHistoryTransactionSummary
Property Type Description
amount number Signed transaction amount
date string Transaction date in string form
currency_code `string \ null \
status `string \ null \
account_name `string \ null \
connection_name `string \ null \
description `string \ null \
categories `string[] \ null \
provider `string \ null \
metadata `Record<string, unknown> \ null \
ConnectedAccount
Property Type Description
id string Normalized connected-account id
name string Display name
provider string Provider name
type string Account type
subtype `string \ null \
access_token `string \ null \
last_synced `string \ null \
status `string \ null \
connection_id `string \ null \
connection_name `string \ null \
account_id `string \ null \
account_name `string \ null \
currency_code `string \ null \
balance_currency `string \ null \
institution_name `string \ null \
official_name `string \ null \
mask `string \ null \
available_balance `number \ null \
current_balance `number \ null \
HousingPaymentAnalysis
Property Type Description
points HousingPaymentHistoryPoint[] Time-series housing payment points
totalHousingSpend number Total housing spend across the analyzed window
trailingTwelveMonthHousingSpend number Spend in the trailing twelve months
averageMonthlyHousingSpend number Average monthly housing spend
delayedMonthKeys string[] Month keys flagged as delayed
delayReasons HousingDelayInsight[] Reason records for delayed payments
delaySummary HousingDelaySummary Aggregate delay summary
categoryTotals { label: string; amount: number }[] Category total breakdown
currencyCode `string \ null`
LoanPaymentAnalysis
Property Type Description
totalPaidTrailingYear number Amount paid over the trailing year
repaymentPeriodMonths number Estimated repayment period in months
latePaymentCount number Count of late payments
uniqueLenderCount number Count of unique lenders
currencyCode `string \ null`

Public methods

Method Description
toApplicationDetail Normalizes an application into an application detail shape with connected accounts and income history resolved
analyseHousingPayments Builds housing spend analysis and delay summaries from payment transactions

Account Coverage Inference

backend/src/usecase/account_detection.py

This backend use case evaluates whether the accounts a user reported in connected_accounts cover the full set of accounts detected by Plaid for the same access token. It aggregates per-connection details, counts missing accounts, and produces a status summary.

Dataclass: AccountCoverageResult

Property Type Description
status str Coverage state: complete, incomplete, or unknown
reported_accounts int Count of reported account ids
detected_accounts int Count of account ids returned by Plaid
missing_accounts int Count of detected accounts missing from the report
coverage_ratio `float \ None`
details list[dict[str, Any]] Per-connection coverage detail records
errors list[str] Error messages collected while evaluating tokens

Public methods

Method Description
infer_account_coverage Compares submitted connected-account records with Plaid-detected accounts and returns coverage totals and details

API Integration

Mission Control Redirect

{
    "title": "Mission Control Redirect",
    "description": "Redirects dashboard API requests to the mission-control page",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/dashboard/mission-control",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "307": {
            "description": "Temporary redirect to /mission-control",
            "body": "[]"
        }
    }
}

Post Payment History

{
    "title": "Post Payment History",
    "description": "Validates payment history inputs, forwards them to the backend payment-history service, and returns the backend JSON response",
    "method": "POST",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/payments/history",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        },
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"plaid_access_tokens\": [\n        \"plaid-access-token-001\"\n    ],\n    \"saltedge_accounts\": [\n        {\n            \"customer_id\": \"cust_001\",\n            \"account_id\": \"acct_001\",\n            \"connection_id\": \"conn_001\",\n            \"account_name\": \"Primary Checking\",\n            \"connection_name\": \"Example Bank\",\n            \"currency_code\": \"USD\"\n        }\n    ],\n    \"start_date\": \"2025-01-01\",\n    \"end_date\": \"2025-01-31\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"transactions\": [\n        {\n            \"amount\": -1450.75,\n            \"date\": \"2025-01-15\",\n            \"currency_code\": \"USD\",\n            \"status\": \"posted\",\n            \"account_name\": \"Primary Checking\",\n            \"connection_name\": \"Example Bank\",\n            \"description\": \"Monthly Rent Payment\",\n            \"categories\": [\n                \"rent\",\n                \"housing\"\n            ],\n            \"provider\": \"plaid\",\n            \"metadata\": {\n                \"source\": \"backend\"\n            }\n        }\n    ],\n    \"start_date\": \"2025-01-01\",\n    \"end_date\": \"2025-01-31\"\n}"
        },
        "400": {
            "description": "Invalid request payload",
            "body": "{\n    \"detail\": \"Invalid request payload\"\n}"
        },
        "502": {
            "description": "Backend or routing failure",
            "body": "{\n    \"detail\": \"Unable to resolve backend API URL\"\n}"
        }
    }
}

Get Applicant Account Coverage

{
    "title": "Get Applicant Account Coverage",
    "description": "Proxies account-coverage checks to the backend and returns the first successful backend payload",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/v1/applicants/{id}/account-coverage",
    "headers": [
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "type": "string",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"application_id\": 123,\n    \"status\": \"incomplete\",\n    \"reported_accounts\": 2,\n    \"detected_accounts\": 3,\n    \"missing_accounts\": 1,\n    \"coverage_ratio\": 0.67,\n    \"details\": [\n        {\n            \"connection_name\": \"Example Bank\",\n            \"institution_name\": \"Example Bank\",\n            \"reported_accounts\": 2,\n            \"detected_accounts\": 3,\n            \"missing_accounts\": 1,\n            \"status\": \"incomplete\"\n        }\n    ],\n    \"errors\": []\n}"
        },
        "400": {
            "description": "Invalid applicant id",
            "body": "{\n    \"detail\": \"Invalid applicant id.\"\n}"
        },
        "500": {
            "description": "Backend API URL resolution failure",
            "body": "{\n    \"detail\": \"Backend API URL is not configured. Set NEXT_PUBLIC_BACKEND_API_URL or BACKEND_API_URL.\"\n}"
        },
        "502": {
            "description": "Backend request failure",
            "body": "{\n    \"detail\": \"Failed to reach backend API.\"\n}"
        }
    }
}

Get Applicant Transaction History

{
    "title": "Get Applicant Transaction History",
    "description": "Builds a filtered transaction history from applicant metadata, connected accounts, backend data, and stored application snapshots",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/v1/applicants/{id}/transactions",
    "headers": [],
    "queryParams": [
        {
            "key": "start_date",
            "type": "string",
            "required": false
        },
        {
            "key": "end_date",
            "type": "string",
            "required": false
        }
    ],
    "pathParams": [
        {
            "key": "id",
            "type": "string",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"applicant_id\": \"123\",\n    \"start_date\": \"2025-01-01\",\n    \"end_date\": \"2025-01-31\",\n    \"transactions\": [\n        {\n            \"amount\": -1450.75,\n            \"date\": \"2025-01-15\",\n            \"currency_code\": \"USD\",\n            \"status\": \"posted\",\n            \"account_name\": \"Primary Checking\",\n            \"connection_name\": \"Example Bank\",\n            \"description\": \"Monthly Rent Payment\",\n            \"categories\": [\n                \"rent\",\n                \"housing\"\n            ],\n            \"provider\": \"plaid\",\n            \"metadata\": {\n                \"transaction_id\": \"tx_001\"\n            }\n        }\n    ]\n}"
        },
        "400": {
            "description": "Invalid request or query parameters",
            "body": "{\n    \"detail\": \"Invalid applicant id.\"\n}"
        },
        "404": {
            "description": "Applicant not found or no transactions available",
            "body": "{\n    \"detail\": \"No transaction history is available for this applicant yet. Connect and sync bank accounts first.\"\n}"
        }
    }
}

Feature Flows

1. Mission Control Redirect Flow

sequenceDiagram
    participant U as User
    participant FE as Frontend Route
    participant NM as NextResponse

    U->>FE: Request /api/dashboard/mission-control
    FE->>NM: Redirect to /mission-control
    NM-->>U: 307 redirect response

2. Payment History Retrieval Flow

sequenceDiagram
    participant U as User
    participant FE as payments history route
    participant B as Backend API

    U->>FE: POST JSON payload with provider tokens and date filters
    FE->>FE: Validate payload with requestSchema
    FE->>FE: Resolve backend base URL candidates
    FE->>FE: Resolve Authorization header or auth cookie
    FE->>B: POST /api/payments/history
    B-->>FE: JSON response or 204
    alt Backend returns 204
        FE-->>U: transactions empty with start and end dates
    else Backend returns JSON
        FE-->>U: backend JSON payload
    end

3. Applicant Transaction History Flow

sequenceDiagram
    participant U as User
    participant FE as transactions route
    participant BA as fetchBackendApplicationById
    participant BL as fetchApplicationsFromBackend
    participant LS as readStoredApplications
    participant CI as collectApplicationIdentifiers

    U->>FE: GET /api/v1/applicants/id/transactions
    FE->>FE: Validate id and date filters
    FE->>BA: Direct applicant lookup with allowAnonymous true
    BA-->>FE: Application or not found
    FE->>BL: List backend applications
    BL-->>FE: Application list
    FE->>LS: Read stored applications
    LS-->>FE: Stored snapshot list
    FE->>CI: Match requested id variants
    CI-->>FE: Matching application id set
    FE->>FE: Extract transactions and filter by start_date and end_date
    FE-->>U: applicant_id and filtered transactions

4. Account Coverage Verification Flow

sequenceDiagram
    participant U as User
    participant FE as account coverage route
    participant B as Backend API candidate
    participant UCase as infer_account_coverage
    participant PG as plaid_gateway

    U->>FE: GET /api/v1/applicants/id/account-coverage
    FE->>FE: Validate applicant id
    FE->>FE: Resolve backend URL candidates
    loop Each backend candidate
        FE->>B: GET /api/v1/applicants/id/account-coverage
        alt 404
            FE->>FE: Try next candidate
        else Success
            B-->>FE: Coverage payload
            FE-->>U: Coverage JSON
        end
    end
    UCase->>PG: get_account_balances token
    PG-->>UCase: Detected account set

State Management

Request Validation and Lookup States

  • Invalid input: paramsSchema.safeParse and querySchema.safeParse gate both applicant endpoints before any backend work starts.
  • Backend resolution: resolveBackendApiUrlCandidates and resolveRequestOriginCandidate determine which backend origin the proxy will try first.
  • Fallback matching: the transaction-history route accumulates candidates from direct backend lookup, backend listing, and stored application snapshots before selecting the first identifier match.
  • Empty-result handling: the transaction-history route returns 404 when the filtered transaction set is empty; the payments-history route returns a normalized empty object when the backend responds with 204.

Integration Points

  • Backend API: all three data endpoints proxy to or aggregate from backend services.
  • Stored application snapshots: the transaction-history route reads persisted applicants and hydrates them before matching ids.
  • Plaid gateway: the backend account-coverage use case compares reported accounts with balances retrieved for each access token.
  • Shared transaction models: PaymentHistoryTransactionSummary is the common transaction payload used by the payments and applicant-history routes.
  • Identifier matching helpers: collectApplicationIdentifiers broadens applicant matching beyond a single raw id.

Error Handling

Observed Patterns

  • Validation errors return 400 with a short detail message.
  • Backend URL misconfiguration returns 500 or 502, depending on the route and failure point.
  • Backend HTTP errors are translated through BackendHttpError and surfaced as JSON errors.
  • Non-fatal lookup failures in the transaction route are logged with console.warn and the route continues with fallback sources.
  • No transaction results are returned as 404 with a domain-specific message that instructs the user to connect and sync accounts.

Caching Strategy

  • Payments history: the proxy fetch uses cache: "no-store" so each request reaches the backend.
  • Account coverage: each backend probe uses cache: "no-store" so the route always evaluates live backend state.
  • Applicant transactions: the route recomputes the transaction list on each request from backend and stored sources.
  • Mission control redirect: no data caching is involved because the handler only redirects.

Dependencies

  • next/server
  • next/headers
  • zod
  • @/app/api/applications/common
  • @/lib/application-types
  • @/lib/financial-insights
  • backend/src/usecase/account_detection.py
  • Local stored-application persistence helpers used by the applicant transaction route

Testing Considerations

  • Reject empty or malformed applicant ids with 400.
  • Reject malformed payment-history payloads with 400.
  • Verify that /api/dashboard/mission-control always redirects to /mission-control.
  • Verify that payment history returns a normalized empty transaction object when the backend responds with 204.
  • Verify that transaction history filters by both start_date and end_date.
  • Verify that transaction history returns 404 when no matching applicant is found.
  • Verify that account coverage tries multiple backend URL candidates and skips 404 responses before failing.

Key Classes Reference

Class Responsibility
route.ts Redirects dashboard mission-control traffic to /mission-control
route.ts Validates and proxies payment-history requests to the backend
route.ts Resolves applicant account-coverage checks through backend candidates
route.ts Builds filtered applicant transaction history from backend and stored sources
financial-insights.ts Normalizes transactions and connected accounts for dashboard analytics
account_detection.py Compares submitted connected accounts with Plaid-detected accounts
route.ts Resolves applicant identifier variants for cross-source matching