ReturnSellBillReports Documentation
Return Sell Bill Reports Controller Documentation
File: /controllers/ReturnSellBillReportsController.php
Purpose: Generates comprehensive reports for sales returns and combined sales/return operations
Last Updated: December 20, 2024
Total Functions: 8
Lines of Code: ~717
---
๐ Overview
The Return Sell Bill Reports Controller is a specialized reporting module that provides detailed analysis of sales return operations and combined sales/return transactions. It handles:
- โข Sales return bill reports with multiple filtering options
- โข Combined sales/return bill analysis
- โข Return bill detail views with bill settings
- โข Date range filtering with timezone support
- โข Client-based return analysis
- โข Serial number and bill ID searching
- โข Discount and tax calculations for returns
- โข User permission-based data filtering
- โข Multi-format return bill display
Primary Functions
- โ Generate return bill summary reports
- โ Display detailed return bill information
- โ Show combined sales/return bill details
- โ Filter by client, date, serial, or bill ID
- โ Calculate return totals and quantities
- โ Apply discount and tax calculations
- โ Handle user permission restrictions
- โ Process both pure returns and combined bills
- โ Generate bill receipt formats
- โ Support timezone-adjusted reporting
Related Controllers
- โข sellbillController.php - Sales operations
- โข clientReportsController.php - Customer reports
- โข sellbillandruternController.php - Combined sales/returns
- โข billreceiptController.php - Bill receipts
---
๐๏ธ Database Tables
Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **returnsellbill** | Sales return bills | returnsellbillid, returnsellbillclientid, returnsellbillaftertotalbill, returnsellQuantity, returnsellbilldate, conditions, billnameid | |
| **returnsellbilldetail** | Return bill line items | returnsellbilldetailid, returnsellbillid, returnsellbilldetailproductid, returnsellbilldetailquantity, returnsellbilldetailtotalprice | |
| **sellbillandrutern** | Combined sales/return bills | sellbillid, sellbillclientid, sellbillaftertotalbill, returnsellQuantity, sellbilldate, conditions, billnameid | |
| **sellandruternbilldetail** | Combined bill details | sellandruternbilldetailid, sellbillid, sellbilldetailproductid, sellbilldetailquantity, selltype |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **client** | Customer master data | clientid, clientname | |
| **billname** | Bill format definitions | billnameid, billname, billtype | |
| **billsettings** | Bill formatting settings | billsettingid, billnameid, settingkey, settingvalue | |
| **user** | System users | userid, username, viewbills, usergroupid | |
| **programsettings** | System configuration | programsettingsid, settingkey, settingvalue, reportsPlusHours | |
| **youtubelink** | Tutorial links | youtubelinkid, title, url |
๐ Key Functions
1. show() / Default Action - Main Report Display
Location: Line 120-167
Purpose: Generate filtered return bill reports based on search criteria
Function Signature:
// Triggered when: do=show or empty $do
$startDate = $_REQUEST['from'];
$endDate = $_REQUEST['to'];
$sellbillSerial = $_REQUEST['sellbillserial'];
$clientId = $_REQUEST['clientid'];
Process Flow:
1. Load client data for dropdown filters
2. Parse search parameters (date range, serial, client)
3. Call showAll() for main report generation
4. Display via returnSellBillReportsview/show.html template
5. Include YouTube tutorial links
Features:
- โข Multi-criteria filtering capabilities
- โข Client dropdown population
- โข Default report generation
---
2. showAll() - Core Report Generation Logic
Location: Line 294-540
Purpose: Build comprehensive return bill report with advanced filtering
Function Signature:
function showAll()
Process Flow:
1. Initialize Query Strings
โโ Build WHERE clauses for returns and combined bills
โโ Apply user permission restrictions
โโ Set up date range handling
2. Apply Search Filters
โโ Client ID filter
โโ Bill serial filter
โโ Bill ID filter
โโ Date range with timezone support
โโ Default to today if no criteria
3. Process Return Bills
โโ Query returnsellbill table with filters
โโ Calculate totals and quantities
โโ Apply discount calculations
โโ Calculate tax amounts
โโ Mark as type "returnSell"
4. Process Combined Bills
โโ Query sellbillandrutern table
โโ Extract return portions only
โโ Calculate combined bill totals
โโ Apply discount calculations
โโ Mark as type "sellAndReturn"
5. Generate Final Report
โโ Merge both datasets
โโ Calculate grand totals
โโ Assign to template variables
โโ Display comprehensive results
Permission Handling:
if ($userData->viewbills == 0) {
// User can only see their own bills
$queryString .= ' sellbillandrutern.userid =' . $_SESSION['userid'] . ' AND';
$returnqueryString .= ' returnsellbill.userid =' . $_SESSION['userid'] . ' AND';
} elseif ($userData->viewbills == 2) {
// User can see bills from their user group
$queryString .= ' u.usergroupid =' . $_SESSION['usergroupid'] . ' AND';
$returnqueryString .= ' user2.usergroupid =' . $_SESSION['usergroupid'] . ' AND';
}
Timezone Support:
$Programsetting = $ProgramsettingDAO->load(1);
if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
$reportsPlusHours = $Programsetting->reportsPlusHours + 24;
$endDate = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour', strtotime($endDate)));
$startDate = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour', strtotime($startDate)));
}
---
3. returnDetail() - Return Bill Detail View
Location: Line 168-187
Purpose: Display detailed information for a specific return bill
Function Signature:
// Triggered when: do=returnDetail
$returnsellbillId = $_GET['returnsellbillid'];
Process Flow:
1. Call showDetail() to load return bill data
2. Load bill formatting settings via loadBillProperty()
3. Load bill name configuration
4. Load program settings for display formatting
5. Display via returnSellBillReportsview/returnDetail.html
Data Loaded:
- โข Return bill header information
- โข Return bill detail line items
- โข Total quantity returned
- โข Bill formatting settings
- โข Program configuration
---
4. sellAndReturnDetail() - Combined Bill Detail View
Location: Line 188-211
Purpose: Display detailed information for combined sales/return bills
Function Signature:
// Triggered when: do=sellAndReturnDetail
$sellbillId = $_GET['sellbillid'];
Process Flow:
1. Call showsellAndReturnDetail() to load combined bill data
2. Load bill formatting settings
3. Load bill name configuration
4. Load program settings
5. Display via returnSellBillReportsview/sellAndReturnDetail.html
Data Loaded:
- โข Combined bill header information
- โข Sales detail line items (selltype = 0)
- โข Return detail line items (selltype = 1)
- โข Separate quantity totals for sales and returns
---
5. showDetail() - Return Bill Data Loader
Location: Line 250-267
Purpose: Load comprehensive data for a specific return bill
Function Signature:
function showDetail($returnsellbillId)
Process Flow:
1. Load return bill header via loadReturnsellbillById()
2. Load return bill details via queryWithReturnsellbillId()
3. Calculate total returned quantity
4. Return array with all data components
Return Value:
return array(
$returnsellbillData, // Header information
$returnsellbilldetailData, // Line item details
$quantity // Total quantity
);
---
6. showsellAndReturnDetail() - Combined Bill Data Loader
Location: Line 269-292
Purpose: Load comprehensive data for a combined sales/return bill
Function Signature:
function showsellAndReturnDetail($sellbillid)
Process Flow:
1. Load combined bill header via loadSellbillandruternById()
2. Load sales details via queryWithSellBillIdAndSellType(billid, 0)
3. Calculate total sales quantity
4. Load return details via queryWithSellBillIdAndSellType(billid, 1)
5. Calculate total return quantity
6. Return array with all data components
Return Value:
return array(
$sellbillandruternData, // Header information
$sellbilldetailData, // Sales line items
$ruternbilldetailData, // Return line items
$sellQuantity, // Total sales quantity
$returnQuantity // Total return quantity
);
---
7. loadAllClient() - Client Data Loader
Location: Line 222-228
Purpose: Load all clients for dropdown filter population
Function Signature:
function loadAllClient()
Returns: Array of all client objects
---
8. loadBillProperty() - Bill Settings Loader
Location: Line 241-248
Purpose: Load bill formatting settings for a specific bill type
Function Signature:
function loadBillProperty($billnameid)
Returns: Array of bill setting configurations
---
๐ Workflows
Workflow 1: Return Bill Report Generation
---
Workflow 2: Return Bill Detail Display
---
๐ URL Routes & Actions
| URL Parameter | Function Called | Description | |
|---|---|---|---|
| `do=` (empty) or `do=show` | `showAll()` | Main return bill report | |
| `do=returnDetail` | `showDetail()` | Individual return bill detail | |
| `do=sellAndReturnDetail` | `showsellAndReturnDetail()` | Combined bill detail |
Main Report (do=show):
- โข
from- Start date (optional, YYYY-MM-DD) - โข
to- End date (optional, YYYY-MM-DD) - โข
clientid- Customer ID filter (optional, -1 for all) - โข
sellbillserial- Bill serial number filter (optional) - โข
sellbillid- Specific bill ID filter (optional)
Return Detail (do=returnDetail):
- โข
returnsellbillid- Return bill ID (required)
Combined Detail (do=sellAndReturnDetail):
- โข
sellbillid- Combined bill ID (required)
---
๐งฎ Calculation Methods
Discount Calculation
// Fixed amount discount (type = 1)
if ($sellbilldiscounttype == 1) {
$discount = $sellbilldiscount + $detaildiscount;
$taxValue = $sellbillaftertotalbill - ($sellbilltotalbill - $sellbilldiscount);
}
// Percentage discount (type != 1)
else {
$discountValue = ($sellbilltotalbill / 100) * $sellbilldiscount;
$discount = $discountValue + $detaildiscount;
$taxValue = $sellbillaftertotalbill - ($sellbilltotalbill - $discountValue);
}
Tax Calculation
// Tax calculated after discount application
$taxValue = $billAfterTotal - ($billBeforeDiscount - $discountAmount);
Total Quantity Calculation
// For return bills
foreach ($returnsellbilldetailData as $detail) {
$quantity = $quantity + $detail->returnsellbilldetailquantity;
}
// For combined bills (separate sales and returns)
foreach ($sellbilldetailData as $detail) {
$sellQuantity = $sellQuantity + $detail->sellbilldetailquantity;
}
foreach ($returnbilldetailData as $detail) {
$returnQuantity = $returnQuantity + $detail->sellbilldetailquantity;
}
---
๐ Security & Permissions
User Permission Levels
// ViewBills Permission Check
$userData = $myUserRecord->load($_SESSION['userid']);
if ($userData->viewbills == 0) {
// User can only see their own bills
$queryString .= ' returnsellbill.userid =' . $_SESSION['userid'] . ' AND';
} elseif ($userData->viewbills == 2) {
// User can see bills from their user group
$queryString .= ' user2.usergroupid =' . $_SESSION['usergroupid'] . ' AND';
}
Permission Levels:
- โข
viewbills = 0- User can only see their own return bills - โข
viewbills = 1- User can see all return bills - โข
viewbills = 2- User can see return bills from their user group
Input Sanitization
- โข All
$_REQUESTand$_GETparameters filtered through framework - โข Date validation and format checking
- โข ID parameters cast to integers where appropriate
- โข SQL injection prevented by DAO layer
---
๐ Performance Considerations
Database Optimization Tips
1. Required Indexes:
- returnsellbill(returnsellbillclientid, returnsellbilldate, conditions)
- sellbillandrutern(sellbillclientid, sellbilldate, conditions)
- returnsellbilldetail(returnsellbillid)
- sellandruternbilldetail(sellbillid, selltype)
2. Query Optimization:
- Use of efficient date range filtering
- Proper condition filtering to exclude cancelled bills
- Efficient joins for client name resolution
- Separate queries for different bill types to optimize indexes
3. Memory Management:
- Large date ranges may return significant data
- Consider pagination for high-volume return operations
- Efficient array merging for combined datasets
Known Performance Issues
-- This pattern can be slow for large datasets
SELECT * FROM returnsellbill r
LEFT JOIN client c ON r.returnsellbillclientid = c.clientid
WHERE conditions = 0
ORDER BY returnsellbilldate DESC;
-- Solution: Add composite indexes and limit results
CREATE INDEX idx_return_client_date ON returnsellbill(returnsellbillclientid, returnsellbilldate, conditions);
---
๐ Common Issues & Troubleshooting
1. Missing Return Data
Issue: Some return bills don't appear in reports
Cause: Bills marked as cancelled or permission restrictions
Debug:
-- Check for cancelled bills
SELECT COUNT(*) FROM returnsellbill WHERE conditions != 0;
-- Check user permission restrictions
SELECT userid, viewbills FROM user WHERE userid = [SESSION_USERID];
2. Incorrect Discount Calculations
Issue: Discount amounts don't match bill totals
Cause: Mixed discount types or missing detail discounts
Debug:
-- Check discount configuration
SELECT returnsellbillid, returnsellbilldiscount, returnsellbilldiscounttype,
returnsellbilltotalbill, returnsellbillaftertotalbill
FROM returnsellbill WHERE returnsellbillid = [BILL_ID];
-- Check detail-level discounts
SELECT SUM(returnsellbilldetaildiscount)
FROM returnsellbilldetail WHERE returnsellbillid = [BILL_ID];
3. Date Range Issues
Issue: Reports show no data for valid date ranges
Cause: Timezone configuration or date format problems
Fix:
// Check timezone settings
$Programsetting = $ProgramsettingDAO->load(1);
echo "Report Plus Hours: " . $Programsetting->reportsPlusHours;
// Ensure proper date format
if (!empty($startDate)) $startDate .= " 00:00:00";
if (!empty($endDate)) $endDate .= " 23:59:59";
4. Combined Bill Display Issues
Issue: Combined bills show incorrect separation between sales and returns
Cause: Selltype field confusion or missing detail records
Debug:
-- Check selltype values in combined bill details
SELECT selltype, COUNT(*)
FROM sellandruternbilldetail
WHERE sellbillid = [BILL_ID]
GROUP BY selltype;
-- Verify data consistency
SELECT * FROM sellandruternbilldetail WHERE sellbillid = [BILL_ID];
---
๐งช Testing Scenarios
Test Case 1: Basic Return Report
1. Create test return bills with different clients and dates
2. Apply various discount types and amounts
3. Run report with different date ranges
4. Verify calculations match bill totals
5. Check that cancelled bills are excluded
Test Case 2: Permission Enforcement
1. Login as user with viewbills = 0 (own bills only)
2. Create bills for different users
3. Run return report and verify only own bills appear
4. Test with different permission levels
5. Verify user group restrictions work correctly
Test Case 3: Combined Bill Processing
1. Create combined sales/return bills
2. Add both sales and return line items
3. Run combined bill detail report
4. Verify correct separation of sales vs returns
5. Check quantity calculations for each type
Debug Mode Enable
// Add at top of showAll() function for debugging
echo "Query String: " . $queryString . "<br>";
echo "Return Query String: " . $returnqueryString . "<br>";
echo "Date Range: " . $startDate . " to " . $endDate . "<br>";
// Debug data processing
foreach ($returnsellbillData as $bill) {
echo "Bill ID: " . $bill->returnsellbillid .
" Amount: " . $bill->returnsellbillaftertotalbill .
" Discount: " . $bill->returnsellbilldiscount . "<br>";
}
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข sellbillController.md - Sales operations
- โข clientReportsController.md - Customer reports
- โข sellbillandruternController.php - Combined operations
- โข Database Schema Documentation - Table relationships
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When return processing logic changes