# Schema Update Changes Required

## Core Field Name Changes

### Global Changes
- Update all references from `product_id` to `pid` in all tables and queries
  - This includes foreign key references in related tables
  - Update TypeScript interfaces and types (e.g., `interface Product { pid: number; ... }`)
  - Update API request/response types
- Update all references from `category_id` to `cat_id` in category-related queries
  - This affects the `categories` table and all tables with category foreign keys
- Update purchase order status to use numeric codes instead of strings
  - Status codes: 0=canceled, 1=created, 10=electronically_ready_send, 11=ordered, 12=preordered, 13=electronically_sent, 15=receiving_started, 50=done
  - Receiving status codes: 0=canceled, 1=created, 30=partial_received, 40=full_received, 50=paid
- Handle NULL brand values as 'Unbranded'
  - Add COALESCE(brand, 'Unbranded') in all brand-related queries
  - Update frontend brand filters to handle 'Unbranded' as a valid value

## Backend Route Changes

### Product Routes
1. Update ID field references in all product routes:
   - `/api/products/:id` -> `/api/products/:pid`
   - All query parameters using `product_id` should be changed to `pid`
   - Update all SQL queries to use `pid` instead of `product_id`
   - Update `/api/products/:id/metrics` -> `/api/products/:pid/metrics`
   - Update `/api/products/:id/time-series` -> `/api/products/:pid/time-series`
   - Update request parameter validation in routes
   - Example query change:
     ```sql
     -- Old
     SELECT * FROM products WHERE product_id = ?
     -- New
     SELECT * FROM products WHERE pid = ?
     ```

2. Update purchase order status checks:
   - Change `status = 'closed'` to `receiving_status >= 30` in all relevant queries
   - Update any route logic that checks PO status to use the new numeric status codes
   - Example status check change:
     ```sql
     -- Old
     WHERE po.status = 'closed'
     -- New
     WHERE po.receiving_status >= 30 -- Partial or fully received
     ```

### Category Routes
1. Update ID references:
   - `/api/categories/:id` -> `/api/categories/:cat_id`
   - Update all SQL queries to use `cat_id` instead of `category_id`
   - Update join conditions in category-related queries
   - Example join change:
     ```sql
     -- Old
     JOIN categories c ON p.category_id = c.category_id
     -- New
     JOIN categories c ON p.cat_id = c.cat_id
     ```

2. Update category metrics queries:
   - Modify field size handling for financial fields (DECIMAL(15,3) instead of DECIMAL(10,3))
   - Update category performance calculations to use new field sizes
   - Example field size change:
     ```sql
     -- Old
     total_value DECIMAL(10,3)
     -- New
     total_value DECIMAL(15,3)
     ```

### Vendor Routes
1. Update product references:
   - Change all queries to use `pid` instead of `product_id`
   - Update purchase order status checks to use new numeric codes
   - Example vendor query change:
     ```sql
     -- Old
     SELECT v.*, p.product_id FROM vendors v
     JOIN products p ON p.vendor = v.name
     WHERE p.product_id = ?
     -- New
     SELECT v.*, p.pid FROM vendors v
     JOIN products p ON p.vendor = v.name
     WHERE p.pid = ?
     ```

2. Update vendor metrics queries:
   - Add COALESCE for NULL brand handling:
     ```sql
     -- Old
     GROUP BY brand
     -- New
     GROUP BY COALESCE(brand, 'Unbranded')
     ```
   - Update field references in performance metrics calculations

### Dashboard Routes
1. Update all dashboard endpoints:
   - `/dashboard/best-sellers`:
     ```typescript
     interface BestSellerProduct {
       pid: number;  // Changed from product_id
       sku: string;
       title: string;
       units_sold: number;
       revenue: number;  // Now handles larger decimals
       profit: number;   // Now handles larger decimals
     }
     ```
   - `/dashboard/overstock/products`:
     ```typescript
     interface OverstockedProduct {
       pid: number;  // Changed from product_id
       sku: string;
       title: string;
       stock_quantity: number;
       overstocked_amt: number;
       excess_cost: number;    // Now DECIMAL(15,3)
       excess_retail: number;  // Now DECIMAL(15,3)
     }
     ```

