# dawoodmehmood/psxworth architecture

> Architecture diagram of the GitHub repository dawoodmehmood/psxworth, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-22). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/dawoodmehmood/psxworth
- Repository: https://github.com/dawoodmehmood/psxworth

## Overview

#### Purpose and runtime
PsxWorth is a Next.js 16 / React 19 App Router application for Pakistan Stock Exchange investors. It manages portfolios and transactions, calculates performance and allocation, surfaces payouts/corporate actions, and uses AI to parse broker or CDC transaction statements. The browser experience is responsive and installable as a PWA.

Entry routes are rooted in `src/app/page.tsx`, with portfolio workspace routes at `src/app/portfolio/page.tsx` and `src/app/portfolio/[portfolioId]/page.tsx`. Global composition and error handling live in `src/app/layout.tsx` and `src/app/global-error.tsx`.

#### Application boundary and access
The App Router owns page rendering, route layouts, loading/error states, metadata, sitemap, and the PWA manifest. Request-level protection or routing policy is likely centralized at `src/proxy.ts`. Authentication is provided by Clerk; app code should treat Clerk identity as the boundary between anonymous public pages and user-owned portfolio data.

Relevant paths: `src/app/layout.tsx`, `src/proxy.ts`, `src/app/manifest.ts`.

#### Portfolio workspace
The portfolio route is the primary authenticated product surface. It composes portfolio selection, creation, transaction entry/import, transaction tables, allocation charts, and performance views around a selected `portfolioId`. The last active portfolio is persisted through a cookie action, allowing navigation to restore context.

Relevant paths: `src/app/portfolio/[portfolioId]/page.tsx`, `src/app/portfolio/[portfolioId]/components/PortfoliosSidebar/index.tsx`, `src/actions/cookies/lastActivePortfolio.ts`.

#### Server-side domain operations
`src/actions` is the core server-side domain boundary. Portfolio and transaction actions mutate user records; stock, ETF, payout, and performance actions read market data and derive investor-facing views. Action middleware/errors provide a shared enforcement and failure-handling layer.

Primary flow: UI or React Query hook → action → database/query or market-data lookup → normalized domain result → UI invalidation/render.

Relevant paths: `src/actions/portfolio/portfolioActions.ts`, `src/actions/transaction/TransactionFunctions.ts`, `src/actions/portfolioPerformance/portfolioPerformance.ts`.

#### Dual database model
Drizzle ORM connects to two PostgreSQL domains: a user database for portfolios/transactions and a data database for public PSX market data. Their schemas are intentionally separated, as are migrations. This is a material boundary: user writes must not couple to market-data snapshot management.

Relevant paths: `src/db/index.ts`, `src/db/userdb-schema.ts`, `src/db/datadb-schema.ts`, `migrations-userdb`, `migrations`.

#### Market data, analytics, and entitlements
Portfolio calculations combine user transactions with prices, stock metadata, ETF constituents, and payout/corporate-action records. Historical returns is a self-contained feature with query/action/chart layers. Allocation and performance UI consume these derived outputs rather than directly owning persistence logic.

Relevant paths: `src/features/historicalReturns/actions/historicalReturnsActions.ts`, `src/features/stockPrices/queries.ts`, `src/actions/payouts/index.ts`.

#### AI import and client data flow
AI-assisted import is encapsulated in `src/lib/ai`: client integration, prompts, schemas, and parsing helpers should constrain untrusted statement input into validated transaction candidates before user review and transaction persistence. TanStack Query provides client fetching/cache coordination via the root provider; forms and tables are client interaction boundaries.

Relevant paths: `src/lib/ai/aiClient.ts`, `src/lib/ai/schema.ts`, `src/components/QueryProvider/index.tsx`.

#### Operations and external services
External services include Clerk authentication, PostHog product analytics, PostgreSQL, and an AI provider behind the AI client. Client/server instrumentation and PostHog integration are explicit. The app ships as a standalone Dockerized Next deployment; GitHub workflows cover verification, deployment, and market-data snapshot synchronization.

Relevant paths: `instrumentation.js`, `src/app/posthog-server.js`, `Dockerfile`, `.github/workflows/sync-data-snapshot.yml`.

