StoreProfite Documentation
Store Profit Controller Documentation
File: /controllers/storeProfiteController.php
Purpose: Comprehensive store profitability analysis with multi-pricing method support and detailed cost calculations
Last Updated: December 21, 2024
Total Functions: 2
Lines of Code: ~600
---
๐ Overview
The Store Profit Controller provides detailed profitability analysis across stores with comprehensive cost calculation methods. It handles:
- โข Multi-store profit comparison and analysis
- โข Flexible pricing method selection for cost calculations
- โข Sales, returns, and combined bill profit analysis
- โข Product unit conversion for accurate calculations
- โข Date range filtering with detailed metrics
- โข User permission-based store access control
- โข Real-time profit margin calculations
- โข Integration with multiple bill types and discount systems
Primary Functions
- โ Multi-store profit analysis and comparison
- โ Flexible cost calculation methods (8 different pricing strategies)
- โ Sales vs returns profit impact analysis
- โ Product unit conversion handling
- โ Date range filtering with detailed breakdowns
- โ User permission-based store access
- โ Real-time cost and profit calculations
- โ Discount impact on profitability
Related Controllers
- โข sellbillController.php - Sales operations
- โข returnsellbillController.php - Sales returns
- โข storeController.php - Store management
- โข productController.php - Product management
---
๐๏ธ Database Tables
Primary Sales Tables
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **sellbill** | Sales bills master | sellbillid, sellbillstoreid, sellbillsysdate, sellbilltotalbill, sellbillaftertotalbill, deletedsellid | |
| **sellbilldetail** | Sales line items | sellbilldetailid, sellbillid, sellbilldetailproductid, sellbilldetailquantity, sellbilldetailtotalprice, productunitid | |
| **returnsellbill** | Return bills master | returnsellbillid, returnsellbillstoreid, returnsellbillsysdate, returnsellbilltotalbill, returnsellbillaftertotalbill | |
| **returnsellbilldetail** | Return line items | returnsellbilldetailid, returnsellbillid, returnsellbilldetailproductid, returnsellbilldetailquantity, productunitid | |
| **sellbillandrutern** | Combined bills | sellbillid, sellbillstoreid, sellbillsysdate, sellbilltotalbill, sellbillaftertotalbill | |
| **sellandruternbilldetail** | Combined bill details | sellandruternbilldetailid, sellbillid, sellbilldetailproductid, sellbilldetailquantity, productunitid |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **productunit** | Product units with pricing | productunitid, productid, productnumber, overAllAveragePrice, buyprice, lastbuyprice, meanbuyprice | |
| **product** | Product master data | productId, productName, productBuyPrice |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **store** | Store information | storeId, storeName | |
| **user** | System users | userid, username, usergroupid | |
| **usergroup** | User groups | usergroupid, groupname |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **programsettings** | System settings | programsettingsid, settingkey, settingvalue | |
| **youtubelink** | Tutorial links | youtubelinkid, title, url |
๐ Key Functions
1. all Action - Main Profit Analysis
Location: Line 184
Purpose: Comprehensive profit analysis across stores with flexible cost calculation
Process Flow:
1. Load program settings and user permissions
2. Process search parameters (store, date range, pricing method)
3. Build dynamic query strings with store access control
4. Query sales bills, return bills, and combined bills
5. Calculate profits using selected pricing method
6. Apply discount calculations and generate totals
7. Display results via storeProfitView template
Key Variables:
- โข
$storeId- Store filter selection - โข
$dateFrom/$dateTo- Date range for analysis - โข
$buyPriceType- Pricing method selection - โข
$totalOfTotal- Net profit across all stores
---
2. loadProductUnitWithProductAndUnit() - Product Unit Data Loading
Location: Line 589
Purpose: Loads detailed product unit information with pricing data
Function Signature:
function loadProductUnitWithProductAndUnit($productId, $unitId)
Returns: Complete product unit object with all pricing fields and conversion factors
---
๐ Workflows
Workflow 1: Store Profitability Analysis
---
๐ URL Routes & Actions
| URL Parameter | Function Called | Description | |
|---|---|---|---|
| `do=all` | Main analysis | Comprehensive store profit analysis | |
| `do=sucess` | Success page | Display success message | |
| `do=error` | Error page | Display error message |
- โข
store- Store ID filter (-1 for all stores) - โข
dateFrom- Analysis start date (YYYY-MM-DD) - โข
dateTo- Analysis end date (YYYY-MM-DD) - โข
buyPriceType- Cost calculation method
Cost Calculation Methods
- โข
first- Buy price from bill detail record - โข
last- Last buy price from product unit - โข
mean- Mean/average buy price - โข
last_discount- Last buy price with discount applied - โข
mean_discount- Mean buy price with discount applied - โข
generalPrice- Overall average price from product - โข
tax- Last buy price with tax included - โข
mean_tax- Mean buy price with tax included
---
๐งฎ Calculation Methods
Cost Calculation by Method
switch ($buyPriceType) {
case "first":
$buyprice = (float) $mySellBillDetail->buyprice;
break;
case "last":
$buyprice = (float) $mySellBillDetail->lastbuyprice;
break;
case "mean":
$buyprice = (float) $mySellBillDetail->meanbuyprice;
break;
case "last_discount":
$buyprice = (float) $mySellBillDetail->lastbuyprice_withDiscount;
break;
case "mean_discount":
$buyprice = (float) $mySellBillDetail->meanbuyprice_withDiscount;
break;
case "generalPrice":
$buyprice = (float) $overAllAveragePrice;
break;
case "tax":
$buyprice = (float) $mySellBillDetail->lastbuyprice_withTax;
break;
case "mean_tax":
$buyprice = (float) $mySellBillDetail->meanbuyprice_withTax;
break;
}
// Calculate total cost for line item
$myBuyPrice = $buyprice * ($mySellBillDetail->sellbilldetailquantity * $myproductNumber);
Discount Processing
// Get bill discount settings
$sellbilldiscounttype = $mysellBill->sellbilldiscounttype;
$sellbilldiscount = $mysellBill->sellbilldiscount;
if ($sellbilldiscounttype == 1) {
// Fixed amount discount
$sellBillTotal = $mysellBill->sellbilldiscount;
} elseif ($sellbilldiscounttype == 2) {
// Percentage discount
$sellBillTotal = ($mysellBill->sellbilldiscount / 100) * $mysellBill->sellbilltotalbill;
}
Final Profit Calculation
// Calculate bill profit
$thisProfits += ($mySellBillDetail->sellbilldetailtotalprice) - $myBuyPrice;
$totalBuy += $myBuyPrice;
$totalSell += $mySellBillDetail->sellbilldetailtotalprice;
// Apply discount to final profit
$mysellBill->sellBillTotalx = $sellBillTotal;
$mysellBill->totalBuyx = $totalBuy;
$mysellBill->totalSellx = $totalSell;
// Net profit for bill
$totalOfTotal += ($mysellBill->sellbillaftertotalbill - $mysellBill->totalBuyx);
Product Unit Conversion
// Load product unit data
$productunitData = loadProductUnitWithProductAndUnit($productId, $unitId);
$overAllAveragePrice = $productunitData->overAllAveragePrice;
$myproductNumber = $productunitData->productnumber;
// Convert to base units for costing
$finalQuantity = $sellbilldetailquantity * $myproductNumber;
$lineCost = $buyprice * $finalQuantity;
---
๐ Security & Permissions
Store Access Control
// Multi-store vs single-store access
if ($_SESSION['searchinonestore'] == 0) {
// Multi-store user
if ($_SESSION['storeids'] != 0) {
$queryString .= ' sellbill.sellbillstoreid in (' . $_SESSION['storeids'] . ') AND';
}
} else {
// Single-store user
$queryString .= ' sellbill.sellbillstoreid = ' . $_SESSION['storeid'] . ' AND';
}
// Admin override for store selection
if (isset($storeId) && $storeId != -1) {
$queryString .= ' sellbill.sellbillstoreid = ' . $storeId . ' AND';
}
User Group Permissions
// Load user group data for permissions
$myUserGroupRecord = new UsergroupMySqlDAO();
$loadData = $myUserGroupRecord->load($_SESSION['usergroupid']);
$smarty->assign("loadData", $loadData);
Query Security
// Exclude deleted records
$queryString .= ' and sellbill.deletedsellid = 0 ';
// Date filtering with proper format
if (isset($dateFrom) && !empty($dateFrom) && isset($dateTo) && !empty($dateTo)) {
$queryString .= ' DATE( sellbill.sellbillsysdate ) >= "' . $dateFrom . '" AND DATE( sellbill.sellbillsysdate ) <= "' . $dateTo . '"';
}
---
๐ Performance Considerations
Query Optimization
1. Efficient Joins:
- Uses getSellBillsUsingQueryString() for optimized queries
- Proper JOIN relationships between bills and details
- Date indexing for performance
2. Memory Management:
- Processes bills in sequence rather than loading all at once
- Efficient aggregation of totals
- Minimal template variable usage
3. Database Indexes Required:
- sellbill(sellbillsysdate, sellbillstoreid, deletedsellid)
- sellbilldetail(sellbillid, sellbilldetailproductid)
- productunit(productid, productunitid)
Performance Monitoring
// Monitor query performance for large date ranges
$startTime = microtime(true);
$sellBill = $sellBillEx->getSellBillsUsingQueryString($queryString);
$queryTime = microtime(true) - $startTime;
// Alert if queries are slow
if ($queryTime > 2.0) {
error_log("Slow profit analysis query: " . $queryTime . "s");
}
---
๐ Common Issues & Troubleshooting
1. Incorrect Profit Calculations
Issue: Profit margins don't match manual calculations
Cause: Wrong pricing method selection or missing cost data
Debug:
// Debug cost calculation
echo "Selected Method: " . $buyPriceType . "<br>";
echo "Unit Data: " . print_r($productunitData, true) . "<br>";
echo "Buy Price: " . $buyprice . "<br>";
echo "Quantity: " . $sellbilldetailquantity . "<br>";
echo "Product Number: " . $myproductNumber . "<br>";
echo "Final Cost: " . $myBuyPrice . "<br>";
2. Store Access Issues
Issue: User can't see expected stores or data
Cause: Session permissions or store assignment problems
Debug:
// Check user store permissions
echo "User Store ID: " . $_SESSION['userid'] . "<br>";
echo "Search In One Store: " . $_SESSION['searchinonestore'] . "<br>";
echo "Store IDs: " . $_SESSION['storeids'] . "<br>";
echo "Default Store: " . $_SESSION['storeid'] . "<br>";
3. Missing Bill Data
Issue: Known bills not appearing in profit analysis
Cause: Date range issues or deleted bill filtering
Fix:
// Check bill status
SELECT sellbillid, sellbilldate, deletedsellid, conditions
FROM sellbill
WHERE sellbillid = [MISSING_BILL_ID];
// Verify date filtering
echo "Date From: " . $dateFrom . "<br>";
echo "Date To: " . $dateTo . "<br>";
echo "Query String: " . $queryString . "<br>";
---
๐งช Testing Scenarios
Test Case 1: Multi-Store Profit Comparison
1. Create sales in different stores using same products
2. Set different cost prices for comparison
3. Run profit analysis for all stores
4. Verify store-wise profit calculations
5. Check grand total accuracy across stores
Test Case 2: Pricing Method Accuracy
1. Set up products with different cost price types
2. Create sales using various pricing methods
3. Run profit analysis with each method (first, last, mean, etc.)
4. Verify cost calculations use correct price source
5. Compare profit margins across methods
Test Case 3: Discount Impact Analysis
1. Create bills with various discount types:
- Fixed amount discounts
- Percentage discounts
- No discounts
2. Run profit analysis
3. Verify discount impact on profit calculations
4. Check that discounts reduce profitability correctly
Test Case 4: Combined Bill Type Analysis
1. Create regular sales, returns, and combined bills
2. Use same products across different bill types
3. Run comprehensive profit analysis
4. Verify returns reduce profits appropriately
5. Check combined bill profit calculations
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข sellbillController.md - Sales operations
- โข returnsellbillController.md - Return bill management
- โข storeController.md - Store management
- โข Database Schema Documentation - Table relationships
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When major changes occur