# 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
- [x] Retrieve supplier current debt via AJAX
- [x] Direct database query execution
- [x] Minimal response for fast loading
- [x] Simple GET parameter handling

### Related Controllers
- [supplierController.php](supplierController.md) - Full supplier management
- [supplierReportsController.php](supplierReportsController.md) - Supplier reporting
- [buyBillController.php](buyBillController.md) - 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**:
```php
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
```
┌─────────────────────────────────────────────────────────────┐
│                START: AJAX Request                          │
│             ?do=getsuppliercurrentDebt&supplierid=123       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Extract Supplier ID                                     │
│     - Get supplierid from $_GET                            │
│     - No validation or sanitization                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Query Supplier Debt                                     │
│     - Use SupplierMySqlExtDAO                              │
│     - Call querysuppliercurrentDebt($supID)               │
│     - Return supplier record with debt                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Extract and Return Debt                                 │
│     - Get suppliercurrentDebt from first result            │
│     - Output raw numeric value                              │
│     - No formatting or JSON wrapping                       │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=getsuppliercurrentDebt` | Inline function | Get supplier current debt amount |

### Required Parameters
**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
```php
// 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
```sql
-- 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
```php
// 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**:
```php
$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**:
```php
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**:
```javascript
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
```bash
# 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
```javascript
// 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
```php
// Include in other controllers
function getSupplierCurrentDebt($supplierId) {
    $url = "getSupplierDept.php?do=getsuppliercurrentDebt&supplierid=" . $supplierId;
    return file_get_contents($url);
}
```

---

## 🚀 Recommended Improvements

### 1. **Enhanced Security**
```php
// 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**
```php
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**
```php
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](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [supplierController.md](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