Get Supplier Debt Controller Documentation
File: /controllers/getSupplierDept.php
Purpose: AJAX utility controller for retrieving supplier current debt information
Last Updated: December 20, 2024
Total Functions: 1
Lines of Code: ~67
---
๐ Overview
The Get Supplier Debt Controller is a lightweight AJAX utility that provides real-time supplier debt information. It serves as a simple API endpoint for retrieving current supplier debt balances without full page reloads.
Primary Functions
- โ Retrieve supplier current debt via AJAX
- โ Direct database query execution
- โ Minimal response for fast loading
- โ Simple GET parameter handling
Related Controllers
- โข supplierController.php - Full supplier management
- โข supplierReportsController.php - Supplier reporting
- โข buyBillController.php - Purchase transactions affecting debt
---
๐๏ธ Database Tables
Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|---|---|---|
| **supplier** | Supplier master data | supplierid, suppliername, suppliercurrentDebt, conditions |
๐ Key Functions
1. getsuppliercurrentDebt - Retrieve Supplier Debt
Location: Line 56
Purpose: AJAX endpoint to get current supplier debt amount
URL Route: ?do=getsuppliercurrentDebt
Function Implementation:
if ($do == "getsuppliercurrentDebt") {
$supID = $_GET["supplierid"];
$getsuppliercurrentDebt = $supplierEX->querysuppliercurrentDebt($supID);
$dept = $getsuppliercurrentDebt[0]->suppliercurrentDebt;
echo $dept;
}
Process Flow:
1. Extract supplier ID from GET parameter
2. Query supplier debt using extended DAO
3. Extract debt amount from result object
4. Output raw debt value
Response Format: Plain text number (e.g., "1500.00")
---
๐ Workflows
Workflow 1: AJAX Debt Retrieval
---
๐ URL Routes & Actions
| URL Parameter | Function Called | Description |
|---|---|---|
| `do=getsuppliercurrentDebt` | Inline function | Get supplier current debt amount |
Get Supplier Debt (do=getsuppliercurrentDebt):
- โข
supplierid- Supplier ID (numeric)
Response Format
Content-Type: text/plain
Body: 1500.00
---
๐ Security & Permissions
Security Considerations
โ ๏ธ Security Issues Identified:
1. No Authentication: Controller lacks authentication checks
2. No Input Validation: Supplier ID not validated or sanitized
3. SQL Injection Risk: Direct parameter usage without filtering
4. No Permission Checks: Any user can access any supplier's debt
5. Information Disclosure: Exposes sensitive financial data
Recommended Security Improvements
// Add authentication check
include_once("../public/authentication.php");
// Validate supplier ID
$supID = filter_input(INPUT_GET, 'supplierid', FILTER_VALIDATE_INT);
if (!$supID) {
http_response_code(400);
echo "Invalid supplier ID";
exit;
}
// Check user permissions
if (!checkSupplierAccess($supID, $_SESSION['userid'])) {
http_response_code(403);
echo "Access denied";
exit;
}
---
๐ Performance Considerations
Current Performance
- โข Pros: Very fast, minimal overhead
- โข Cons: No caching, direct database hit per request
Database Optimization
-- Ensure index exists for fast lookup
CREATE INDEX idx_supplier_id ON supplier(supplierid);
-- Query analysis
EXPLAIN SELECT suppliercurrentDebt FROM supplier WHERE supplierid = ?;
Caching Recommendations
// Add simple caching
$cacheKey = "supplier_debt_" . $supID;
$cachedDebt = getFromCache($cacheKey);
if ($cachedDebt !== false) {
echo $cachedDebt;
exit;
}
// Query database and cache result
$dept = $getsuppliercurrentDebt[0]->suppliercurrentDebt;
setCache($cacheKey, $dept, 300); // 5 minute cache
echo $dept;
---
๐ Common Issues & Troubleshooting
1. Empty or Invalid Response
Issue: No output or "0" returned for valid supplier
Cause: Invalid supplier ID or database connection issue
Debug:
$supID = $_GET["supplierid"];
echo "Supplier ID: " . $supID . "<br>";
$result = $supplierEX->querysuppliercurrentDebt($supID);
echo "Query result count: " . count($result) . "<br>";
print_r($result);
2. Database Connection Errors
Issue: PHP errors or blank response
Cause: Missing DAO includes or database connectivity
Debug:
try {
$getsuppliercurrentDebt = $supplierEX->querysuppliercurrentDebt($supID);
if (empty($getsuppliercurrentDebt)) {
echo "No supplier found with ID: " . $supID;
} else {
echo $getsuppliercurrentDebt[0]->suppliercurrentDebt;
}
} catch (Exception $e) {
echo "Database error: " . $e->getMessage();
}
3. JavaScript Integration Issues
Issue: AJAX calls failing or returning unexpected data
Cause: Incorrect URL format or response handling
Example AJAX Implementation:
function getSupplierDebt(supplierId) {
$.ajax({
url: 'getSupplierDept.php?do=getsuppliercurrentDebt&supplierid=' + supplierId,
method: 'GET',
success: function(response) {
$('#supplierDebt').text(parseFloat(response).toFixed(2));
},
error: function() {
$('#supplierDebt').text('Error loading debt');
}
});
}
---
๐งช Testing Scenarios
Test Case 1: Valid Supplier ID
1. Call: getSupplierDept.php?do=getsuppliercurrentDebt&supplierid=123
2. Verify: Returns numeric debt amount
3. Check: Response is valid number format
Test Case 2: Invalid Supplier ID
1. Call: getSupplierDept.php?do=getsuppliercurrentDebt&supplierid=99999
2. Verify: Returns appropriate error or 0
3. Check: No PHP errors generated
Test Case 3: Missing Parameter
1. Call: getSupplierDept.php?do=getsuppliercurrentDebt
2. Verify: Handles missing supplierid gracefully
3. Check: No fatal errors occur
Manual Testing
# Test with curl
curl "http://localhost/erp19/controllers/getSupplierDept.php?do=getsuppliercurrentDebt&supplierid=1"
# Expected output: numeric value like 1500.00
---
๐ง Integration Examples
Frontend JavaScript Integration
// jQuery implementation
function updateSupplierDebt(supplierId, targetElement) {
$.get('getSupplierDept.php', {
do: 'getsuppliercurrentDebt',
supplierid: supplierId
}).done(function(debt) {
$(targetElement).text(parseFloat(debt).toFixed(2));
}).fail(function() {
$(targetElement).text('N/A');
});
}
// Vanilla JavaScript implementation
function fetchSupplierDebt(supplierId) {
return fetch(`getSupplierDept.php?do=getsuppliercurrentDebt&supplierid=${supplierId}`)
.then(response => response.text())
.then(debt => parseFloat(debt));
}
PHP Integration
// Include in other controllers
function getSupplierCurrentDebt($supplierId) {
$url = "getSupplierDept.php?do=getsuppliercurrentDebt&supplierid=" . $supplierId;
return file_get_contents($url);
}
---
๐ Recommended Improvements
1. Enhanced Security
// Add to beginning of file
include_once("../public/authentication.php");
// Validate input
$supID = filter_input(INPUT_GET, 'supplierid', FILTER_VALIDATE_INT);
if (!$supID) {
http_response_code(400);
exit('Invalid supplier ID');
}
// Check permissions (example)
if (!userCanViewSupplier($_SESSION['userid'], $supID)) {
http_response_code(403);
exit('Access denied');
}
2. JSON API Format
if ($do == "getsuppliercurrentDebt") {
$supID = filter_input(INPUT_GET, 'supplierid', FILTER_VALIDATE_INT);
header('Content-Type: application/json');
if (!$supID) {
echo json_encode(['error' => 'Invalid supplier ID']);
exit;
}
try {
$result = $supplierEX->querysuppliercurrentDebt($supID);
if (empty($result)) {
echo json_encode(['error' => 'Supplier not found']);
} else {
echo json_encode([
'success' => true,
'debt' => (float) $result[0]->suppliercurrentDebt,
'supplierId' => $supID
]);
}
} catch (Exception $e) {
echo json_encode(['error' => 'Database error']);
}
}
3. Error Handling
try {
$getsuppliercurrentDebt = $supplierEX->querysuppliercurrentDebt($supID);
if (empty($getsuppliercurrentDebt)) {
echo "0";
} else {
echo number_format($getsuppliercurrentDebt[0]->suppliercurrentDebt, 2, '.', '');
}
} catch (Exception $e) {
error_log("Supplier debt query failed: " . $e->getMessage());
echo "0"; // Return 0 on error to prevent breaking frontend
}
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข supplierController.md - Full supplier management
- โข AJAX Integration Guidelines - Frontend integration patterns
- โข Security Best Practices - API security recommendations
---
Documented By: AI Assistant
Review Status: โ ๏ธ Needs Security Review
Security Issues: Authentication, input validation, permissions
Next Review: Immediate security improvements needed