# Maintenance Sends Controller Documentation

**File**: `/controllers/maintenancesends.php`  
**Purpose**: Manages shipment policies and tracking for products sent to maintenance centers  
**Last Updated**: December 20, 2024  
**Total Functions**: 5  
**Lines of Code**: ~288

---

## 📋 Overview

The Maintenance Sends Controller handles the logistics and documentation of shipping products to external maintenance centers. It manages:
- Creation of maintenance shipping policies
- Tracking of maintenance companies and shipping costs
- Bulk assignment of maintenance items to shipping policies
- Status management for shipped items (sent vs. received)
- Integration with maintenance workflow stages

### Primary Functions
- [x] Create and manage shipping policies
- [x] Track maintenance companies
- [x] Assign shipping costs per item
- [x] Manage shipment numbers and charges
- [x] Filter and search shipped items
- [x] Update maintenance case statuses
- [x] Policy document management

### Related Controllers
- [maintenances.php](maintenances.md) - Maintenance requests
- [maintenancesuppliers.php](maintenancesuppliers.md) - Supplier management
- [maintennanceArchiveController.php](maintennanceArchiveController.md) - Archive management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **maintenancepolicys** | Shipping policy records | id, policydate, policynumber, supplierid, maintenancecompanieid, policystatement, shippingvalue, sendorreceipt, conditions, userid |
| **maintenancecompanies** | Maintenance service companies | id, companyname, companyphone, companyaddress, conditions, userid |
| **maintenances** | Items being shipped | id, supplierid, maintenancepolicyid, maintenancecaseid, shipprice, shipcharge, shipnumber |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **supplier** | Product suppliers | supplierid, suppliername |
| **product** | Product catalog | productId, productName |
| **user** | System users | userid, employeename |

---

## 🔑 Key Functions

### 1. **Default Action** - Add New Shipping Policy
**Location**: Lines 9-14  
**Purpose**: Display form for creating new maintenance shipping policies

**Process Flow**:
1. Display header and add form template
2. Set maintenance module flag for navigation

---

### 2. **show()** - Display Shipping Policies
**Location**: Lines 15-22  
**Purpose**: Show listing of all shipping policies with filtering

**Features**:
- Authentication required
- YouTube tutorial links integration
- DataTables AJAX integration via `showajax()`

---

### 3. **edit()** - Edit Shipping Policy
**Location**: Lines 23-46  
**Purpose**: Edit existing policy and manage associated maintenance items

**Function Signature**:
```php
$id = filter_input(INPUT_GET, 'id');
$del = filter_input(INPUT_GET, 'del');
```

**Process Flow**:
1. Load maintenance policy data by ID
2. Query maintenance items for specific supplier
3. Filter items that are warranty type 2 with case < 3
4. Load product names for display
5. Assign data to edit template

**SQL Query**:
```sql
SELECT maintenances.*, suppliername 
FROM maintenances 
LEFT JOIN supplier ON maintenances.supplierid = supplier.supplierid 
WHERE maintenances.maintorguar = 2 
  AND maintenances.maintenancecaseid < 3 
  AND maintenances.conditions = 0 
  AND maintenances.supplierid = [supplierid]
```

---

### 4. **savedata()** - Save/Update Shipping Policy
**Location**: Lines 105-161  
**Purpose**: Main function for saving shipping policies with item assignments

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

**Input Parameters**:
- `policydate` - Policy creation date
- `policynumber` - Policy reference number
- `supplier` - Supplier ID
- `maintenancecompanies` - Maintenance company ID
- `policystatement` - Policy description/statement
- `shippingvalue` - Total shipping cost
- `maintenanceitr` - Number of maintenance items

**Process Flow**:
1. Create or update maintenance policy record
2. Set `sendorreceipt = 1` (indicates sending)
3. Reset shipping details for existing policy items
4. Loop through maintenance items and update shipping information
5. Change maintenance case status to 2 (shipped)
6. Return JSON response

