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:

Primary Functions

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

---

๐Ÿ—„๏ธ Database Tables

Revenue Tables

Table NamePurposeKey Columns
**sellbill**Sales transactionssellbillid, sellbillaftertotalbill, sellbilldiscount, sellbilldiscounttype
**sellbillandrutern**Combined sell/return billssellbillid, sellbillprice, returnsellbillprice
**bills**Optical salesbillid, netbillvalue, billdate
**billsproducts**Optical product detailsproductid, productno, productprice, buyprice
### Cost & Expense Tables

Table NamePurposeKey Columns
**sellbilldetail**Sales COGS datasellbilldetailproductid, buyprice, lastbuyprice, meanbuyprice, quantity
**expenses**Business expensesexpensesid, expensesvalue, expensesdate
**salaryreport**Employee salariessalaryreportnet, salarymonthdate, conditions
**employeepersonnel**Personnel transactionsemployeepersonnelvalue, employeepersonneltype, employeepersonneldate
### Adjustment Tables

Table NamePurposeKey Columns
**clientdebtchange**Client debt adjustmentsclientdebtchangeamount, clientdebtchangetype, clientdebtchangedate, discountearlyRepayment
**supplierdebtchange**Supplier debt adjustmentssupplierdebtchangeamount, supplierdebtchangetype, supplierdebtchangedate
**restaurantrawdestruction**Raw material lossesproductid, quantity, productBuyPrice, sysdate
### Return Tables

Table NamePurposeKey Columns
**returnsellbill**Sales returnsreturnsellbillid, returnsellbillaftertotalbill
**billsreturn**Optical returnsbillsreturnid, returnedprice
**billsreturnproducts**Optical return detailsproductid, productno, productprice
### Configuration Tables

Table NamePurposeKey Columns
**programsettings**System settingsreportsplusHours, vatvalue, profitevaluation
**lastbillidspricesupdated**Price update trackingbuybill, 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

---

๐Ÿ“š Related Documentation

---

Documented By: AI Assistant

Review Status: โœ… Complete

Next Review: When major changes occur