Main entry points: [`src/app/portfolio/[portfolioId]/page.tsx`](https://github.com/dawoodmehmood/psxworth/blob/develop/src/app/portfolio/%5BportfolioId%5D/page.tsx) (Portfolio workspace), [`src/db/index.ts`](https://github.com/dawoodmehmood/psxworth/blob/develop/src/db/index.ts) (Drizzle data access), [`src/lib/ai/aiClient.ts`](https://github.com/dawoodmehmood/psxworth/blob/develop/src/lib/ai/aiClient.ts) (AI statement parser), [`src/app/layout.tsx`](https://github.com/dawoodmehmood/psxworth/blob/develop/src/app/layout.tsx) (App Router)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_app["Next.js application"]
  node_router["App Router<br/>Next.js routes<br/>[layout.tsx]"]
  node_access["Request access policy<br/>proxy<br/>[proxy.ts]"]
  node_pwa["PWA manifest<br/>[manifest.ts]"]
  node_portfolio_page["Portfolio workspace<br/>authenticated route<br/>[page.tsx]"]
  node_portfolio_sidebar["Portfolio selector<br/>workspace component<br/>[index.tsx]"]
  node_query_provider["Client query cache<br/>TanStack Query provider<br/>[index.tsx]"]
end

subgraph group_domain["Domain services"]
  node_portfolio_actions["Portfolio actions<br/>server actions"]
  node_transaction_actions["Transaction actions<br/>server actions"]
  node_performance_actions["Performance calculations<br/>server actions"]
  node_historical_returns["Historical returns<br/>feature actions"]
  node_payout_actions["Payouts and actions<br/>server actions<br/>[index.ts]"]
  node_last_active_cookie["Last active portfolio<br/>cookie action"]
  node_ai_import["AI statement parser<br/>AI client<br/>[aiClient.ts]"]
  node_ai_schema["Import validation schema<br/>AI schema<br/>[schema.ts]"]
end

subgraph group_data["Data and integrations"]
  node_drizzle["Drizzle data access<br/>ORM connections<br/>[index.ts]"]
  node_user_db[("User PostgreSQL domain<br/>portfolio schema<br/>[userdb-schema.ts]")]
  node_market_db[("Market-data PostgreSQL domain<br/>market schema<br/>[datadb-schema.ts]")]
  node_stock_queries["Market price queries<br/>data queries<br/>[queries.ts]"]
  node_clerk{{"Clerk<br/>authentication service"}}
  node_ai_provider{{"AI provider<br/>external AI service"}}
end

subgraph group_ops["Delivery and observability"]
  node_posthog["PostHog instrumentation<br/>product analytics<br/>[posthog-server.js]"]
  node_instrumentation["Runtime instrumentation<br/>[instrumentation.js]"]
  node_docker["Standalone deployment<br/>Docker image"]
  node_snapshot_workflow["Market snapshot sync<br/>GitHub workflow"]
end

node_router -->|"requests pass through"| node_access
node_access -->|"authenticates"| node_clerk
node_router -->|"publishes"| node_pwa
node_router -->|"renders"| node_portfolio_page
node_portfolio_page -->|"composes"| node_portfolio_sidebar
node_portfolio_page -->|"uses cache"| node_query_provider
node_portfolio_sidebar -->|"persists selection"| node_last_active_cookie
node_query_provider -->|"calls and invalidates"| node_portfolio_actions
node_query_provider -->|"calls and invalidates"| node_transaction_actions
node_portfolio_page -->|"loads views"| node_performance_actions
node_portfolio_page -->|"loads returns"| node_historical_returns
node_portfolio_page -->|"loads payouts"| node_payout_actions
node_portfolio_page -->|"imports statements"| node_ai_import
node_ai_import -->|"validates candidates"| node_ai_schema
node_ai_import -->|"parses statement"| node_ai_provider
node_ai_import -->|"submits reviewed entries"| node_transaction_actions
node_portfolio_actions -->|"reads and writes"| node_drizzle
node_transaction_actions -->|"writes transactions"| node_drizzle
node_performance_actions -->|"combines domains"| node_drizzle
node_historical_returns -->|"uses prices"| node_stock_queries
node_payout_actions -->|"reads actions"| node_drizzle
node_stock_queries -->|"reads market data"| node_drizzle
node_drizzle -->|"user connection"| node_user_db
node_drizzle -->|"market-data connection"| node_market_db
node_snapshot_workflow -->|"synchronizes snapshots"| node_market_db
node_instrumentation -->|"reports telemetry"| node_posthog
node_docker -->|"deploys"| node_router

click node_router "https://github.com/dawoodmehmood/psxworth/blob/develop/src/app/layout.tsx"
click node_access "https://github.com/dawoodmehmood/psxworth/blob/develop/src/proxy.ts"
click node_pwa "https://github.com/dawoodmehmood/psxworth/blob/develop/src/app/manifest.ts"
click node_portfolio_page "https://github.com/dawoodmehmood/psxworth/blob/develop/src/app/portfolio/%5BportfolioId%5D/page.tsx"
click node_portfolio_sidebar "https://github.com/dawoodmehmood/psxworth/blob/develop/src/app/portfolio/%5BportfolioId%5D/components/PortfoliosSidebar/index.tsx"
click node_query_provider "https://github.com/dawoodmehmood/psxworth/blob/develop/src/components/QueryProvider/index.tsx"
click node_portfolio_actions "https://github.com/dawoodmehmood/psxworth/blob/develop/src/actions/portfolio/portfolioActions.ts"
click node_transaction_actions "https://github.com/dawoodmehmood/psxworth/blob/develop/src/actions/transaction/TransactionFunctions.ts"
click node_performance_actions "https://github.com/dawoodmehmood/psxworth/blob/develop/src/actions/portfolioPerformance/portfolioPerformance.ts"
click node_historical_returns "https://github.com/dawoodmehmood/psxworth/blob/develop/src/features/historicalReturns/actions/historicalReturnsActions.ts"
click node_payout_actions "https://github.com/dawoodmehmood/psxworth/blob/develop/src/actions/payouts/index.ts"
click node_last_active_cookie "https://github.com/dawoodmehmood/psxworth/blob/develop/src/actions/cookies/lastActivePortfolio.ts"
click node_ai_import "https://github.com/dawoodmehmood/psxworth/blob/develop/src/lib/ai/aiClient.ts"
click node_ai_schema "https://github.com/dawoodmehmood/psxworth/blob/develop/src/lib/ai/schema.ts"
click node_drizzle "https://github.com/dawoodmehmood/psxworth/blob/develop/src/db/index.ts"
click node_user_db "https://github.com/dawoodmehmood/psxworth/blob/develop/src/db/userdb-schema.ts"
click node_market_db "https://github.com/dawoodmehmood/psxworth/blob/develop/src/db/datadb-schema.ts"
click node_stock_queries "https://github.com/dawoodmehmood/psxworth/blob/develop/src/features/stockPrices/queries.ts"
click node_posthog "https://github.com/dawoodmehmood/psxworth/blob/develop/src/app/posthog-server.js"
click node_instrumentation "https://github.com/dawoodmehmood/psxworth/blob/develop/instrumentation.js"
click node_docker "https://github.com/dawoodmehmood/psxworth/blob/develop/Dockerfile"
click node_snapshot_workflow "https://github.com/dawoodmehmood/psxworth/blob/develop/.github/workflows/sync-data-snapshot.yml"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_router,node_access,node_pwa,node_portfolio_page,node_portfolio_sidebar,node_query_provider toneBlue
class node_portfolio_actions,node_transaction_actions,node_performance_actions,node_historical_returns,node_payout_actions,node_last_active_cookie,node_ai_import,node_ai_schema toneAmber
class node_drizzle,node_user_db,node_market_db,node_stock_queries,node_clerk,node_ai_provider toneMint
class node_posthog,node_instrumentation,node_docker,node_snapshot_workflow toneRose
```

## Components

### Next.js application

- [App Router](https://github.com/dawoodmehmood/psxworth/blob/develop/src/app/layout.tsx): Next.js routes · Renders pages, layouts, metadata, and PWA surfaces. · `src/app/layout.tsx`
- [Request access policy](https://github.com/dawoodmehmood/psxworth/blob/develop/src/proxy.ts): proxy · Applies routing and request-level protection. · `src/proxy.ts`
- [PWA manifest](https://github.com/dawoodmehmood/psxworth/blob/develop/src/app/manifest.ts): manifest · `src/app/manifest.ts`
- [Portfolio workspace](https://github.com/dawoodmehmood/psxworth/blob/develop/src/app/portfolio/%5BportfolioId%5D/page.tsx): authenticated route · Primary selected-portfolio product surface. · `src/app/portfolio/[portfolioId]/page.tsx`
- [Portfolio selector](https://github.com/dawoodmehmood/psxworth/blob/develop/src/app/portfolio/%5BportfolioId%5D/components/PortfoliosSidebar/index.tsx): workspace component · `src/app/portfolio/[portfolioId]/components/PortfoliosSidebar/index.tsx`
- [Client query cache](https://github.com/dawoodmehmood/psxworth/blob/develop/src/components/QueryProvider/index.tsx): TanStack Query provider · Coordinates client fetching, cache, and invalidation. · `src/components/QueryProvider/index.tsx`

### Domain services

- [Portfolio actions](https://github.com/dawoodmehmood/psxworth/blob/develop/src/actions/portfolio/portfolioActions.ts): server actions · Mutates user-owned portfolio records. · `src/actions/portfolio/portfolioActions.ts`
- [Transaction actions](https://github.com/dawoodmehmood/psxworth/blob/develop/src/actions/transaction/TransactionFunctions.ts): server actions · Persists reviewed transaction entries and imports. · `src/actions/transaction/TransactionFunctions.ts`
- [Performance calculations](https://github.com/dawoodmehmood/psxworth/blob/develop/src/actions/portfolioPerformance/portfolioPerformance.ts): server actions · Derives investor-facing portfolio performance. · `src/actions/portfolioPerformance/portfolioPerformance.ts`
- [Historical returns](https://github.com/dawoodmehmood/psxworth/blob/develop/src/features/historicalReturns/actions/historicalReturnsActions.ts): feature actions · Provides historical-return query and chart data. · `src/features/historicalReturns/actions/historicalReturnsActions.ts`
- [Payouts and actions](https://github.com/dawoodmehmood/psxworth/blob/develop/src/actions/payouts/index.ts): server actions · `src/actions/payouts/index.ts`
- [Last active portfolio](https://github.com/dawoodmehmood/psxworth/blob/develop/src/actions/cookies/lastActivePortfolio.ts): cookie action · Restores portfolio context on navigation. · `src/actions/cookies/lastActivePortfolio.ts`
- [AI statement parser](https://github.com/dawoodmehmood/psxworth/blob/develop/src/lib/ai/aiClient.ts): AI client · Converts untrusted statements into validated transaction candidates. · `src/lib/ai/aiClient.ts`
- [Import validation schema](https://github.com/dawoodmehmood/psxworth/blob/develop/src/lib/ai/schema.ts): AI schema · `src/lib/ai/schema.ts`

### Data and integrations

- [Drizzle data access](https://github.com/dawoodmehmood/psxworth/blob/develop/src/db/index.ts): ORM connections · Separates user and market-data PostgreSQL access. · `src/db/index.ts`
- [User PostgreSQL domain](https://github.com/dawoodmehmood/psxworth/blob/develop/src/db/userdb-schema.ts): portfolio schema · Owns portfolios and transactions. · `src/db/userdb-schema.ts`
- [Market-data PostgreSQL domain](https://github.com/dawoodmehmood/psxworth/blob/develop/src/db/datadb-schema.ts): market schema · Owns public prices, metadata, ETFs, and payouts. · `src/db/datadb-schema.ts`
- [Market price queries](https://github.com/dawoodmehmood/psxworth/blob/develop/src/features/stockPrices/queries.ts): data queries · `src/features/stockPrices/queries.ts`
- **Clerk**: authentication service · Identity boundary for user-owned data.
- **AI provider**: external AI service

### Delivery and observability

- [PostHog instrumentation](https://github.com/dawoodmehmood/psxworth/blob/develop/src/app/posthog-server.js): product analytics · `src/app/posthog-server.js`
- [Runtime instrumentation](https://github.com/dawoodmehmood/psxworth/blob/develop/instrumentation.js): instrumentation · `instrumentation.js`
- [Standalone deployment](https://github.com/dawoodmehmood/psxworth/blob/develop/Dockerfile): Docker image · `Dockerfile`
- [Market snapshot sync](https://github.com/dawoodmehmood/psxworth/blob/develop/.github/workflows/sync-data-snapshot.yml): GitHub workflow · Synchronizes market-data snapshots. · `.github/workflows/sync-data-snapshot.yml`

## Connections

- App Router → Request access policy: requests pass through
- Request access policy → Clerk: authenticates
- App Router → PWA manifest: publishes
- App Router → Portfolio workspace: renders
- Portfolio workspace → Portfolio selector: composes
- Portfolio workspace → Client query cache: uses cache
- Portfolio selector → Last active portfolio: persists selection
- Client query cache → Portfolio actions: calls and invalidates
- Client query cache → Transaction actions: calls and invalidates
- Portfolio workspace → Performance calculations: loads views
- Portfolio workspace → Historical returns: loads returns
- Portfolio workspace → Payouts and actions: loads payouts
- Portfolio workspace → AI statement parser: imports statements
- AI statement parser → Import validation schema: validates candidates
- AI statement parser → AI provider: parses statement
- AI statement parser → Transaction actions: submits reviewed entries
- Portfolio actions → Drizzle data access: reads and writes
- Transaction actions → Drizzle data access: writes transactions
- Performance calculations → Drizzle data access: combines domains
- Historical returns → Market price queries: uses prices
- Payouts and actions → Drizzle data access: reads actions
- Market price queries → Drizzle data access: reads market data
- Drizzle data access → User PostgreSQL domain: user connection
- Drizzle data access → Market-data PostgreSQL domain: market-data connection
- Market snapshot sync → Market-data PostgreSQL domain: synchronizes snapshots
- Runtime instrumentation → PostHog instrumentation: reports telemetry
- Standalone deployment → App Router: deploys
