# ACOT Server

This server replaces the Klaviyo integration with direct database queries to the production MySQL database via SSH tunnel. It provides seamless API compatibility for all frontend components without requiring any frontend changes.

## Setup

1. **Environment Variables**: Copy `.env.example` to `.env` and configure:
   ```
   DB_HOST=localhost
   DB_PORT=3306
   DB_USER=your_db_user
   DB_PASSWORD=your_db_password
   DB_NAME=your_db_name
   PORT=3007
   NODE_ENV=development
   ```

2. **SSH Tunnel**: Ensure your SSH tunnel to the production database is running on localhost:3306.

3. **Install Dependencies**:
   ```bash
   npm install
   ```

4. **Start Server**:
   ```bash
   npm start
   ```

## API Endpoints

All endpoints provide exact API compatibility with the previous Klaviyo implementation:

### Main Statistics
- `GET /api/acot/events/stats` - Complete statistics dashboard data
  - Query params: `timeRange` (today, yesterday, thisWeek, lastWeek, thisMonth, lastMonth, last7days, last30days, last90days) or `startDate`/`endDate` for custom ranges
  - Returns: Revenue, orders, AOV, shipping data, order types, brands/categories, refunds, cancellations, best day, peak hour, order ranges, period progress, projections

### Daily Details
- `GET /api/acot/events/stats/details` - Daily breakdown with previous period comparisons
  - Query params: `timeRange`, `metric` (revenue, orders, average_order, etc.), `daily=true`
  - Returns: Array of daily data points with trend comparisons

### Products
- `GET /api/acot/events/products` - Top products with sales data
  - Query params: `timeRange`
  - Returns: Product list with images, sales quantities, revenue, and order counts

### Projections
- `GET /api/acot/events/projection` - Smart revenue projections for incomplete periods
  - Query params: `timeRange`
  - Returns: Projected revenue with confidence levels based on historical patterns

### Health Check
- `GET /api/acot/test` - Server health and database connectivity test

## Database Schema

The server queries the following main tables:

### Orders (`_order`)
- **Key fields**: `order_id`, `date_placed`, `summary_total`, `order_status`, `ship_method_selected`, `stats_waiting_preorder`
- **Valid orders**: `order_status > 15`
- **Cancelled orders**: `order_status = 15`
- **Shipped orders**: `order_status IN (100, 92)`
- **Pre-orders**: `stats_waiting_preorder > 0`
- **Local pickup**: `ship_method_selected = 'localpickup'`
- **On-hold orders**: `ship_method_selected = 'holdit'`

### Order Items (`order_items`)
- **Fields**: `order_id`, `prod_pid`, `qty_ordered`, `prod_price`
- **Purpose**: Links orders to products for detailed analysis

### Products (`products`)
- **Fields**: `pid`, `description` (product name), `company`
- **Purpose**: Product information and brand data

### Product Images (`product_images`)
- **Fields**: `pid`, `iid`, `order` (priority)
- **Primary image**: `order = 255` (highest priority)
- **Image URL generation**: `https://sbing.com/i/products/0000/{prefix}/{pid}-{type}-{iid}.jpg`

### Payments (`order_payment`)
- **Refunds**: `payment_amount < 0`
- **Purpose**: Track refund amounts and counts

## Business Logic

### Time Handling
- **Timezone**: All calculations in UTC-5 (Eastern Time)
- **Business Day**: 1 AM - 12:59 AM Eastern (25-hour business day)
- **Format**: MySQL DATETIME format (YYYY-MM-DD HH:MM:SS)
- **Period Boundaries**: Calculated using `timeUtils.js` for consistent time range handling

### Order Processing
- **Revenue Calculation**: Only includes orders with `order_status > 15`
- **Order Types**:
  - Pre-orders: `stats_waiting_preorder > 0`
  - Local pickup: `ship_method_selected = 'localpickup'`
  - On-hold: `ship_method_selected = 'holdit'`
- **Shipping Methods**: Mapped to friendly names (e.g., `usps_ground_advantage` → "USPS Ground Advantage")

### Projections
- **Period Progress**: Calculated based on current time within the selected period
- **Simple Projection**: Linear extrapolation based on current progress
- **Smart Projection**: Uses historical data patterns for more accurate forecasting
- **Confidence Levels**: Based on data consistency and historical accuracy

### Image URL Generation
- **Pattern**: `https://sbing.com/i/products/0000/{prefix}/{pid}-{type}-{iid}.jpg`
- **Prefix**: First 2 digits of product ID
- **Type**: "main" for primary images
- **Fallback**: Uses primary image (order=255) when available

## Frontend Integration

### Service Layer (`services/acotService.js`)
- **Purpose**: Replaces direct Klaviyo API calls with acot-server calls
- **Methods**: `getStats()`, `getStatsDetails()`, `getProducts()`, `getProjection()`
- **Logging**: Axios interceptors for request/response logging
- **Environment**: Automatic URL handling (proxy in dev, direct in production)

### Component Updates
All 5 main components updated to use `acotService`:
- **StatCards.jsx**: Main dashboard statistics
- **MiniStatCards.jsx**: Compact statistics view
- **SalesChart.jsx**: Revenue and order trends
- **MiniSalesChart.jsx**: Compact chart view
- **ProductGrid.jsx**: Top products table

### Proxy Configuration (`vite.config.js`)
```javascript
'/api/acot': {
  target: 'http://localhost:3007',
  changeOrigin: true,
  secure: false
}
```

## Key Features

### Complete Business Intelligence
- **Revenue Analytics**: Total revenue, trends, projections
- **Order Analysis**: Counts, types, status tracking
- **Product Performance**: Top sellers, revenue contribution
- **Shipping Intelligence**: Methods, locations, distribution
- **Customer Insights**: Order value ranges, patterns
- **Operational Metrics**: Refunds, cancellations, peak hours

### Performance Optimizations
- **Connection Pooling**: Efficient database connection management
- **Query Optimization**: Indexed queries with proper WHERE clauses
- **Caching Strategy**: Frontend caching for detail views
- **Batch Processing**: Efficient data aggregation

### Error Handling
- **Database Connectivity**: Graceful handling of connection issues
- **Query Failures**: Detailed error logging and user-friendly messages
- **Data Validation**: Input sanitization and validation
- **Fallback Mechanisms**: Default values for missing data

## Simplified Elements

Due to database complexity, some features are simplified:
- **Brands**: Shows "Various Brands" (companies table structure complex)
- **Categories**: Shows "General" (category relationships complex)

These can be enhanced in future iterations with proper category mapping.

## Testing

Test the server functionality:

```bash
# Health check
curl http://localhost:3007/api/acot/test

# Today's stats
curl http://localhost:3007/api/acot/events/stats?timeRange=today

# Last 30 days with details
curl http://localhost:3007/api/acot/events/stats/details?timeRange=last30days&daily=true

# Top products
curl http://localhost:3007/api/acot/events/products?timeRange=thisWeek

# Revenue projection
curl http://localhost:3007/api/acot/events/projection?timeRange=today
```

## Development Notes

- **No Frontend Changes**: Complete drop-in replacement for Klaviyo
- **API Compatibility**: Maintains exact response structure
- **Business Logic**: Implements all complex e-commerce calculations
- **Scalability**: Designed for production workloads
- **Maintainability**: Well-documented code with clear separation of concerns

## Future Enhancements

- Enhanced category and brand mapping
- Real-time notifications for significant events
- Advanced analytics and forecasting
- Customer segmentation analysis
- Inventory integration 