# Preparation Controller Documentation

**File**: `/controllers/preparationController.php`  
**Purpose**: Maintenance and warranty preparation workflow management  
**Last Updated**: December 20, 2024  
**Total Functions**: 6  
**Lines of Code**: ~246

---

## 📋 Overview

The Preparation Controller manages the maintenance workflow for products in the preparation stage, specifically handling warranty and insurance processing. It provides:
- Product preparation stage tracking
- Insurance workflow management  
- Stage transition automation
- Product history tracking
- Batch processing capabilities
- Maintenance workflow integration

### Primary Functions
- [x] Product preparation stage display
- [x] Insurance workflow processing
- [x] Stage transition management
- [x] Product history tracking
- [x] Batch operation processing
- [x] Maintenance integration

### Related Controllers
- [insuranceGo.php](insuranceGo.md) - Insurance dispatch management
- [insuranceReturn.php](insuranceReturn.md) - Insurance return handling
- [maintenances.php](maintenances.md) - General maintenance workflow
- [maintennanceArchiveController.php](maintennanceArchiveController.md) - Maintenance archival

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **mcomreceiptdetail** | Maintenance receipt details | id, ourserial, productSerial, currentstage, branchId |
| **minsurance** | Insurance processing records | id, ourSerial, stageIdBefore, currentStage, shipNameGo, shipCompanyGo, type, returned |
| **mproducthistory** | Product stage history | id, ourSerial, stageFrom, stageTo, cost, comment, status, productHistoryDate |

### Supporting Tables (Referenced)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **shippercompanies** | Shipping companies | shippercompaniesid, shippercompaniesname |
| **representativecompany** | Representative companies | representativecompanyid, representativecompanyname |
| **user** | System users | userid, username |

### System Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **youtubelink** | Tutorial videos | youtubelinkid, title, url |

---

## 🔑 Key Functions

### 1. **Default Display / Product Listing** - Preparation Stage Overview
**Location**: Line 92  
**Purpose**: Display all products currently in preparation stage for processing

**Function Signature**:
```php
// Triggered when: empty($do) || $do == "all"
// Displays products in preparation stage (stage 4)
```

**Process Flow**:
1. Query products in preparation stage for current branch
2. Count total products for display
3. Load data into Smarty template
4. Display maintenance header with navigation

**Query Logic**:
```php
$comReceiptData = $MComReceiptDetailEX->getProductsInpreparationStage($_SESSION['branchId']);
$smarty->assign("itr", count($comReceiptData));
$smarty->assign("comReceiptData", $comReceiptData);
```

---

### 2. **insuranceGO() / Insurance Processing** - Stage Transition Processing
**Location**: Line 164  
**Purpose**: Process multiple products from preparation to insurance stage

**Function Signature**:
```php
function insuranceGO()
// Processes form data with iteration counter
$itr = $_POST["hidden_itr"];
```

**Process Flow**:
1. **Batch Processing Loop**: Iterate through form submissions
2. **Validation**: Check required fields for each product
3. **Stage Update**: Move products from stage 4 to stage 7
4. **History Recording**: Log stage transition in product history
5. **Current Stage Update**: Update master record with new stage

**Batch Processing Logic**:
```php
for ($i = 1; $i <= $itr; $i++) {
    $thisGo = $_POST["go" . $i];
    $ourserial = $_POST["ourserial" . $i];
    $productSerial = $_POST["productSerial" . $i];
    
    if (isset($thisGo) && !empty($thisGo) && 
        isset($ourserial) && !empty($ourserial) && 
        isset($productSerial) && !empty($productSerial)) {
        
        updateInsuranceStages($ourserial, 4, 7);
        insertProductHistory($ourserial, 4, 7, 0, '', 0);
        updateCurrentStage(7, $ourserial);
    }
}
```

---

### 3. **insertInsurance() / Insurance Record Creation** - Complete Insurance Documentation
**Location**: Line 180  
**Purpose**: Create detailed insurance record with shipping and processing information

