> ## Documentation Index
> Fetch the complete documentation index at: https://docs-terra.withunify.org/llms.txt
> Use this file to discover all available pages before exploring further.

# System Map

> Visual architecture diagram of Pathfinder's components and data flows

# System Map

> A visual guide to how Pathfinder's components connect and data flows through the system.

***

## High-Level Architecture

```mermaid theme={null}
flowchart TB
    subgraph Client["Client Layer"]
        Browser[Web Browser]
        PWA[PWA Shell]
        IDB[(IndexedDB Cache)]
    end

    subgraph Edge["Edge/CDN"]
        Vercel[Vercel Edge]
        Static[Static Assets]
    end

    subgraph App["Application Layer"]
        Next[Next.js App Router]
        Actions[Server Actions]
        DAL[Data Access Layer]
    end

    subgraph Data["Data Layer"]
        Supabase[(Supabase PostgreSQL)]
        Storage[(Supabase Storage)]
        Search[Full-Text Search Index]
    end

    subgraph External["External Services"]
        Nominatim[Nominatim Geocoding]
        Resend[Resend Email]
        Twilio[Twilio SMS]
    end

    Browser --> Vercel
    PWA --> IDB
    IDB -.->|Offline| Browser
    Vercel --> Next
    Vercel --> Static

    Next --> Actions
    Actions --> DAL
    DAL --> Supabase
    DAL --> Storage
    Supabase --> Search

    Actions --> Nominatim
    Actions --> Resend
    Actions --> Twilio
```

***

## Component Breakdown

### Client Layer

| Component           | Purpose                    | Technology               |
| ------------------- | -------------------------- | ------------------------ |
| **Web Browser**     | Primary user interface     | React 19, Next.js 15     |
| **PWA Shell**       | Installable app experience | next-pwa, Service Worker |
| **IndexedDB Cache** | Offline program storage    | Custom wrapper with IDB  |

### Application Layer

| Component             | Purpose                     | Location           |
| --------------------- | --------------------------- | ------------------ |
| **App Router**        | Page routing and layouts    | `src/app/`         |
| **Server Actions**    | Mutations and data fetching | `src/app/actions/` |
| **Data Access Layer** | Repository pattern for DB   | `src/lib/dal/`     |
| **Components**        | Reusable UI elements        | `src/components/`  |

### Data Layer

| Component            | Purpose          | Details                       |
| -------------------- | ---------------- | ----------------------------- |
| **PostgreSQL**       | Primary database | Supabase-hosted, RLS enabled  |
| **Full-Text Search** | Program search   | `tsvector` with GIN index     |
| **File Storage**     | Document uploads | Supabase Storage, signed URLs |

***

## Data Flow: Screener to Match

```mermaid theme={null}
sequenceDiagram
    participant U as User
    participant S as Screener UI
    participant A as Server Action
    participant G as Geocoding
    participant D as Database
    participant E as Eligibility Engine

    U->>S: Enter ZIP code (78701)
    S->>A: updateScreenerLocation()
    A->>G: geocodeZip("78701")
    G->>A: {lat, lng, fips: "48453"}
    A->>D: Store location in session
    A->>S: Location confirmed

    U->>S: Enter household info
    S->>A: updateScreenerHousehold()
    A->>D: Store household data
    A->>E: matchPrograms(householdData)
    E->>D: Query programs by geography
    D->>E: 847 programs
    E->>E: Apply eligibility rules
    E->>A: {matched: 23, maybe: 45}
    A->>S: Display results
```

***

## Data Flow: Document Upload

```mermaid theme={null}
sequenceDiagram
    participant U as User
    participant UI as Upload UI
    participant A as Server Action
    participant S as Supabase Storage
    participant D as Database

    U->>UI: Select file (pay_stub.pdf)
    UI->>UI: Validate file type/size
    UI->>A: uploadDocument(file, metadata)
    A->>A: Generate safe path
    A->>S: Upload to private bucket
    S->>A: Storage path
    A->>D: Create document record
    D->>A: Document ID
    A->>UI: Upload complete
    UI->>U: Show preview
```

***

## Data Flow: Notification Delivery

```mermaid theme={null}
flowchart LR
    subgraph Trigger
        Deadline[Deadline Approaching]
        Status[Status Change]
        Match[New Program Match]
    end

    subgraph Queue
        Create[Create Notification]
        Prefs[Check Preferences]
    end

    subgraph Delivery
        Email[Resend Email]
        SMS[Twilio SMS]
        Push[Web Push]
    end

    subgraph UI
        Bell[Notification Bell]
        Center[Notification Center]
    end

    Deadline --> Create
    Status --> Create
    Match --> Create

    Create --> Prefs
    Prefs -->|Email enabled| Email
    Prefs -->|SMS enabled| SMS
    Prefs -->|Push enabled| Push
    Prefs --> Bell
    Prefs --> Center
```

