# Delivery Report Controller Documentation

**File**: `/controllers/deleveryReportController.php`  
**Purpose**: Manages maintenance service delivery tracking, product history, and completion processing  
**Last Updated**: December 20, 2024  
**Total Functions**: 8 main functions  
**Lines of Code**: ~366

---

## 📋 Overview

The Delivery Report Controller is a maintenance service tracking system that manages the delivery and completion of maintenance/repair services. It handles the complete lifecycle from service intake to final delivery, with comprehensive history tracking and payment processing integration.

### Primary Functions
- [x] Track maintenance items ready for delivery
- [x] Process bulk delivery confirmations
- [x] Update service completion status
- [x] Maintain detailed product history logs
- [x] Handle receipt completion workflows
- [x] Support client-based filtering and reporting
- [x] Integrate with payment processing system
- [x] Provide Arabic interface for Middle East operations

### Related Controllers
- [receiptController.php](#) - Receipt generation
- [clientController.php](clientController.md) - Customer management
- Maintenance receipt management system
- Payment processing system

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **m_check** | Items ready for delivery | mcheckid, ourSerial, branchId |
| **m_producthistory** | Service history log | mproducthistoryid, ourSerial, stageFrom, stageTo, cost, comment, status, userId, productHistoryDate, branchId, del |
| **m_comreceipt** | Maintenance receipts | mcomreceiptid, clientid, receiptdat, done |
| **m_comreceiptdetail** | Receipt line items | mcomreceiptdetailid, ourSerial, initialcost, discount, currentstage |

### Supporting Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **client** | Customer information | clientid, clientname |

---

## 🔑 Key Functions

### 1. **Default Dashboard** (`do=all` or empty) - Delivery Tracking Interface
**Location**: Lines 131-158  
**Purpose**: Main interface for viewing and processing items ready for delivery

**Process Flow**:
1. Include authentication check
2. Load client data for filtering dropdown
3. Process search parameters (client, date range, receipt ID)
4. Call `show()` function to load delivery items
5. Display via maintenance header and delivery report template

**Search Parameters**:
```php
$clientname = $_REQUEST['clientid'];
$startDate = $_REQUEST['from'];
$endDate = $_REQUEST['to'];
$recitID = $_POST["recitID"];
```

**Template Assignment**:
```php
$smarty->assign("title1", 'الصيانة');           // Maintenance
$smarty->assign("title2", ' تقرير التسليم');    // Delivery Report
$smarty->assign("title3", ' عرض المنتجات');     // Product Display
```

---

### 2. **Process Delivery** (`do=delever`) - Bulk Delivery Processing
**Location**: Lines 159-192  
**Purpose**: Process multiple items for delivery and update their status

**Process Flow**:
1. Get iteration count from form
2. Loop through selected items
3. For each selected item:
   - Insert product history record
   - Update current stage to 11 (delivered)
   - Check if entire receipt is complete
   - Mark receipt as done if all items delivered
   - Remove from m_check table
4. Display success/error message

**Delivery Processing Logic**:
```php
for ($i = 1; $i <= $itr; $i++) {
    $done = $_POST["done" . $i];
    $ourSerial = $_POST["ourSerial" . $i];
    
    if (isset($done) && !empty($done) && isset($ourSerial) && !empty($ourSerial)) {
        // Insert product history
        insertProductHistory($ourSerial, 6, 11, 0, '', 0);
        
        // Update current stage
        updateCurrentStage(11, $ourSerial);
        
        // Check if receipt is complete
        $flag = checkIfComReceiptDone($ourSerial);
        if ($flag == 0) {
            markAsDone($ourSerial);
        }
        
        // Remove from delivery queue
        $mCheckEX->deleteUsingOurSerial($ourSerial);
    }
}
```

**Stage Code Meanings**:
- Stage 6: Previous stage (before delivery)
- Stage 11: Delivered/completed status

---

### 3. **Process Delivery with Payment** (`do=deleverandPay`) - Delivery + Payment Flow
**Location**: Lines 193-228  
**Purpose**: Same as delivery processing but redirects to receipt/payment system

**Process Flow**:
1. Identical delivery processing as `delever` action
2. Different redirect: goes to `receiptController.php` for payment processing
3. Integrates delivery completion with payment collection

**Redirect Difference**:
```php
// Regular delivery redirects back to this controller
$url = "deleveryReportController.php?do=all";

// Delivery with payment redirects to receipt controller
$url = "receiptController.php";
```

---

### 4. **Update Current Stage** (`updateCurrentStage()`) - Stage Management
**Location**: Lines 237-240  
**Purpose**: Update the current processing stage for an item

**Function Signature**:
```php
function updateCurrentStage($currentstage, $ourSerial)
```

**Implementation**:
```php
global $MComreceiptDetailEX;
$MComreceiptDetailEX->updateCurrentStageUsingOurSerial($currentstage, $ourSerial);
```

---

### 5. **Check Receipt Completion** (`checkIfComReceiptDone()`) - Completion Validation
**Location**: Lines 242-255  
**Purpose**: Verify if all items in a receipt have been delivered

**Function Signature**:
```php
function checkIfComReceiptDone($ourSerial)
```

**Process Flow**:
1. Get receipt ID from the item's serial number
2. Load all items in that receipt
3. Check if any items are not at stage 11 (delivered)
4. Return flag: 0 = all complete, 1 = items pending

**Completion Logic**:
```php
$id = $MComreceiptDetailEX->getReceiptId($ourSerial);
$data = $MComreceiptDetailEX->getCurrentStages($id);

$flag = 0;
foreach ($data as $myData) {
    if ($myData->currentstage != 11) {
        $flag = 1;
        return $flag;  // Exit early if any item not delivered
    }
}
```

---

### 6. **Mark Receipt as Done** (`markAsDone()`) - Receipt Completion
**Location**: Lines 257-263  
**Purpose**: Mark entire receipt as completed when all items delivered

**Function Signature**:
```php
function markAsDone($ourSerial)
```

**Implementation**:
```php
$id = $MComreceiptDetailEX->getReceiptId($ourSerial);
$MComreceiptEX->markAsDone($id);
```

---

### 7. **Insert Product History** (`insertProductHistory()`) - History Tracking
**Location**: Lines 265-282  
**Purpose**: Create detailed history records for service progression

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

**History Record Creation**:
```php
$MProductHistory->ourSerial = $ourSerial;
$MProductHistory->stageFrom = $stageFrom;
$MProductHistory->stageTo = $stageTo;
$MProductHistory->cost = $cost;
$MProductHistory->comment = $comment;
$MProductHistory->status = $status;

// Audit fields
$MProductHistory->userId = $_SESSION['userid'];
$MProductHistory->productHistoryDate = date("Y-m-d H:i:s");
$MProductHistory->branchId = $_SESSION['branchId'];
$MProductHistory->del = 0;
```

---

### 8. **Show Delivery Items** (`show()`) - Data Loading and Display
**Location**: Lines 292-364  
**Purpose**: Load and display items ready for delivery based on search criteria

**Function Signature**:
```php
function show($clientid, $startDate, $endDate, $recitID)
```

**Query Building Process**:
1. Start with base WHERE clause
2. Add client filter if specified
3. Add date range filter if provided
4. Add receipt ID filter if specified
5. Clean up query string (remove trailing AND/WHERE)
6. Execute query with branch restriction

**Dynamic Query Construction**:
```php
$queryString = ' WHERE';

if (isset($clientid) && $clientid != '-1' && $clientid != "all") {
    $queryString .= '  m_comreceipt.clientid = ' . $clientid . ' AND';
}

if (!empty($startDate) && !empty($endDate)) {
    $queryString .= '  m_comreceipt.receiptdat >= "' . $startDate . '" AND m_comreceipt.receiptdat <= "' . $endDate . '" AND';
}

// Clean up trailing AND/WHERE
$arr = explode(' ', $queryString);
$lastWord = end($arr);
if ($lastWord == 'AND') {
    array_pop($arr);
    $queryString = implode(' ', $arr);
} else if ($lastWord == 'WHERE') {
    $queryString = ' ';
}
```

**Data Enhancement**:
```php
foreach ($checkData as $row) {
    // Get latest status
    $data = $mProductHistoryEX->GetStatusOfSerialWithMaxDate($row->ourSerial);
    $row->productHistoryStatus = $data->status;
    $row->stageFrom = $data->stageFrom;
    $row->m_stageTitle = $data->stageTitle;
    
    // Get costs
    $myInitialCost = $MComreceiptDetailEX->getInitialCostByOurserialEX($row->ourSerial);
    $row->Initialcost = $myInitialCost;
    
    $discount = $MComreceiptDetailEX->getdiscountByOurserialEX($row->ourSerial);
    $row->discount = $discount;
}
```

---

## 🔄 Workflows

### Workflow 1: Item Delivery Processing
```
┌─────────────────────────────────────────────────────────────┐
│              START: Items Ready for Delivery                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Display Delivery Dashboard                              │
│     - Show items in m_check table                          │
│     - Filter by client/date if specified                    │
│     - Show current stage and history                        │
│     - Display costs and discounts                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. User Selects Items for Delivery                        │
│     - Check boxes for items to deliver                      │
│     - Choose delivery mode:                                 │
│       ├─ Regular delivery (do=delever)                     │
│       └─ Delivery with payment (do=deleverandPay)          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Each Selected Item                              │
│     FOR EACH selected item:                                 │
│       │                                                     │
│       ├─→ Insert history record (stage 6 → 11)            │
│       ├─→ Update current stage to 11 (delivered)          │
│       ├─→ Check if entire receipt complete                 │
│       ├─→ Mark receipt as done if all items delivered     │
│       └─→ Remove from delivery queue (m_check)            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Complete Process                                        │
│     - Display success message                               │
│     - Redirect based on delivery type:                      │
│       ├─ Regular: Back to delivery report                  │
│       └─ With payment: To receipt controller               │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Receipt Completion Check
```
┌─────────────────────────────────────────────────────────────┐
│           START: Item Delivered (Stage 11)                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Get Receipt ID                                          │
│     - Find receipt containing this item                     │
│     - Using ourSerial to lookup receipt ID                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Check All Items in Receipt                              │
│     FOR EACH item in receipt:                               │
│       │                                                     │
│       ├─→ Check current stage                              │
│       ├─→ If any item != stage 11                         │
│       │   └─→ Return flag=1 (not complete)                │
│       └─→ If all items = stage 11                         │
│           └─→ Return flag=0 (complete)                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Mark Receipt Status                                     │
│     - If flag=0 (all items delivered):                     │
│       └─→ Mark entire receipt as done                      │
│     - If flag=1 (items pending):                           │
│       └─→ Leave receipt open                               │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) or `do=all` | Default dashboard | Display items ready for delivery |
| `do=delever` | Process delivery | Mark selected items as delivered |
| `do=deleverandPay` | Delivery + payment | Deliver items and redirect to payment |

