# Maintenance Deliverys Controller Documentation

**File**: `/controllers/maintenancedeliverys.php`  
**Purpose**: Manages delivery operations for completed maintenance items including cost calculations and delivery tracking  
**Last Updated**: December 20, 2024  
**Total Functions**: 3  
**Lines of Code**: ~223

---

## 📋 Overview

The Maintenance Deliverys Controller handles the final stage of the maintenance workflow - delivering completed maintenance items back to customers. It manages cost calculations, payment processing, delivery scheduling, and the transition of maintenance items from case 3 (completed) to case 4 (delivered). This controller is crucial for completing the maintenance service cycle and finalizing customer billing.

### Primary Functions
- [x] Process maintenance delivery forms
- [x] Calculate total maintenance costs including shipping
- [x] Handle payment processing (prepaid, later payment, full payment)
- [x] Update maintenance case status to delivered (case 4)
- [x] Track delivery dates and clip numbers
- [x] Display delivery listings with search and filtering
- [x] AJAX data grid functionality for delivery management

### Related Controllers
- [maintenancereceipts.php](maintenancereceipts.md) - Initial maintenance receipt processing
- [maintenanceclients.php](maintenanceclients.md) - Client management
- [externalMaintenanceGoReport.php](externalMaintenanceGoReport.md) - Maintenance reporting

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **maintenances** | Core maintenance records | id, clientid, productid, supplierid, maintenancepolicyid, maintenancecaseid, sendorreceipt |
| **maintenancepolicys** | Maintenance policies/batches | id, supplierid, maintenancecompanieid |

### Cost & Payment Fields in maintenances
| Field | Purpose | Data Type |
|-------|---------|-----------|
| **repayment** | Repayment amount | DECIMAL |
| **clipnumber** | Delivery clip number | VARCHAR |
| **deliverydate** | Scheduled delivery date | DATE |
| **prepaid** | Amount paid in advance | DECIMAL |
| **totalcost** | Total maintenance cost | DECIMAL |
| **requiredcustomer** | Amount required from customer | DECIMAL |
| **maintenancecost** | Core maintenance service cost | DECIMAL |
| **paidlater** | Amount to be paid later | DECIMAL |
| **paidall** | Total amount paid | DECIMAL |
| **residual** | Remaining balance | DECIMAL |
| **bshipcharge** | Backward shipping charge | DECIMAL |
| **shipcharge** | Forward shipping charge | DECIMAL |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **client** | Customer information | clientid, clientname |
| **product** | Product details | productId, productName |
| **supplier** | Service provider details | supplierid, suppliername |
| **branch** | Branch information | branchId, branchName |
| **user** | System users | userid, employeename |
| **maintenancecenters** | Service centers | id, centername |

---

## 🔑 Key Functions

### 1. **Default Action (Empty $do)** - Add Delivery Form
**Location**: Lines 19-25  
**Purpose**: Display the maintenance delivery processing form

**Process Flow**:
1. Set username from session
2. Set current date for form
3. Display header template
4. Load `maintenancedeliveryview/add.html` template
5. Set maintenance flag to 1
6. Display footer template

**Template**: `maintenancedeliveryview/add.html`

---

### 2. **show** - Display Delivery Grid
**Location**: Lines 25-33  
**Purpose**: Show completed maintenance deliveries in a data table

**Process Flow**:
1. Include authentication check
2. Load YouTube tutorial links (inherited functionality)
3. Assign YouTube data to template
4. Display `maintenancedeliveryview/show.html` template
5. Set maintenance flag to 1

**Security**: Requires authentication

---

### 3. **edit** - Edit Delivery Details
**Location**: Lines 33-46  
**Purpose**: Display delivery editing form with maintenance and policy data

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

**Process Flow**:
1. Include authentication check
2. Load maintenance record by ID
3. Load associated maintenance policy data
4. Assign both datasets to template
5. Display `maintenancedeliveryview/edit.html` template

**Data Loading**:
```php
$maintenancedata = R::load('maintenances',$id);
$maintenancepolicydata = R::load('maintenancepolicys',$maintenancedata->maintenancepolicyid);
```

---

### 4. **savedata()** - Process Delivery & Payments
**Location**: Lines 55-96  
**Purpose**: Handle delivery processing with cost calculations and payment management

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

