# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Commands

```bash
npm run dev       # Start Vite dev server on port 3000
npm run build     # Production build to dist/
npm run preview   # Preview production build
```

No test or lint scripts are configured. ESLint config exists (`eslint.config.js`) but has no npm script.

## Deployment

Project: `craze-analytix2` under Vercel team `christians-projects-dd62b5fc`.

```bash
vercel --prod --scope christians-projects-dd62b5fc
```

The `.vercel/project.json` must point to `projectId: prj_TYI5xVvuZ0kPI5Ap8zmX7cqfjsCi` and `orgId: team_5AhzZHthpZINNw9vOrKxOINr`.

## Environment Variables

| Variable | Used in | Purpose |
|---|---|---|
| `GEMINI_API_KEY` | `.env.local` | AI chat (Google Gemini) |
| `SUPABASE_URL` | Vercel env / serverless | Supabase project URL |
| `SUPABASE_SERVICE_KEY` | `api/experiments.ts`, `api/upload-vendor-data.ts` | Server-side Supabase access |
| `SUPABASE_ANON_KEY` | `services/supabase.ts` | Client-side Supabase access |

## Architecture

Amazon seller analytics dashboard: React 19 + TypeScript + Vite + Tailwind CSS (CDN). Deployed on Vercel with serverless API routes.

### Data Flow

```
Dropbox (CSV/Excel files)
  → /api/* serverless functions (fetch + proxy)
  → dataProcessor.ts (parse, normalize, aggregate)
  → App.tsx state (useState, no Redux)
  → View components (Dashboard, DataGrid, AdsPerformance, etc.)
```

Data is cached in IndexedDB via `services/storage.ts`. On load, cached data displays immediately while fresh data fetches in the background.

All data sources are fetched automatically from Dropbox — there is no manual file upload.

### Key Files

- **App.tsx** — Main orchestrator. Holds all global state and passes data/handlers as props to views. All data fetching (`handleDataFetch`, `handleAdsFetch`, `handleBSRFetch`, etc.) is initiated here.
- **services/dataProcessor.ts** (~2400 lines) — Core data engine. Handles CSV/Excel parsing, currency normalization (EU `1.234,56` and US `1,234.56` formats), Spanish/English month mapping, filtering (`filterData`, `filterAdsData`, `filterBsrData`), aggregation, and pivot table generation.
- **types.ts** — All TypeScript interfaces: `SalesRecord`, `AdsRecord`, `TrafficRecord`, `ForecastRecord`, `BSRRecord`, `FilterState`, `AggregatedData`, `PivotRow`, `Experiment`, etc.
- **services/storage.ts** — IndexedDB + localStorage caching with schema versioning. Increment `SCHEMA_VERSION` when changing cached data shapes.
- **services/experiments.ts** — CRUD operations for experiments via `/api/experiments` (Supabase-backed). Includes ASIN resolution logic for line-level experiments.
- **services/experimentAnalysis.ts** — Difference-in-Differences (DiD) statistical analysis engine. Uses ISO week boundaries (Monday start).

### Views

| View key | Component | Purpose |
|----------|-----------|---------|
| `dashboard` | Dashboard.tsx | KPI cards, charts, YoY comparisons |
| `table` | DataGrid.tsx | Pivot table with Excel-style column filters |
| `weekly` | WeeklyGrid.tsx | Weekly time-series breakdown |
| `movers` | TopMovers.tsx | Top growth/decline products |
| `ads` | AdsPerformance.tsx | Ad spend, ROAS, ACOS metrics |
| `forecast` | ForecastView.tsx | Product forecasts with velocity mapping |
| `vendor` | VendorDataView.tsx | BSR trends, ratings per market. Shows product card (SKU/ASIN/title/BuyBox) when a single ASIN is filtered |
| `experiments` | ExperimentsView.tsx | A/B experiment tracking with DiD analysis and Bayesian verdicts |

### API Routes (`/api/`)

All fetch routes proxy Dropbox direct-download URLs (`dl=1`) and return raw file content for client-side parsing:

- `fetch-data.ts` — Sales CSV
- `fetch-ads.ts` — Ads Excel (weekly)
- `fetch-traffic.ts` — Traffic/Glance Views Excel
- `fetch-stock.ts` — Item availability
- `fetch-paneu-stock.ts` — PAN-EU vendor stock
- `fetch-uk-inventory.ts` — UK inventory
- `fetch-buybox.ts` — Buy Box tracker Excel
- `fetch-forecast.ts` — Forecast Excel
- `fetch-bsr.ts` — BSR/ratings Excel (feeds Vendor tab)
- `ask-gemini.ts` — Proxies AI chat to Gemini API
- `experiments.ts` — CRUD for experiments stored in Supabase
- `upload-vendor-data.ts` — Batch upsert of vendor rows to Supabase

### Important Constants (in dataProcessor.ts)

- `PAN_EU_COUNTRIES = ['Amazon DE', 'Amazon IT', 'Amazon FR', 'Amazon ES']` — Default country filter when no customer is selected
- `parseCurrency()` — Handles both EU (`1.234,56`) and US (`1,234.56`) number formats
- Country mapping normalizes various spellings → `Amazon DE`, `Amazon UK`, etc.
- `MONTH_MAP` — Normalizes Spanish month names (Enero→Jan, etc.)

### Filtering Architecture

Filters flow: `FilterBar.tsx` → `App.tsx` state → `filterData()` / `filterAdsData()` / `filterBsrData()` in dataProcessor.ts. When no customer filter is selected, ads data defaults to PAN_EU_COUNTRIES only. Sales and ads data have separate filter functions.

`globalAsinMetadata` (`Map<string, {sku, title, line}>`) is built from `rawData` in App.tsx and passed to views that need product metadata lookups.

### Path Alias

`@/*` maps to project root (configured in both `tsconfig.json` and `vite.config.ts`).