**Function Signature**:
```php
function insertInsurance($ourSerial, $stageIdBefore, $currentStage, 
                        $shipNameGo, $shipCompanyGo, $shipPersonalGo, $shipCostGo,
                        $shipNameReturned, $shipCompanyReturned, $shipPersonalReturned, $shipCostReturned, 
                        $type, $oldSN, $newSN, $insuranceCost, $kindOfInsurance, 
                        $insuranceDate, $insuranceDiscount, $comment, $returned)
```

**Data Structure**:
```php
$MInsurance->ourSerial = $ourSerial;              // Product identifier
$MInsurance->stageIdBefore = $stageIdBefore;      // Previous stage
$MInsurance->currentStage = $currentStage;        // Current stage
$MInsurance->shipNameGo = $shipNameGo;           // Outbound shipping
$MInsurance->shipCompanyGo = $shipCompanyGo;     // Shipping company
$MInsurance->type = $type;                       // Insurance type
$MInsurance->insuranceCost = $insuranceCost;     // Processing cost
$MInsurance->returned = $returned;               // Return status
```

**Audit Fields**:
```php
$MInsurance->branchId = $_SESSION['branchId'];   // Branch tracking
$MInsurance->userId = $_SESSION['userid'];       // User tracking  
$MInsurance->del = 0;                           // Deletion flag
```

---

### 4. **updateCurrentStage() / Stage Management** - Master Record Updates
**Location**: Line 214  
**Purpose**: Update product's current stage in master record

**Function Signature**:
```php
function updateCurrentStage($currentstage, $ourserial)
// Updates mcomreceiptdetail.currentstage
```

---

### 5. **updateInsuranceStages() / Insurance Stage Updates** - Insurance Record Management
**Location**: Line 220  
**Purpose**: Update existing insurance records with new stage information

**Function Signature**:
```php
function updateInsuranceStages($ourSerial, $stageIdBefore, $currentStage)
// Updates insurance records for stage transitions
```

---

### 6. **insertProductHistory() / History Tracking** - Complete Audit Trail
**Location**: Line 227  
**Purpose**: Record detailed product stage transition history

**Function Signature**:
```php
function insertProductHistory($ourSerial, $stageFrom, $stageTo, $cost, $comment, $status)
```

**History Record Structure**:
```php
$MProductHistory->ourSerial = $ourSerial;        // Product identifier
$MProductHistory->stageFrom = $stageFrom;        // Source stage
$MProductHistory->stageTo = $stageTo;            // Destination stage  
$MProductHistory->cost = $cost;                 // Associated cost
$MProductHistory->comment = $comment;            // Process notes
$MProductHistory->status = $status;              // Operation status
$MProductHistory->productHistoryDate = date("Y-m-d H:i:s"); // Timestamp
$MProductHistory->branchId = $_SESSION['branchId'];          // Branch context
$MProductHistory->userId = $_SESSION['userid'];              // User context
```

---

## 🔄 Workflows

