Profitproduct Documentation
Profit Product Controller Documentation
File: /controllers/profitproductController.php
Purpose: Generates detailed product-level profitability analysis and reports
Last Updated: December 20, 2024
Total Functions: 23
Lines of Code: 1,668
---
๐ Overview
The Profit Product Controller provides comprehensive product-level profit analysis with multiple buy price evaluation methods. It handles:
- โข Individual product profitability analysis
- โข Multiple buy price calculation methods (first, last, mean, with discounts, with tax)
- โข Product category-based filtering
- โข Optical products integration
- โข Complex discount calculations at product and bill levels
- โข Unit conversion handling
- โข VAT calculations for accurate profit margins
Primary Functions
- โ Generate product-specific profit reports
- โ Support 8 different buy price evaluation methods
- โ Handle product category filtering
- โ Process optical product transactions
- โ Calculate complex discount structures
- โ Apply unit conversions automatically
- โ Include VAT calculations
- โ Process sales, returns, and combined bills
- โ Generate discount-focused reports
Buy Price Evaluation Methods
1. first - Original purchase price (buyprice)
2. last - Last purchase price (lastbuyprice)
3. mean - Average purchase price (meanbuyprice)
4. last_discount - Last price after purchase discount
5. mean_discount - Average price after purchase discount
6. generalPrice - Overall average price
7. tax - Last price including VAT
8. mean_tax - Average price including VAT
Related Controllers
- โข profitdetailController.php - Overall profit analysis
- โข profitproductcatController.php - Category profit analysis
- โข profitreportController.php - Comprehensive profit reports
---
๐๏ธ Database Tables
Primary Sales Tables
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **sellbilldetail** | Sales line items | sellbilldetailproductid, sellbilldetailquantity, sellbilldetailprice, buyprice, lastbuyprice, meanbuyprice, discountvalue | |
| **returnsellbilldetail** | Return line items | returnsellbilldetailproductid, returnsellbilldetailquantity, returnsellbilldetailprice, buyprice | |
| **sellandruternbilldetail** | Combined bill details | sellbilldetailproductid, sellbilldetailquantity, selltype, buyprice, sellbilldiscount |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **product** | Product master data | productid, productname, productcatid, overallaverageprice, lastbuyprice, meanbuyprice | |
| **productcat** | Product categories | productcatid, productcatname, productcatparent | |
| **productunit** | Units of measure | productunitid, productnumber |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **billsproducts** | Optical sales | productid, productno, productprice, producttotalprice, netbillvalue, buyprice | |
| **billsreturnproducts** | Optical returns | productid, productno, productprice, producttotalprice, returnedprice |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **programsettings** | System settings | reportsplusHours, vatvalue | |
| **youtubelink** | Tutorial links | title, url |
๐ Key Functions
1. show() / Default Action - Product Profit Report
Location: Line 175
Purpose: Generate comprehensive profit analysis for a specific product
Function Signature:
// Triggered when: do=show or empty $do
$productSearchId = $_REQUEST['productId'];
$startDate = $_REQUEST['from'];
$endDate = $_REQUEST['to'];
$isOptic = filter_input(INPUT_POST, 'proIsOptic');
Process Flow:
1. Load category data and YouTube tutorials
2. Validate input parameters
3. Handle time zone adjustments
4. Process product vs category selection
5. Call getProductInBillByDateAndProductId() for calculations
6. Display results via show.html or showdiscount.html
Features:
- โข Product category filtering support
- โข Time zone adjustment for reports
- โข Optical product integration
- โข Discount-focused view option
---
2. getProductInBillByDateAndProductId() - Core Profit Calculator
Location: Line 256
Purpose: Calculate detailed profit metrics for a specific product
Function Signature:
function getProductInBillByDateAndProductId($startDate, $endDate, $productId, $overAllAveragePrice)
Process Flow:
1. Calculate sales data from multiple sources
2. Calculate return data from multiple sources
3. Calculate buy/cost data
4. Calculate return buy data
5. Apply VAT calculations
6. Compute final profit
Calculation Structure:
// Sales Revenue
$sellPrice = $sellPriceData[0] + $sellPricePulsData[0] + $sellOpticData[0];
$quantityUnit = $sellPriceData[1] + $sellPricePulsData[1] + $sellOpticData[1];
// Returns
$returnSellPrice = $returnSellPriceData[0] + $returnSellPricePulsData[0] + $returnOpticData[0];
// Final Profit Calculation
$yy = $sellPrice - $returnSellPrice;
$profitForOneProduct = ($yy) - ($quantityForOneProduct * $xx * $vatValue);
---
3. getTotalSellPriceByDateAndProductId() - Regular Sales Analysis
Location: Line 371
Purpose: Calculate sales revenue and costs for regular sales bills
Function Signature:
function getTotalSellPriceByDateAndProductId($startDate, $endDate, $ProductIdselected, $overAllAveragePrice)
Complex Discount Calculation:
// Product-level discount
$firstStep = $discountValue;
// Bill-level discount calculation
$thirdStep = ($totalPrice / $sellbillTotalBill) * $sellbillDiscount;
// Final price after all discounts
$sellPriceForOneProduct = $totalPriceBeforeDiscount - ($discountValue + $thirdStep);
Buy Price Selection Logic:
switch ($buyPriceType) {
case "first":
$buyprice = (float) $sellbilldetail->buyprice;
break;
case "last":
$buyprice = (float) $sellbilldetail->lastbuyprice;
break;
case "mean":
$buyprice = (float) $sellbilldetail->meanbuyprice;
break;
case "last_discount":
$buyprice = (float) $sellbilldetail->lastbuyprice_withDiscount;
break;
case "mean_discount":
$buyprice = (float) $sellbilldetail->meanbuyprice_withDiscount;
break;
case "generalPrice":
$buyprice = (float) $overAllAveragePrice;
break;
case "tax":
$buyprice = (float) $sellbilldetail->lastbuyprice_withTax;
break;
case "mean_tax":
$buyprice = (float) $sellbilldetail->meanbuyprice_withTax;
break;
}
---
4. getTotalAditionalSellPriceByDateAndProductId() - Combined Bills
Location: Line 465
Purpose: Process sales from combined sell/return bills
Special Handling:
// Handle combined bill discount calculation
$sellbillTotalBillnor = $sellbillTotalBillnor + $totalPrice;
$sellbillTotalBillnor = $sellbillTotalBillnor - $returnsellbillprice;
if ($sellbillDiscountType == 2) {
$sellbillDiscountxx = ($sellbillDiscount / 100) * $sellbillTotalBillnor;
} else {
$sellbillDiscountxx = ($sellbillDiscount);
}
$sellPrice = $sellPrice - $sellbillDiscountxx;
---
5. getTotalOpticByDateAndProductId() - Optical Products
Location: Line 1527
Purpose: Handle optical product sales with different pricing structure
Process Flow:
1. Query billsproducts table for optical sales
2. Apply simpler discount structure (no unit conversions)
3. Calculate based on direct product pricing
Optical-specific Calculation:
$quantity = $sellbilldetail->productno; // Direct quantity (no unit conversion)
$price = $sellbilldetail->productprice;
$totalPrice = $sellbilldetail->producttotalprice;
$sellbillTotalBill = $sellbilldetail->netbillvalue;
---
6. getTotalReturnOpticByDateAndProductId() - Optical Returns
Location: Line 1601
Purpose: Process optical product returns
Return Calculation:
$sellbillTotalBill = $returnsellbilldetail->returnedprice;
$thirdStep = ($totalPrice / $sellbillTotalBill);
$ReturnSellPriceForOneProduct = $totalPriceBeforeDiscount - $thirdStep;
---
๐ Workflows
Workflow 1: Product Profit Analysis
---
Workflow 2: Discount Calculation Process
---
๐ URL Routes & Actions
| URL Parameter | Function Called | Description | |
|---|---|---|---|
| `do=` (empty) or `do=show` | Default action | Product profit analysis | |
| `dis=T` | Discount view | Show discount-focused report |
Product Analysis (do=show):
- โข
productId- Product ID or category ID - โข
from- Start date (YYYY-MM-DD) - โข
to- End date (YYYY-MM-DD) - โข
buyPriceType- Price evaluation method (POST) - โข
proIsOptic- Optical product flag (POST)
---
๐งฎ Calculation Methods
Multi-Level Discount Calculation
// Step 1: Product-level discount
$productDiscount = $discountValue;
// Step 2: Bill-level discount (proportional)
$billDiscountShare = ($totalPrice / $sellbillTotalBill) * $sellbillDiscount;
// Step 3: Final price
$sellPriceForOneProduct = $totalPriceBeforeDiscount - ($productDiscount + $billDiscountShare);
Buy Price Selection with Tax
switch ($buyPriceType) {
case "tax":
$buyprice = (float) $sellbilldetail->lastbuyprice_withTax;
break;
case "mean_tax":
$buyprice = (float) $sellbilldetail->meanbuyprice_withTax;
break;
}
VAT-Adjusted Profit Calculation
$vatValue = 1 + ($Programsetting->vatValue / 100);
$profitForOneProduct = ($netSales) - ($quantityForOneProduct * $unitCost * $vatValue);
Unit Conversion Handling
$productnumber = $myProductunitEx->getProductNumber($productunitId);
$quantityUnit += ($quantity * $productnumber);
$costPerBaseUnit = $buyPrice * $productnumber;
---
๐ Security & Permissions
Authentication
- โข Includes authentication.php for session validation
- โข No specific role-based access control implemented
Input Validation
- โข Basic input filtering using filter_input()
- โข Date parameter validation
- โข Product ID validation
Potential Issues
- โข No explicit permission checks for financial data
- โข Direct database queries without additional sanitization
- โข Missing rate limiting for report generation
---
๐ Performance Considerations
Database Optimization
1. Critical Indexes:
- sellbilldetail(sellbilldetailproductid, sysdate)
- product(productid)
- billsproducts(productid, sysdate)
- productunit(productunitid)
2. Query Performance Issues:
- Multiple separate queries for each transaction type
- Could benefit from JOIN optimization
- No result caching implemented
3. Memory Usage:
- Loads all matching records simultaneously
- Large product datasets may cause memory issues
- No pagination for results
Optimization Opportunities
-- Current: Multiple queries
SELECT * FROM sellbilldetail WHERE productid = ? AND date BETWEEN ? AND ?
SELECT * FROM returnsellbilldetail WHERE productid = ? AND date BETWEEN ? AND ?
SELECT * FROM sellandruternbilldetail WHERE productid = ? AND date BETWEEN ? AND ?
-- Optimized: Single UNION query possible
---
๐ Common Issues & Troubleshooting
1. Incorrect Profit Calculations
Issue: Profit values don't match expected results
Common Causes:
- โข Wrong buy price evaluation method selected
- โข VAT calculations applied incorrectly
- โข Unit conversion errors
- โข Discount calculation mistakes
Debug Steps:
// Add debugging output
echo "Buy Price Type: " . $buyPriceType . "\n";
echo "VAT Value: " . $vatValue . "\n";
echo "Unit Number: " . $productnumber . "\n";
echo "Discount Value: " . $discountValue . "\n";
2. Missing Optical Products
Issue: Optical products not included in calculations
Cause: isOptic flag not set correctly
Solution: Ensure proIsOptic parameter is passed correctly
3. Zero Division Errors
Issue: Division by zero in unit cost calculations
Locations: Lines where $quantityUnit is used as divisor
Fix: Add zero checks before division operations
4. Unit Conversion Errors
Issue: Incorrect quantities due to unit mismatches
Solution: Verify productunit table data integrity
---
๐งช Testing Scenarios
Test Case 1: Basic Product Profit
1. Create product with known buy/sell prices
2. Create sales transaction
3. Run profit report
4. Verify calculations match manual computation
Test Case 2: Complex Discount Scenarios
1. Create sales with both product and bill discounts
2. Test percentage vs fixed amount discounts
3. Verify multi-level discount calculations
4. Check discount report view accuracy
Test Case 3: Multiple Price Methods
1. Create product with different price history
2. Test each buy price evaluation method
3. Verify price selection logic
4. Check VAT calculations
Test Case 4: Optical Products
1. Create optical product transactions
2. Verify different calculation methodology
3. Check integration with regular products
4. Test optical returns processing
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข profitdetailController.md - Overall profit analysis
- โข profitproductcatController.md - Category analysis
- โข sellbillController.md - Sales operations
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When major changes occur