ProfitandlossCTRL Documentation
Profit and Loss Controller Documentation
File: /controllers/profitandlossCTRL.php
Purpose: Comprehensive profit and loss statement generation (Legacy System)
Last Updated: December 20, 2024
Total Functions: 1 main flow with 3 operational modes
Lines of Code: ~182
---
๐ Overview
The Profit and Loss Controller is a legacy system component that generates comprehensive profit and loss statements by analyzing sales, purchases, returns, and expenses across specified date ranges. IMPORTANT: This is a legacy controller using old PHP practices and database connectivity. It should be considered for modernization.
Key Characteristics
- โข Legacy Code: Uses old PHP practices and mysql_* functions
- โข Password Protected: Requires hardcoded password for access
- โข Direct SQL Queries: No ORM/DAO layer usage
- โข Comprehensive Analysis: Covers all major financial aspects
- โข Date Range Reporting: Flexible period analysis
Primary Functions
- โ Profit and loss statement generation
- โ Sales revenue analysis
- โ Purchase cost calculation
- โ Return transaction processing
- โ Expense tracking integration
- โ Inventory valuation
- โ Cost of goods sold calculation
Related Controllers
- โข sellbillController.php - Sales transactions
- โข buyBillController.php - Purchase transactions
- โข returnsellbillController.php - Sales returns
- โข expensesController.php - Expense management
---
๐๏ธ Database Tables (Legacy Schema)
Primary Sales Tables
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **sell_bill_tbl** | Sales transactions | ID, sell_billDate, sell_billAfterTotalBill, sell_billSysDate | |
| **back_sell_bill_tbl** | Sales returns | ID, back_sell_billAfterTotalBill, back_sell_billSysDate | |
| **sell_bill_details_tbl** | Sales line items | sell_billProductId, sell_billQuantity, buyprice, sell_billDate | |
| **back_sell_bill_details_tbl** | Return line items | back_sell_billProductId, back_sell_billQuantity, buyprice |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **buy_bill_tbl** | Purchase transactions | ID, buy_billAfterTotalBill, buy_billSysDate | |
| **back_buy_bill_tbl** | Purchase returns | ID, back_buy_billAfterTotalBill, back_buy_billSysDate |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **product_tbl** | Product master | ID, buyprice, productTypeDeleted | |
| **store_details_tbl** | Inventory quantities | store_detailsProductId, store_detailsQty, store_detailsStoreId | |
| **cat_tbl** | Product categories | ID (category information) |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **expenses_tbl** | Expense records | value, date, type_deleted | |
| **product_setting_tbl** | System settings | ID, product_settingValue |
๐ Key Functions
1. Password Protection Gate - Security Access Control
Location: Line 30
Purpose: Protect sensitive financial reports with hardcoded password
Implementation:
if (!isset($_GET['do'])) {
if ($_POST['pass'] != "1597530") {
$smarty->display('../templates/1/profitandlossCTRL/pass.html');
}
if ($_POST['pass'] == "1597530") {
// Display date selection form
$smarty->display('../templates/1/profitandlossCTRL/ser.html');
}
}
Security Note: Hardcoded password is a security risk and should be modernized.
---
2. Comprehensive P&L Calculation - Main Financial Analysis
Location: Line 40
Purpose: Calculate complete profit and loss statement for specified date range
Function Signature:
// Triggered when: $_GET['do'] == "result"
$firstDate = $_POST['startDate'];
$secondDate = $_POST['endDate'];
Process Flow:
A. Sales Revenue Analysis
$sqlallse1ls = mysql_query("SELECT * FROM sell_bill_tbl
WHERE sell_bill_tbl.sell_billSysDate >= CAST('$firstDate' AS DATETIME)
AND sell_bill_tbl.sell_billSysDate <= CAST('$secondDate' AS DATETIME)");
$totalsellbill = 0;
while ($row = mysql_fetch_array($sqlallse1ls)) {
$totalsellbill += $row['sell_billAfterTotalBill'];
}
B. Sales Returns Analysis
$sqlallbackse1ls = mysql_query("SELECT * FROM back_sell_bill_tbl
WHERE back_sell_bill_tbl.back_sell_billSysDate >= CAST('$firstDate' AS DATETIME)
AND back_sell_bill_tbl.back_sell_billSysDate <= CAST('$secondDate' AS DATETIME)");
$totalbacksellbill = 0;
while ($row = mysql_fetch_array($sqlallbackse1ls)) {
$totalbacksellbill += $row['back_sell_billAfterTotalBill'];
}
C. Purchase Cost Analysis
$sqlallbackse1ls = mysql_query("SELECT * FROM buy_bill_tbl
WHERE buy_bill_tbl.buy_billSysDate >= CAST('$firstDate' AS DATETIME)
AND buy_bill_tbl.buy_billSysDate <= CAST('$secondDate' AS DATETIME)");
$totalbuybill = 0;
while ($row = mysql_fetch_array($sqlallbackse1ls)) {
$totalbuybill += $row['buy_billAfterTotalBill'];
}
D. Purchase Returns Analysis
$totalbuybackbill = 0;
$sqlallbackse1ls = mysql_query("SELECT * FROM back_buy_bill_tbl
WHERE back_buy_bill_tbl.back_buy_billSysDate >= CAST('$firstDate' AS DATETIME)
AND back_buy_bill_tbl.back_buy_billSysDate <= CAST('$secondDate' AS DATETIME)");
E. Cost of Goods Sold Calculation
$totalquantitbuyprice = 0;
$totalquantitbuybackprice = 0;
$sqlproduct = mysql_query("SELECT product_tbl.ID, product_tbl.buyprice FROM product_tbl");
while ($row = mysql_fetch_array($sqlproduct)) {
$productid = $row['ID'];
$buyprice = $row['buyprice'];
// Calculate cost of sales for this product
$sellbillq = mysql_query("SELECT * FROM sell_bill_details_tbl
WHERE sell_billProductId='$productid'
AND sell_billDate >= CAST('$firstDate' AS DATETIME)
AND sell_billDate <= CAST('$secondDate' AS DATETIME)");
while ($rows = mysql_fetch_array($sellbillq)) {
$totalquantitbuyprice += $rows['sell_billQuantity'] * $rows['buyprice'];
}
}
F. Expense Analysis
$expensesQuery = mysql_query("SELECT SUM(expenses_tbl.value) as value
FROM expenses_tbl
WHERE expenses_tbl.type_deleted = 0
AND expenses_tbl.date >= CAST('$firstDate' AS DATETIME)
AND expenses_tbl.date <= CAST('$secondDate' AS DATETIME)");
while ($row = mysql_fetch_array($expensesQuery)) {
$totalExpenses = $row['value'];
}
G. Inventory Valuation
$store_id = 1;
$xx = "SELECT * FROM product_tbl
JOIN store_details_tbl ON product_tbl.id = store_details_tbl.store_detailsProductId
JOIN cat_tbl ON cat_tbl.ID = product_tbl.productCatId
WHERE store_detailsStoreId = '$store_id'
AND product_tbl.productTypeDeleted = 0
GROUP BY store_detailsProductId";
$totalmoney = 0;
while ($row = mysql_fetch_array($result)) {
$totalmoney += $row['store_detailsQty'] * $row['buyprice'];
}
---
๐ Workflows
Workflow 1: P&L Report Generation Process
---
๐ URL Routes & Actions
| URL Parameter | Function Called | Description | |
|---|---|---|---|
| `do=` (not set) | Password gate | Password protection and date selection | |
| `do=result` | P&L calculation | Generate profit and loss statement | |
| `do=sucess` | Success page | Operation success display | |
| `do=error` | Error page | Operation error display |
Password Gate (no do parameter):
- โข
pass(POST) - Password for access ("1597530")
P&L Generation (do=result):
- โข
startDate(POST) - Report start date - โข
endDate(POST) - Report end date
---
๐งฎ Calculation Methods
Net Sales Revenue
$netSales = $totalsellbill - $totalbacksellbill;
// Gross sales minus returns
Net Purchase Cost
$netPurchases = $totalbuybill - $totalbuybackbill;
// Gross purchases minus purchase returns
Cost of Goods Sold
// For each product sold in period:
$cogs += $soldQuantity * $productBuyPrice;
$netCOGS = $totalquantitbuyprice - $totalquantitbuybackprice;
// COGS for sales minus COGS for returns
Gross Profit Calculation
$grossProfit = $netSales - $netCOGS;
// Revenue minus direct product costs
Net Profit Calculation
$netProfit = $grossProfit - $totalExpenses;
// Gross profit minus operating expenses
Inventory Valuation
// Current inventory value
$inventoryValue = $quantity * $buyPrice;
// For all products in store
---
๐ Security & Permissions
Critical Security Issues
1. Hardcoded Password: Password "1597530" is embedded in code
2. SQL Injection Vulnerability: Direct variable insertion in queries
3. Deprecated Functions: Uses mysql_* functions (removed in PHP 7.0+)
4. No Modern Authentication: No role-based access control
Legacy Security Model
// CRITICAL: This is insecure
if ($_POST['pass'] != "1597530") {
// Reject access
}
// CRITICAL: SQL injection vulnerability
$firstDate = $_POST['startDate'];
WHERE sell_billSysDate >= CAST('$firstDate' AS DATETIME)
Recommended Security Modernization
// Modern approach needed:
// 1. Role-based authentication
// 2. Prepared statements
// 3. Input validation
// 4. Secure session management
---
๐ Performance Considerations
Critical Performance Issues
1. No Indexes Specified: Legacy queries may lack proper indexing
2. Multiple Product Loops: N+1 query pattern for COGS calculation
3. Large Date Ranges: No pagination for large periods
4. No Query Optimization: Direct SQL without optimization
Performance Bottlenecks
// PERFORMANCE ISSUE: N+1 queries
$sqlproduct = mysql_query("SELECT * FROM product_tbl");
while ($row = mysql_fetch_array($sqlproduct)) {
// Individual query for each product
$sellbillq = mysql_query("SELECT * FROM sell_bill_details_tbl WHERE sell_billProductId='$productid'");
}
Modernization Recommendations
1. Use Modern Database Layer: Replace mysql_* with PDO/MySQLi
2. Implement Proper Indexing: Add composite indexes for date/product queries
3. Optimize COGS Calculation: Use single aggregated query
4. Add Result Caching: Cache expensive calculations
5. Implement Pagination: For large date ranges
---
๐ Common Issues & Troubleshooting
1. PHP 7.0+ Compatibility Issues
Issue: mysql_* functions not available
Cause: Legacy code using deprecated functions
Error:
Fatal error: Uncaught Error: Call to undefined function mysql_query()
Solution: Complete modernization required using MySQLi or PDO
2. SQL Injection Vulnerabilities
Issue: Direct variable insertion in SQL
Cause: No prepared statements or input sanitization
Risk: Malicious date input could compromise database
3. Incorrect Financial Calculations
Issue: P&L figures don't match expected values
Cause: Date range issues or missing transaction types
Debug:
// Add logging to verify calculations
error_log("Sales total: " . $totalsellbill);
error_log("Returns total: " . $totalbacksellbill);
error_log("COGS total: " . $totalquantitbuyprice);
4. Performance Issues with Large Datasets
Issue: Report generation times out
Cause: Inefficient queries and lack of optimization
Symptoms: Long loading times, memory exhaustion
---
๐งช Testing Scenarios
โ ๏ธ WARNING: This controller cannot be tested on PHP 7.0+ without modernization.
Test Case 1: Password Protection (If PHP 5.6 available)
1. Access controller without password
2. Verify password form appears
3. Submit incorrect password
4. Submit correct password "1597530"
5. Verify date selection form appears
Test Case 2: Basic P&L Generation
1. Enter valid date range
2. Submit for processing
3. Verify all financial sections calculate
4. Check for reasonable values
5. Validate calculation accuracy
Test Case 3: Edge Case Testing
1. Test with very short date range (1 day)
2. Test with very long date range (1 year)
3. Test with date range having no transactions
4. Test with invalid date formats
5. Verify error handling
---
๐ง Modernization Requirements
Immediate Actions Required
1. Database Layer: Replace mysql_* with modern MySQLi/PDO
2. Security: Implement proper authentication system
3. SQL Injection: Use prepared statements
4. Input Validation: Sanitize all user inputs
Code Modernization Example
// CURRENT (INSECURE):
$query = "SELECT * FROM sell_bill_tbl WHERE sell_billSysDate >= '$firstDate'";
$result = mysql_query($query);
// MODERN (SECURE):
$stmt = $pdo->prepare("SELECT * FROM sell_bill_tbl WHERE sell_billSysDate >= ?");
$stmt->execute([$firstDate]);
$result = $stmt->fetchAll();
Performance Optimization
-- Add required indexes
CREATE INDEX idx_sell_bill_sysdate ON sell_bill_tbl(sell_billSysDate);
CREATE INDEX idx_sell_bill_details_date_product ON sell_bill_details_tbl(sell_billDate, sell_billProductId);
CREATE INDEX idx_expenses_date_deleted ON expenses_tbl(date, type_deleted);
-- Optimize COGS calculation with single query
SELECT
SUM(sbd.sell_billQuantity * sbd.buyprice) as total_cogs
FROM sell_bill_details_tbl sbd
WHERE sbd.sell_billDate BETWEEN ? AND ?;
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข sellbillController.md - Sales transaction system
- โข buyBillController.md - Purchase transaction system
- โข expensesController.md - Expense management
- โข Legacy Code Modernization Guide - Required for this controller
---
Documented By: AI Assistant
Review Status: โ ๏ธ LEGACY SYSTEM - REQUIRES MODERNIZATION
Security Status: ๐ด CRITICAL SECURITY ISSUES
PHP Compatibility: ๐ด PHP 5.6 ONLY
Next Review: IMMEDIATE - Complete rewrite recommended