### Workflow 1: Preparation to Insurance Processing
```
┌─────────────────────────────────────────────────────────────┐
│           START: Products in Preparation Stage             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Display Preparation Dashboard                           │
│     - Load all products in stage 4 (preparation)           │
│     - Group by branch for multi-branch systems             │
│     - Display product details and serial numbers           │
│     - Show batch processing form                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Select Products for Insurance Processing               │
│     - Review product list                                  │
│     - Select products ready for insurance                  │
│     - Verify product serial numbers                       │
│     - Add processing notes if needed                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Submit Batch Processing Request                        │
│     - Validate form data                                   │
│     - Count selected products                             │
│     - Prepare batch operation                             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Process Each Selected Product                          │
│     FOR EACH selected product:                             │
│     ┌─────────────────────────────────────────────────────┐ │
│     │  4a. Validate Product Data                         │ │
│     │      - Check ourserial exists                      │ │
│     │      - Verify productSerial present                │ │
│     │      - Confirm go flag is set                      │ │
│     └─────────────────────────────────────────────────────┘ │
│     ┌─────────────────────────────────────────────────────┐ │
│     │  4b. Update Insurance Records                      │ │
│     │      - Update existing insurance entry             │ │
│     │      - Set stageIdBefore = 4                       │ │
│     │      - Set currentStage = 7                        │ │
│     └─────────────────────────────────────────────────────┘ │
│     ┌─────────────────────────────────────────────────────┐ │
│     │  4c. Record Stage Transition                       │ │
│     │      - Insert product history entry               │ │
│     │      - Log transition from stage 4 to 7           │ │
│     │      - Record timestamp and user                  │ │
│     └─────────────────────────────────────────────────────┘ │
│     ┌─────────────────────────────────────────────────────┐ │
│     │  4d. Update Master Record                          │ │
│     │      - Set currentstage = 7 in receipt detail     │ │
│     │      - Update using ourserial identifier          │ │
│     └─────────────────────────────────────────────────────┘ │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Complete Batch Operation                               │
│     - Commit all database changes                          │
│     - Display success notification                         │
│     - Redirect to updated preparation list                │
│     - Show remaining products in preparation              │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Stage Management System
```
┌─────────────────────────────────────────────────────────────┐
│                START: Product Stage Tracking               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  Stage 1-3: Initial Processing                             │
│  (Handled by other controllers)                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  Stage 4: PREPARATION STAGE                                │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  - Product preparation and assessment               │   │
│  │  - Ready for insurance processing                   │   │
│  │  - Displayed in preparationController              │   │
│  │  - Batch selection available                       │   │
│  └─────────────────────────────────────────────────────┘   │
└────────────────────┬────────────────────────────────────────┘
                     │ (Transition via insuranceGO)
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  Stage 7: INSURANCE PROCESSING                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  - Product sent for insurance processing            │   │
│  │  - Shipping information recorded                   │   │
│  │  - Insurance company handling                      │   │
│  │  - Cost tracking enabled                           │   │
│  └─────────────────────────────────────────────────────┘   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  Stage 8+: Subsequent Processing                           │
│  (Handled by insuranceGo.php and other controllers)        │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) or `do=all` | Default display | Products in preparation stage |
| `do=insuranceGO` | `insuranceGO()` | Process batch insurance transitions |
| `do=add` | `add()` | Additional processing (deprecated) |

### Required Parameters by Action

**Default Display** (empty or `do=all`):
- No parameters required
- Uses session branchId automatically

**Insurance Processing** (`do=insuranceGO`):
- `hidden_itr` - Number of products in form
- `go{n}` - Selection flag for product n
- `ourserial{n}` - Our internal serial for product n  
- `productSerial{n}` - Product serial number for product n

---

## 🧮 Calculation Methods

### Stage Transition Logic
```php
// Fixed stage transition: Preparation (4) → Insurance (7)
updateInsuranceStages($ourserial, 4, 7);
insertProductHistory($ourserial, 4, 7, 0, '', 0);
updateCurrentStage(7, $ourserial);
```

### Batch Processing Counter
```php
$itr = $_POST["hidden_itr"]; // Total form items
for ($i = 1; $i <= $itr; $i++) {
    // Process each numbered form element
    $thisGo = $_POST["go" . $i];
    $ourserial = $_POST["ourserial" . $i];
    $productSerial = $_POST["productSerial" . $i];
}
```

### Validation Logic
```php
// All three conditions must be met for processing
if (isset($thisGo) && !empty($thisGo) && 
    isset($ourserial) && !empty($ourserial) && 
    isset($productSerial) && !empty($productSerial)) {
    // Process product
}
```

---

## 🔒 Security & Permissions

### Authentication Requirements
```php
// No explicit authentication check in main flow
// Relies on session-based branch filtering
```

### Branch-Based Security
```php
// Branch-specific data filtering
$comReceiptData = $MComReceiptDetailEX->getProductsInpreparationStage($_SESSION['branchId']);
```

### Data Integrity
- Input validation on all form fields
- Existence checks before processing
- Audit trail maintenance
- Session-based user tracking

