Billsreturn Documentation
Bills Return Controller Documentation
File: /controllers/billsreturn.php
Purpose: Manages product returns and refund processing for optical sales
Last Updated: December 20, 2024
Total Functions: 15+
Lines of Code: 734
---
๐ Overview
The Bills Return Controller handles the complete return process for optical products sold through the ERP system. It provides:
- โข Product return processing from sales bills
- โข Partial and full return handling
- โข Inventory restoration management
- โข Customer refund processing (cash/account credit)
- โข Financial accounting for returns
- โข Return audit trail and reporting
- โข Integration with original sales bills
- โข Multi-product return support
- โข Return authorization and validation
- โข Cost tracking for returned items
Primary Functions
- โ Product return processing from sales bills
- โ Partial and full quantity returns
- โ Inventory quantity restoration
- โ Customer refund processing (cash/credit)
- โ Financial journal entries for returns
- โ Return validation against original sales
- โ Multi-product return handling
- โ Return audit trail and reporting
- โ Cost tracking for returned inventory
- โ Integration with sales bill system
Related Controllers
- โข billsfunctions.php - Sales utilities
- โข sellbillController.php - Sales operations
- โข buyBillController.php - Purchase operations
---
๐๏ธ Database Tables
Primary Return Tables
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **billsreturn** | Return bill master | id, billid, returnedprice, clientreceivevalue, date, userid, deleted, dailyentryid | |
| **billsreturnproducts** | Return line items | id, returnbillid, productid, productno, productprice, producttotalprice, billproductid, deleted | |
| **bills** | Original sales bills | id, clientid, billno, finalnetbillvalue, clientdebt, deleted | |
| **billsproducts** | Original sales line items | id, billid, productid, productno, productprice, producttotalprice, deleted |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **client** | Customer master data | clientid, clientname, clientdebt, treeId | |
| **product** | Product catalog | productid, productName, productBuyPrice, lastbuyprice, meanbuyprice | |
| **storedetail** | Current inventory | storedetailid, productid, storeid, productquantity | |
| **storereport** | Inventory movement log | id, productid, storeid, productbefore, productafter, storereporttype, tablename |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **dailyentry** | Accounting journal entries | dailyentryid, dDateTime, entryComment, fromFlag | |
| **dailyentrycreditor** | Credit entries | id, dailyentryid, accountstreeid, value, pluginControllerName | |
| **dailyentrydebtor** | Debit entries | id, dailyentryid, accountstreeid, value, pluginControllerName | |
| **save** | Cash registers | saveid, savename, savecurrentvalue, treeId |
๐ Key Functions
1. Default Action / Return Form - Return Processing Interface
Location: Line 166
Purpose: Display return creation form with store selection
Process Flow:
1. Load all available stores for dropdown
2. Display return form template
3. Enable bill selection and return processing
---
2. add() - Process Complete Return
Location: Line 395
Purpose: Process complete return transaction with all components
Function Signature:
function add()
Process Flow:
1. Save return bill details via saveBillDetails()
2. Process returned products via saveBillProducts()
3. Create financial entries via saveDailyEntry()
4. Handle transaction completion
Features:
- โข Complete return processing
- โข Inventory restoration
- โข Financial accounting integration
- โข Customer refund handling
---
3. saveBillDetails() - Return Bill Creation
Location: Line 401
Purpose: Create return bill master record
Function Signature:
function saveBillDetails()
// Returns: Return bill ID
Process Flow:
1. Extract return parameters (bill ID, amounts)
2. Load original bill information
3. Create return bill record
4. Set system metadata (date, user, branch)
Key Data Captured:
$billId = filter_input(INPUT_POST, "billId"); // Original bill
$discValue = filter_input(INPUT_POST, "discValue"); // Total return value
$clientReceiveValue = filter_input(INPUT_POST, "clientReceiveValue"); // Cash refund
---
4. saveBillProducts() - Process Returned Products
Location: Line 427
Purpose: Process individual returned products with inventory restoration
Function Signature:
function saveBillProducts($billsReturnId)
Process Flow:
1. Process each returned product line
2. Create return product records
3. Update inventory quantities (restore stock)
4. Log inventory movements
5. Update product cost tracking
Inventory Restoration Logic:
if ($billProductId && $billProductId != -1 && $productNum > 0) {
// Get current inventory
$storeDetail = $storeDetailEX->getProductQuantity($billsProducts->productid, $storeId);
$productbefore = $storeDetail->productquantity;
$productafter = $productbefore + $productNum; // Add back to inventory
// Update inventory
$storeDetail->productquantity = $productafter;
$storeDetailDAO->update($storeDetail);
// Log movement
insertStorereportupdate($billsProducts->productid, $storeId, $productNum,
$productbefore, $productafter, 0, $billsReturnId,
"ู
ุฑุชุฌุน ูุงุชูุฑุฉ ู
ุจูุนุงุช", "billsreturn.php", date('Y-m-d'));
}
---
5. saveDailyEntry() - Return Financial Processing
Location: Line 524
Purpose: Create accounting entries for return transactions
Function Signature:
function saveDailyEntry($billsReturnId)
Accounting Logic:
1. Debit: Returns & Allowances account (expense)
2. Credits:
- Cash account (if cash refund given)
- Customer receivable (if account credit)
Journal Entry Structure:
// Debit: Returns account
$dailyEntryDebtor->value = $discValue; // Total return amount
$dailyEntryDebtor->accountstreeid = 16; // Returns account
// Credit: Cash account (if cash refund)
if ($clientReceiveValue > 0) {
$dailyEntryCreditor->value = $clientReceiveValue;
$dailyEntryCreditor->accountstreeid = $save->treeId; // Cash register
}
// Credit: Customer account (if account credit)
if ($clientDeptChangeValue > 0) {
$dailyEntryCreditor2->value = $clientDeptChangeValue;
$dailyEntryCreditor2->accountstreeid = $client->treeId; // Customer receivable
}
---
6. show() - Return Listing
Location: Line 192
Purpose: Display all return transactions with filtering options
Process Flow:
1. Load customer data for filtering
2. Load bill numbers for reference
3. Display return listing template
4. Enable return management operations
---
7. details() - Return Detail View
Location: Line 275
Purpose: Display comprehensive return transaction details
Function Signature:
// Called via: GET parameter 'id' (return bill ID)
$billsReturnId = filter_input(INPUT_GET, "id");
Process Flow:
1. Load return bill record
2. Calculate other returns for same bill
3. Display bill details via getBillDetails()
4. Show return-specific information
---
8. edit() / update() - Return Modification
Location: Line 240 (edit), Line 699 (update)
Purpose: Modify existing return transactions
Edit Process:
1. Load return record and related data
2. Calculate return totals and balances
3. Display edit form with current values
Update Process:
1. Update return bill details via updateBillDetails()
2. Update returned products via updateBillProducts()
3. Reverse and recreate financial entries
4. Handle transaction completion
---
9. delete() - Return Deletion
Location: Line 210
Purpose: Soft delete return with inventory reversal
Process Flow:
1. Mark return as deleted
2. Reverse financial entries
3. Reverse inventory changes (remove returned quantities)
4. Log inventory movements
Inventory Reversal Logic:
foreach ($billsReturnProducts as $productR) {
$productNum = $productR->productno;
$storeDetail = $storeDetailEX->getProductQuantity($productR->productid, $storeId);
$productbefore = $storeDetail->productquantity;
$productafter = $productbefore - $productNum; // Remove returned quantity
$storeDetail->productquantity = $productafter;
$storeDetailDAO->update($storeDetail);
}
---
10. getBillDetails() / getBillProducts() - Return Data Assembly
Location: Line 302 (details), Line 336 (products)
Purpose: Assemble complete return transaction information
Data Assembly Components:
1. Original Bill: Load source sales bill
2. Customer Info: Client details and history
3. Return Calculations: Net amounts after returns
4. Product Details: Line-by-line return information
5. Return History: Previous returns for same bill
---
๐ Workflows
Workflow 1: Complete Product Return Processing
---
Workflow 2: Return Validation and Business Rules
---
๐งฎ Return Calculations
Return Value Calculation
// Calculate total return amount
$totalReturnValue = 0;
for ($i = 1; $i <= $itr; $i++) {
$returnQty = filter_input(INPUT_POST, 'retnum' . $i);
$productPrice = filter_input(INPUT_POST, 'proprice' . $i);
$lineReturnValue = $returnQty * $productPrice;
$totalReturnValue += $lineReturnValue;
}
Refund Distribution
$discValue = filter_input(INPUT_POST, "discValue"); // Total return value
$clientReceiveValue = filter_input(INPUT_POST, "clientReceiveValue"); // Cash refund
$clientDeptChangeValue = $discValue - $clientReceiveValue; // Account credit
Inventory Impact
// For each returned product
$storeDetail = $storeDetailEX->getProductQuantity($productid, $storeId);
$productbefore = $storeDetail->productquantity;
$productafter = $productbefore + $returnedQuantity; // Add back to stock
// Log the movement
insertStorereportupdate($productid, $storeId, $returnedQuantity,
$productbefore, $productafter, 0, $returnBillId,
"ู
ุฑุชุฌุน ูุงุชูุฑุฉ ู
ุจูุนุงุช", "billsreturn.php", date('Y-m-d'));
---
๐ URL Routes & Actions
| URL Parameter | Function Called | Description | |
|---|---|---|---|
| `do=` (empty) | Default action | Return creation form | |
| `do=add` | `add()` | Process new return | |
| `do=show` | `show()` | List all returns | |
| `do=edit` | `edit()` | Edit return form | |
| `do=update` | `update()` | Update return | |
| `do=delete` | `delete()` | Delete return (soft) | |
| `do=details` | `details()` | View return details | |
| `do=sucess` | Success page | Operation completed | |
| `do=error` | Error page | Operation failed |
Add Return (do=add):
- โข
billId- Original sales bill ID - โข
discValue- Total return value - โข
clientReceiveValue- Cash refund amount - โข
hidden_itr- Number of returned products - โข
product[i]- Product IDs - โข
retnum[i]- Return quantities - โข
proprice[i]- Product prices - โข
storeid- Store location
Edit Return (do=edit):
- โข
id- Return bill ID
Delete Return (do=delete):
- โข
id- Return bill ID
View Details (do=details):
- โข
id- Return bill ID
---
๐ Security & Permissions
Input Validation
$billId = filter_input(INPUT_POST, "billId");
$discValue = filter_input(INPUT_POST, "discValue");
$clientReceiveValue = filter_input(INPUT_POST, "clientReceiveValue");
Business Rule Validation
- โข Return quantities cannot exceed original sales quantities
- โข Return dates must be within acceptable timeframe
- โข Product condition must meet return policy
- โข Financial limits and authorization requirements
Transaction Integrity
- โข All return operations wrapped in transactions
- โข Rollback on any validation failure
- โข Consistent inventory and financial updates
---
๐ Performance Considerations
Database Optimization
1. Critical Indexes:
- billsreturn(billid, deleted)
- billsreturnproducts(returnbillid, billproductid)
- billsproducts(billid, productid)
- storereport(productid, storeid, tablename)
2. Query Optimization:
- Efficient return history queries
- Fast product availability checks
- Optimized inventory updates
Return Processing Performance
- โข Batch inventory updates
- โข Efficient return validation
- โข Quick return total calculations
---
๐ Common Issues & Troubleshooting
1. Inventory Discrepancies After Returns
Issue: Inventory levels incorrect after processing returns
Cause: Missing or incorrect inventory restoration
Debug:
-- Check inventory movement logs
SELECT * FROM storereport
WHERE tablename = 'billsreturn.php'
AND productid = [PRODUCT_ID]
ORDER BY storereportdate DESC;
-- Verify current vs calculated inventory
SELECT
p.productName,
sd.productquantity as current_qty,
-- Calculate expected based on movements
(SELECT SUM(CASE WHEN storereporttype = 1 THEN productquantity
ELSE -productquantity END)
FROM storereport sr
WHERE sr.productid = p.productid
AND sr.storeid = sd.storeid) as calculated_qty
FROM storedetail sd
JOIN product p ON p.productid = sd.productid
WHERE sd.productid = [PRODUCT_ID];
2. Return Validation Failures
Issue: Cannot return products that should be returnable
Cause: Incorrect return quantity calculations
Debug:
-- Check return eligibility
SELECT
bp.productid,
bp.productno as original_qty,
COALESCE(SUM(brp.productno), 0) as returned_qty,
bp.productno - COALESCE(SUM(brp.productno), 0) as available_for_return
FROM billsproducts bp
LEFT JOIN billsreturnproducts brp ON brp.billproductid = bp.id AND brp.deleted = 0
WHERE bp.billid = [BILL_ID] AND bp.deleted = 0
GROUP BY bp.id, bp.productid, bp.productno;
3. Financial Entry Mismatches
Issue: Return accounting entries don't balance
Cause: Incorrect credit/debit calculations
Debug:
// Verify return entry totals
$totalReturn = $discValue;
$cashRefund = $clientReceiveValue;
$accountCredit = $totalReturn - $cashRefund;
// Check that debits = credits
$totalDebits = $totalReturn;
$totalCredits = $cashRefund + $accountCredit;
if ($totalDebits != $totalCredits) {
throw new Exception("Return entry doesn't balance");
}
---
๐งช Testing Scenarios
Test Case 1: Partial Product Return
1. Create sales bill with multiple products
2. Return only some products with partial quantities
3. Verify inventory restoration is correct
4. Check financial entries are accurate
5. Validate original bill net amounts updated
Test Case 2: Full Bill Return
1. Create sales bill with multiple products
2. Return all products in full quantities
3. Verify complete inventory restoration
4. Check full refund processing (cash + credit)
5. Validate bill status after full return
Test Case 3: Multiple Partial Returns
1. Create sales bill
2. Process first partial return
3. Process second partial return
4. Verify cumulative return tracking
5. Check inventory levels throughout process
Test Case 4: Return Validation
1. Attempt return with quantities > original
2. Attempt return for non-existent products
3. Test return period validation
4. Verify authorization requirements
Test Case 5: Cash vs Credit Returns
1. Test full cash refund return
2. Test full account credit return
3. Test mixed cash + credit return
4. Verify accounting entries for each scenario
---
๐ Future Enhancement Opportunities
1. Advanced Return Management
- โข Return authorization workflow
- โข Return reason code tracking
- โข Product condition assessment
- โข Return analytics and reporting
2. Customer Experience
- โข Self-service return portal
- โข Return status tracking
- โข Automated refund processing
- โข Return policy automation
3. Inventory Optimization
- โข Returned product grading
- โข Refurbishment workflow
- โข Restocking optimization
- โข Return cost tracking
4. Financial Integration
- โข Advanced return accounting
- โข Tax handling for returns
- โข Multi-currency returns
- โข Return reserve accounting
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข billsfunctions.md - Sales utilities
- โข sellbillController.md - Sales operations
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When return management features are enhanced