### Analytics Routes
1. Update analytics endpoints:
   - `/analytics/stats` - Update all ID references and decimal handling
   - `/analytics/profit` - Update decimal precision in calculations
   - `/analytics/vendors` - Add brand NULL handling
   - Example analytics query change:
     ```sql
     -- Old
     SELECT product_id, SUM(price * quantity) as revenue
     FROM orders
     GROUP BY product_id
     -- New
     SELECT pid, CAST(SUM(price * quantity) AS DECIMAL(15,3)) as revenue
     FROM orders
     GROUP BY pid
     ```

## Frontend Component Changes

### Product Components
1. Update API calls:
   ```typescript
   // Old
   fetch(`/api/products/${product_id}`)
   // New
   fetch(`/api/products/${pid}`)
   ```
   - Update route parameters in React Router:
     ```typescript
     // Old
     <Route path="/products/:product_id" />
     // New
     <Route path="/products/:pid" />
     ```
   - Update useParams usage:
     ```typescript
     // Old
     const { product_id } = useParams();
     // New
     const { pid } = useParams();
     ```

2. Update data display:
   ```typescript
   // Old
   <td>{formatCurrency(product.price)}</td>
   // New
   <td>{formatCurrency(Number(product.price))}</td>
   ```

### Dashboard Components
1. Update metrics displays:
   ```typescript
   // Old
   interface ProductMetrics {
     product_id: number;
     total_value: number;
   }
   // New
   interface ProductMetrics {
     pid: number;
     total_value: string;  // Handle as string due to DECIMAL(15,3)
   }
   ```

2. Update stock status displays:
   ```typescript
   // Old
   const isReceived = po.status === 'closed';
   // New
   const isReceived = po.receiving_status >= 30;
   ```

### Product Filters Component
1. Update filter options:
   ```typescript
   // Old
   const productFilter = { id: 'product_id', value: id };
   // New
   const productFilter = { id: 'pid', value: id };
   ```

2. Update status filters:
   ```typescript
   // Old
   const poStatusOptions = [
     { label: 'Closed', value: 'closed' }
   ];
   // New
   const poStatusOptions = [
     { label: 'Received', value: '30' }  // Using numeric codes
   ];
   ```

## Data Type Considerations

### Financial Fields
- Update TypeScript types:
  ```typescript
  // Old
  price: number;
  // New
  price: string;  // Handle as string due to DECIMAL(15,3)
  ```
- Update formatting:
  ```typescript
  // Old
  formatCurrency(value)
  // New
  formatCurrency(Number(value))
  ```

### Status Codes
- Add status code mapping:
  ```typescript
  const PO_STATUS_MAP = {
    0: 'Canceled',
    1: 'Created',
    10: 'Ready to Send',
    11: 'Ordered',
    12: 'Preordered',
    13: 'Sent',
    15: 'Receiving Started',
    50: 'Done'
  };
  ```

## Testing Requirements

1. API Route Testing:
   ```typescript
   // Test decimal handling
   expect(typeof response.total_value).toBe('string');
   expect(response.total_value).toMatch(/^\d+\.\d{3}$/);
   
   // Test status codes
   expect(response.receiving_status).toBeGreaterThanOrEqual(30);
   
   // Test brand handling
   expect(response.brand || 'Unbranded').toBeDefined();
   ```

## Notes
- All numeric status code comparisons should use >= for status checks to handle future status codes
- All financial values should be handled as strings in TypeScript/JavaScript to preserve precision
- Brand grouping should always use COALESCE(brand, 'Unbranded') in SQL queries
- All ID parameters in routes should be validated as numbers 