Executorsreport Documentation
Executors Report Controller Documentation
File: /controllers/executorsreport.php
Purpose: Financial analysis and profitability reporting for sales bill execution assignments with comprehensive cost tracking
Last Updated: December 20, 2024
Total Functions: 4+
Lines of Code: ~164
---
๐ Overview
The Executors Report Controller provides advanced financial analysis for sales bill execution assignments, focusing on profitability analysis, cost tracking, and comprehensive financial reporting. It integrates sales bill data with execution costs and client payment tracking to provide detailed insights into the financial performance of executed sales orders.
Key Capabilities
- โข Comprehensive profitability analysis for executed sales bills
- โข Integration of sales amounts, client payments, and execution costs
- โข Multi-dimensional financial calculations (gross profit, net profit, collection efficiency)
- โข Date range filtering for period-based analysis
- โข Client and sales bill filtering for targeted reporting
- โข Ajax-powered DataTables integration for dynamic reporting
- โข Financial KPI calculation and display
Primary Functions
- โ Calculate gross profit (Sales Amount - Execution Costs)
- โ Track client payment collection against sales amounts
- โ Calculate net profit (Client Payments - Execution Costs)
- โ Provide comprehensive financial analysis for executions
- โ Support date range and entity filtering
- โ Ajax search for clients and sales bills
- โ DataTables integration for advanced reporting
Related Controllers
- โข executors.php - Execution assignment management
- โข sellbillController.php - Sales bill operations
- โข clientPayedDeptController.php - Payment tracking
- โข expensesController.php - Cost management
---
๐๏ธ Database Tables
Core Execution Tables
| Table Name | Purpose | Key Columns |
|---|---|---|
| **executors** | Execution assignments | id, executorsclientid, executorssellid, executorsuserids, executorsdate, del |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **sellbill** | Sales bill master data | sellbillid, sellbillclientid, sellbillaftertotalbill, sellbilldate, datestarting, conditions | |
| **expenses** | Execution-related costs | id, sellbillid, expensesValue, expensesdate, conditions | |
| **clientdebtchange** | Payment tracking | id, billid, clientdebtchangeamount, tablename, debtchangedate |
| Table Name | Purpose | Key Columns |
|---|---|---|
| **client** | Customer information | clientid, clientname, conditions |
๐ Key Functions
1. Default Display - Report Interface
Location: Line 8-12
Purpose: Display the main executors financial report interface
Implementation:
if (empty($do)) {
$smarty->display("header.html");
$smarty->display("executorsreport/show.html");
$smarty->display("footer.html");
}
Features:
- โข Clean report interface
- โข Filter controls for date range and entities
- โข Ajax-powered data loading
- โข Export capabilities
---
2. select2client() - Client Search for Filtering
Location: Line 21-37
Purpose: Provide Ajax-powered client search for report filtering
Function Signature:
function select2client()
// POST Parameter: searchTerm - Client name search
Implementation:
$name = $_POST['searchTerm'];
$productsData = R::getAll("SELECT clientid, clientname as name
FROM client
WHERE conditions = 0 and clientname LIKE '%" . $name . "%' limit 50");
foreach ($productsData as $pro) {
$row_array['id'] = $pro['clientid'];
$row_array['text'] = $pro['name'];
array_push($return_arr, $row_array);
}
echo json_encode($return_arr);
Features:
- โข Real-time client search
- โข Select2 dropdown integration
- โข Result limiting for performance
- โข Active client filtering
---
3. select2sellbill() - Sales Bill Search with Client Context
Location: Line 41-57
Purpose: Search sales bills for specific clients with execution context
Function Signature:
function select2sellbill()
// POST Parameters: searchTerm, clientid
Implementation:
$name = $_POST['searchTerm'];
$clientid = $_POST['clientid'];
$productsData = R::getAll("SELECT sellbillid, CONCAT(sellbillid,'/',datestarting) as texts
FROM sellbill
WHERE conditions = 0 and CONCAT(sellbillid,'/',datestarting) LIKE '%" . $name . "%'
and sellbill.sellbillclientid = $clientid limit 50");
foreach ($productsData as $pro) {
$row_array['id'] = $pro['sellbillid'];
$row_array['text'] = $pro['texts'];
array_push($return_arr, $row_array);
}
Features:
- โข Client-filtered bill search
- โข Bill ID and date display
- โข Contextual bill selection
- โข Integration with execution assignments
---
4. showajax() - Comprehensive Financial Report
Location: Line 61-157
Purpose: Generate detailed financial analysis for execution assignments
Function Signature:
function showajax()
// POST Parameters: fromdate, todate, data1 (client), data2 (sellbill), DataTables parameters
Filter Building:
$searchQuery = " ";
if($data1 != ''){
$searchQuery .= " and executors.executorsclientid = ".$data1. " ";
}
if($data2 != ''){
$searchQuery .= " and executors.executorssellid = ".$data2. " ";
}
if($start_date != '' && $end_date != ''){
$searchQuery .='and sellbill.datestarting >= "' . $start_date . '" and sellbill.datestarting <= "' . $end_date . '" ';
}
Main Query:
$rResult = R::getAll('SELECT executors.* ,clientname, expensesValue, sellbillaftertotalbill, sellbilldate, datestarting
FROM `executors`
LEFT JOIN sellbill ON executors.executorssellid = sellbill.sellbillid
LEFT JOIN client ON executors.executorsclientid = client.clientid
LEFT JOIN expenses ON expenses.sellbillid = sellbill.sellbillid
WHERE 1 '.$searchQuery.' ');
Financial Calculations for Each Record:
foreach ($rResult as $row) {
// 1. Get client payments for this bill
$clientdebtchangeamount = R::getCell('SELECT sum(clientdebtchangeamount) as clientdebtchangeamount
FROM clientdebtchange
WHERE billid = '. $row["executorssellid"]. '
and tablename = "clientPayedDeptSellBillsController.php"');
// 2. Financial KPI calculations
$sub_array[] = $row["id"]; // Execution ID
$sub_array[] = $row["clientname"]; // Client Name
$sub_array[] = $row["executorssellid"]; // Sales Bill ID
$sub_array[] = $row["sellbilldate"]; // Bill Date
$sub_array[] = $row["sellbillaftertotalbill"]; // Sales Amount
$sub_array[] = $clientdebtchangeamount; // Client Payments
$sub_array[] = $row["expensesValue"]; // Execution Costs
$sub_array[] = $row["sellbillaftertotalbill"] - $clientdebtchangeamount; // Outstanding Amount
$sub_array[] = $row["sellbillaftertotalbill"] - $row["expensesValue"]; // Gross Profit
$sub_array[] = $clientdebtchangeamount - $row["expensesValue"]; // Net Profit
}
---
๐งฎ Financial Calculation Methods
1. Sales Amount
$salesAmount = $row["sellbillaftertotalbill"];
- โข Base sales bill amount after discounts and taxes
- โข Source: sellbill.sellbillaftertotalbill
2. Client Payments Collection
$clientdebtchangeamount = R::getCell('SELECT sum(clientdebtchangeamount) as clientdebtchangeamount
FROM clientdebtchange
WHERE billid = '. $row["executorssellid"]. '
and tablename = "clientPayedDeptSellBillsController.php"');
- โข Total payments received from client for this specific bill
- โข Tracks actual cash collection efficiency
3. Execution Costs
$executionCosts = $row["expensesValue"];
- โข Direct costs associated with executing this sales bill
- โข Source: expenses.expensesValue linked to sellbillid
4. Outstanding Amount (Collection Gap)
$outstandingAmount = $salesAmount - $clientPayments;
- โข Amount still owed by client
- โข Indicates collection efficiency and credit risk
5. Gross Profit (Sales Margin)
$grossProfit = $salesAmount - $executionCosts;
- โข Profit before considering collection issues
- โข Measures execution efficiency and cost control
6. Net Profit (Realized Profit)
$netProfit = $clientPayments - $executionCosts;
- โข Actual profit realized after accounting for collections
- โข Most accurate measure of execution profitability
---
๐ Workflows
Workflow 1: Financial Analysis Report Generation
---
Workflow 2: Profitability Analysis Process
---
๐ URL Routes & Actions
| URL Parameter | Function Called | Description | Ajax | |
|---|---|---|---|---|
| (empty) | Default display | Show financial report interface | No | |
| `do=select2client` | `select2client()` | Ajax client search for filtering | Yes | |
| `do=select2sellbill` | `select2sellbill()` | Ajax sales bill search | Yes | |
| `do=showajax` | `showajax()` | DataTables financial data provider | Yes |
Client Search (do=select2client):
- โข
searchTerm- Client name search string
Sales Bill Search (do=select2sellbill):
- โข
searchTerm- Bill search string - โข
clientid- Client filter for bill context
Financial Report (do=showajax):
- โข Standard DataTables parameters (draw, start, length, search, order)
- โข
fromdate- Analysis period start date - โข
todate- Analysis period end date - โข
data1- Client filter (clientid) - โข
data2- Sales bill filter (sellbillid)
---
๐ Financial KPIs and Metrics
Core Financial Metrics
1. Sales Amount: Base sales value after discounts
2. Client Payments: Actual cash collected from client
3. Execution Costs: Direct costs of order fulfillment
4. Outstanding Amount: Uncollected receivables
5. Gross Profit: Sales margin before collection issues
6. Net Profit: Realized profit after collections
Derived Analytics
// Collection Efficiency Rate
$collectionRate = ($clientPayments / $salesAmount) * 100;
// Cost Efficiency Rate
$costRate = ($executionCosts / $salesAmount) * 100;
// Profit Margin (Gross)
$grossMargin = (($salesAmount - $executionCosts) / $salesAmount) * 100;
// Profit Margin (Net)
$netMargin = (($clientPayments - $executionCosts) / $clientPayments) * 100;
// Return on Execution Investment
$roi = (($clientPayments - $executionCosts) / $executionCosts) * 100;
Business Intelligence Insights
- โข High Outstanding Amount: Collection issues or extended credit terms
- โข Low Gross Profit: High execution costs or pricing problems
- โข Negative Net Profit: Execution costs exceed collections (loss-making)
- โข High Collection Rate: Efficient credit management
- โข Low Cost Rate: Efficient execution processes
---
๐ Security & Permissions
Session Management
include("../public/impOpreation.php");
- โข Session-based access control
- โข User context for report generation
- โข Standard authentication integration
Input Validation
$searchTerm = $_POST['searchTerm'];
$clientid = $_POST['clientid'];
$start_date = $_POST['fromdate'];
$end_date = $_POST['todate'];
Security Features:
- โข RedBean ORM provides SQL injection protection
- โข Input parameter validation through framework
- โข Read-only operations (no data modification)
- โข Standard session security
---
๐ Common Issues & Troubleshooting
1. Missing Payment Data
Issue: NULL values in client payment calculations
Cause: No payment records in clientdebtchange table
Debug Query:
-- Check payment records for bills
SELECT cdc.billid, SUM(cdc.clientdebtchangeamount) as payments
FROM clientdebtchange cdc
WHERE cdc.tablename = 'clientPayedDeptSellBillsController.php'
AND cdc.billid IN (SELECT executorssellid FROM executors)
GROUP BY cdc.billid;
Fix: Handle NULL payments in calculation:
$clientdebtchangeamount = R::getCell('...') ?? 0;
2. Missing Expense Data
Issue: NULL values in execution costs
Cause: No expense records linked to sales bills
Solution: Default to zero costs:
$expensesValue = $row["expensesValue"] ?? 0;
3. Date Range Issues
Issue: No data returned for valid date ranges
Cause: Date format mismatch or timezone issues
Debug: Check date formats in sellbill.datestarting vs filter dates
4. Performance Issues
Issue: Slow loading with large datasets
Solutions:
- โข Add proper indexes on JOIN columns
- โข Implement result limiting
- โข Use date range filters effectively
---
๐ Performance Considerations
Database Optimization
1. Critical Indexes:
-- Execution queries
CREATE INDEX idx_executors_sellbill_del ON executors(executorssellid, del);
CREATE INDEX idx_executors_client_del ON executors(executorsclientid, del);
-- Financial data queries
CREATE INDEX idx_sellbill_client_date ON sellbill(sellbillclientid, datestarting, conditions);
CREATE INDEX idx_expenses_sellbill ON expenses(sellbillid, conditions);
CREATE INDEX idx_clientdebtchange_bill_table ON clientdebtchange(billid, tablename);
```
2. **Query Optimization**:
- Use appropriate date ranges to limit result sets
- Optimize JOIN conditions in main query
- Consider materialized views for complex aggregations
### Memory Management
- Efficient processing of financial calculations
- Proper variable cleanup in loops
- Optimized JSON response generation
### Report Performance
- Implement caching for frequently accessed data
- Use pagination for large result sets
- Optimize DataTables server-side processing
---
## ๐งช Testing Scenarios
### Test Case 1: Basic Financial Calculations
1. Create execution with known sales amount, costs, and payments
2. Verify all financial metrics calculated correctly
3. Check outstanding amount = sales - payments
4. Confirm gross profit = sales - costs
5. Validate net profit = payments - costs
### Test Case 2: Edge Cases
1. Test with zero payments (all outstanding)
2. Test with costs exceeding sales (negative gross profit)
3. Test with zero costs (100% gross profit)
4. Test with payments exceeding sales (overpayment)
5. Verify NULL handling in all calculations
### Test Case 3: Date Range Filtering
1. Generate report for specific month
2. Test with custom date ranges
3. Verify date filtering accuracy
4. Check edge cases (single day, year ranges)
5. Test with no data in range
### Test Case 4: Search and Filtering
1. Test client search functionality
2. Test sales bill search with client context
3. Verify filtering by client affects results appropriately
4. Test DataTables search across columns
5. Validate sorting functionality
```
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข executors.md - Execution assignment management
- โข sellbillController.md - Sales bill operations
- โข clientPayedDeptController.md - Payment tracking
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When major changes occur