# Receipt Controller Documentation

**File**: `/controllers/receiptController.php`  
**Purpose**: Manages maintenance receipt processing for customer service payments and debt adjustments  
**Last Updated**: December 20, 2024  
**Total Functions**: 9  
**Lines of Code**: ~665

---

## 📋 Overview

The Receipt Controller is a specialized maintenance system controller that handles customer service receipts, payment processing, and debt management. It's primarily designed for service-based businesses where customers bring items for maintenance/repair and need to pay for services rendered.

### Primary Functions
- [x] Create customer service receipts
- [x] Process customer payments and debt adjustments
- [x] Apply discounts to service charges
- [x] Track maintenance completion payments
- [x] Generate receipt reports by date/customer
- [x] Edit and update existing receipts
- [x] Delete receipt transactions
- [x] Link receipts to maintenance orders

### Related Controllers
- [clientController.php](#) - Customer management
- [clientPayedDeptController.php](#) - Customer payment processing
- [maintenanceController.php](#) - Maintenance order management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **clientdebtchange** | Customer debt transaction log | clientdebtchangeid, clientid, clientdebtchangeamount, clientdebtchangebefore, clientdebtchangeafter, clientdebtchangetype, discount, reciptid |
| **mfinishingpayed** | Maintenance payment records | finishingPayedId, clientId, clientDebtChangeId, payed, finishingType, remain, userId, branchId |
| **client** | Customer master data | clientid, clientname, clientdebt, clientarea, userid |
| **mcomreceipt** | Maintenance receipts | id, clientid, shipcost, del |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **youtubelink** | Tutorial videos | youtubelinkid, title, url |
| **user** | System users | userid, username, branchId |

---

## 🔑 Key Functions

### 1. **Default Action** - Add Receipt Form
**Location**: Lines 102-116  
**Purpose**: Display form for creating new maintenance receipts

**Process Flow**:
1. Load all active clients for dropdown
2. Display maintenance-specific header
3. Show add receipt form

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

---

### 2. **add()** - Create New Receipt
**Location**: Lines 302-398  
**Purpose**: Process new maintenance receipt with payment and debt calculations

**Function Signature**:
```php
// Global function parameters from POST
$clientid = $_POST['clientid'];
$totaldebt = $_POST['totaldebt'];    // Current customer debt
$payed = $_POST['payed'];            // Amount paid
$discount = $_POST['discount'];      // Discount applied
$textDetails = $_POST['textDetails']; // Receipt notes
$receiptid = $_POST['receiptid'];    // Associated receipt (-1 for none)
```

**Process Flow**:
1. **Payment Processing**: Calculate debt after payment
2. **Discount Application**: Apply discount to remaining debt
3. **Receipt Linking**: Associate with maintenance receipt if provided
4. **Debt Change Recording**: Insert clientdebtchange record
5. **Client Update**: Update customer's current debt
6. **Finishing Payment**: Create mfinishingpayed record

**Calculation Logic**:
```php
// Payment calculation
if ($payed && $payed <= $totaldebt) {
    $debtafter = $totaldebt - $payed;
}

// Discount application
if ($discount && $discount <= $debtafter) {
    $remain = $debtafter - $discount;
    $finalDebt = $remain;
} else {
    $finalDebt = $debtafter;
}
```

---

### 3. **show()** - Display Receipt Reports
**Location**: Lines 401-460  
**Purpose**: Generate filtered receipt reports by customer and date range

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

**Process Flow**:
1. Build dynamic query based on filters
2. Query clientdebtchange for receipt transactions
3. Calculate total payment amounts
4. Display results with summary totals

**Query Building**:
```php
// Client filter
if (isset($clientname) && $clientname != '-1' && $clientname != "all") {
    $queryString .= ' clientdebtchange.clientid =' . $clientname . ' AND';
}

// Date filter
if (!empty($startDate) && !empty($endDate)) {
    $queryString .= ' clientdebtchange.clientdebtchangedate >= "' . $startDate . 
                   '" AND clientdebtchange.clientdebtchangedate <= "' . $endDate . '" AND';
}
```

**Features**:
- Client-specific filtering
- Date range reporting
- Payment amount summation
- "All clients" option

---

### 4. **edit()** - Edit Receipt Form
**Location**: Lines 463-469  
**Purpose**: Load existing receipt for editing

**Process Flow**:
1. Load receipt data by clientdebtchange ID
2. Calculate remaining debt (discount + debt after)
3. Display edit form with current values

**Template**: `receiptview/edit.html`

---

### 5. **update()** - Update Existing Receipt
**Location**: Lines 472-592  
**Purpose**: Update receipt with debt adjustment and recalculation

**Process Flow**:
1. **Reverse Original Transaction**: Add back original payment + discount
2. **Recalculate Customer Debt**: Get fresh debt total
3. **Apply New Values**: Process new payment and discount
4. **Update Records**: Update clientdebtchange and mfinishingpayed
5. **Update Client**: Adjust customer's total debt

**Key Features**:
- Automatic debt reversal and recalculation
- Maintains transaction integrity
- Updates all related financial records

---

### 6. **delete()** - Remove Receipt Transaction
**Location**: Lines 595-646  
**Purpose**: Delete receipt and reverse all associated financial changes

**Process Flow**:
1. **Load Original Transaction**: Get payment and discount amounts
2. **Reverse Financial Impact**: Add back total amount to customer debt
3. **Delete Records**: Remove clientdebtchange entry
4. **Mark Finishing Payment**: Set mfinishingpayed as deleted

---

### 7. **getclient()** - Load Active Clients
**Location**: Lines 285-291  
**Purpose**: Retrieve list of active clients for dropdowns

**Returns**: Array of active client objects (`conditions = 0`)

---

### 8. **getreceiptdata()** - Load Receipt Data
**Location**: Lines 293-300  
**Purpose**: Get active maintenance receipts for linking

**Returns**: Array of active receipt objects (`del = 0`)

---

### 9. **getdebtValueAndPlus()** - Debt Calculation Helper
**Location**: Lines 649-663  
**Purpose**: Calculate debt changes for reversal operations

**Function Signature**:
```php
function getdebtValueAndPlus($clientid, $clientvalue)
```

**Returns**: Array with client ID, debt before, debt after

---

## 🔄 Workflows

### Workflow 1: Process Customer Service Payment
```
┌─────────────────────────────────────────────────────────────┐
│           START: Customer Pays for Service                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Customer Data                                      │
│     - Get current debt balance                              │
│     - Load associated receipt if exists                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Calculate Payment Impact                                │
│     - Validate payment amount ≤ total debt                 │
│     - Calculate remaining debt after payment               │
│     - Apply any discount offered                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Record Financial Transaction                            │
│     - Insert clientdebtchange entry                        │
│     - Include payment amount and discount                  │
│     - Link to receipt if applicable                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Update Customer Records                                 │
│     - Update customer debt balance                          │
│     - Create finishing payment record                      │
│     - Set transaction metadata                              │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Receipt Editing and Correction
```
┌─────────────────────────────────────────────────────────────┐
│              START: Edit Existing Receipt                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Original Transaction                               │
│     - Get original payment and discount amounts             │
│     - Calculate impact on customer debt                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Reverse Original Financial Impact                       │
│     - Add back original payment to customer debt            │
│     - Add back original discount                           │
│     - Get fresh debt balance                               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Apply New Transaction Values                            │
│     - Process new payment amount                            │
│     - Apply new discount if any                            │
│     - Calculate final debt balance                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Update All Records                                      │
│     - Update clientdebtchange record                       │
│     - Update finishing payment record                      │
│     - Update customer debt balance                         │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| (empty) | Default action | Display receipt add form |
| `do=add` | `add()` | Process new receipt creation |
| `do=show` | `show()` | Display receipt reports |
| `do=edit` | `edit()` | Display receipt edit form |
| `do=editprint` | Print edit | Display print-friendly edit |
| `do=update` | `update()` | Process receipt updates |
| `do=delete` | `delete()` | Delete receipt transaction |
| `do=addrecept` | Add from receipt | Create receipt from maintenance order |
| `do=sucess` | Success | Show success page |
| `do=error` | Error | Show error page |

### Required Parameters by Action

**Add Receipt** (`do=add`):
- `clientid` - Customer ID (required)
- `totaldebt` - Current customer debt
- `payed` - Amount being paid
- `discount` - Discount amount (optional)
- `textDetails` - Receipt notes
- `receiptid` - Associated receipt ID (-1 for none)

**Show Reports** (`do=show`):
- `clientid` - Customer filter ('all' or specific ID)
- `from` - Start date (YYYY-MM-DD)
- `to` - End date (YYYY-MM-DD)

**Edit Receipt** (`do=edit`):
- `id` - clientdebtchange ID

**Update Receipt** (`do=update`):
- `clientdebtchangeid` - Transaction ID
- `clientid` - Customer ID
- `payed` - New payment amount
- `discount` - New discount amount
- `textDetails` - Updated notes

**Delete Receipt** (`do=delete`):
- `id` - clientdebtchange ID
- `clientid` - Customer ID
- `finishingPayedId` - Finishing payment record ID

---

## 🧮 Calculation Methods

### Payment Processing
```php
// Basic payment calculation
if ($payed && $payed <= $totaldebt) {
    $debtafter = $totaldebt - $payed;
    $Clientdebtchange->clientdebtchangeafter = $debtafter;
    $Client->clientdebt = $debtafter;
}
```

### Discount Application
```php
// Apply discount to remaining debt
if ($discount && $discount <= $debtafter) {
    $remain = $debtafter - $discount;
    $Clientdebtchange->clientdebtchangeafter = $remain;
    $Client->clientdebt = $remain;
    $Clientdebtchange->discount = $discount;
}
```

### Debt Reversal (for updates/deletes)
```php
// Calculate total impact for reversal
$clientvalue = $changeamount + $clientdiscount;

// Add back to customer debt
$debtValueafter = $debtValuebefore + $clientvalue;
```

### Report Summation
```php
// Sum all payments in report period
$changeAmountSum = 0;
foreach ($shownData as $clientdata) {
    $changeAmountSum1 += $clientdata->clientdebtchangeamount;
    $changeAmountSum = round(($changeAmountSum1 * 2)) / 2; // Round to nearest 0.5
}
```

---

## 🔒 Security & Permissions

### Authentication
```php
include_once("../public/authentication.php");
```
- All actions require valid user session
- Branch-based access control (`$_SESSION['branchId']`)

### Input Validation
```php
$clientid = $_POST['clientid'];
$payed = $_POST['payed'];
$discount = $_POST['discount'];
```

**Validation Rules**:
- Payment amount cannot exceed total debt
- Discount cannot exceed remaining debt after payment
- Client ID must be valid and not -1
- Numeric validation for amounts

### Data Integrity
- Transaction-based updates
- Debt balance validation
- Payment history preservation
- Branch isolation of data

---

## 📊 Performance Considerations

### Database Optimization
1. **Indexes Recommended**:
   - `clientdebtchange(clientid, tablename, clientdebtchangedate)`
   - `clientdebtchange(tablename, branchId)`
   - `client(conditions)`
   - `mcomreceipt(del)`

2. **Query Efficiency**:
   - Proper WHERE clause construction
   - Branch-based filtering
   - Date range optimization

### Memory Management
- Minimal data loading in dropdowns
- Efficient query string building
- Clean array operations

### Known Performance Issues
```php
// Potential issue: String manipulation in query building
$arr = explode(' ', $queryString);
$lastWord = end($arr);
// Consider using proper query builders for complex filtering
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Payment Exceeds Debt**
**Issue**: Payment amount greater than customer debt  
**Cause**: No validation in add() function

**Fix**:
```php
if ($payed > $totaldebt) {
    // Show error - payment too large
    return false;
}
```

### 2. **Discount Calculation Errors**
**Issue**: Discount applied incorrectly or to wrong amount  
**Cause**: Complex conditional logic

**Debug**:
```php
echo "Total Debt: $totaldebt<br>";
echo "Payment: $payed<br>";  
echo "Debt After Payment: $debtafter<br>";
echo "Discount: $discount<br>";
echo "Final Debt: $remain<br>";
```

### 3. **Receipt Linking Issues**
**Issue**: Receipt ID -1 handling inconsistent  
**Cause**: Different handling in add vs update

**Fix**:
```php
// Standardize receipt ID handling
$receiptid = ($receiptid == -1) ? 0 : $receiptid;
```

### 4. **Query String Build Errors**
**Issue**: Malformed WHERE clauses with trailing AND  
**Solution**: The controller includes proper cleanup logic

```php
$arr = explode(' ', $queryString);
$lastWord = end($arr);
if ($lastWord == 'AND') {
    array_pop($arr);
    $queryString = implode(' ', $arr);
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: Simple Payment Receipt
```
1. Select customer with existing debt
2. Enter payment amount less than debt
3. Add receipt notes
4. Submit and verify debt reduction
5. Check clientdebtchange and mfinishingpayed records
```

### Test Case 2: Payment with Discount
```
1. Select customer with debt
2. Enter partial payment
3. Add discount amount
4. Verify final debt = original - payment - discount
5. Check discount field populated in database
```

### Test Case 3: Receipt Editing
```
1. Create receipt with specific amounts
2. Edit receipt with new payment/discount
3. Verify debt properly recalculated
4. Check old amounts properly reversed
```

### Test Case 4: Receipt Deletion
```
1. Create and save receipt
2. Delete the receipt
3. Verify customer debt restored to original
4. Check mfinishingpayed marked as deleted
```

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

// Debug calculations
echo "Original Debt: $totaldebt<br>";
echo "Payment: $payed<br>";
echo "Discount: $discount<br>";
echo "Final Debt: " . $Clientdebtchange->clientdebtchangeafter . "<br>";
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [clientController.php](#) - Customer management
- [clientPayedDeptController.php](#) - Payment processing
- [Database Schema Documentation](#) - Table relationships

---

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