# Insurance Go Controller Documentation

**File**: `/controllers/insuranceGo.php`  
**Purpose**: Manages outgoing insurance warranty shipments for product repair/maintenance services  
**Last Updated**: December 20, 2024  
**Total Functions**: 8  
**Lines of Code**: ~332

---

## 📋 Overview

The Insurance Go Controller handles the process of sending products out for warranty repairs or maintenance services. It manages the selection of products to be shipped, tracks shipping costs and companies, and updates product status through various warranty stages. The controller integrates with financial systems to track warranty-related expenses and maintains comprehensive audit trails through product history tracking.

### Primary Functions
- [x] Display products available for warranty shipment by supplier
- [x] Select products and shipping details for outbound warranty
- [x] Track shipping costs and update cash registers
- [x] Manage shipping company and representative information
- [x] Update product stages through warranty workflow
- [x] Maintain product history for warranty tracking
- [x] Calculate total warranty costs for client receipts
- [x] Handle cash flow impacts of warranty expenses

### Related Controllers
- [insuranceReturn.php](insuranceReturn.md) - Return from warranty service
- [insurancecompany.php](insurancecompany.md) - Insurance company management
- [MComreceiptController.php](#) - Customer receipt management
- [saveController.php](saveController.md) - Cash register operations
- [savedailyController.php](savedailyController.md) - Daily cash tracking

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **minsurance** | Insurance/warranty tracking | insuranceid, ourserial, stageidbefore, currentstage, shipnamego, shipcompanygo, shippersonalgo, shipcostgo, date |
| **mproducthistory** | Product stage change history | producthistoryid, ourserial, stagefrom, stageto, cost, comment, status, userid, producthistorydate, branchid |
| **mcomreceiptdetail** | Customer receipt product details | id, ourserial, currentstage, clientid |
| **mcomreceipt** | Customer receipt master | id, clientid, totalcost |

### Financial Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **save** | Cash registers/safes | saveid, savename, savecurrentvalue, userid |
| **savedaily** | Daily cash transactions | savedailyid, savedailydate, userid, savedailysavebefore, savedailychangeamount, savedailychangetype, saveid, processname, savedailymodelid, savedailysaveafter, tablename |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **shippercompanies** | Shipping company information | id, companyname, contactinfo |
| **representativecompany** | Shipping representatives | id, representativename, companyid, contactinfo |

---

## 🔑 Key Functions

### 1. **show() / Default Action** - Product Selection by Supplier
**Location**: Lines 120-139  
**Purpose**: Display summary of suppliers with products available for warranty shipment

**Function Signature**:
```php
// Triggered when: do=all or empty $do
$data = $MComReceiptDetailEX->getSupplierVSNoOfProducts($_SESSION['branchId']);
```

**Process Flow**:
1. Query products available for warranty shipment by supplier
2. Group products by supplier for easy selection
3. Display supplier summary with product counts
4. Present via `insuranceGOPrepare.html` template

**Features**:
- Branch-specific filtering
- Supplier-based grouping
- Product count summaries
- Arabic interface support

---

### 2. **send()** - Product Selection and Shipping Details
**Location**: Lines 140-150  
**Purpose**: Show detailed product list for selected supplier with shipping options

**Function Signature**:
```php
// Triggered when: do=send&supplierid=X
$supplierid = $_GET["supplierid"];
$productsData = $MComReceiptDetailEX->getProductsToGo2($supplierid, $_SESSION['branchId']);
```

**Process Flow**:
1. Load detailed product list for specific supplier
2. Query available shipping companies
3. Query available shipping representatives  
4. Display products with shipping company selection
5. Present via `insuranceGO.html` template

**Template Variables**:
- `$productsData` - Products available for warranty shipment
- `$ShipperCompanies` - Available shipping companies
- `$RepresentativeCompanies` - Available representatives
- `$itr` - Number of products

---

### 3. **add()** - Process Warranty Shipment
**Location**: Lines 188-231  
**Purpose**: Execute warranty shipment and update all related systems

**Function Signature**:
```php
function add()
```

**Process Flow**:
1. Process each selected product from form submission:
   ```php
   for ($i = 1; $i <= $itr; $i++) {
       $ourserial = $_POST["ourserial" . $i];
       $cost = $_POST["cost" . $i];
   }
   ```
2. Validate required fields (serial, cost, company, representative)
3. For each valid product:
   - Update cash register (subtract shipping cost)
   - Insert daily cash transaction record
   - Update insurance record with shipping details
   - Insert product history record
   - Update product current stage
   - Increase total cost in customer receipt

**Key Validations**:
```php
if (isset($ourserial) && !empty($ourserial) && 
    isset($cost) && !empty($cost) && 
    isset($companyId) && $companyId != -1 && 
    isset($representativeId) && $representativeId != -1)
```

**Stage Transitions**:
- From Stage: 7 (Ready for warranty)
- To Stage: 10 (Shipped for warranty)

---

### 4. **updateInsuranceGo()** - Update Insurance Record
**Location**: Lines 241-246  
**Purpose**: Update insurance table with outbound shipping details

**Function Signature**:
```php
function updateInsuranceGo($ourSerial, $stageIdBefore, $currentStage, $shipNameGo, $shipCompanyGo, $shipPersonalGo, $shipCostGo, $date)
```

**Fields Updated**:
- `stageidbefore` - Previous stage (7)
- `currentstage` - New stage (10)
- `shipnamego` - Policyholder name
- `shipcompanygo` - Shipping company ID
- `shippersonalgo` - Representative ID
- `shipcostgo` - Shipping cost
- `date` - Shipment date

---

### 5. **insertProductHistory()** - Audit Trail
**Location**: Lines 254-271  
**Purpose**: Create comprehensive audit record of product stage change

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

**Audit Fields**:
- Stage transition (7 → 10)
- Cost associated with stage change
- User responsible for change
- Branch context
- Date/time of change
- Status flags

---

### 6. **getSaveValueAndMins()** - Cash Register Calculation
**Location**: Lines 286-297  
**Purpose**: Calculate cash register balance after warranty cost deduction

**Function Signature**:
```php
function getSaveValueAndMins($saveid, $savevaluechanged)
```

**Return Array**:
```php
return array($saveId, $saveValuebefore, $saveValueafter);
// [0] = Save ID
// [1] = Balance before transaction
// [2] = Balance after deduction
```

**Calculation**:
```php
$saveValueafter = $saveValuebefore - $savevaluechanged;
```

---

### 7. **insertSavedaily()** - Cash Transaction Recording
**Location**: Lines 313-330  
**Purpose**: Record warranty cost transaction in daily cash log

**Function Signature**:
```php
function insertSavedaily($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename)
```

**Transaction Details**:
- `savedailychangetype = 1` - Cash outflow (expense)
- `processname = "شحن ذهاب"` - "Outbound shipping"
- `tablename = "insuranceGo.php"` - Source reference

---

### 8. **increaseComRecIDTotalCost()** - Customer Cost Update
**Location**: Lines 233-239  
**Purpose**: Add warranty shipping cost to customer's total receipt cost

**Function Signature**:
```php
function increaseComRecIDTotalCost($comRecID, $changeAmount)
```

**Process Flow**:
1. Get current total cost for customer receipt
2. Add warranty shipping cost
3. Update receipt with new total

---

## 🔄 Workflows

### Workflow 1: Warranty Shipment Process
```
┌─────────────────────────────────────────────────────────────┐
│                START: Select Warranty Products             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. View Suppliers with Available Products                  │
│     - Query products in stage 7 (ready for warranty)       │
│     - Group by supplier for easy selection                 │
│     - Display product counts per supplier                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Select Supplier and View Products                       │
│     - Load detailed product list for supplier              │
│     - Query available shipping companies                   │
│     - Query available representatives                      │
│     - Display product selection form                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Enter Shipping Details                                  │
│     - Select products to ship (by serial number)           │
│     - Enter shipping cost for each product                 │
│     - Select shipping company                              │
│     - Select shipping representative                       │
│     - Enter policyholder name                              │
│     - Set shipment date                                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Process Each Selected Product                           │
│     FOR EACH valid product:                                 │
│       │                                                     │
│       ├─→ Update Cash Register                             │
│       │   ├─ Get current balance                           │
│       │   ├─ Subtract shipping cost                        │
│       │   └─ Update balance                                │
│       │                                                     │
│       ├─→ Record Cash Transaction                          │
│       │   ├─ Insert into savedaily table                  │
│       │   ├─ Record cost as expense                       │
│       │   └─ Link to insurance ID                         │
│       │                                                     │
│       ├─→ Update Insurance Record                          │
│       │   ├─ Set shipping company                          │
│       │   ├─ Set representative                            │
│       │   ├─ Set shipping cost                             │
│       │   └─ Set shipment date                             │
│       │                                                     │
│       ├─→ Update Product Stage                             │
│       │   ├─ Change from stage 7 to 10                    │
│       │   └─ Update current stage                          │
│       │                                                     │
│       ├─→ Insert Product History                           │
│       │   ├─ Record stage transition                       │
│       │   ├─ Record shipping cost                          │
│       │   └─ Record user and timestamp                     │
│       │                                                     │
│       └─→ Update Customer Receipt Total                    │
│           ├─ Get customer receipt ID                       │
│           ├─ Add shipping cost to total                    │
│           └─ Update receipt total                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Complete Transaction                                    │
│     - Display success or error message                     │
│     - Return to product selection screen                   │
│     - Update all related systems consistently              │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) or `do=all` | Default action | View suppliers with available products |
| `do=send&supplierid=X` | send() | Product selection for specific supplier |
| `do=add` | add() | Process warranty shipment |
| `do=sucess` | Default | Success page display |
| `do=error` | Default | Error page display |

### Required Parameters by Action

**Supplier Product View** (`do=all`):
- No additional parameters required
- Uses `$_SESSION['branchId']` for filtering

**Product Selection** (`do=send`):
- `supplierid` - Supplier ID to filter products

**Process Shipment** (`do=add`):
- `hidden_itr` - Number of products being processed
- `mydate` - Shipment date
- `companyId` - Shipping company ID
- `representativeId` - Representative ID
- `Policyholder` - Policyholder name (optional)
- `ourserial{N}` - Product serial numbers (N = 1 to itr)
- `cost{N}` - Shipping costs per product (N = 1 to itr)

---

## 🧮 Calculation Methods

### Cash Register Balance Update
```php
// Get current balance and calculate new balance after cost
$saveData = getSaveValueAndMins($_SESSION['saveid'], $cost);
$saveValuebefore = $saveData[1];
$saveValueafter = $saveData[2];

// Calculation logic
$saveValueafter = $saveValuebefore - $savevaluechanged;
```

### Customer Receipt Total Update
```php
// Add warranty cost to customer's total receipt cost
$totalCost = $MComreceiptEX->getTotalCostComRecIDTotalCost($comRecID);
$totalCostNew = $totalCost + $changeAmount;
$MComreceiptEX->increaseComRecIDTotalCost($comRecID, $totalCostNew);
```

### Stage Transition Logic
```php
// Standard warranty outbound transition
$stageFrom = 7;  // Ready for warranty
$stageTo = 10;   // Shipped for warranty
```

---

## 🔒 Security & Permissions

### Session Requirements
```php
// Required session variables
$_SESSION['userid']    - User performing the operation
$_SESSION['branchId']  - Branch context for operations  
$_SESSION['saveid']    - Default cash register for costs
```

### Input Validation
```php
// Validate required shipping details
if (isset($ourserial) && !empty($ourserial) && 
    isset($cost) && !empty($cost) && 
    isset($companyId) && $companyId != -1 && 
    isset($representativeId) && $representativeId != -1)
```

### SQL Injection Prevention
- All database operations use DAO layer with parameterized queries
- No direct SQL concatenation in controller
- Input sanitization handled by framework layer

---

## 📊 Performance Considerations

### Database Optimization
1. **Required Indexes**:
   - `mcomreceiptdetail(ourserial)`
   - `mcomreceiptdetail(currentstage, branchid)`
   - `minsurance(ourserial)`
   - `save(saveid)`

2. **Query Efficiency**:
   - Branch-specific filtering reduces result sets
   - Stage-based filtering limits to relevant products
   - Supplier grouping reduces UI complexity

3. **Transaction Management**:
   - Multiple table updates should be wrapped in transactions
   - Cash register updates are critical financial operations
   - Product history maintains comprehensive audit trail

### Memory Considerations
- Product lists filtered by branch and stage reduce memory usage
- Iterator pattern used for bulk processing
- Session data cached for user context

---

## 🐛 Common Issues & Troubleshooting

### 1. **Cash Register Balance Issues**
**Issue**: Cash register goes negative or shows incorrect balance  
**Cause**: Insufficient funds or concurrent transactions

**Debug**:
```sql
-- Check current cash register balance
SELECT saveid, savename, savecurrentvalue FROM save WHERE saveid = ?;

-- Check recent cash transactions
SELECT * FROM savedaily WHERE saveid = ? ORDER BY savedailydate DESC LIMIT 10;
```

### 2. **Product Stage Stuck in Transition**
**Issue**: Products remain in stage 7 instead of moving to stage 10  
**Cause**: Failed stage update or validation errors

**Debug**:
```sql
-- Check product current stage
SELECT ourserial, currentstage FROM mcomreceiptdetail WHERE ourserial = ?;

-- Check insurance record
SELECT * FROM minsurance WHERE ourserial = ?;

-- Check product history
SELECT * FROM mproducthistory WHERE ourserial = ? ORDER BY producthistorydate DESC;
```

### 3. **Missing Shipping Companies/Representatives**
**Issue**: Dropdowns appear empty in product selection form  
**Cause**: No shipping companies or representatives configured

**Fix**:
```sql
-- Check available shipping companies
SELECT * FROM shippercompanies WHERE del = 0;

-- Check available representatives  
SELECT * FROM representativecompany WHERE del = 0;
```

### 4. **Customer Receipt Total Incorrect**
**Issue**: Customer receipt total doesn't include warranty costs  
**Cause**: Failed total cost update

**Debug**:
```sql
-- Check customer receipt totals
SELECT id, clientid, totalcost FROM mcomreceipt WHERE id = ?;

-- Check if products belong to receipt
SELECT id, ourserial, clientid FROM mcomreceiptdetail WHERE ourserial = ?;
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Warranty Shipment
```
1. Login and navigate to warranty management
2. Select supplier with products in stage 7
3. Choose products and enter shipping details
4. Verify cash register deduction
5. Confirm product moved to stage 10
6. Check product history updated
```

### Test Case 2: Multiple Product Shipment
```
1. Select multiple products from same supplier
2. Enter different costs for each product
3. Process shipment
4. Verify individual cost tracking
5. Confirm all products updated correctly
```

### Test Case 3: Validation Error Handling
```
1. Try to ship without selecting company
2. Try to ship without representative  
3. Enter invalid costs
4. Verify appropriate error messages
5. Confirm no partial updates occur
```

### Debug Mode Enable
```php
// Add at top of controller for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Debug product processing
echo "Processing product: " . $ourserial . " with cost: " . $cost . "<br>";

// Debug cash calculations
echo "Save before: " . $saveValuebefore . ", after: " . $saveValueafter . "<br>";
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [insuranceReturn.md](insuranceReturn.md) - Return from warranty service  
- [insurancecompany.md](insurancecompany.md) - Insurance company management
- [saveController.md](saveController.md) - Cash register operations
- [savedailyController.md](savedailyController.md) - Daily cash tracking

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When warranty processes change