### Required Parameters by Action

**Default Dashboard** (`do=all`):
- Search filters (all optional):
  - `clientid` - Filter by customer ID
  - `from` - Start date filter
  - `to` - End date filter
  - `recitID` - Specific receipt ID filter

**Process Delivery** (`do=delever`):
- `itr` - Number of items in form
- `done{N}` - Checkbox values for delivery (N = 1 to itr)
- `ourSerial{N}` - Serial numbers of items to deliver

**Delivery with Payment** (`do=deleverandPay`):
- Same parameters as `do=delever`

---

## 🔒 Security & Permissions

### Authentication Requirements
```php
include_once("../public/authentication.php");
```

### Branch-Based Access Control
```php
// Users can only see items from their branch
$checkData = $mCheckEX->queryByBranchEX2xx($queryString, $_SESSION['branchId']);
```

**Permission Levels**:
- All authenticated users can view delivery items
- Access restricted to items from user's branch only
- No cross-branch data visibility

### Input Sanitization
```php
// Request parameters are filtered through the framework
$clientname = $_REQUEST['clientid'];
$startDate = $_REQUEST['from'];
$endDate = $_REQUEST['to'];
```

### Audit Trail Maintenance
```php
// All delivery actions logged with user/branch/timestamp
$MProductHistory->userId = $_SESSION['userid'];
$MProductHistory->branchId = $_SESSION['branchId'];
$MProductHistory->productHistoryDate = date("Y-m-d H:i:s");
```

