Receipt Documentation
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
- โ Create customer service receipts
- โ Process customer payments and debt adjustments
- โ Apply discounts to service charges
- โ Track maintenance completion payments
- โ Generate receipt reports by date/customer
- โ Edit and update existing receipts
- โ Delete receipt transactions
- โ 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 |
| 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:
// 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:
// 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:
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:
// 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:
function getdebtValueAndPlus($clientid, $clientvalue)
Returns: Array with client ID, debt before, debt after
---
๐ Workflows
Workflow 1: Process Customer Service Payment
---
Workflow 2: Receipt Editing and Correction
---
๐ 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 |
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
// Basic payment calculation
if ($payed && $payed <= $totaldebt) {
$debtafter = $totaldebt - $payed;
$Clientdebtchange->clientdebtchangeafter = $debtafter;
$Client->clientdebt = $debtafter;
}
Discount Application
// 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)
// Calculate total impact for reversal
$clientvalue = $changeamount + $clientdiscount;
// Add back to customer debt
$debtValueafter = $debtValuebefore + $clientvalue;
Report Summation
// 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
include_once("../public/authentication.php");
- โข All actions require valid user session
- โข Branch-based access control (
$_SESSION['branchId'])
Input Validation
$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
// 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:
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:
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:
// 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
$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
// 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 - 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