**Item Processing Loop**:
```php
for ($i = 1; $i <= $maintenanceitr; $i++) {
    $maintenanceid = filter_input(INPUT_POST, 'maintenanceid_' . $i);
    $shipprice = filter_input(INPUT_POST, 'shipprice_' . $i);
    $shipcharge = filter_input(INPUT_POST, 'shipcharge_' . $i);
    $shipnumber = filter_input(INPUT_POST, 'shipnumber_' . $i);
    
    // Update maintenance record with shipping details
    $maintenances->maintenancecaseid = 2; // Status: Shipped
    $maintenances->maintenancepolicyid = $maintenancepolicyid;
}
```

---

### 5. **savecompany()** - Maintenance Company Management
**Location**: Lines 75-103  
**Purpose**: Create or update maintenance company information

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

**Input Parameters**:
- `companyname` - Company name
- `companyphone` - Company phone number
- `companyaddress` - Company address

**Process Flow**:
1. Create new company or update existing
2. Store company information with user tracking
3. Return JSON with company data for dropdown updates

---

### 6. **showajax()** - DataTables AJAX Handler
**Location**: Lines 164-271  
**Purpose**: Provide server-side processing for policy listing table

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

**Filter Parameters**:
- `start_date` / `end_date` - Date range filtering
- `del` - Show deleted records
- `data1` - Supplier ID filter
- `data2` - Maintenance company filter
- `data3` - Policy ID filter

**Process Flow**:
1. Build dynamic WHERE clause based on filters
2. Add search functionality across policy fields
3. Apply sorting and pagination
4. Join with supplier and company tables
5. Generate action buttons based on policy status

**SQL Query Structure**:
```sql
SELECT maintenancepolicys.*, employeename, suppliername, companyname 
FROM maintenancepolicys 
LEFT JOIN user ON maintenancepolicys.userid = user.userid 
LEFT JOIN supplier ON maintenancepolicys.supplierid = supplier.supplierid
LEFT JOIN maintenancecompanies ON maintenancepolicys.maintenancecompanieid = maintenancecompanies.id
WHERE 1 [filters]
```

---

### 7. **getmaintenances** - Load Available Maintenance Items
**Location**: Lines 55-70  
**Purpose**: AJAX endpoint to load maintenance items for a specific supplier

**Function Signature**:
```php
$supplierid = filter_input(INPUT_POST, 'supplierid');
```

**Process Flow**:
1. Query maintenance items that are:
   - Warranty type 2 (repair)
   - Case status 1 (new/awaiting shipment)  
   - Not assigned to any policy (`maintenancepolicyid = 0`)
   - Belong to specified supplier
2. Load product names for each item
3. Display via template for selection

---

## 🔄 Workflows

### Workflow 1: Maintenance Shipping Policy Creation
```
┌─────────────────────────────────────────────────────────────┐
│              START: Create Shipping Policy                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Policy Information                                      │
│     - Enter policy date and number                         │
│     - Select supplier                                       │
│     - Choose maintenance company                            │
│     - Add policy statement/description                      │
│     - Set total shipping value                             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Load Available Items                                    │
│     - System queries maintenance items for supplier         │
│     - Filter: maintorguar = 2 (repair)                     │
│     - Filter: maintenancecaseid = 1 (new)                  │
│     - Filter: maintenancepolicyid = 0 (unassigned)         │
│     - Display with product names                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Assign Shipping Details                                 │
│     FOR EACH selected maintenance item:                     │
│       │                                                     │
│       ├─→ Set shipping price                               │
│       ├─→ Set shipping charge                              │
│       ├─→ Assign shipment tracking number                  │
│       └─→ Update maintenance status to 2 (shipped)         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Save and Track                                          │
│     - Create policy record                                  │
│     - Link all items to policy                             │
│     - Update maintenance case statuses                      │
│     - Ready for shipment tracking                          │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Maintenance Status Progression
```
┌─────────────────────────────────────────────────────────────┐
│                 Maintenance Lifecycle                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  Case 1: New Request                                        │
│     - Created in maintenances.php                          │
│     - Ready for center assignment                          │
│     - maintenancecaseid = 1                                │
│     - maintenancepolicyid = 0                              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  Case 2: Shipped to Maintenance                            │
│     - Assigned to shipping policy                          │
│     - maintenancecaseid = 2                                │
│     - maintenancepolicyid = [policy_id]                    │
│     - Shipping details filled                              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  Case 3+: Further Processing                               │
│     - Work in progress at center                           │
│     - Completion and return                                │
│     - Customer pickup                                      │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display add policy form |
| `do=show` | show() | Display policy listing |
| `do=edit` | edit() | Edit policy and items |
| `do=savedata` | savedata() | Save/update policy |
| `do=showajax` | showajax() | DataTables AJAX data |
| `do=savecompany` | savecompany() | Save maintenance company |
| `do=getmaintenances` | getmaintenances | Load available items AJAX |