**Input Parameters**:
- `maintenances` - Maintenance record ID
- `repayment` - Repayment amount
- `clipnumber` - Delivery clip/tracking number
- `deliverydate` - Scheduled delivery date
- `prepaid` - Amount paid in advance
- `totalcost` - Total maintenance cost
- `requiredcustomer` - Amount customer needs to pay
- `maintenancecost` - Core service cost
- `paidlater` - Amount for later payment
- `paidall` - Total amount paid
- `residual` - Remaining balance
- `bshipcharge` - Backward shipping cost
- `shipcharge` - Forward shipping cost
- `selectitr` - Form iteration selector

**Process Flow**:
1. Get session data (userid, date/time)
2. Filter and sanitize all input parameters
3. Load existing maintenance record
4. Update all cost and payment fields
5. **Key Status Updates**:
   ```php
   $maintenances->maintenancecaseid = 4;   // Set to "Delivered"
   $maintenances->sendorreceipt = 3;       // Set delivery status
   ```
6. Save updated maintenance record
7. Return JSON response with updated ID

**Cost Calculation Fields**:
```php
// All monetary fields are directly updated from form input
$maintenances->repayment = $repayment;
$maintenances->prepaid = $prepaid;
$maintenances->totalcost = $totalcost;
$maintenances->requiredcustomer = $requiredcustomer;
$maintenances->maintenancecost = $maintenancecost;
$maintenances->paidlater = $paidlater;
$maintenances->paidall = $paidall;
$maintenances->residual = $residual;
$maintenances->bshipcharge = $bshipcharge;
$maintenances->shipcharge = $shipcharge;
```

---

### 5. **showajax()** - AJAX Data Grid
**Location**: Lines 99-219  
**Purpose**: Provide server-side DataTables processing for delivery grid

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

**Filter Parameters**:
- `start_date` / `end_date` - Date range filter
- `del` - Deletion status filter
- `data1` - Supplier ID filter
- `data2` - Client ID filter
- `data3` - Branch ID filter  
- `data4` - Maintenance/guarantee type filter
- `data5` - Maintenance case ID filter

**Key Filter - Delivered Items Only**:
```php
WHERE maintenances.maintenancecaseid = 4  // Only show delivered items
```

**Process Flow**:
1. Define column mapping for DataTables
2. Build dynamic WHERE clause based on filters
3. Apply soft delete filter (`conditions = 0`)
4. Handle multi-column search functionality
5. Execute main query with all necessary JOINs
6. Format each row with action buttons
7. Return JSON response for DataTables

**Main Query Structure**:
```sql
SELECT maintenances.* ,employeename ,clientname ,productName ,suppliername ,branchName, centername, maintenancecenterid 
FROM `maintenances` 
LEFT JOIN user ON maintenances.userid = user.userid 
LEFT JOIN client ON maintenances.clientid = client.clientid 
LEFT JOIN product ON maintenances.productid = product.productId 
LEFT JOIN supplier ON maintenances.supplierid = supplier.supplierid 
LEFT JOIN branch ON maintenances.branchid = branch.branchId  
LEFT JOIN maintenancecenters ON maintenances.maintenancecenterid = maintenancecenters.id  
WHERE maintenances.maintenancecaseid = 4 [ADDITIONAL FILTERS]
```

**Search Fields**:
- Maintenance ID
- Client name
- Product name
- Supplier name
- Invoice date
- Branch name
- Employee name

**Action Buttons**:
```php
// For active deliveries
$sub_array[] = '<a href="maintenancedeliverys.php?do=edit&id='. $row["id"] .'&del=0" type="button" class="btn btn-default btn-lg editicon"></a>';
$sub_array[] = '<a href="javascript:;" data-id="'. $row["id"] .'" data-tableid="id" data-table="maintenances" type="button" class="btn btn-default btn-lg deleteicon removeteble"></a>';

// For deleted items  
$sub_array[] = '<a href="maintenancedeliverys.php?do=edit&id='. $row["id"] .'&del=1" type="button" class="btn btn-default btn-lm">تفاصيل</a>';
$sub_array[] = 'محذوف';
```

---

## 🔄 Workflows

