Profitreport Documentation
Profit Report Controller Documentation
File: /controllers/profitreportController.php
Purpose: Comprehensive business profit analysis and financial reporting system
Last Updated: December 20, 2024
Total Functions: 17
Lines of Code: 1,152
---
๐ Overview
The Profit Report Controller is the most comprehensive financial analysis tool in the ERP system, providing complete business profitability analysis with:
- โข Complete revenue and cost analysis
- โข Multi-source transaction integration (sales, returns, combined bills, optical)
- โข Advanced expense tracking and salary calculations
- โข Client and supplier debt adjustments
- โข Restaurant raw material destruction costs
- โข VAT calculations and tax handling
- โข Multiple buy price evaluation methods with discount and tax options
- โข Comprehensive profit margin analysis
- โข Income statement generation
Primary Functions
- โ Generate comprehensive profit/loss statements
- โ Calculate total business revenue from all sources
- โ Process all cost components including COGS, expenses, salaries
- โ Handle client/supplier debt adjustments
- โ Track restaurant raw material destruction costs
- โ Apply VAT calculations throughout
- โ Support 8 different buy price evaluation methods
- โ Generate income statement-style reports
- โ Provide net profit calculations
- โ Handle optical products integration
- โ Process early repayment discounts
Business Components Analyzed
1. Revenue Sources: Sales, optical sales, additional income
2. Cost Components: COGS, expenses, salaries, raw material destruction
3. Adjustments: Client debt changes, supplier debt changes, early repayment discounts
4. Tax Handling: VAT calculations, tax-inclusive pricing methods
Related Controllers
- โข profitdetailController.php - Detailed profit breakdowns
- โข profitproductController.php - Product-level analysis
- โข profitproductcatController.php - Category analysis
---
๐๏ธ Database Tables
Revenue Tables
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **sellbill** | Sales transactions | sellbillid, sellbillaftertotalbill, sellbilldiscount, sellbilldiscounttype | |
| **sellbillandrutern** | Combined sell/return bills | sellbillid, sellbillprice, returnsellbillprice | |
| **bills** | Optical sales | billid, netbillvalue, billdate | |
| **billsproducts** | Optical product details | productid, productno, productprice, buyprice |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **sellbilldetail** | Sales COGS data | sellbilldetailproductid, buyprice, lastbuyprice, meanbuyprice, quantity | |
| **expenses** | Business expenses | expensesid, expensesvalue, expensesdate | |
| **salaryreport** | Employee salaries | salaryreportnet, salarymonthdate, conditions | |
| **employeepersonnel** | Personnel transactions | employeepersonnelvalue, employeepersonneltype, employeepersonneldate |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **clientdebtchange** | Client debt adjustments | clientdebtchangeamount, clientdebtchangetype, clientdebtchangedate, discountearlyRepayment | |
| **supplierdebtchange** | Supplier debt adjustments | supplierdebtchangeamount, supplierdebtchangetype, supplierdebtchangedate | |
| **restaurantrawdestruction** | Raw material losses | productid, quantity, productBuyPrice, sysdate |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **returnsellbill** | Sales returns | returnsellbillid, returnsellbillaftertotalbill | |
| **billsreturn** | Optical returns | billsreturnid, returnedprice | |
| **billsreturnproducts** | Optical return details | productid, productno, productprice |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **programsettings** | System settings | reportsplusHours, vatvalue, profitevaluation | |
| **lastbillidspricesupdated** | Price update tracking | buybill, sell, retsell, buyquantity |
๐ Key Functions
1. show() / Default Action - Comprehensive Profit Report
Location: Line 324
Purpose: Generate complete business profit and loss statement
Function Signature:
// Triggered when: do=show or empty $do
$startDate = $_REQUEST['from'];
$endDate = $_REQUEST['to'];
$buyPriceType = $_POST["buyPriceType"];
Complete Business Analysis Process:
1. Revenue Calculation:
- Regular sales (getTotalSellbillByDate)
- Combined bills (getTotalAditionalSellbillByDate)
- Optical sales (getTotalSellOpticByDate)
- Additional income (getTotalIncomesByDate)
2. Cost Calculation:
- Cost of goods sold (getTotalQuantityBuyPriceByDate + getTotalAditionalQuantityBuyPriceByDate)
- Optical COGS (get_total_sellcost)
- Business expenses (getTotalExpensesByDate)
- Salaries (gettotalsalary)
- Raw material destruction (getRestaurantRawDestruction)
3. Debt Adjustments:
- Client debt changes (positive/negative)
- Supplier debt changes (positive/negative)
- Early repayment discounts
4. Final Profit Calculation:
$total_profit = $totalSellCost - $totalBuyCost - $restaurantRawDestruction;
$profitFinal = $total_profit - ($totalExpenses + $cdeficitCttotalExpenses +
$sdeficitCttotalExpenses + $totalsalary - $totalIncomes -
$cdeficitCttotalIncomes - $sdeficitCttotalIncomes);
```
---
### 2. **getTotalSellbillByDate()** - Regular Sales Revenue
**Location**: Line 631
**Purpose**: Calculate total revenue from regular sales bills
**Function Signature**:
php
function getTotalSellbillByDate($startDate, $endDate)
**Implementation**:
php
$totalSellbill = $mySellbillEx->queryWithDateAndConditionsExt($startDate, $endDate);
return $totalSellbill;
---
### 3. **getTotalQuantityBuyPriceByDate()** - Cost of Goods Sold
**Location**: Line 692
**Purpose**: Calculate total cost of goods sold with advanced buy price evaluation
**Function Signature**:
php
function getTotalQuantityBuyPriceByDate($startDate, $endDate)
**Advanced Buy Price Selection**:
php
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) $sellbilldetail->generalPrice;
break;
case "tax":
$buyPrice = (float) $sellbilldetail->lastbuyprice_withTax;
break;
case "mean_tax":
$buyPrice = (float) $sellbilldetail->meanbuyprice_withTax;
break;
}
**VAT Application**:
php
$vatValue = 1 + ($Programsetting->vatValue / 100);
return $totalQuantityBuyPrice * $vatValue;
**Discount Processing**:
php
$productBuyPrice = $buyPrice;
if ($buyDiscount > 0 && $buyDiscountType == 0) {
$productBuyPrice = $buyPrice - $buyDiscount; // Fixed amount
} elseif ($buyDiscount > 0 && $buyDiscountType == 1) {
$productBuyPrice = $buyPrice - (($buyDiscount / 100) * $buyPrice); // Percentage
}
---
### 4. **gettotalsalary()** - Complete Salary Calculations
**Location**: Line 1017
**Purpose**: Calculate total salary costs including bonuses, withdrawals, and loans
**Function Signature**:
php
function gettotalsalary($startDate, $endDate)
**Salary Components**:
php
// Monthly salaries (end-of-month calculation)
$fdate = date("Y-m-d", strtotime($_REQUEST['from']));
$tdate = date("Y-m-d", strtotime($_REQUEST['to']));
$lastDayOfMonth = date("Y-m-t", strtotime(date($fdate)));
$lastDayOfMonthTo = date("Y-m-t", strtotime(date($tdate)));
if ($fdate == $lastDayOfMonth || $tdate == $lastDayOfMonthTo) {
$allsalary = R::getAll('SELECT * FROM salaryreport WHERE conditions=0 AND
(salarymonthdate = "' . date_format(date_create($startDate),"Y-m") . '" OR
salarymonthdate = "' . date_format(date_create($endDate),"Y-m") . '")');
foreach ($allsalary as $myallsalary) {
$sumsalary += $myallsalary['salaryreportnet'];
}
}
// Personnel transactions
foreach ($allpersonaldata as $myallpersonaldata) {
if ($myallpersonaldata->employeepersonneltype == 4) {
$Borrow += $myallpersonaldata->employeepersonnelvalue; // Employee loans
} elseif ($myallpersonaldata->employeepersonneltype == 3) {
$Withdrawal += $myallpersonaldata->employeepersonnelvalue; // Withdrawals
} elseif ($myallpersonaldata->employeepersonneltype == 6) {
$Repayment += $myallpersonaldata->employeepersonnelvalue; // Loan repayments
}
}
$allfinal = ($sumsalary + $Withdrawal + $Borrow) - $Repayment;
---
### 5. **Client & Supplier Debt Adjustments** - Comprehensive Debt Processing
**Location**: Lines 411-451
**Purpose**: Process client and supplier debt adjustments affecting profit
**Client Debt Processing**:
php
$cdqueryString = ' AND DATE(clientdebtchange.clientdebtchangedate) >= "' . $startDate .
'" AND DATE(clientdebtchange.clientdebtchangedate) <= "' . $endDate . '"';
$clientDeficitCs = $clientDeptChangeExt->queryWithQueryString($cdqueryString, "clientDeficitController.php");
$cdeficitCDiscount = 0;
$cdeficitCadd = 0;
foreach ($clientDeficitCs as $clientDeficitC) {
if ($clientDeficitC->clientdebtchangetype == 0) {
$cdeficitCadd += $clientDeficitC->clientdebtchangeamount; // Debt increase
} else {
$cdeficitCDiscount += $clientDeficitC->clientdebtchangeamount; // Debt decrease
}
}
$cdeficitCtotals = $cdeficitCadd - $cdeficitCDiscount;
**Supplier Debt Processing**:
php
$supplierDeficitCs = $supplierDeptChangeExt->queryWithDateAndTableName($startDate, $endDate, "supplierDeficitController.php");
foreach ($supplierDeficitCs as $supplierDeficitC) {
if ($supplierDeficitC->supplierdebtchangetype == 0) {
$sdeficitCadd += $supplierDeficitC->supplierdebtchangeamount;
} else {
$sdeficitCDiscount += $supplierDeficitC->supplierdebtchangeamount;
}
}
---
### 6. **getRestaurantRawDestruction()** - Raw Material Loss Calculation
**Location**: Line 1110
**Purpose**: Calculate cost of destroyed/wasted raw materials for restaurants
**Function Signature**:
php
function getRestaurantRawDestruction($startDate, $endDate, $buyPriceType)
**Cost Calculation by Price Type**:
php
foreach ($restaurantRawDestruction as $value) {
switch ($buyPriceType) {
case 'first':
$rawDestructionCost += $value->productBuyPrice * $value->quantity;
break;
case 'last':
$rawDestructionCost += $value->lastbuyprice * $value->quantity;
break;
case "last_discount":
$rawDestructionCost += $value->lastbuyprice_withDiscount * $value->quantity;
break;
case "mean_discount":
$rawDestructionCost += $value->meanbuyprice_withDiscount * $value->quantity;
break;
case "tax":
$rawDestructionCost += $value->lastbuyprice_withTax * $value->quantity;
break;
case "mean_tax":
$rawDestructionCost += $value->meanbuyprice_withTax * $value->quantity;
break;
default:
$rawDestructionCost += $value->meanbuyprice * $value->quantity;
break;
}
}
---
### 7. **get_total_sellcost()** - Optical Products COGS
**Location**: Line 1092
**Purpose**: Calculate cost of goods sold for optical products
**Integration with Main Cost Calculation**:
php
// Regular COGS
$totalQuantityBuyPrice += getTotalQuantityBuyPriceByDate($startDate, $endDate);
// Optical COGS
$bills_sellcost = get_total_sellcost($startDate, $endDate);
$total_sellcost = 0;
foreach ($bills_sellcost as $value) {
$productid = $value->productid;
$product_data = $myProductRecord->load($productid);
// Apply same buy price logic as regular products
switch ($buyPriceType) {
case "first": $pro_price = (float) $value->buyprice; break;
case "last": $pro_price = (float) $product_data->lastbuyprice; break;
// ... other cases
}
$total_sellcost += ($value->productno * $pro_price);
}
$totalQuantityBuyPrice += $total_sellcost;
---
## ๐ Workflows
### Workflow 1: Complete Profit Analysis
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ START: Enter Date Range โ
โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 1. Initialize System Settings โ
โ - Load program settings โ
โ - Set VAT values โ
โ - Determine buy price evaluation method โ
โ - Apply time zone adjustments โ
โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 2. Calculate Total Revenue โ
โ โโโ Regular sales (getTotalSellbillByDate) โ
โ โโโ Combined bills (getTotalAditionalSellbillByDate) โ
โ โโโ Optical sales (getTotalSellOpticByDate) โ
โ โโโ Additional income (getTotalIncomesByDate) โ
โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 3. Calculate Total Returns โ
โ โโโ Regular returns (getTotalReturnSellbillByDate) โ
โ โโโ Combined returns (getTotalAditionalReturnSellbill) โ
โ โโโ Optical returns (getTotalReturnSellOpticByDate) โ
โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 4. Calculate Cost of Goods Sold โ
โ โโโ Regular COGS (getTotalQuantityBuyPriceByDate) โ
โ โโโ Combined COGS (getTotalAditionalQuantityBuyPrice) โ
โ โโโ Optical COGS (get_total_sellcost) โ
โ โโโ Return COGS (getTotalQuantityReturnBuyPrice...) โ
โ โโโ Apply VAT calculations โ
โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 5. Calculate Operating Expenses โ
โ โโโ Business expenses (getTotalExpensesByDate) โ
โ โโโ Salaries & payroll (gettotalsalary) โ
โ โโโ Raw material destruction (getRestaurantRaw...) โ
โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 6. Process Debt Adjustments โ
โ โโโ Client debt changes โ
โ โ โโ Debt increases (expenses) โ
โ โ โโ Debt decreases (income) โ
โ โ โโ Early repayment discounts โ
โ โ โ
โ โโโ Supplier debt changes โ
โ โโ Debt increases (income) โ
โ โโ Debt decreases (expenses) โ
โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 7. Calculate Final Profit โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Net Sales = Total Sales - Total Returns โ โ
โ โ Net COGS = Total COGS - Return COGS โ โ
โ โ Gross Profit = Net Sales - Net COGS โ โ
โ โ Net Profit = Gross Profit - Expenses โ โ
โ โ - Raw Destruction โ โ
โ โ - Salaries โ โ
โ โ + Income โ โ
โ โ + Debt Adjustments โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 8. Display Comprehensive Report โ
โ - Show all revenue components โ
โ - Show all cost components โ
โ - Show all adjustments โ
โ - Display final profit/loss โ
โ - Include gross profit margins โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
---
## ๐ URL Routes & Actions
| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) or `do=show` | Default action | Comprehensive profit report |
| `do=success` | Success page | Display success message |
| `do=error` | Error page | Display error message |
### Required Parameters
**Profit Report** (`do=show`):
- `from` - Start date (YYYY-MM-DD)
- `to` - End date (YYYY-MM-DD)
- `buyPriceType` - Price evaluation method (POST) - Optional, uses system default
### Optional Parameters
- None required, system uses defaults for missing values
---
## ๐งฎ Calculation Methods
### Complete Profit Formula
php
// Gross Sales Calculation
$totalSellPrice = getTotalSellbillByDate($startDate, $endDate) +
getTotalAditionalSellbillByDate($startDate, $endDate) +
$opticSell;
// Net Sales Calculation
$totalSellCost = ($totalSellPrice - $totalReturnSellPrice);
// Cost of Goods Sold
$totalBuyCost = $totalQuantityBuyPrice - $totalQuantityReturnBuyPrice;
// Gross Profit
$total_profit = $totalSellCost - $totalBuyCost - $restaurantRawDestruction;
// Net Profit (Final)
$profitFinal = $total_profit - ($totalExpenses + $cdeficitCttotalExpenses +
$sdeficitCttotalExpenses + $totalsalary - $totalIncomes -
$cdeficitCttotalIncomes - $sdeficitCttotalIncomes);
### Buy Price Evaluation with Tax Integration
php
switch ($buyPriceType) {
case "tax":
$buyPrice = (float) $sellbilldetail->lastbuyprice_withTax;
break;
case "mean_tax":
$buyPrice = (float) $sellbilldetail->meanbuyprice_withTax;
break;
case "last_discount":
$buyPrice = (float) $sellbilldetail->lastbuyprice_withDiscount;
break;
case "mean_discount":
$buyPrice = (float) $sellbilldetail->meanbuyprice_withDiscount;
break;
}
// Apply VAT to final cost calculation
$vatValue = 1 + ($Programsetting->vatValue / 100);
return $totalQuantityBuyPrice * $vatValue;
### Debt Adjustment Impact
php
// Client debt adjustments
if ($cdeficitCtotals > 0) {
$cdeficitCttotalExpenses = $cdeficitCtotals; // Add to expenses
} else {
$cdeficitCttotalIncomes = abs($cdeficitCtotals); // Add to income
}
// Supplier debt adjustments
if ($sdeficitCtotals > 0) {
$sdeficitCttotalIncomes = $sdeficitCtotals; // Add to income
} else {
$sdeficitCttotalExpenses = abs($sdeficitCtotals); // Add to expenses
}
---
## ๐ Security & Permissions
### Authentication
- Includes authentication.php for session validation
- Access to comprehensive financial data requires authentication
### Input Validation
- Date parameter validation and sanitization
- Buy price type validation against allowed values
- Protection against SQL injection through DAO layer
### Financial Data Access
- No specific role-based permissions implemented
- All authenticated users can access complete financial data
- Consider implementing role-based access for sensitive profit data
---
## ๐ Performance Considerations
### Database Optimization
1. **Critical Indexes Required**:
```sql
-- Sales data
CREATE INDEX idx_sellbill_date_conditions ON sellbill(sellbilldate, conditions);
CREATE INDEX idx_sellbilldetail_date ON sellbilldetail(sellbilldetaildate);
-- Expenses and income
CREATE INDEX idx_expenses_date ON expenses(expensesdate);
CREATE INDEX idx_income_date ON income(incomedate);
-- Debt changes
CREATE INDEX idx_clientdebt_date ON clientdebtchange(clientdebtchangedate);
CREATE INDEX idx_supplierdebt_date ON supplierdebtchange(supplierdebtchangedate);
-- Salary and personnel
CREATE INDEX idx_salary_month ON salaryreport(salarymonthdate, conditions);
CREATE INDEX idx_personnel_date ON employeepersonnel(employeepersonneldate);
```
2. **Query Performance Issues**:
- Multiple separate queries for each component
- Large date ranges may cause timeouts
- No result caching implemented
- JOIN optimization opportunities exist
### Memory Usage
- Loads all transaction data into memory
- Large businesses may encounter memory limits
- Consider implementing pagination or streaming for large datasets
### Optimization Opportunities
sql
-- Current: Multiple separate queries
-- Optimized: Single comprehensive query possible for main components
SELECT
SUM(CASE WHEN table_type = 'sell' THEN amount ELSE 0 END) as total_sales,
SUM(CASE WHEN table_type = 'return' THEN amount ELSE 0 END) as total_returns,
SUM(CASE WHEN table_type = 'expense' THEN amount ELSE 0 END) as total_expenses
FROM (
SELECT 'sell' as table_type, sellbillaftertotalbill as amount FROM sellbill WHERE ...
UNION ALL
SELECT 'return' as table_type, returnsellbillaftertotalbill as amount FROM returnsellbill WHERE ...
UNION ALL
SELECT 'expense' as table_type, expensesvalue as amount FROM expenses WHERE ...
) combined_data;
---
## ๐ Common Issues & Troubleshooting
### 1. **Incorrect Final Profit Calculations**
**Issue**: Net profit doesn't match expected business results
**Common Causes**:
- Wrong buy price evaluation method selected
- VAT calculations applied incorrectly
- Debt adjustments processed wrong
- Missing transaction data from certain periods
**Debug Steps**:
php
// Add comprehensive debugging
echo "Buy Price Type: " . $buyPriceType . "\n";
echo "VAT Value: " . $vatValue . "\n";
echo "Total Sales: " . $totalSellPrice . "\n";
echo "Total Returns: " . $totalReturnSellPrice . "\n";
echo "Total COGS: " . $totalQuantityBuyPrice . "\n";
echo "Total Expenses: " . $totalExpenses . "\n";
echo "Total Salaries: " . $totalsalary . "\n";
echo "Client Debt Adjustments: " . $cdeficitCtotals . "\n";
echo "Supplier Debt Adjustments: " . $sdeficitCtotals . "\n";
### 2. **Missing Optical Products Data**
**Issue**: Optical product transactions not included in totals
**Cause**: Bills/billsproducts tables not properly integrated
**Solution**: Verify optical product data exists and dates match query range
### 3. **Salary Calculation Issues**
**Issue**: Salaries not calculating for certain periods
**Cause**: End-of-month logic restricting salary inclusion
**Fix**: Review month-end logic in gettotalsalary() function
### 4. **Large Dataset Performance**
**Issue**: Reports timing out for large date ranges
**Solutions**:
- Add database indexes
- Implement result caching
- Add pagination for large reports
- Consider report generation queue for complex calculations
---
## ๐งช Testing Scenarios
### Test Case 1: Complete Business Cycle
1. Create sales, returns, expenses, salaries for test period
2. Add client/supplier debt adjustments
3. Include optical product transactions
4. Run comprehensive profit report
5. Verify all components included correctly
6. Cross-check with manual calculation
### Test Case 2: Buy Price Method Validation
1. Create products with different price histories
2. Create sales using various buy price methods
3. Run reports with each buy price evaluation type
4. Verify different methods produce expected results
5. Check tax-inclusive vs tax-exclusive calculations
### Test Case 3: Month-End Salary Processing
1. Create salary records for test months
2. Create personnel transactions (loans, withdrawals, repayments)
3. Run reports on month-end vs mid-month dates
4. Verify salary calculation logic working correctly
5. Test multiple month date ranges
### Test Case 4: Debt Adjustment Impact
1. Create client debt increases and decreases
2. Create supplier debt changes
3. Add early repayment discounts
4. Run profit report and verify adjustments affect final profit correctly
5. Test edge cases with large debt adjustments
```
---
๐ Business Logic Summary
Income Statement Generation
The controller essentially generates a complete income statement:
1. Revenue:
- Sales Revenue
- Other Income
- Debt Adjustment Income
2. Cost of Goods Sold:
- Product costs (with selected pricing method)
- VAT adjustments
- Raw material destruction
3. Operating Expenses:
- General business expenses
- Salaries and payroll costs
- Debt adjustment expenses
4. Net Profit:
- Gross Profit - Operating Expenses
Key Business Rules
- โข VAT applied consistently across all cost calculations
- โข Buy price methods allow different costing scenarios
- โข Debt adjustments can be income or expense depending on type
- โข Salary calculations only include month-end periods
- โข Raw material destruction affects restaurants specifically
- โข Early repayment discounts reduce final profit
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข profitdetailController.md - Detailed profit breakdowns
- โข profitproductController.md - Product-level analysis
- โข sellbillController.php - Sales operations
- โข buyBillController.php - Purchase operations
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When major changes occur