### Session Management
```php
$MInsurance->branchId = $_SESSION['branchId'];
$MInsurance->userId = $_SESSION['userid'];
$MProductHistory->userId = $_SESSION['userid'];
```

---

## 📊 Performance Considerations

### Database Optimization
1. **Required Indexes**:
   - `mcomreceiptdetail(currentstage, branchId)` - Stage filtering
   - `mcomreceiptdetail(ourserial)` - Serial lookup
   - `minsurance(ourSerial, stageIdBefore)` - Insurance updates
   - `mproducthistory(ourSerial, productHistoryDate)` - History queries

2. **Query Efficiency**:
   - Branch-specific filtering reduces dataset size
   - Stage-specific queries for focused results
   - Batch operations reduce database round trips

3. **Memory Management**:
   - Form data processing in loops
   - Efficient object reuse
   - Minimal template variable assignment

### Batch Processing Benefits
- Single page load for multiple product processing
- Reduced user interaction time
- Efficient database operations

---

## 🐛 Common Issues & Troubleshooting

### 1. **Products Not Appearing in Preparation**
**Issue**: Expected products missing from preparation stage list  
**Cause**: Incorrect stage assignment or branch filtering

**Debug**:
```sql
-- Check product stages for branch
SELECT ourserial, productSerial, currentstage, branchId 
FROM mcomreceiptdetail 
WHERE branchId = [BRANCH_ID] AND currentstage = 4;
```

### 2. **Stage Transition Failures**
**Issue**: Products not moving to insurance stage  
**Cause**: Missing form data or validation failures

**Debug**:
```php
// Add debug logging in insuranceGO()
error_log("Processing product: {$ourserial}, Serial: {$productSerial}, Go: {$thisGo}");
```

### 3. **History Record Gaps**
**Issue**: Missing entries in product history  
**Cause**: Failed insertProductHistory() calls

**Debug**:
```sql
-- Check history continuity
SELECT ourSerial, stageFrom, stageTo, productHistoryDate 
FROM mproducthistory 
WHERE ourSerial = '[SERIAL]' 
ORDER BY productHistoryDate;
```

### 4. **Insurance Record Inconsistencies**
**Issue**: Insurance records not updating properly  
**Cause**: Multiple records or update failures

**Debug**:
```sql
-- Check insurance record status
SELECT * FROM minsurance 
WHERE ourSerial = '[SERIAL]' AND stageIdBefore = 4;
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Preparation Display
```
1. Access preparation controller (empty do)
2. Verify products in stage 4 appear
3. Check branch filtering works correctly
4. Confirm product count matches display
5. Verify form elements present for batch processing
```

### Test Case 2: Single Product Insurance Processing
```
1. Select one product from preparation list
2. Submit insurance processing form
3. Verify product moved to stage 7
4. Check history record created
5. Confirm insurance record updated
6. Verify product no longer in preparation list
```

### Test Case 3: Batch Insurance Processing
```
1. Select multiple products (3-5 items)
2. Submit batch processing form
3. Verify all selected products processed
4. Check stage transitions for all items
5. Confirm history records for each product
6. Verify preparation list updated correctly
```

### Test Case 4: Form Validation
```
1. Submit form with missing ourserial
2. Submit form with missing productSerial  
3. Submit form with no selections (go flags)
4. Verify proper validation and error handling
5. Check no partial processing occurs
```

### Debug Mode Enable
```php
// Add comprehensive logging
error_log("Preparation Controller - Branch: " . $_SESSION['branchId']);
error_log("Products found: " . count($comReceiptData));

// In insuranceGO function
error_log("Processing iteration: {$i}, Items to process: {$itr}");
error_log("Product data: ourserial={$ourserial}, serial={$productSerial}");
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [insuranceGo.md](insuranceGo.md) - Insurance dispatch processing
- [insuranceReturn.md](insuranceReturn.md) - Insurance return handling
- [maintenances.md](maintenances.md) - General maintenance workflow
- [maintennanceArchiveController.md](maintennanceArchiveController.md) - Maintenance archival

---

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