Client Debt Analysis Controller Documentation
File: /controllers/debtclientController.php
Purpose: Generates comprehensive debt analysis reports for customers, tracking sales, returns, payments, and debt balances by customer types and date ranges
Last Updated: December 20, 2024
Total Functions: 4+
Lines of Code: ~682
---
๐ Overview
The Client Debt Analysis Controller provides detailed financial analysis of customer accounts, focusing on debt tracking and payment analysis. It processes:
- โข Customer debt analysis by customer type
- โข Sales and return transaction summaries
- โข Payment history and debt balance calculations
- โข Government and area-based customer grouping
- โข Date range filtering for financial periods
- โข Comprehensive debt vs payment reconciliation
Primary Functions
- โ Analyze customer debt by customer type classification
- โ Track sales, returns, and payment transactions
- โ Calculate net debt positions and payment totals
- โ Group customers by government and area locations
- โ Filter analysis by date ranges and customer types
- โ Display debt-only customers vs all customers
- โ Generate detailed transaction breakdowns
Related Controllers
- โข clientReportsController.php - Individual customer reports
- โข sellbillController.php - Sales operations
- โข returnsellbillController.php - Return operations
- โข clientPayedDeptController.php - Customer payments
---
๐๏ธ Database Tables
Primary Analysis Tables
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **client** | Customer master data | clientid, clientname, clientdebt, typeclientid, clientarea | |
| **clientdebtchange** | Customer debt transaction history | clientdebtchangeid, clientid, clientdebtchangeamount, clientdebtchangetype, clientdebtchangedate, tablename | |
| **typeclient** | Customer type classifications | typeclientid, typeclientname |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **sellbill** | Sales transactions | sellbillid, sellbillclientid, sellbilltotalbill, sellbillaftertotalbill, sellbilltotalpayed, sellbilldate | |
| **returnsellbill** | Return transactions | returnsellbillid, returnsellbillclientid, returnsellbilltotalbill, returnsellbillaftertotalbill, returnsellbilldate | |
| **sellbillandrutern** | Combined sale/return bills | sellbillid, sellbillclientid, sellbillprice, returnsellbillprice, sellbilldate |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **clientarea** | Customer area definitions | id, name, description | |
| **government** | Government/province data | governmentid, governmentname | |
| **goverarea** | Government area subdivisions | goverareaid, governmentid, goverareaname |
๐ Key Functions
1. Default Action - Report Setup
Location: Line 178
Purpose: Display the debt analysis form with customer type filters
Process Flow:
1. Load all customer types for filtering
2. Load YouTube tutorial links
3. Build initial query strings for different bill types
4. Apply date filtering if provided
5. Display analysis form template
Key Variables:
- โข
$TypeClient- All customer types available - โข
$queryString1- Sales bill filters - โข
$queryString1R- Return bill filters - โข
$queryString1SR- Combined bill filters
---
2. show - Generate Debt Analysis Report
Location: Line 227
Purpose: Main analysis function that processes customer debt by type and date range
Function Signature:
// Triggered when: do=show
$TypeClient = $_POST['TypeClient'];
$showDebitOnly = $_POST['showDebit'];
$datefrom = filter_input(INPUT_POST, 'datefrom');
$dateto = filter_input(INPUT_POST, 'dateto');
Process Flow:
1. Filter Setup: Build customer type and debt filters
2. Date Range Processing: Apply date range to all transaction queries
3. Multi-Table Analysis:
- Query sales bills with customer joins
- Query return bills with customer data
- Query combined sale/return bills
4. Data Consolidation: Merge all transaction data by customer
5. Financial Calculations: Calculate totals and discounts
6. Payment Analysis: Call showAllOperations() for each customer
7. Report Generation: Display consolidated analysis
Customer Data Class:
class clientData {
public $clientid;
public $clientname;
public $totalsell = 0;
public $totalreturn = 0;
public $totaldiscount = 0;
public $clientdebt = 0;
public $clientareaName;
public $clientgovernmentname;
}
---
3. showAllOperations() - Customer Payment Analysis
Location: Line 438
Purpose: Analyze all financial operations for a specific customer
Function Signature:
function showAllOperations($clientid, $datefrom, $dateto)
Process Flow:
1. Sales Analysis: Call showSellBillsByClientAndDate()
2. Returns Analysis: Call showReturnSellBillsByClientAndDate()
3. Payment Analysis: Query clientdebtchange table for payments
4. Transaction Processing: Handle different payment types
5. Double-counting Prevention: Avoid counting bill payments twice
6. Net Calculation: Return total payment amount
Payment Types Handled:
- โข
sellbillController.php- Sales with payments - โข
depositcheckController.php- Check deposits - โข
clientPayedDeptController.php- Direct payments - โข Other debt change transactions
---
4. showSellBillsByClientAndDate() - Sales Transaction Analysis
Location: Line 515
Purpose: Retrieve and process sales bills for customer within date range
Function Signature:
function showSellBillsByClientAndDate($clientid, $datefrom, $dateto)
Process Flow:
1. Regular Sales Bills: Query sellbill table
2. Combined Bills: Query sellbillandrutern table
3. Quantity Calculation: Count products in each bill
4. Discount Processing: Handle percentage and fixed discounts
5. Status Filtering: Exclude cancelled bills
6. Data Merging: Combine both datasets
Discount Calculation:
if ($sellbilldiscounttype == 1) {
// Fixed amount discount
$sellbillprice = ($bill->sellbillprice) - ($bill->sellbilldiscount);
} else {
// Percentage discount
$sellbillprice = ($bill->sellbillprice) - ((($bill->sellbillprice) * ($bill->sellbilldiscount)) / 100);
}
---
5. showReturnSellBillsByClientAndDate() - Returns Analysis
Location: Line 597
Purpose: Retrieve and process return bills for analysis
Function Signature:
function showReturnSellBillsByClientAndDate($clientid, $datefrom, $dateto)
Process Flow:
1. Regular Returns: Query returnsellbill table
2. Combined Returns: Query sellbillandrutern for return portions
3. Quantity Tracking: Count returned products
4. Total Calculation: Sum return amounts
5. Data Structure: Return array with both datasets
Return Value Structure:
$returnsellbill = array($returnsellbillData, $sellbillandruternData);
// [0] = Pure return bills
// [1] = Combined bill return portions
---
๐ Workflows
Workflow 1: Comprehensive Debt Analysis
Workflow 2: Payment Analysis Deep Dive
---
๐ URL Routes & Actions
| URL Parameter | Function Called | Description | |
|---|---|---|---|
| `do=` (empty) | Default | Display debt analysis form with customer type filters | |
| `do=show` | Main analysis | Generate comprehensive debt analysis report |
Debt Analysis (do=show):
- โข
TypeClient- Customer type filter (-1 for all, specific ID for type) - โข
showDebit- Filter for debt-only customers (checkbox) - โข
datefrom- Analysis start date (YYYY-MM-DD, optional) - โข
dateto- Analysis end date (YYYY-MM-DD, optional)
Special Customer Type Values
- โข
-1- All customer types - โข
-20- Special customer type with specific handling - โข
Specific ID- Individual customer type
---
๐ Analysis Metrics
Customer Financial Summary
// Net sales calculation
$t_data->t_bure = $t_data->sellbillaftertotalbill - $t_data->returnsellbillaftertotalbill;
// Total discount calculation
$t_data->t_dis = $t_data->selldis - $t_data->returnselldis + $t_data->sellandreturndis;
// Payment analysis
$dataa->totalPrice = showAllOperations($clientid, $datefrom, $dateto);
Geographic Analysis
- โข Customers grouped by government and area
- โข Missing geographic data handled as "ูุงููุฌุฏ" (Not Available)
- โข Area and government names included in customer data
Transaction Analysis
- โข Sales totals with discount breakdown
- โข Return totals with credit calculations
- โข Payment totals preventing double-counting
- โข Net financial position per customer
---
๐ Security & Permissions
Authentication Requirements
include_once("../public/authentication.php");
Data Access Control
- โข User-based filtering available through authentication system
- โข Date range restrictions can be applied
- โข Customer type access can be controlled
Session Management
- โข
$_SESSION['stop_checking_result']used to bypass certain validations during analysis - โข Session cleanup after analysis completion
---
๐ Performance Considerations
Query Optimization
1. Complex Joins: Multiple table joins for customer, geographic, and transaction data
2. Date Range Filtering: Efficient indexing needed on date columns
3. Customer Type Filtering: Index on typeclientid for performance
Memory Management
- โข Large datasets possible with broad date ranges
- โข Customer data objects created for each unique customer
- โข Multiple arrays maintained during processing
Recommended Indexes
-- Customer analysis optimization
CREATE INDEX idx_client_type_debt ON client(typeclientid, clientdebt);
CREATE INDEX idx_sellbill_client_date ON sellbill(sellbillclientid, sellbilldate);
CREATE INDEX idx_returnsellbill_client_date ON returnsellbill(returnsellbillclientid, returnsellbilldate);
CREATE INDEX idx_clientdebtchange_client_date ON clientdebtchange(clientid, clientdebtchangedate);
---
๐ Common Issues & Troubleshooting
1. Incomplete Geographic Data
Issue: Customers show "ูุงููุฌุฏ" for area or government
Cause: Missing geographic assignments or deleted reference data
Solution:
-- Check for customers without geographic data
SELECT c.clientid, c.clientname, c.clientarea, ca.name as areaname
FROM client c
LEFT JOIN clientarea ca ON c.clientarea = ca.id
WHERE ca.id IS NULL;
2. Discount Calculation Errors
Issue: Discount amounts don't match expected values
Cause: Mixed percentage and fixed amount discount types
Debug:
// Verify discount calculation logic
if ($sellbilldiscounttype == 1) {
// Fixed amount - direct subtraction
$discount = $sellbilldiscount;
} else {
// Percentage - calculate from total
$discount = $sellbilltotalbill * $sellbilldiscount / 100;
}
3. Payment Double-Counting
Issue: Payment totals appear inflated
Cause: Bill payments counted in both debt changes and bill records
Verification:
-- Check for duplicate payment counting
SELECT
sb.sellbillid,
sb.sellbilltotalpayed,
cdc.clientdebtchangeamount
FROM sellbill sb
JOIN clientdebtchange cdc ON cdc.clientdebtchangemodelid = sb.sellbillid
AND cdc.tablename = 'sellbillController.php'
WHERE sb.sellbilltotalpayed > 0 AND cdc.clientdebtchangeamount > 0;
4. Date Range Performance Issues
Issue: Analysis takes too long with large date ranges
Cause: Insufficient indexing or too broad date range
Solutions:
- โข Add proper indexes on date columns
- โข Limit date ranges to reasonable periods
- โข Consider pagination for large result sets
---
๐งช Testing Scenarios
Test Case 1: Customer Type Analysis
1. Create customers of different types with varying debt levels
2. Run analysis with specific customer type filter
3. Verify only correct customer type appears in results
4. Check debt-only filter excludes zero-debt customers
Test Case 2: Date Range Filtering
1. Create transactions across multiple date periods
2. Set specific date range for analysis
3. Verify only transactions within range are included
4. Test edge cases (same day, single day ranges)
Test Case 3: Payment Analysis Accuracy
1. Create customer with various payment types
2. Add sales with payments, direct payments, check deposits
3. Run payment analysis
4. Verify no double-counting occurs
5. Check totals match manual calculation
Test Case 4: Geographic Grouping
1. Set up customers in different areas and governments
2. Run analysis and verify geographic data appears
3. Test with customers missing geographic assignments
4. Confirm "ูุงููุฌุฏ" appears for missing data
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข clientReportsController.md - Individual customer reports
- โข sellbillController.md - Sales operations
- โข Database Schema Documentation - Table relationships
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When major changes occur