Profit Detail Controller Documentation
File: /controllers/profitdetailController.php
Purpose: Generates detailed profit breakdown reports for specific date ranges
Last Updated: December 20, 2024
Total Functions: 13
Lines of Code: 574
---
๐ Overview
The Profit Detail Controller provides comprehensive profit analysis by breaking down all revenue and cost components over a specified date range. It calculates:
- โข Total sales revenue (regular sales + combined bills)
- โข Sales returns and refunds
- โข Cost of goods sold with various pricing methods
- โข Expense tracking
- โข Net profit calculations
- โข Detailed cost breakdowns with discount handling
Primary Functions
- โ Generate period profit reports
- โ Calculate total sales revenue
- โ Track sales returns and refunds
- โ Compute cost of goods sold
- โ Apply discount calculations
- โ Process expense deductions
- โ Calculate net profit margins
- โ Support multiple buy price evaluation methods
- โ Handle product unit conversions
- โ Process combined sell/return bills
Related Controllers
- โข profitreportController.php - Comprehensive profit reports
- โข profitproductController.php - Product-level profit analysis
- โข sellbillController.php - Sales operations
---
๐๏ธ Database Tables
Primary Sales Tables
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **sellbill** | Sales transactions | sellbillid, sellbillaftertotalbill, sellbilldiscount, sellbilldiscounttype | |
| **sellbilldetail** | Sales line items | sellbilldetailproductid, sellbilldetailquantity, sellbilldetailprice, buyprice, buydiscount | |
| **sellbillandrutern** | Combined sell/return bills | sellbillid, sellbillaftertotalbill, sellbillprice, returnsellbillprice | |
| **sellandruternbilldetail** | Combined bill details | sellbilldetailproductid, sellbilldetailquantity, selltype, buyprice |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **returnsellbill** | Sales returns | returnsellbillid, returnsellbillaftertotalbill, returnsellbilldiscount | |
| **returnsellbilldetail** | Return line items | returnsellbilldetailproductid, returnsellbilldetailquantity, buyprice |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **product** | Product master data | productid, productname, productbuyprice, productsellprice | |
| **productunit** | Unit of measure | productunitid, productnumber, productunitname | |
| **expenses** | Business expenses | expensesid, expensesvalue, expensesdate |
๐ Key Functions
1. show() / Default Action - Main Report Generator
Location: Line 154
Purpose: Generate comprehensive profit report for specified date range
Function Signature:
// Triggered when: do=show or empty $do
$startDate = $_REQUEST['from'];
$endDate = $_REQUEST['to'];
Process Flow:
1. Validate date parameters
2. Calculate total sales revenue
3. Calculate returns and refunds
4. Compute cost of goods sold
5. Process expenses
6. Calculate final profit
7. Display via profitdetailview/show.html
Calculations:
$totalSellPrice = getTotalSellbillByDate($startDate, $endDate) + getTotalAditionalSellbillByDate($startDate, $endDate);
$totalReturnSellPrice = getTotalReturnSellbillByDate($startDate, $endDate) + getTotalAditionalReturnSellbillByDate($startDate, $endDate);
$totalQuantityBuyPrice = getTotalQuantityBuyPriceByDate($startDate, $endDate) + getTotalAditionalQuantityBuyPriceByDate($startDate, $endDate);
$profitFinal = ($totalSellCost - $totalBuyCost) - $totalExpenses;
---
2. getTotalSellbillByDate() - Regular Sales Revenue
Location: Line 245
Purpose: Calculate total revenue from regular sales bills
Function Signature:
function getTotalSellbillByDate($startDate, $endDate)
Process Flow:
1. Query sellbill table with date filter
2. Sum sellbillaftertotalbill values
3. Return total sales amount
SQL Logic:
$sellbillData = $mySellbillEx->queryWithDateAndConditions($startDate, $endDate);
foreach ($sellbillData as $sellbill) {
$totalSellbill += $sellbill->sellbillaftertotalbill;
}
---
3. getTotalAditionalSellbillByDate() - Combined Bill Sales
Location: Line 267
Purpose: Calculate revenue from combined sell/return bills (sell portion only)
Process Flow:
1. Query sellbillandrutern table
2. Filter for positive totals (sells, not returns)
3. Sum sellbillaftertotalbill where >= 0
Business Logic:
foreach ($sellbillandruternData as $sellbillandrutern) {
if ($sellbillandrutern->sellbilltotalbill >= 0) {
$totalSellbill += $sellbillandrutern->sellbillaftertotalbill;
}
}
---
4. getTotalQuantityBuyPriceByDate() - Cost of Goods Sold
Location: Line 341
Purpose: Calculate total cost of goods sold with discount handling
Function Signature:
function getTotalQuantityBuyPriceByDate($startDate, $endDate)
Process Flow:
1. Query sellbilldetail for sold quantities
2. Get buy prices and discount information
3. Apply unit conversions
4. Calculate total cost with discounts
Discount Calculation:
if ($buyDiscount > 0 && $buyDiscountType == 0) {
$productBuyPrice = $buyPrice - $buyDiscount; // Fixed amount
} elseif ($buyDiscount > 0 && $buyDiscountType == 1) {
$productBuyPrice = $buyPrice - (($buyDiscount / 100) * $buyPrice); // Percentage
}
Unit Conversion:
$productnumber = $myProductunitRecord->load($productunitId)->productnumber;
$productBuyPrice = $productBuyPrice * $productnumber;
$totalQuantityBuyPrice += ($quantity * $productBuyPrice);
---
5. getTotalReturnSellbillByDate() - Return Revenue
Location: Line 294
Purpose: Calculate total value of sales returns
Process Flow:
1. Query returnsellbill table
2. Sum returnsellbillaftertotalbill values
3. Return total return amount
---
6. getTotalExpensesByDate() - Business Expenses
Location: Line 558
Purpose: Calculate total business expenses for the period
Function Signature:
function getTotalExpensesByDate($startDate, $endDate)
Process Flow:
1. Query expenses table with date filter
2. Sum expensesValue column
3. Return total expenses
---
๐ Workflows
Workflow 1: Profit Report Generation
---
๐ URL Routes & Actions
| URL Parameter | Function Called | Description | |
|---|---|---|---|
| `do=` (empty) or `do=show` | Default action | Generate profit detail report | |
| `do=success` | Success page | Display success message | |
| `do=error` | Error page | Display error message |
Date Range Report (do=show):
- โข
from- Start date (YYYY-MM-DD) - โข
to- End date (YYYY-MM-DD)
---
๐งฎ Calculation Methods
Revenue Calculation
$totalSellPrice = getTotalSellbillByDate($startDate, $endDate) +
getTotalAditionalSellbillByDate($startDate, $endDate);
Cost Calculation with Discounts
// Fixed discount
if ($buyDiscountType == 0) {
$productBuyPrice = $buyPrice - $buyDiscount;
}
// Percentage discount
else {
$productBuyPrice = $buyPrice - (($buyDiscount / 100) * $buyPrice);
}
Unit Conversion
$productnumber = $myProductunitRecord->load($productunitId)->productnumber;
$productBuyPrice = $productBuyPrice * $productnumber;
$totalCost += ($quantity * $productBuyPrice);
Final Profit Formula
$totalSellCost = $totalSellPrice - $totalReturnSellPrice;
$totalBuyCost = $totalQuantityBuyPrice - $totalQuantityReturnBuyPrice;
$profitFinal = ($totalSellCost - $totalBuyCost) - $totalExpenses;
---
๐ Security & Permissions
Input Validation
- โข Date parameters validated before database queries
- โข No direct SQL injection points identified
- โข All queries use DAO layer with parameterization
Potential Issues
- โข No explicit authentication check (relies on include)
- โข No input sanitization for date formats
- โข Missing permission checks for financial data access
---
๐ Performance Considerations
Database Optimization
1. Indexes Required:
- sellbill(sellbilldate, conditions)
- sellbilldetail(sellbilldetaildate)
- returnsellbill(returnsellbilldate)
- expenses(expensesdate)
2. Query Performance:
- Multiple separate queries could be optimized with JOINs
- Large date ranges may cause timeouts
- No pagination implemented
Memory Usage
- โข Loads all records into memory simultaneously
- โข Could cause issues with large datasets
- โข No result caching implemented
---
๐ Common Issues & Troubleshooting
1. Incorrect Profit Calculations
Issue: Profit values don't match manual calculations
Causes:
- โข Discount calculations applied incorrectly
- โข Unit conversion errors
- โข Missing or duplicated entries
Debug:
// Add debugging output
echo "Sales: " . $totalSellPrice . "\n";
echo "Returns: " . $totalReturnSellPrice . "\n";
echo "COGS: " . $totalQuantityBuyPrice . "\n";
echo "Expenses: " . $totalExpenses . "\n";
2. Missing Data
Issue: Some transactions not included in calculations
Causes:
- โข Date range issues
- โข Cancelled/deleted records
- โข Incorrect status filters
Fix: Check conditions filters in queries
3. Unit Conversion Errors
Issue: Incorrect cost calculations due to unit mismatches
Solution: Verify productunit table data integrity
---
๐งช Testing Scenarios
Test Case 1: Basic Profit Calculation
1. Create test sales with known values
2. Add corresponding expense entries
3. Run report for test date range
4. Verify calculations match expected values
Test Case 2: Discount Handling
1. Create sales with various discount types
2. Verify both fixed amount and percentage discounts
3. Check unit conversion accuracy
4. Confirm final calculations
Test Case 3: Return Processing
1. Create sales with subsequent returns
2. Verify return amounts subtract correctly
3. Check cost calculations for returned items
4. Confirm net profit accuracy
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข profitreportController.md - Comprehensive profit reports
- โข sellbillController.md - Sales operations
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When major changes occur