# CLAUDE.md

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

## Project Overview

This is a full-stack inventory management system with a React + TypeScript frontend and Node.js/Express backend using PostgreSQL. The system includes product management, analytics, forecasting, purchase orders, and a comprehensive dashboard for business metrics.

**Monorepo Structure:**
- `inventory/` - Vite-based React frontend with TypeScript
- `inventory-server/` - Express backend API server
- Root `package.json` contains shared dependencies

## Development Commands

### Frontend (inventory/)
```bash
cd inventory
npm run dev        # Start dev server on port 5175
npm run build      # Build for production (outputs to build/ then copies to ../inventory-server/frontend/build)
npm run lint       # Run ESLint
npm run preview    # Preview production build
```

### Backend (inventory-server/)
```bash
cd inventory-server
npm run dev        # Start with nodemon (auto-reload)
npm start          # Start server (production)
npm run prod       # Start with PM2 for production
npm run prod:stop  # Stop PM2 instance
npm run prod:restart  # Restart PM2 instance
npm run prod:logs  # View PM2 logs
npm run setup      # Create required directories (logs, uploads)
```

## Architecture

### Frontend Architecture

**Router Structure:** React Router with lazy loading for code splitting:
- Main chunks: Core inventory, Dashboard, Product Import, Chat Archive
- Authentication flow uses `RequireAuth` and `Protected` components with permission-based access
- All routes except `/login` and `/small` require authentication

**Key Directories:**
- `src/pages/` - Top-level page components (Overview, Products, Analytics, Dashboard, etc.)
- `src/components/` - Organized by feature (dashboard/, products/, analytics/, etc.)
- `src/components/ui/` - shadcn/ui components
- `src/types/` - TypeScript type definitions
- `src/contexts/` - React contexts (AuthContext, DashboardScrollContext)
- `src/hooks/` - Custom React hooks (use-toast, useDebounce, use-mobile)
- `src/utils/` - Utility functions (emojiUtils, productUtils, naturalLanguagePeriod)
- `src/services/` - API service layer
- `src/config/` - Configuration files

**State Management:**
- React Context for auth and global state
- @tanstack/react-query for server state management
- zustand for client state management
- Local storage for auth tokens, session storage for login state

**Key Dependencies:**
- UI: Radix UI primitives, shadcn/ui, Tailwind CSS, Framer Motion
- Data: @tanstack/react-table, react-data-grid, @tanstack/react-virtual
- Forms: react-hook-form, zod
- Charts: recharts, chart.js, react-chartjs-2
- File handling: xlsx for Excel export, react-dropzone for uploads
- Other: axios for HTTP, date-fns/luxon for dates

**Path Alias:** `@/` maps to `./src/`

### Backend Architecture

**Entry Point:** `inventory-server/src/server.js`

**Key Directories:**
- `src/routes/` - Express route handlers (products, dashboard, analytics, import, etc.)
- `src/middleware/` - Express middleware (CORS, auth, etc.)
- `src/utils/` - Utility functions (database connection, API helpers)
- `src/types/` - Type definitions (e.g., status-codes)

**Database:**
- PostgreSQL with connection pooling (pg library)
- Pool initialized in `utils/db.js` via `initPool()`
- Pool attached to `app.locals.pool` for route access
- Environment variables loaded from `/var/www/html/inventory/.env` (production path)

**API Routes:** All prefixed with `/api/`
- `/api/products` - Product CRUD operations
- `/api/dashboard` - Dashboard metrics and data
- `/api/analytics` - Analytics and reporting
- `/api/orders` - Order management
- `/api/purchase-orders` - Purchase order management
- `/api/csv` - CSV import/export (data management)
- `/api/import` - Product import workflows
- `/api/config` - Configuration management
- `/api/metrics` - System metrics
- `/api/ai-validation` - AI-powered validation
- `/api/ai-prompts` - AI prompt management
- `/api/templates` - Template management
- `/api/reusable-images` - Image management
- `/api/categoriesAggregate`, `/api/vendorsAggregate`, `/api/brandsAggregate` - Aggregate data endpoints

**Authentication:**
- External auth service at `/auth-inv` endpoint
- Token-based authentication (Bearer tokens)
- Frontend stores tokens in localStorage
- Protected routes verify tokens via auth service `/me` endpoint

**File Uploads:**
- Multer middleware for file handling
- Uploads directory: `inventory-server/uploads/`

### Development Proxy Setup

The Vite dev server (port 5175) proxies API requests to `https://inventory.kent.pw`:
- `/api/*` → production API
- `/auth-inv/*` → authentication service
- `/chat-api/*` → chat service
- `/uploads/*` → uploaded files
- Various third-party services (Aircall, Klaviyo, Meta, Gorgias, Typeform, ACOT, Clarity)

### Build Process

When building the frontend:
1. TypeScript compilation (`tsc -b`)
2. Vite build (outputs to `inventory/build/`)
3. Custom Vite plugin copies build to `inventory-server/frontend/build/`
4. Manual chunks for vendor splitting (react-vendor, ui-vendor, query-vendor)

## Testing

Run tests for individual components or features:
```bash
# No test suite currently configured
# Tests would typically use Jest or Vitest with React Testing Library
```

## Common Development Workflows

### Adding a New Page
1. Create page component in `inventory/src/pages/YourPage.tsx`
2. Add lazy import in `inventory/src/App.tsx`
3. Add route with `<Protected>` wrapper and permission check
4. Add corresponding backend route in `inventory-server/src/routes/`
5. Update permission system if needed

### Adding a New API Endpoint
1. Create or update route file in `inventory-server/src/routes/`
2. Use `executeQuery()` helper for database queries
3. Register router in `inventory-server/src/server.js`
4. Frontend can access at `/api/{route-name}`

### Working with Database
- Use parameterized queries: `executeQuery(sql, [param1, param2])`
- Pool is accessed via `db.getPool()` or `app.locals.pool`
- Connection helper: `db.getConnection()` returns a client for transactions

### Permissions System
- User permissions stored in `user.permissions` array (permission codes)
- Check permissions in `<Protected page="permission_code">` component
- Admin users (`is_admin: true`) have access to all pages

## Important Notes

- Environment variables must be configured in `/var/www/html/inventory/.env` for production
- The frontend expects the backend at `/api` (proxied in dev, served together in production)
- PM2 is used for production process management
- Database uses PostgreSQL with SSL support (configurable via `DB_SSL` env var)
- File uploads stored in `inventory-server/uploads/` directory
- Build artifacts in `inventory/build/` are copied to `inventory-server/frontend/build/`