### Workflow 1: Processing Maintenance Delivery
```
┌─────────────────────────────────────────────────────────────┐
│              START: Maintenance Item Completed             │
│                (maintenancecaseid = 3)                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Access Delivery Form                                    │
│     - Load maintenancedeliveryview/add.html                 │
│     - Display current date and username                     │
│     - Select maintenance item to deliver                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Fill Delivery Details                                   │
│     - Set delivery date and clip number                     │
│     - Calculate total costs:                                │
│       ├─ Core maintenance cost                             │
│       ├─ Forward shipping charge                           │
│       ├─ Backward shipping charge                          │
│       └─ Total cost = maintenance + ship charges           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Payment Calculations                            │
│     - Required from customer = total - prepaid             │
│     - Paid later = amount for deferred payment             │
│     - Paid all = prepaid + paid later                      │
│     - Residual = total - paid all                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Submit Delivery (savedata)                              │
│     - Update maintenance record                             │
│     - Set maintenancecaseid = 4 (Delivered)                │
│     - Set sendorreceipt = 3 (Delivery status)             │
│     - Save all cost and payment data                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Complete Delivery Process                               │
│     - Item marked as delivered                              │
│     - Available in delivery reports                         │
│     - Customer billing finalized                           │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Delivery Management & Tracking
```
┌─────────────────────────────────────────────────────────────┐
│                START: View Deliveries                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Delivery Grid                                      │
│     - Authentication check                                  │
│     - Load maintenancedeliveryview/show.html               │
│     - Initialize DataTables                                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. AJAX Data Request (showajax)                           │
│     - Filter by maintenancecaseid = 4                      │
│     - Join with all related tables                         │
│     - Apply user-specified filters                         │
│     - Include pagination and sorting                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Display Delivery Information                            │
│     - Client name and contact details                      │
│     - Product name and specifications                      │
│     - Supplier and service center                          │
│     - Invoice date and delivery date                       │
│     - Payment status and amounts                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Management Actions                                      │
│     - Edit delivery details                                │
│     - View delivery history                                │
│     - Update payment status                                │
│     - Print delivery receipts                              │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default display | Show delivery processing form |
| `do=show` | show action | Display deliveries data grid |
| `do=edit` | edit action | Show delivery edit form |
| `do=savedata` | `savedata()` | Process delivery and payments |
| `do=showajax` | `showajax()` | DataTables AJAX endpoint |

### Required Parameters by Action

**Process Delivery** (empty `do`):
- No parameters required - shows form

**Show Deliveries** (`do=show`):
- Authentication required
- No additional parameters

**Edit Delivery** (`do=edit`):
- `id` - Maintenance record ID
- `del` - Deletion status flag

**Save Delivery** (`do=savedata`):
- `maintenances` - Maintenance record ID (required)
- `deliverydate` - Delivery date
- `clipnumber` - Delivery tracking number
- Cost fields: `totalcost`, `maintenancecost`, `shipcharge`, `bshipcharge`
- Payment fields: `prepaid`, `paidlater`, `paidall`, `residual`, `requiredcustomer`

**AJAX Data** (`do=showajax`):
- DataTables parameters for pagination and sorting
- Optional filters: `data1` (supplier), `data2` (client), `data3` (branch), `data4` (type), `data5` (case)
- Date range: `start_date`, `end_date`

---

## 🧮 Calculation Methods

### 1. **Total Cost Calculation**
```php
// Frontend calculation (should match)
Total Cost = Maintenance Cost + Forward Shipping + Backward Shipping
```

### 2. **Customer Payment Calculations**
```php
// Required from Customer
$required_customer = $total_cost - $prepaid;

// Total Paid
$paid_all = $prepaid + $paid_later;

// Remaining Balance
$residual = $total_cost - $paid_all;
```

### 3. **Payment Status Logic**
```php
// Payment scenarios:
if ($residual == 0) {
    // Fully paid
    $status = "Paid in Full";
} elseif ($prepaid > 0) {
    // Partially paid
    $status = "Partial Payment";
} else {
    // No payment yet
    $status = "Payment Due";
}
```

### 4. **Case Status Progression**
```php
// Maintenance case progression:
// Case 1: Initial Receipt
// Case 2: Under Service  
// Case 3: Service Completed
// Case 4: Delivered (this controller)
$maintenances->maintenancecaseid = 4;  // Delivered
$maintenances->sendorreceipt = 3;      // Delivery status
```

---

## 🔒 Security & Permissions