---

## 🧮 Calculation Methods

### Shipping Cost Allocation
```php
// Total shipping value distributed among items
$shippingvalue = filter_input(INPUT_POST, 'shippingvalue');

// Individual item shipping costs
for ($i = 1; $i <= $maintenanceitr; $i++) {
    $shipprice = filter_input(INPUT_POST, 'shipprice_' . $i);
    $shipcharge = filter_input(INPUT_POST, 'shipcharge_' . $i);
}
```

### Policy Cost Summary
- Policy contains total shipping value
- Individual items have itemized shipping prices and charges
- Allows for different shipping rates per product type

---

## 🔒 Security & Permissions

### Authentication
- All modification actions require authentication
- Session-based user tracking
- User ID stored with all policy records

### Input Sanitization
```php
// All inputs properly filtered
$policydate = filter_input(INPUT_POST, 'policydate');
$policynumber = filter_input(INPUT_POST, 'policynumber');
$supplierid = filter_input(INPUT_POST, 'supplier');
```

### Data Validation
- Required field validation
- Supplier and company relationship validation
- Exception handling for database operations

---

## 📊 Performance Considerations

### Database Optimization
1. **Indexes Needed**:
   - `maintenancepolicys(supplierid, sendorreceipt)`
   - `maintenances(supplierid, maintenancecaseid, maintenancepolicyid)`
   - `maintenancecompanies(conditions)`

2. **Query Performance**:
   - Efficient filtering of available maintenance items
   - Bulk updates during policy assignment
   - Optimized joins for policy display

### Bulk Operations
- Mass update of maintenance records when assigning to policy
- Efficient processing of multiple items in single transaction

---

## 🐛 Common Issues & Troubleshooting

### 1. **Missing Maintenance Items**
**Issue**: No items show when creating policy  
**Cause**: Items already assigned to other policies or wrong case status

**Debug**:
```sql
SELECT COUNT(*) FROM maintenances 
WHERE supplierid = [ID] 
  AND maintorguar = 2 
  AND maintenancecaseid = 1 
  AND maintenancepolicyid = 0 
  AND conditions = 0;
```

### 2. **Policy Assignment Errors**
**Issue**: Items not properly assigned to policy  
**Cause**: Transaction failure during bulk update

**Fix**: Check for proper transaction handling and verify foreign key constraints

### 3. **Status Update Issues**  
**Issue**: Maintenance case status not changing to 2  
**Cause**: Invalid maintenance ID or database constraint

**Debug**:
```sql
SELECT id, maintenancecaseid, maintenancepolicyid 
FROM maintenances 
WHERE maintenancepolicyid = [POLICY_ID];
```

### 4. **Company Selection Problems**
**Issue**: Maintenance companies not appearing in dropdown  
**Cause**: Companies marked as deleted or not properly saved

**Fix**:
```sql
SELECT * FROM maintenancecompanies WHERE conditions = 0;
```

---

## 🧪 Testing Scenarios

### Test Case 1: Policy Creation
```
1. Create new shipping policy with valid supplier
2. Verify maintenance items load correctly
3. Assign shipping details to items
4. Confirm policy saves and items update status
```

### Test Case 2: Company Management
```
1. Create new maintenance company via AJAX
2. Verify company appears in policy dropdown
3. Test company edit functionality
4. Confirm company data integrity
```

### Test Case 3: Item Status Tracking
```
1. Start with maintenance in case 1
2. Assign to shipping policy
3. Verify status changes to case 2
4. Confirm policy relationship established
```

### Test Case 4: Bulk Operations
```
1. Select multiple maintenance items for policy
2. Set different shipping costs per item
3. Verify all items update correctly
4. Test partial assignment scenarios
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [maintenances.php](maintenances.md) - Maintenance requests
- [Database Schema Documentation](#) - Table relationships
- [Shipping Workflow Guide](#) - Business process documentation

---

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