> ## Documentation Index
> Fetch the complete documentation index at: https://dhanurgo.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Data Flows

> How data moves through the system — CSV import, KPI calculation, investor payments

# Data Flows

Three critical data flows power HostMetrics.

## 1. CSV Import Flow

Data enters the system via CSV file upload or Chrome extension sync.

```mermaid theme={null}
sequenceDiagram
    participant User
    participant UI as FileUploader / Extension
    participant API as /api/turo/sync
    participant IS as import-service.ts
    participant DB as Supabase (PostgreSQL)

    User->>UI: Upload CSV / Click Sync
    UI->>API: POST (csv_content, csv_type, token)
    API->>API: Validate auth token
    API->>IS: parseCSV(content, type)
    IS->>IS: Detect CSV type by headers
    IS->>IS: Map fields (TRIP_FIELD_MAPPING)
    IS->>IS: Parse currency, dates, integers
    IS->>DB: Check for existing records (dedup)
    IS->>DB: Batch upsert (500 rows/batch)
    IS->>DB: Auto-create vehicles if missing
    IS->>DB: Create csv_imports audit record
    DB-->>API: Success + stats
    API-->>UI: {total, new, updated}
```

**Key details:**

* Trip records are deduplicated by `(user_id, reservation_id)`
* Earnings records are deduplicated by `(user_id, composite_key)`
* Previous imports of the same type are marked "superseded"
* Vehicle records are auto-created from trip data if they don't exist

## 2. KPI Calculation Pipeline

Dashboard metrics are computed from raw data using pure functions.

```mermaid theme={null}
flowchart LR
    subgraph Fetch["Data Fetching (parallel)"]
        T["trips"]
        E["expenses"]
        M["maintenance"]
        V["vehicles"]
    end

    subgraph Calc["Pure Calculations"]
        F["Financial KPIs<br/>(earnings, profit, margin)"]
        TR["Trip KPIs<br/>(count, avg, duration)"]
        FL["Fleet KPIs<br/>(utilization, daily rate)"]
        RS["Revenue Streams<br/>(price, delivery, extras...)"]
        PV["Per-Vehicle KPIs"]
        MO["Monthly Trends"]
    end

    subgraph Output["Dashboard"]
        D["StatCards + Charts"]
    end

    T & E & M & V -->|"Promise.all()"| Calc
    F & TR & FL & RS & PV & MO --> D
```

**Key files:**

* `src/lib/kpi/queries.ts` — Parallel data fetching
* `src/lib/kpi/calculations.ts` — Pure calculation functions (869 lines)
* `src/hooks/useKPIs.ts` — React hook wrapper

## 3. Investor Payment Flow

Revenue sharing between host and investor.

```mermaid theme={null}
sequenceDiagram
    participant Host
    participant Modal as RecordPaymentModal
    participant Calc as investorEarnings.ts
    participant DB as Supabase

    Host->>Modal: Click "Record Payment"
    Modal->>DB: Fetch vehicle trips for period
    Modal->>DB: Fetch investor settings + inclusions
    Modal->>Calc: calculateInvestorEarnings()

    Note over Calc: Step 1: Adjust revenue<br/>(exclude toggled-off items:<br/>tolls, gas, EV, etc.)
    Note over Calc: Step 2: Apply expense treatment<br/>(three-pool model)
    Note over Calc: Step 3: Apply split ratio<br/>(e.g., Host 20% / Investor 80%)
    Note over Calc: Step 4: Subtract charges<br/>(maintenance, violations, etc.)

    Calc-->>Modal: Net investor payout amount
    Host->>Modal: Confirm payment
    Modal->>DB: Create investor_payments record
    Modal->>DB: Create investor_activities log
    DB-->>Modal: Success
```

**Key files:**

* `src/lib/calculations/investorEarnings.ts` — Three-pool expense model
* `src/lib/calculations/vehicleRevenue.ts` — Revenue adjustment with inclusion toggles
* `src/lib/db/investors.ts` — Payment CRUD + calculations