---

## 📊 Performance Considerations

### Database Optimization Tips
1. **Indexes Required**:
   - `m_check(branchId)` - For branch filtering
   - `m_check(ourSerial)` - For item lookups
   - `m_producthistory(ourSerial, productHistoryDate)` - For history queries
   - `m_comreceiptdetail(ourSerial)` - For receipt lookups
   - `m_comreceipt(clientid, receiptdat)` - For client/date filtering

2. **Query Performance**:
   - Branch filtering reduces dataset size
   - Date range filtering prevents large result sets
   - Serial number indexing enables fast lookups

3. **Transaction Management**:
   - Bulk delivery processing in single transaction
   - Error handling prevents partial updates
   - Atomic receipt completion checks

### Known Performance Issues
```sql
-- Complex join query may be slow without proper indexing:
SELECT * FROM m_check 
JOIN m_comreceipt ON m_check.ourSerial = m_comreceiptdetail.ourSerial
JOIN m_comreceiptdetail ON m_comreceipt.id = m_comreceiptdetail.receiptid
WHERE m_check.branchId = ? AND m_comreceipt.receiptdat BETWEEN ? AND ?;
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Items Not Appearing in Delivery Queue**
**Issue**: Expected items not showing in delivery report  
**Cause**: Items not in m_check table or wrong branch

**Debug**:
```sql
-- Check if items exist in m_check
SELECT COUNT(*) FROM m_check WHERE branchId = ?;

