# Architecture

## System Overview

```mermaid
flowchart TB
    subgraph Client["Client (Browser)"]
        UI[Handlebars Views]
        Charts[Chart.js]
        CSS[Bootstrap 4 / CSS]
    end

    subgraph Server["Express Server"]
        direction TB
        Auth[Passport.js Auth]
        Router[Express Router]
        
        subgraph Controllers["Controllers"]
            RC[recordController]
            UC[userController]
            DC[debtController]
            GC[goalController]
            PC[projectController]
            IC[investmentController]
        end

        subgraph Utils["Utilities"]
            Agg[Aggregation Helpers]
            HB[Handlebars Helpers]
        end
    end

    subgraph Data["Data Layer"]
        Mongoose[Mongoose ODM]
        
        subgraph Models["Models"]
            Record[Record]
            Category[Category]
            User[User]
            Debt[Debt]
            Goal[Goal]
            Project[Project]
            Investment[Investment]
        end
    end

    subgraph External["External Services"]
        MongoDB[(MongoDB)]
        Redis[(Redis Sessions)]
        OAuth[Google / Facebook OAuth]
        Imgur[Imgur (Avatars)]
    end

    UI --> Router
    Router --> Auth
    Auth --> OAuth
    Router --> Controllers
    Controllers --> Utils
    Controllers --> Mongoose
    Mongoose --> Models
    Mongoose --> MongoDB
    Auth --> Redis
    UC --> Imgur
    Charts --> UI
```

## Request Flow

```mermaid
sequenceDiagram
    participant B as Browser
    participant E as Express
    participant P as Passport
    participant C as Controller
    participant M as Mongoose
    participant DB as MongoDB
    participant R as Redis

    B->>E: HTTP Request
    E->>R: Session lookup
    R-->>E: Session data
    E->>P: Check authentication
    P-->>E: Authenticated user
    E->>C: Route handler
    C->>M: Query / Aggregate
    M->>DB: Execute operation
    DB-->>M: Result
    M-->>C: Parsed data
    C->>C: Format / Compute
    C-->>E: Render view or redirect
    E-->>B: HTML Response
```

## Ledger System

The core architectural decision: every money transaction carries a `ledger` field (`Personal` or `Business`). This single flag powers separation everywhere.

```mermaid
flowchart LR
    Entry[Transaction Entry] --> Ledger{Ledger?}
    
    Ledger -->|Personal| PE[Personal Expenses]
    Ledger -->|Business| BE[Business Ledger]
    
    PE --> PD[Personal Dashboard]
    BE --> BD[Business Dashboard]
    
    PD --> NP[Net Position]
    BD --> NP
    
    PE --> PB[Personal Budget]
    BE --> BP[Business P&L]
```

### How the Ledger Flag Propagates

```mermaid
sequenceDiagram
    participant U as User
    participant F as Form
    participant C as Controller
    participant DB as MongoDB
    participant V as View

    U->>F: Selects Personal/Business toggle
    F->>C: POST /records with ledger=Personal
    C->>C: Filter categories by ledger
    C->>DB: Record.create({ ledger: 'Personal', ... })
    DB-->>C: Saved record
    
    Note over C,V: On dashboard load
    C->>DB: Aggregate with $match: { ledger }
    DB-->>C: Split totals
    C->>V: personalExpense, businessExpense, etc.
    V->>V: Render side-by-side columns
```

## Authentication Flow

```mermaid
flowchart TD
    A[Login Request] --> B{Strategy?}
    
    B -->|Local| C[Email + Password]
    C --> D[Bcrypt Compare]
    D --> E[Success?]
    
    B -->|Google| F[OAuth Redirect]
    F --> G[Google Callback]
    G --> H[Find or Create User]
    
    B -->|Facebook| I[OAuth Redirect]
    I --> J[Facebook Callback]
    J --> H
    
    E -->|Yes| K[Serialize User]
    H --> K
    E -->|No| L[Flash Error]
    
    K --> M[Create Session]
    M --> N[Store in Redis]
    N --> O[Redirect to /]
```

## Module Independence

Each module is self-contained. The only cross-reference is `Investment ↔ Record.linkedInvestment`.

```mermaid
flowchart TB
    Record[Record] -->|linkedInvestment| Investment[Investment]
    
    Record -.->|no link| Debt[Debt]
    Record -.->|no link| Goal[Goal]
    Record -.->|no link| Project[Project]
    
    Debt --- User[User]
    Goal --- User
    Project --- User
    Investment --- User
    Record --- User
    Category --- User[User]
```

## Tech Stack Details

| Component | Technology | Purpose |
|---|---|---|
| **Web Framework** | Express 4.x | HTTP server, routing, middleware |
| **Template Engine** | express-handlebars 5.x | Server-side rendering |
| **Database** | MongoDB + Mongoose 5.x | Data storage, schema validation |
| **Authentication** | Passport.js | Local, Google, Facebook strategies |
| **Session Store** | Redis + connect-redis | Persistent sessions across restarts |
| **UI Framework** | Bootstrap 4 (Litera) | Responsive layout, components |
| **Charts** | Chart.js 3.x | Doughnut, bar, pie charts |
| **File Upload** | Multer | Avatar image upload |
| **Image Hosting** | Imgur API | Cloud avatar storage |
| **Date Handling** | Moment.js | Date formatting and manipulation |
| **Password Hashing** | bcryptjs | Secure password storage |
| **Method Override** | method-override | PUT/DELETE via POST forms |
