User Dashboard Domain Mission Control Payment History and Financial Insight APIs
Overview
This dashboard domain turns raw application, banking, and payment data into reviewer-facing summaries. The API routes here either redirect reviewers into the mission-control surface, proxy payment-history requests into the backend, or assemble applicant transactions from backend records and stored snapshots so the UI can show behavior over time.
The supporting helpers in frontend/lib/financial-insights.ts and frontend/lib/affluence-scoring.ts normalize connected accounts, derive housing and loan payment summaries, aggregate annual cash flow, and produce affluence signals that the reviewer list can render. The dashboard pages consume these helpers to combine transaction history, payment behavior, and metadata into the concise summary cards and badges used during review.
Architecture Overview
flowchart TB
subgraph DashboardRoutes [Dashboard API Routes]
MissionControlRoute[Mission Control Redirect]
PaymentsHistoryRoute[Payments History Proxy]
ApplicantTransactionsRoute[Applicant Transactions Aggregator]
end
subgraph InsightHelpers [Financial Insight Helpers]
ApplicationDetailHelper[toApplicationDetail]
LoanSummaryHelper[summariseLoanPayments]
HousingSummaryHelper[analyseHousingPayments]
CashFlowHelper[aggregateAnnualCashFlowTotals]
AffluenceHelper[buildAffluenceSummary]
AffluenceDisplay[Affluence display formatters]
end
subgraph DataSources [Data Sources]
BackendApplications[Backend applications API]
BackendPayments[Backend payments history API]
StoredApplications[Stored applications]
ApplicationMetadata[Application metadata]
ConnectedAccounts[Connected accounts]
end
MissionControlRoute --> MissionControlPage[Mission Control page]
PaymentsHistoryRoute --> BackendPayments
ApplicantTransactionsRoute --> BackendApplications
ApplicantTransactionsRoute --> StoredApplications
ApplicantTransactionsRoute --> ApplicationMetadata
ApplicantTransactionsRoute --> ConnectedAccounts
ApplicationDetailHelper --> ApplicationMetadata
ApplicationDetailHelper --> ConnectedAccounts
LoanSummaryHelper --> TransactionSummaries[Payment history transactions]
HousingSummaryHelper --> TransactionSummaries
CashFlowHelper --> TransactionSummaries
AffluenceHelper --> ConnectedAccounts
AffluenceHelper --> ApplicationMetadata
AffluenceDisplay --> ReviewUI[Reviewer list badges and stars]
HTTP API Endpoints
Mission Control Redirect
frontend/app/api/dashboard/mission-control/route.ts
{
"title": "Mission Control Redirect",
"description": "Redirects dashboard traffic to the mission-control page.",
"method": "GET",
"baseUrl": "<FrontendAppUrl>",
"endpoint": "/api/dashboard/mission-control",
"headers": [],
"queryParams": [],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"307": {
"description": "Temporary redirect to /mission-control",
"body": "[]"
}
}
}
Get Payment History
frontend/app/api/payments/history/route.ts
{
"title": "Get Payment History",
"description": "Validates a payment-history request, selects a backend API origin, forwards the request to /api/payments/history, and returns the backend JSON or a normalized empty-history payload when the backend replies with 204.",
"method": "POST",
"baseUrl": "<FrontendAppUrl>",
"endpoint": "/api/payments/history",
"headers": [
{
"key": "Content-Type",
"value": "application/json",
"required": true
},
{
"key": "Authorization",
"value": "Bearer <token>",
"required": false
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "application/json",
"requestBody": "{\n \"plaid_access_tokens\": [\n \"plaid-access-token-1\"\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-12-31\"\n}",
"formData": [],
"rawBody": "{\"plaid_access_tokens\":[\"plaid-access-token-1\"],\"saltedge_accounts\":[{\"customer_id\":\"cust-001\",\"account_id\":\"acct-001\",\"connection_id\":\"conn-001\",\"account_name\":\"Primary Checking\",\"connection_name\":\"Example Bank\",\"currency_code\":\"USD\"}],\"start_date\":\"2025-01-01\",\"end_date\":\"2025-12-31\"}",
"responses": {
"200": {
"description": "Backend JSON passthrough or the normalized empty-history response returned when the backend replies with 204.",
"body": "{\n \"transactions\": [],\n \"start_date\": \"2025-01-01\",\n \"end_date\": \"2025-12-31\"\n}"
},
"400": {
"description": "Invalid request payload.",
"body": "{\n \"detail\": \"Invalid request payload\"\n}"
},
"502": {
"description": "Backend URL resolution failure, network failure, or non-JSON backend response.",
"body": "{\n \"detail\": \"Unable to resolve backend API URL\"\n}"
}
}
}
Get Applicant Transactions
frontend/app/api/v1/applicants/[id]/transactions/route.ts
{
"title": "Get Applicant Transactions",
"description": "Finds an applicant by id, pulls transactions from backend records and stored application snapshots, filters them by date range, and returns a reviewer-facing transaction history summary.",
"method": "GET",
"baseUrl": "<FrontendAppUrl>",
"endpoint": "/api/v1/applicants/{id}/transactions",
"headers": [],
"queryParams": [
{
"key": "start_date",
"required": false,
"value": "2025-01-01"
},
{
"key": "end_date",
"required": false,
"value": "2025-12-31"
}
],
"pathParams": [
{
"key": "id",
"required": true,
"value": "123"
}
],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Applicant transaction summary filtered to the requested date window.",
"body": "{\n \"applicant_id\": \"123\",\n \"start_date\": \"2025-01-01\",\n \"end_date\": \"2025-12-31\",\n \"transactions\": [\n {\n \"amount\": 2500,\n \"date\": \"2025-03-01\",\n \"currency_code\": \"USD\",\n \"status\": \"booked\",\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 }\n ]\n}"
},
"400": {
"description": "Invalid applicant id or invalid query parameters.",
"body": "{\n \"detail\": \"Invalid applicant id.\"\n}"
},
"404": {
"description": "Application not found or no transaction history was available after filtering.",
"body": "{\n \"detail\": \"No transaction history is available for this applicant yet. Connect and sync bank accounts first.\"\n}"
}
}
}
Component Structure
1. Dashboard Route Handlers
Mission Control Redirect
frontend/app/api/dashboard/mission-control/route.ts
This route is a pure redirect entry point. It does not fetch dashboard data or inspect request headers; it sends the browser to /mission-control through NextResponse.redirect.
Public methods
| Method | Description |
|---|---|
GET |
Redirects the incoming request to /mission-control. |
Payments History Proxy
frontend/app/api/payments/history/route.ts
This route validates a payment-history request, resolves the backend origin with resolveBackendApiUrlCandidates and resolveRequestOriginCandidate, and forwards the JSON body to the backend /api/payments/history endpoint. It preserves an incoming authorization header when one is available and normalizes the backend 204 case into an empty transaction payload.
Request schema
| Property | Type | Description |
|---|---|---|
plaid_access_tokens |
string[] |
Plaid access tokens to query. Defaults to an empty array. |
saltedge_accounts |
SaltEdgeAccountSummary[] |
Salt Edge account summaries. Defaults to an empty array. |
start_date |
`string \ | undefined` |
end_date |
`string \ | undefined` |
Salt Edge account schema
| Property | Type | Description |
|---|---|---|
customer_id |
string |
Required Salt Edge customer identifier. |
account_id |
string |
Required 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 request, selects a backend base URL, forwards the request, and returns the backend response. |
Applicant Transactions Aggregator
frontend/app/api/v1/applicants/[id]/transactions/route.ts
This route combines three sources of truth before it returns a transaction history: a direct backend application lookup, a backend application list, and stored application snapshots. It then extracts transactions from application metadata and connected accounts, sorts them by date descending, and filters them against the requested date range.
Path and query validation
| Property | Type | Description |
|---|---|---|
id |
string |
Required applicant identifier from the path. |
start_date |
`string \ | undefined` |
end_date |
`string \ | undefined` |
Transaction extraction sources
application.metadata.transactionsapplication.metadata.payment_transactionsapplication.metadata.bank_transactionsapplication.metadata.cashflow_transactionsapplication.connected_accounts[*].transactions
Transaction normalization rules
amountis read fromamount,value, ortransaction_amount.dateis read fromdate,transaction_date,booked_at, orcreated_at.currency_codefalls back tocurrency.account_namefalls back toaccount.connection_namefalls back toinstitution_name.categoriesis retained when it is already an array of strings.metadatais the raw transaction record.
Public methods
| Method | Description |
|---|---|
GET |
Resolves the applicant, extracts transactions, applies date filters, and returns the summary payload. |
2. Financial Insight Helpers
frontend/lib/financial-insights.ts
This module is the core normalizer for dashboard payment intelligence. It converts backend application records into a dashboard-friendly shape, turns raw transactions into consistent summaries, and derives loan, housing, and annual cash-flow insights for reviewer views.
Public methods
| Method | Description |
|---|---|
toApplicationDetail |
Normalizes connected_accounts and resolves income_history into a dashboard-friendly ApplicationDetail. |
summariseLoanPayments |
Reduces a transaction list into trailing payment totals, repayment period, late-payment count, unique lenders, and currency. |
analyseHousingPayments |
Classifies housing-related payments across a month window and returns delay and category summaries. |
aggregateAnnualCashFlowTotals |
Groups inflow amounts by year and returns annual net totals. |
generateDemoPaymentDataFromIncomeHistory |
Builds demo payment-history data from income history for charting and summary surfaces. |
Payment history transaction summary
| Property | Type | Description |
|---|---|---|
amount |
number |
Signed transaction amount. |
date |
string |
ISO-like transaction date string. |
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 \ |
Connected account
| Property | Type | Description |
|---|---|---|
id |
string |
Normalized account identifier. |
name |
string |
Display name, synthesized when needed. |
provider |
string |
Provider label. |
type |
string |
Account type. |
subtype |
`string \ | null` |
access_token |
`string \ | null \ |
last_synced |
`string \ | null \ |
status |
`string \ | undefined` |
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` |
Application detail
| Property | Type | Description |
|---|---|---|
connected_accounts |
Record<string, ConnectedAccount[]> |
Normalized connected accounts grouped by category. |
income_history |
`IncomeHistoryProfile \ | null` |
Housing payment history point
| Property | Type | Description |
|---|---|---|
monthKey |
string |
Month key used for grouping. |
isoDate |
string |
Month date in ISO form. |
housingTotal |
number |
Housing spend for the month. |
incomeTotal |
number |
Income total for the month. |
netCashTotal |
number |
Net cash after the monthly bucket is processed. |
hasHousingPayment |
boolean |
Whether the month contains a housing payment. |
Housing payment analysis
| Property | Type | Description |
|---|---|---|
points |
HousingPaymentHistoryPoint[] |
Month-by-month output series. |
totalHousingSpend |
number |
Total housing spend across the analysis window. |
trailingTwelveMonthHousingSpend |
number |
Housing spend in the last twelve months. |
averageMonthlyHousingSpend |
number |
Average monthly housing spend for months with payments. |
delayedMonthKeys |
string[] |
Month keys flagged as delayed. |
delayReasons |
HousingDelayInsight[] |
Per-month delay reasons and expected spend context. |
delaySummary |
HousingDelaySummary |
Aggregate counts for delay reasons. |
categoryTotals |
{ label: string; amount: number }[] |
Totals grouped by transaction label. |
currencyCode |
`string \ | null` |
Loan payment analysis
| Property | Type | Description |
|---|---|---|
totalPaidTrailingYear |
number |
Total paid in the trailing year. |
repaymentPeriodMonths |
number |
Span between first and latest loan-payment month. |
latePaymentCount |
number |
Count of missing payment months in the observed period. |
uniqueLenderCount |
number |
Distinct lender labels found. |
currencyCode |
`string \ | null` |
Demo payment data
| Property | Type | Description |
|---|---|---|
transactions |
PaymentHistoryTransactionSummary[] |
Synthesized cash-flow transactions. |
annualTotals |
{ year: number; net: number }[] |
Annual inflow totals derived from the generated transactions. |
range |
`{ start: string; end: string } \ | null` |
currencyCode |
`string \ | null` |
Behavioral notes
toApplicationDetailprefersconnected_accounts.income_historybeforemetadata.income_history.summariseLoanPaymentskeeps only loan-like transactions after normalization, sorts them chronologically, and computes the trailing-year sum from the current date.analyseHousingPaymentsbuilds a fixed month grid, classifies each transaction, and falls back to recurring descriptor candidates when no direct housing hit is available.aggregateAnnualCashFlowTotalsonly counts inflow amounts and ignores malformed date values.- The classification constants visible in this module group inflows and outflows by payment, deposit, rent, mortgage, salary, payroll, utilities, bills, subscriptions, and similar terms.
frontend/lib/affluence-scoring.ts
This module derives the affluence summary used by the reviewer list. It uses open-banking evidence first, then metadata enrichment, then declared income, and it can elevate the score when the applicant is C-suite leadership at a top-tier enterprise.
Public methods
| Method | Description |
|---|---|
buildAffluenceSummary |
Derives the affluence summary from an application and its connected accounts. |
extractAffluenceSummary |
Reads a previously stored affluence summary from application metadata when present. |
Priority level values
priority, watchlistPlus, watchlist, none
Score scenario values
default, selfDeclared, verifiedLight, openBanking
Account-like properties
| Property | Type | Description |
|---|---|---|
available |
`number \ | null \ |
current |
`number \ | null \ |
providerLabel |
`string \ | null \ |
category |
`string \ | null \ |
institution |
`string \ | null \ |
currency |
`string \ | null \ |
lastUpdated |
`string \ | null \ |
Affluence summary output
The returned summary is shaped as:
result.stars— rounded to half-star increments and clamped between 1 and 5result.label—Active Income A★result.explanation— narrative reason for the scoreresult.dataQuality— evidence quality scoreresult.metrics— supporting labels and valuessources— evidence sources used to support the summary
Behavioral notes
- Open-banking income has precedence over metadata enrichment and declared income.
- C-suite status adds a role-based uplift path.
- A top-tier enterprise or very high valuation can force a five-star result.
- The summary collects evidence strings such as open banking feeds, enrichment, or applicant declaration.
frontend/lib/affluence-display.ts
This file is consumed by frontend/app/applicants/page.tsx through formatAffluenceStars and resolvePriorityBadgeClassName. The reviewer list uses it to translate affluence summaries into visible star markers and priority badge styles.
3. Dashboard Composition Surfaces
The dashboard pages combine the route outputs and helper results into reviewer-facing summaries:
frontend/app/applicants/page.tsxresolves an affluence summary by tryingextractAffluenceSummary, then wiki-derived affluence data, thenbuildAffluenceSummary.- The same page uses
formatAffluenceStarsandresolvePriorityBadgeClassNamefromfrontend/lib/affluence-display.tsto render the summary consistently. frontend/app/corporate-overview/page.tsxconsumestoApplicationDetail,aggregateAnnualCashFlowTotals,resolveCashInflowAmount, andformatCurrencyWithFallbackto build its chart and payment breakdown surface.frontend/app/api/v1/applicants/[id]/transactions/route.tssupplies the transaction history that later feeds those reviewer summaries.
Feature Flows
Payment History Proxy Flow
sequenceDiagram
participant User
participant Route as Payments History Route
participant Selector as Backend Url Selector
participant Backend as Backend Payments History
User->>Route: POST request with JSON payload
Route->>Route: Parse body and validate with zod
Route->>Selector: Resolve backend base url
Selector-->>Route: Base url
Route->>Backend: POST /api/payments/history
Backend-->>Route: JSON response or 204
Route-->>User: JSON response
The route keeps the request local to the frontend app, but the actual payment history lives behind the backend API. When the backend returns 204, the route emits a normalized JSON object with an empty transaction array and the original date window.
Applicant Transaction Aggregation Flow
sequenceDiagram
participant User
participant Route as Applicant Transactions Route
participant Backend as Backend Applications API
participant Store as Stored Applications
participant Helper as Transaction Extraction
User->>Route: GET request with id and date filters
Route->>Route: Validate path and query parameters
Route->>Route: Extract auth token from headers
Route->>Backend: Fetch application by id
alt direct match found
Backend-->>Route: Application record
else no direct match
Backend-->>Route: Not found or invalid
Route->>Backend: List applications
Route->>Store: Read stored applications
Store-->>Route: Stored application snapshot
end
Route->>Helper: Extract and normalize transactions
Helper-->>Route: Sorted transaction list
Route->>Route: Filter by start and end date
Route-->>User: Applicant transaction summary
The route prefers a direct application match first, then falls back to a broad backend list, and finally to stored snapshots. That makes the transaction history resilient when the applicant is not immediately available from the direct lookup path.
Reviewer Summary Composition Flow
sequenceDiagram
participant ReviewPage as Reviewer Page
participant Detail as toApplicationDetail
participant Payment as Payment Summary Helpers
participant Affluence as Affluence Scoring
participant Display as Affluence Display
ReviewPage->>Detail: Normalize application detail
Detail-->>ReviewPage: Application detail with connected accounts and income history
ReviewPage->>Payment: Derive payment behavior summaries
Payment-->>ReviewPage: Loan and housing summaries
ReviewPage->>Affluence: Build affluence summary
Affluence-->>ReviewPage: Summary with stars, explanation, metrics, sources
ReviewPage->>Display: Format stars and badge classes
Display-->>ReviewPage: UI-ready affluence presentation
This is the path that converts raw banking inputs into the compact reviewer-facing cards and badges shown in the dashboard.
State Management
Summary Derivation Patterns
PriorityLevel:priority,watchlistPlus,watchlist,noneScoreScenario:default,selfDeclared,verifiedLight,openBanking
These values guide how buildAffluenceSummary prioritizes evidence and how the reviewer list classifies the applicant.
Request-Scoped Data Handling
payments/historyvalidates the incoming request body before it contacts the backend.applicants/[id]/transactionsvalidates the path id and query window before it looks up any application data.toApplicationDetailand the summary helpers derive their outputs from the current input objects, so the dashboard view always reflects the data passed into each call.
Integration Points
- Backend application lookup and list endpoints are used by
applicants/[id]/transactions. - Stored application snapshots provide fallback transaction data when the backend lookup is incomplete.
app/api/applications/[id]/route.tscontributescollectApplicationIdentifiersfor applicant matching.@/app/api/applications/commonsuppliesBackendHttpError,buildErrorResponse,extractAuthToken,fetchApplicationsFromBackend,fetchBackendApplicationById,hydrateStoredApplications,readStoredApplications,resolveBackendApiUrlCandidates, andresolveRequestOriginCandidate.frontend/app/applicants/page.tsxconsumesbuildAffluenceSummary,extractAffluenceSummary,formatAffluenceStars, andresolvePriorityBadgeClassName.frontend/app/corporate-overview/page.tsxconsumestoApplicationDetailand the cash-flow helpers to render dashboard charts.
Error Handling
Route-level response patterns
mission-controlredirect: no JSON error path; it simply redirects.payments/history:- invalid JSON body →
400 - schema validation failure →
400 - backend URL resolution failure →
502 - backend network failure →
502 - backend non-OK response → propagated status when possible
- backend
204→ normalized empty transaction JSON
- invalid JSON body →
applicants/[id]/transactions:- invalid path id →
400 - invalid query parameters →
400 - no applicant match →
404 - no transaction history after filtering →
404
- invalid path id →
Logging behavior
payments/historylogs payload validation failures, backend URL resolution errors, network failures, and response parsing failures withconsole.warnorconsole.error.applicants/[id]/transactionslogs backend and stored-data fallback failures, then continues with the remaining sources whenever possible.
Caching Strategy
payments/historyforwards the backend request withcache: "no-store".applicants/[id]/transactionscomputes its response from the current backend and stored application sources on each request.aggregateAnnualCashFlowTotals,summariseLoanPayments,analyseHousingPayments, andbuildAffluenceSummaryare pure transformation helpers over the input data they receive.
Dependencies
next/servernext/headerszod@/app/api/applications/common@/app/api/applications/[id]/route@/lib/application-typesfrontend/lib/affluence-display.tsfrontend/app/corporate-overview/page.tsx- Backend
/api/payments/history - Backend application read and lookup paths
Testing Considerations
GET /api/dashboard/mission-controlreturns a redirect to/mission-control.POST /api/payments/historyrejects malformed JSON and malformed account payloads.POST /api/payments/historypreserves the backend success body and normalizes backend204responses.GET /api/v1/applicants/{id}/transactionsrejects invalid ids and invalid date filters.GET /api/v1/applicants/{id}/transactionsprefers direct backend matches before falling back to lists and stored snapshots.GET /api/v1/applicants/{id}/transactionsreturns404when the filtered transaction set is empty.toApplicationDetailresolvesincome_historyfrom connected accounts before metadata.summariseLoanPaymentsandanalyseHousingPaymentsshould be checked with mixed currencies, missing dates, and empty transaction sets.buildAffluenceSummaryshould be checked with open-banking, metadata-only, and declared-income inputs.
Key Classes Reference
| Class | Responsibility |
|---|---|
route.ts |
Redirects dashboard traffic from mission-control API to /mission-control. |
route.ts |
Proxies payment-history requests to the backend and normalizes the 204 case. |
route.ts |
Builds applicant transaction histories from backend records and stored snapshots. |
financial-insights.ts |
Normalizes applications and derives loan, housing, and annual cash-flow insights. |
affluence-scoring.ts |
Derives reviewer-facing affluence summaries and priority signals. |
affluence-display.ts |
Formats affluence summaries into stars and priority badge classes for the reviewer UI. |