-- Check item stages
SELECT ourSerial, currentstage FROM m_comreceiptdetail 
WHERE currentstage != 11;
```

### 2. **Receipt Not Marking as Complete**
**Issue**: Receipt stays open despite all items delivered  
**Cause**: Stage checking logic failure or data inconsistency

**Debug**:
```sql
-- Check stages for all items in receipt
SELECT cd.ourSerial, cd.currentstage 
FROM m_comreceiptdetail cd 
WHERE cd.receiptid = ?;

-- Verify stage 11 assignments
SELECT COUNT(*) FROM m_comreceiptdetail 
WHERE receiptid = ? AND currentstage = 11;
```

### 3. **History Records Missing**
**Issue**: Product history not being recorded  
**Cause**: Insert function failure or database constraints

**Debug**:
```sql
-- Check recent history insertions
SELECT * FROM m_producthistory 
WHERE productHistoryDate >= CURDATE() 
ORDER BY productHistoryDate DESC;
```

### 4. **Branch Filtering Issues**
**Issue**: Wrong items appearing for user's branch  
**Cause**: Session branch ID issues or data corruption

**Debug**:
```php
// Check session branch ID
echo "Current branch: " . $_SESSION['branchId'];

// Verify branch data consistency
$branchItems = R::getAll("SELECT branchId, COUNT(*) as count FROM m_check GROUP BY branchId");
print_r($branchItems);
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Delivery Processing
```
1. Create test items in m_check table
2. Assign to current user's branch
3. Access delivery report
4. Select items for delivery
5. Process delivery (do=delever)
6. Verify items removed from queue
7. Check history records created
```

### Test Case 2: Receipt Completion Logic
```
1. Create receipt with multiple items
2. Deliver some items (not all)
3. Verify receipt stays open
4. Deliver remaining items
5. Verify receipt marked as complete
```

### Test Case 3: Branch Access Control
```
1. Create items in different branches
2. Login as user from branch A
3. Verify only branch A items visible
4. Switch to branch B user
5. Verify different item set
```

### Test Case 4: Search and Filtering
```
1. Create items across different date ranges
2. Create items for different clients
3. Test date range filtering
4. Test client filtering
5. Test receipt ID specific filtering
```

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

// Debug query building
echo "Query String: " . $queryString . "<br>";

// Debug processing loops
for ($i = 1; $i <= $itr; $i++) {
    echo "Processing item " . $i . ": " . $_POST["ourSerial" . $i] . "<br>";
}
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [receiptController.php](#) - Receipt and payment processing
- [clientController.md](clientController.md) - Customer management
- Maintenance workflow documentation
- Database Schema Documentation

---

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