### Authentication Requirements
- **show** and **edit** actions require authentication
- **savedata** and **showajax** should include authentication checks

### Input Sanitization
```php
// All inputs are properly filtered
$repayment = filter_input(INPUT_POST, 'repayment');
$clipnumber = filter_input(INPUT_POST, 'clipnumber');
$deliverydate = filter_input(INPUT_POST, 'deliverydate');
// ... all other fields
```

### Session Security
```php
$userid = $_SESSION['userid'];
$today = date("Y-m-d H:i:s");
$date = date('Y-m-d');
```

### Data Integrity
- Uses RedBeanPHP ORM for safe database operations
- Proper parameter binding in load operations
- Numeric fields are properly handled

---

## 📊 Performance Considerations

### Database Optimization
1. **Critical Indexes**:
   - `maintenances(maintenancecaseid)` - For filtering delivered items
   - `maintenances(clientid)` - For client-based queries  
   - `maintenances(maintenancepolicyid)` - For policy relationships
   - `maintenances(conditions)` - For soft delete filtering

2. **Query Efficiency**:
   - Single query with LEFT JOINs is efficient
   - Date range filtering properly indexed
   - Avoids N+1 query problems

### Potential Performance Issues
- Large result sets when no date filters applied
- Multiple text field searches with LIKE operators
- Complex JOIN operations with multiple tables

---

## 🐛 Common Issues & Troubleshooting

### 1. **Cost Calculation Mismatches**
**Issue**: Frontend totals don't match saved values  
**Cause**: JavaScript calculation differs from PHP processing

**Debug**:
```sql
SELECT 
    totalcost, 
    maintenancecost, 
    shipcharge, 
    bshipcharge,
    (maintenancecost + shipcharge + bshipcharge) as calculated_total
FROM maintenances 
WHERE id = [ID];
```

### 2. **Payment Balance Issues**
**Issue**: Residual amounts don't calculate correctly  
**Cause**: Inconsistent payment field updates

**Debug**:
```sql
SELECT 
    totalcost,
    prepaid,
    paidlater,
    paidall,
    residual,
    requiredcustomer,
    (totalcost - paidall) as should_be_residual
FROM maintenances 
WHERE id = [ID];
```

### 3. **Status Not Updating**
**Issue**: Items don't appear as delivered  
**Cause**: Case ID or sendorreceipt not properly set

**Debug**:
```sql
SELECT 
    maintenancecaseid,
    sendorreceipt,
    deliverydate,
    clipnumber
FROM maintenances 
WHERE id = [ID];
```

### 4. **DataTable Loading Issues**
**Issue**: Grid shows no data or errors  
**Cause**: AJAX query problems or JOIN failures

**Debug**:
```php
// Add to showajax() function
error_log("Search Query: " . $searchQuery);
error_log("Result Count: " . count($rResult));
```

---

## 🧪 Testing Scenarios

### Test Case 1: Complete Delivery Process
```
1. Ensure maintenance item exists with caseid = 3
2. Navigate to maintenancedeliverys.php
3. Fill delivery form with all cost details
4. Submit and verify successful processing
5. Check database for caseid = 4 and sendorreceipt = 3
6. Verify item appears in delivery grid
```

### Test Case 2: Payment Calculations
```
1. Create delivery with known costs
2. Test different payment scenarios:
   - Full prepayment
   - Partial prepayment
   - No prepayment
   - Mixed payment methods
3. Verify all calculations are correct
4. Check residual amounts match expectations
```

### Test Case 3: Grid Functionality
```
1. Create multiple delivered items
2. Test all filter options (date, client, supplier, etc.)
3. Verify search across different fields
4. Test sorting by various columns
5. Check pagination with large datasets
6. Verify action buttons work correctly
```

### Test Case 4: Data Integrity
```
1. Test with missing maintenance policy data
2. Verify foreign key relationships
3. Test soft delete functionality
4. Check branch and user associations
5. Validate date handling and formatting
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [maintenancereceipts.md](maintenancereceipts.md) - Prior stage in maintenance workflow
- [maintenanceclients.md](maintenanceclients.md) - Client management for maintenance
- [Database Schema Documentation](#) - Maintenance table relationships

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Key Features**: Cost calculation, payment processing, delivery tracking  
**Next Review**: When payment integration changes