# Inventory Expiration Controller Documentation

**File**: `/controllers/inventoryexpirationController.php`  
**Purpose**: Serial number and expiration date management for inventory items  
**Last Updated**: December 20, 2024  
**Total Functions**: 8+  
**Lines of Code**: ~444

---

## 📋 Overview

The Inventory Expiration Controller manages product serial numbers, expiration dates, and detailed product tracking. It provides:
- Serial number generation and management
- Product expiration date tracking
- Size/color variant serial tracking
- Car chassis and motor number tracking
- AJAX-based real-time updates
- Batch serial number processing

### Primary Functions
- [x] Serial number generation and assignment
- [x] Product expiration date management
- [x] Size/color variant tracking
- [x] Car-specific data (chassis, motor, color)
- [x] AJAX real-time updates
- [x] Batch processing capabilities
- [x] Automatic serial generation

### Related Controllers
- [inventoryController.php](inventoryController.md) - Main inventory management
- [inventorybybarcodeController.php](inventorybybarcodeController.md) - Barcode inventory
- [productController.php](productController.md) - Product management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **productserial** | Product serial numbers and expiration | productserailid, productid, serialnumber, startdate, enddate, storeid, sizeid, colorid, quantity, type, chassisNo, motorNo, theColor |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **product** | Product master data | productId, productName, productCatId |
| **productcat** | Product categories | productCatId, productCatName |
| **store** | Store locations | storeId, storeName |
| **storedetail** | Store inventory quantities | storedetailid, productid, storeid, productquantity |
| **programsettings** | System configuration | programsettingsid, settings |

---

## 🔑 Key Functions

### 1. **show() / Default Action** - Serial Entry Interface
**Location**: Line 155  
**Purpose**: Display serial number and expiration management interface

**Features**:
- Store-specific access control based on `$_SESSION['searchinonestore']`
- Category hierarchy loading
- Store selection and filtering
- Template variable assignment

### 2. **add()** - Batch Serial Processing
**Location**: Line 285  
**Purpose**: Process multiple product serial entries with expiration dates

**Process Flow**:
1. Process deletion list for removed serials
2. Loop through products and serial quantities
3. Generate or validate serial numbers
4. Insert/update serial records with dates and quantities
5. Handle car-specific data (chassis, motor, color)

**Serial Generation Logic**:
```php
if (empty($serialnumber)) {
    $serialnumber = getserail(6, $productid);
}
```

### 3. **addAjax()** - AJAX Serial Processing
**Location**: Line 348  
**Purpose**: Real-time AJAX processing for single product serial updates

**Returns**: JSON response with status and generated serial IDs
```php
echo json_encode(array('status' => 1, 'result' => $returnArr));
```

### 4. **getserail()** - Serial Number Generator
**Location**: Line 413  
**Purpose**: Generate unique 6-digit serial numbers with collision detection

**Function Signature**:
```php
function getserail($length = 6, $productid)
```

**Algorithm**:
1. Generate random 6-digit number
2. Check against existing serials in database
3. Check against session array to avoid duplicates in same session
4. Recursively generate new number if collision detected
5. Store in session array to prevent duplicates

---

## 🔄 Workflows

### Workflow 1: Product Serial Management
```
┌─────────────────────────────────────────────────────────────┐
│                START: Select Products                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Product and Quantity Entry                              │
│     - Select product with variants (size/color)            │
│     - Specify total quantity needing serials               │
│     - Set store location                                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Serial Details Entry                                    │
│     FOR EACH quantity unit:                                │
│       │                                                     │
│       ├─→ Enter/Generate serial number                     │
│       ├─→ Set start date (production/purchase)            │
│       ├─→ Set end date (expiration)                       │
│       ├─→ Enter quantity per serial                       │
│       ├─→ Add comments/notes                              │
│       └─→ [Cars] Enter chassis, motor, color              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process and Validate                                    │
│     - Generate unique serial numbers if needed             │
│     - Validate date ranges                                 │
│     - Check for duplicate serials                         │
│     - Insert/update productserial records                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Real-time Updates (AJAX)                               │
│     - Return generated serial IDs                         │
│     - Update interface without page reload                │
│     - Enable progressive entry                            │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) or `do=show` | Default action | Serial entry interface |
| `do=add` | `add()` | Process batch serial entries |
| `do=addAjax` | `addAjax()` | AJAX serial processing |

### Required Parameters

**Batch Entry** (`do=add`):
- `itr` - Number of products being processed
- `delIds` - Comma-separated list of serials to delete
- `productid{N}` - Product ID for item N
- `sizeid{N}` - Size variant ID
- `colorid{N}` - Color variant ID
- `totalproduct{N}` - Total quantity for product N
- `storeid{N}` - Store location
- `serialnumber{X}_{N}` - Serial number for unit X of product N
- `stratdate{X}_{N}` - Start date
- `enddate{X}_{N}` - Expiration date
- `quantity{X}_{N}` - Quantity per serial
- `chassisNo{X}_{N}` - Chassis number (cars)
- `motorNo{X}_{N}` - Motor number (cars)
- `theColor{X}_{N}` - Car color

---

## 🧮 Calculation Methods

### Serial Number Generation
```php
$characters = '0123456789';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
    $randomString .= $characters[rand(0, strlen($characters) - 1)];
}
```

### Collision Detection
```php
$data = $ProductserialEX->queryAllbyserial($randomString);
if (count($data) > 0 || @in_array($randomString, $serialArray)) {
    getserail(6, $productid);  // Recursive generation
}
```

---

## 🔒 Security & Permissions

### Store Access Control
```php
if ($_SESSION['searchinonestore'] == 0) {
    // Multi-store access
    if ($_SESSION['storeids'] == 0) {
        $stores = $myStoreEx->queryByConditions();
    } else {
        $stores = $myStoreEx->queryByConditions(' and store.storeId in (' . $_SESSION['storeids'] . ')');
    }
} else {
    // Single store access
    $storedef = $myStoreEx->queryByConditionsOne(' and store.storeId = '.$_SESSION['storeid'].' ');
}
```

### Input Validation
- Serial number uniqueness validation
- Date format validation
- Numeric quantity validation
- Product and store existence checks

---

## 📊 Performance Considerations

### Optimization Features
1. **AJAX Updates**: Real-time processing without page reloads
2. **Session Caching**: Serial number collision prevention
3. **Batch Processing**: Multiple items in single transaction
4. **Conditional Loading**: Store-specific data loading

### Potential Issues
- Large batch processing may timeout
- Serial generation recursion could impact performance
- Session array memory usage for large batches

---

## 🐛 Common Issues & Troubleshooting

### 1. **Serial Number Collisions**
**Issue**: Duplicate serial numbers generated  
**Cause**: High concurrent usage or session data loss

**Fix**: Implement database-level unique constraints
```sql
ALTER TABLE productserial ADD UNIQUE KEY unique_serial (serialnumber);
```

### 2. **Date Validation Errors**
**Issue**: Invalid date formats causing insertion failures  
**Cause**: Client-side date format inconsistencies

**Fix**: Server-side date validation and formatting
```php
$startdate = date('Y-m-d', strtotime($stratdate));
$enddate = date('Y-m-d', strtotime($enddate));
```

### 3. **AJAX Response Issues**
**Issue**: AJAX calls not returning proper responses  
**Cause**: PHP errors or incorrect header settings

**Debug**:
```php
// Add error reporting for AJAX
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');
```

---

## 📚 Related Documentation

- [inventoryController.md](inventoryController.md) - Main inventory management
- [productController.md](productController.md) - Product management
- [storedetailController.md](storedetailController.md) - Store quantities

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When major changes occur