Sell Bill Reports Controller Documentation
File: /controllers/sellBillReportsController.php
Purpose: Generates comprehensive sales reports with filtering, search, and detailed transaction analysis
Last Updated: December 20, 2024
Total Functions: 15+
Lines of Code: ~1,143
---
๐ Overview
The Sell Bill Reports Controller is a specialized reporting module that provides detailed sales transaction analysis and reporting capabilities. It handles:
- โข Sales bill listing and filtering
- โข Date range and client-based filtering
- โข Sales and return bill combined reports
- โข Detailed bill analysis with line items
- โข Tax and discount calculations
- โข Search functionality by serial number, client, and comments
- โข Combined sell & return transaction reports
- โข Bill detail views with print capabilities
- โข YouTube tutorial integration for user guidance
Primary Functions
- โ Generate sales bill reports with filtering
- โ Combined sales and return reports
- โ Detailed bill views with line items
- โ Search by serial number, client, date range
- โ Tax and discount calculations
- โ User permission filtering
- โ Multiple date format support
- โ Bill printing and detail views
- โ YouTube tutorial integration
- โ Real-time total calculations
Related Controllers
- โข sellbillController.php - Sales operations and bill creation
- โข clientReportsController.php - Customer analysis
- โข returnsellbillController.php - Sales returns processing
- โข buyBillReportsController.php - Purchase reports
---
๐๏ธ Database Tables
Primary Sales Tables (Direct Operations)
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **sellbill** | Sales bills master data | sellbillid, sellbillclientid, sellbillserial, sellbilldate, sellbilltotalbill, sellbillaftertotalbill, sellbilltotalpayed, sellbilldiscount, sellbilldiscounttype, tax, conditions, comment | |
| **sellbilldetail** | Sales bill line items | sellbilldetailid, sellbillid, sellbilldetailproductid, sellbilldetailquantity, sellbilldetailtotalprice, sellbilldetaildiscount, sellbilldetaildiscounttype | |
| **returnsellbill** | Sales return bills | returnsellbillid, returnsellbillclientid, returnsellbillserial, returnsellbilldate, returnsellbilltotalbill, returnsellbillaftertotalbill, returnsellbilldiscount, returnsellbilldiscounttype, conditions | |
| **returnsellbilldetail** | Return bill line items | returnsellbilldetailid, returnsellbillid, returnsellbilldetailproductid, returnsellbilldetailquantity, returnsellbilldetailtotalprice, returnsellbilldetaildiscount |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **sellbillandrutern** | Combined sell & return bills | sellbillid, sellbillclientid, sellbillserial, sellbilldate, sellbillprice, returnsellbillprice, sellbilltotalbill, sellbillaftertotalbill, sellbilldiscount, sellbilldiscounttype, conditions | |
| **sellandruternbilldetail** | Combined bill line items | sellandruternbilldetailid, sellbillid, sellbilldetailproductid, sellbilldetailquantity, sellbilldetailtotalprice, selltype, sellbilldetaildiscount |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **client** | Customer master data | clientid, clientname, clientdebt, clientarea, userid | |
| **product** | Product information | productid, productname, productcode, productprice | |
| **storedetail** | Inventory details | storedetailid, storedetailproductid, storedetailquantity | |
| **store** | Warehouse/store data | storeid, storename | |
| **user** | System users | userid, username, viewclients, viewbills, usergroupid |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **billname** | Bill template names | billnameid, billname, billtype | |
| **billsettings** | Bill formatting settings | billsettingsid, billnameid, settingkey, settingvalue | |
| **programsettings** | System configuration | programsettingsid, reportsPlusHours, settingvalue | |
| **youtubelink** | Tutorial video links | youtubelinkid, title, url, description |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **productunit** | Product unit conversions | productunitid, productid, unitid, conversionfactor | |
| **productcat** | Product categories | productcatid, productcatname, productcatdescription | |
| **unit** | Measurement units | unitid, unitname, unitdescription | |
| **productserial** | Serial number tracking | productserialid, productid, serialnumber | |
| **soldserialproduct** | Sold product serials | soldserialproductid, sellbillid, productid, serialnumber | |
| **save** | Cash registers/safes | saveid, savename, savevalue | |
| **savedaily** | Daily cash operations | savedailyid, saveid, amount, operationdate | |
| **storereport** | Store reports | storereportid, storeid, reporttype, reportdate | |
| **clientdebtchange** | Customer debt tracking | clientdebtchangeid, clientid, amount, changetype, changedate |
๐ Key Functions
1. show() / Default Action - Main Sales Report
Location: Line 242
Purpose: Generate comprehensive sales bill report with multiple filtering options
Function Signature:
// Triggered when: do=show or empty $do
$startDate = $_REQUEST['from'];
$endDate = $_REQUEST['to'];
$sellbillSerial = $_REQUEST['sellbillserial'];
$sellbillId = $_REQUEST['sellbillid'];
$clientId = $_REQUEST['clientid'];
$sellbillcomment = $_REQUEST['sellbillcomment'];
Process Flow:
1. Load client data for dropdown filtering
2. Load YouTube tutorial links
3. Call showAll() with filter parameters
4. Display via sellBillReportsview/show.html template
Features:
- โข Multi-parameter filtering (date, client, serial, comment)
- โข User permission enforcement
- โข YouTube tutorial integration
- โข Real-time total calculations
---
2. showAll() - Core Sales Report Logic
Location: Line 445
Purpose: Build detailed sales report with dynamic filtering and calculations
Function Signature:
function showAll()
Process Flow:
1. Parse request parameters for filtering
2. Build dynamic SQL query strings for different bill types
3. Apply user permission restrictions (viewbills check)
4. Handle date range processing with timezone support
5. Query sales bills from sellbill table
6. Query combined bills from sellbillandrutern table
7. Calculate totals, discounts, and taxes
8. Merge datasets and assign to template
Key Variables:
- โข
$queryString- Dynamic WHERE clause for sellbill - โข
$sallandreturnqueryString- WHERE clause for combined bills - โข
$totalBills- Sum of all bill amounts - โข
$totalQTY- Total quantity sold - โข
$totaldiscount- Total discount amount - โข
$totaltax- Total tax amount
Filtering Capabilities:
// Client filtering
if (isset($clientId) && $clientId != '-1') {
$queryString .= ' sellbillclientid = ' . $clientId . ' AND';
}
// Serial number filtering
if (isset($sellbillSerial) && $sellbillSerial != '') {
$queryString .= ' sellbillSerial = "' . $sellbillSerial . '" AND';
}
// Comment search
if (isset($sellbillcomment) && $sellbillcomment != '') {
$queryString .= " sellbill.comment LIKE '%" . $sellbillcomment . "%' AND";
}
Discount Calculation Logic:
if ($sellbilldiscounttype == 1) {
// Fixed amount discount
$totaldiscount = $totaldiscount + $sellbilldiscount + $detaildiscount;
} else {
// Percentage discount
$discountvalue = ($sellbilltotalbill / 100) * $sellbilldiscount;
$totaldiscount = $totaldiscount + $discountvalue + $detaildiscount;
}
---
3. sellandreturnreport - Combined Sales & Returns Report
Location: Line 293
Purpose: Generate unified report showing both sales and return transactions
Process Flow:
1. Load client data for filtering
2. Load YouTube tutorials
3. Call showAll() for sales data
4. Call returnshowAll() for return data
5. Display via sellBillReportsview/sellandreturnreport.html
Template Variables:
- โข
$sellbillData- Sales transactions - โข
$returnsellbillData- Return transactions - โข
$totalBills- Sales total - โข
$returntotalBills- Returns total
---
4. returnshowAll() - Return Bills Report Logic
Location: Line 742
Purpose: Generate return bill report with same filtering capabilities as sales
Function Signature:
function returnshowAll()
Process Flow:
1. Build query strings for return bill filtering
2. Query returnsellbill table for pure returns
3. Query sellbillandrutern table for return portions
4. Calculate return totals, discounts, and taxes
5. Merge return datasets
6. Assign to template variables
Return-Specific Logic:
// Return bills from returnsellbill table
$returnsellbillData = $myReturnsellbillEx->queryallWithqueryString2($returnqueryString);
// Return portions from combined bills
$sellbillandruternData = $mySellbillandruternEx->GetSellBillAndReturnUsingQueryString($queryString);
---
5. sellDetail - Individual Bill Detail View
Location: Line 302
Purpose: Show detailed view of a single sales bill with line items
Function Signature:
// Triggered when: do=sellDetail
$sellbillId = $_GET['sellbillid'];
Process Flow:
1. Call showDetail($sellbillId) to load bill data
2. Load bill formatting settings if available
3. Load bill name configuration
4. Display via sellBillReportsview/sellDetail.html
Data Retrieved:
- โข Bill master data
- โข All line items with quantities and prices
- โข Total quantity calculation
- โข Bill formatting settings
- โข Print-ready layout
---
6. showDetail() - Load Bill Detail Data
Location: Line 402
Purpose: Retrieve comprehensive bill data for detail view
Function Signature:
function showDetail($sellbillid)
Process Flow:
1. Load bill master record via loadSellBillById()
2. Load all bill line items via queryWithSellBillId()
3. Calculate total quantities
4. Return array with bill data, detail data, and totals
Return Array:
return array($sellbillData, $sellbilldetailData, $quantity);
// [0] = Bill master data
// [1] = Line items array
// [2] = Total quantity
---
7. sellAndReturnDetail - Combined Bill Detail View
Location: Line 324
Purpose: Show detailed view of combined sell & return bill
Function Signature:
// Triggered when: do=sellAndReturnDetail
$sellbillId = $_GET['sellbillid'];
Process Flow:
1. Call showsellAndReturnDetail($sellbillId)
2. Load bill formatting settings
3. Display via sellBillReportsview/sellAndReturnDetail.html
Template Variables:
- โข
$sellbillandruternData- Combined bill master - โข
$sellbilldetailData- Sales line items - โข
$ruternbilldetailData- Return line items - โข
$sellQuantity- Total sold quantity - โข
$returnQuantity- Total returned quantity
---
8. showsellAndReturnDetail() - Load Combined Bill Data
Location: Line 420
Purpose: Retrieve data for combined sell & return bill detail view
Function Signature:
function showsellAndReturnDetail($sellbillid)
Process Flow:
1. Load combined bill master data
2. Query sales line items (selltype = 0)
3. Query return line items (selltype = 1)
4. Calculate separate quantities for sales and returns
5. Return comprehensive data array
Sell Type Logic:
// Sales items
$sellbilldetailData = $mySellandruternbilldetailEx->queryWithSellBillIdAndSellType($sellbillid, 0);
// Return items
$ruternbilldetailData = $mySellandruternbilldetailEx->queryWithSellBillIdAndSellType($sellbillid, 1);
---
9. loadAllClient() - Client Data for Filtering
Location: Line 358
Purpose: Load customer list for report filtering dropdowns
Function Signature:
function loadAllClient()
Process Flow:
1. Check user permissions (viewclients)
2. Apply user restriction if needed
3. Query client data via queryByCondition()
4. Return filtered client array
Permission Logic:
$userData = $myUserRecord->load($_SESSION['userid']);
if ($userData->viewclients == 0) {
$queryString .= ' AND client.userid =' . $_SESSION['userid'];
}
---
10. loadBillProperty() - Bill Formatting Settings
Location: Line 392
Purpose: Load bill formatting settings for print layouts
Function Signature:
function loadBillProperty($billnameid)
Process Flow:
1. Query bill settings via queryWithBillnameId()
2. Return settings array for template use
---
11. Date Range Processing Functions
Location: Various (showByDate, showBySriral, etc.)
Purpose: Legacy filtering functions for backward compatibility
Functions:
- โข
showByDate($startDate, $endDate)- Filter by date range - โข
showBySriral($serial)- Filter by serial number - โข
showByClient($clientId)- Filter by client - โข
showBySellbillId($sellbillId)- Filter by bill ID
---
๐ Workflows
Workflow 1: Sales Report Generation
---
Workflow 2: Bill Detail View
---
๐ URL Routes & Actions
| URL Parameter | Function Called | Description | |
|---|---|---|---|
| `do=` (empty) or `do=show` | Default action | Main sales report with filtering | |
| `do=sellandreturnreport` | Combined report | Sales and returns in one view | |
| `do=sellDetail` | `showDetail()` | Individual bill detail view | |
| `do=sellAndReturnDetail` | `showsellAndReturnDetail()` | Combined bill detail view |
Main Sales Report (do=show):
- โข
from- Start date (YYYY-MM-DD) - optional - โข
to- End date (YYYY-MM-DD) - optional - โข
clientid- Customer ID filter - optional - โข
sellbillserial- Serial number filter - optional - โข
sellbillid- Bill ID filter - optional - โข
sellbillcomment- Comment search terms - optional
Combined Report (do=sellandreturnreport):
- โข Same parameters as main report
- โข Shows both sales and returns data
Bill Detail View (do=sellDetail):
- โข
sellbillid- Required: Bill ID to display
Combined Bill Detail (do=sellAndReturnDetail):
- โข
sellbillid- Required: Combined bill ID to display
---
๐งฎ Calculation Methods
Discount Processing
// Bill-level discount calculation
if ($sellbilldiscounttype == 1) {
// Fixed amount discount
$discount = $sellbilldiscount;
} else {
// Percentage discount
$discount = ($sellbilltotalbill / 100) * $sellbilldiscount;
}
// Include detail-level discounts
$detaildiscount = $mySellbilldetailEx->getsumdiscount($sellbillid);
$totalDiscount = $discount + $detaildiscount;
Tax Calculation
// Tax calculated after discount
$taxvalue = $sellbillaftertotalbill - ($sellbilltotalbill - $discount);
Quantity Totals
$quantity = 0;
foreach ($sellbilldetailData as $sellbilldetail) {
$quantity = $quantity + ($sellbilldetail->sellbilldetailquantity);
}
Date Range Processing
// Handle timezone offset from program settings
$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)));
} else {
$endDate = $endDate . ' 23:59:59';
$startDate = $startDate . " 00:00:00";
}
---
๐ Security & Permissions
User Permission Levels
// ViewBills Permission Check
$userData = $myUserRecord->load($_SESSION['userid']);
if ($userData->viewbills == 0) {
$queryString .= ' client.userid =' . $_SESSION['userid'] . ' AND';
}
Permission Levels:
- โข
viewbills = 0- User can only see bills from their own customers - โข
viewbills = 1- User can see all bills - โข
viewbills = 2- User can see bills from their user group
Input Sanitization
- โข All
$_REQUESTparameters are filtered through the framework - โข Numeric IDs cast to integer where appropriate
- โข SQL injection prevented by DAO layer parameterized queries
- โข String escaping handled by MySQL DAO classes
---
๐ Performance Considerations
Database Optimization Tips
1. Required Indexes:
- sellbill(sellbillclientid, sellbilldate)
- sellbill(sellbillserial)
- sellbill(sellbillid)
- sellbilldetail(sellbillid)
- returnsellbill(returnsellbillclientid, returnsellbilldate)
- sellbillandrutern(sellbillclientid, sellbilldate)
2. Query Optimization:
- Date filtering with proper datetime format
- Efficient WHERE clause building
- Avoid N+1 queries by batching related data
3. Memory Management:
- Large date ranges may return thousands of bills
- Consider pagination for high-volume periods
- Limit detail view to necessary data
Known Performance Issues
-- This query can be slow without proper indexing
SELECT * FROM sellbill
WHERE sellbilldate BETWEEN ? AND ?
AND sellbillclientid = ?
ORDER BY sellbilldate DESC;
-- Solution: Composite index
CREATE INDEX idx_sellbill_client_date ON sellbill(sellbillclientid, sellbilldate);
---
๐ Common Issues & Troubleshooting
1. Missing Bills in Report
Issue: Bills don't appear in report despite being in date range
Cause: conditions field not equal to 0 (bill is cancelled/draft)
Debug:
SELECT conditions, COUNT(*) FROM sellbill
WHERE sellbilldate BETWEEN '[START]' AND '[END]'
GROUP BY conditions;
2. Incorrect Total Calculations
Issue: Report totals don't match individual bill totals
Cause: Discount calculation errors or mixed bill types
Debug:
-- Check discount types and amounts
SELECT sellbilldiscounttype, sellbilldiscount,
sellbilltotalbill, sellbillaftertotalbill
FROM sellbill WHERE sellbillid = [ID];
3. Date Range Issues
Issue: No results for valid date ranges
Cause: DateTime format mismatch or timezone settings
Fix:
// Check program settings for timezone offset
$Programsetting = $ProgramsettingDAO->load(1);
echo "Reports Plus Hours: " . $Programsetting->reportsPlusHours;
4. Permission Errors
Issue: Users see bills they shouldn't access
Cause: Permission checks not properly applied
Fix:
-- Check user permission settings
SELECT userid, viewbills, viewclients FROM user WHERE userid = [USER_ID];
---
๐งช Testing Scenarios
Test Case 1: Basic Sales Report
1. Create test sales bills with known amounts
2. Set date range covering test bills
3. Verify bill count and totals match database
4. Test different filter combinations
5. Check permission filtering works
Test Case 2: Discount Calculations
1. Create bills with fixed amount discounts
2. Create bills with percentage discounts
3. Add line-item level discounts
4. Verify total discount calculations
5. Check tax calculations after discount
Test Case 3: Combined Bill Types
1. Create regular sales bills
2. Create combined sell/return bills
3. Run report covering both types
4. Verify no double-counting occurs
5. Check totals are properly segregated
Debug Mode Enable
// Add at top of controller for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Debug query building
echo "Sales Query: " . $queryString . "<br>";
echo "Combined Query: " . $sallandreturnqueryString . "<br>";
// Debug totals
echo "Total Bills: " . $totalBills . "<br>";
echo "Total Quantity: " . $totalQTY . "<br>";
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide and performance fixes
- โข sellbillController.md - Sales bill creation and management
- โข clientReportsController.md - Customer analysis reports
- โข Database Schema Documentation - Table relationships and structure
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When major changes occur