***

## Directory Structure

```
apps/pathfinder/src/
├── app/
│   ├── (dashboard)/           # Authenticated pages
│   │   ├── dashboard/         # User dashboard
│   │   ├── programs/          # Program details
│   │   ├── applications/      # Application tracking
│   │   ├── documents/         # Document management
│   │   ├── notifications/     # Notification history
│   │   ├── share-story/       # Story submission
│   │   └── case-manager/      # Case manager portal
│   ├── (public)/              # Public pages
│   │   ├── browse/            # Program browser
│   │   ├── screener/          # Eligibility screener
│   │   └── stories/           # Success stories
│   ├── api/                   # API routes
│   └── actions/               # Server actions
├── components/
│   ├── browse/                # Browse page components
│   ├── screener/              # Screener flow components
│   ├── dashboard/             # Dashboard widgets
│   ├── documents/             # Document management
│   ├── calendar/              # Calendar integration
│   ├── notifications/         # Notification UI
│   ├── success-stories/       # Story components
│   ├── case-manager/          # Case manager UI
│   ├── map/                   # Map components
│   ├── pwa/                   # PWA install prompt
│   ├── offline/               # Offline indicators
│   └── skeletons/             # Loading skeletons
├── lib/
│   ├── dal/                   # Data Access Layer
│   │   └── repositories/      # Database repositories
│   ├── eligibility/           # Eligibility engine
│   ├── calendar/              # ICS generation
│   ├── offline/               # IndexedDB caching
│   ├── geocoding.ts           # ZIP to coordinates
│   ├── notifications.ts       # Email/SMS sending
│   ├── email.ts               # Resend client
│   └── sms.ts                 # Twilio client
├── hooks/                     # React hooks
└── types/                     # TypeScript types
```

***

## Database Schema Overview

```mermaid theme={null}
erDiagram
    PROFILES ||--o{ APPLICATIONS : has
    PROFILES ||--o{ DOCUMENTS : uploads
    PROFILES ||--o{ SUCCESS_STORIES : writes
    PROFILES ||--o{ NOTIFICATION_PREFERENCES : configures

    PROGRAMS ||--o{ APPLICATIONS : receives
    PROGRAMS ||--o{ SUCCESS_STORIES : inspires
    PROGRAMS }|--|| CATEGORIES : belongs_to

    APPLICATIONS ||--o{ DOCUMENTS : requires
    APPLICATIONS ||--o{ APPLICATION_NOTES : has

    SUCCESS_STORIES ||--o{ STORY_VOTES : receives

    ORGANIZATIONS ||--o{ USER_ROLES : defines
    ORGANIZATIONS ||--o{ CASE_MANAGER_CLIENTS : manages

    PROFILES {
        text id PK
        text email
        text full_name
        jsonb screener_data
        jsonb notification_preferences
    }

    PROGRAMS {
        uuid id PK
        text name
        text category
        text coverage_type
        jsonb eligibility_rules
        tsvector search_vector
    }

    APPLICATIONS {
        uuid id PK
        text user_id FK
        uuid program_id FK
        text status
        date renewal_date
    }

    DOCUMENTS {
        uuid id PK
        text user_id FK
        text document_type
        text storage_path
        date expiration_date
    }

    SUCCESS_STORIES {
        uuid id PK
        text author_id FK
        uuid program_id FK
        text status
        integer helpful_count
    }
```

***

## External Service Integration

<CardGroup cols={2}>
  <Card title="Nominatim Geocoding" icon="map-location-dot">
    OpenStreetMap-based geocoding for ZIP to coordinates conversion. Self-hosted option available for high volume.
  </Card>

  <Card title="Resend Email" icon="envelope">
    Transactional email delivery for notifications, reminders, and status updates. React Email templates.
  </Card>

  <Card title="Twilio SMS" icon="message-sms">
    SMS notifications for time-sensitive alerts like deadline reminders and status changes.
  </Card>

  <Card title="Supabase" icon="database">
    PostgreSQL database with Row Level Security, real-time subscriptions, and file storage.
  </Card>
</CardGroup>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Programs Database" icon="database" href="/pathfinder/core-systems/programs-database">
    Deep dive into the programs schema and queries
  </Card>

  <Card title="Eligibility Engine" icon="gears" href="/pathfinder/core-systems/eligibility-engine">
    How the matching algorithm works
  </Card>
</CardGroup>
