# Amount Paid Display Fix

## Problem
The "Amount Paid" field was showing KSh 0 for all loans in reports, even for loans that had received payments.

**Example:**
- LOAN-000128: Amount Paid KSh 0 (should show actual payments)
- LOAN-000127: Amount Paid KSh 0 (should show actual payments)
- LOAN-000110: Amount Paid KSh 0 (should show actual payments)

## Root Cause

### Issue 1: Wrong Dictionary Key in Enhanced Loans Due Report
The view was calculating `amount_paid` correctly using `LoanCalculationService.calculate_amount_paid(loan)`, but storing it with the wrong key in the loan_data dictionary:

```python
# WRONG
loan_data = {
    ...
    'last_payment_amount': amount_paid,  # Wrong key!
    ...
}
```

The template was looking for `loan.amount_paid`, but the dictionary only had `last_payment_amount`.

### Issue 2: Hardcoded Zero in Delinquent Loans Report
The delinquent loans report was hardcoding the amount to zero instead of calculating it:

```python
# WRONG
'last_payment_date': None,
'last_payment_amount': Decimal('0.00'),  # Hardcoded!
```

## Solution Applied

### Fix 1: Enhanced Loans Due Report (reports/views.py line ~5986)
Added the correct key to the loan_data dictionary:

```python
# FIXED
loan_data = {
    ...
    'amount_paid': amount_paid,  # Correct key for template
    'last_payment_amount': amount_paid,  # Keep for backward compatibility
    ...
}
```

### Fix 2: Delinquent Loans Report (reports/views.py line ~1253)
Calculate the actual amount paid instead of hardcoding zero:

```python
# FIXED
amount_paid = LoanCalculationService.calculate_amount_paid(loan)

loans_data.append({
    ...
    'last_payment_date': loan.last_payment_date,
    'amount_paid': amount_paid,  # Calculate actual amount
    'last_payment_amount': amount_paid,  # Keep for backward compatibility
    ...
})
```

## Files Modified

1. **reports/views.py**
   - Line ~5986: Fixed enhanced_loans_due_report view
   - Line ~1240: Fixed enhanced_delinquent_loans_report view

## Impact

### Reports Fixed
✅ Enhanced Loans Due Report (`/reports/loans-due/enhanced/`)  
✅ Delinquent Loans Report (`/reports/delinquent-loans/`)  

### What Now Works
- Amount Paid now shows the actual total of all repayments
- Outstanding Balance is calculated correctly (Total - Amount Paid)
- Reports accurately reflect payment history

## How It Works

The fix uses the `LoanCalculationService.calculate_amount_paid(loan)` method which:
1. Queries all repayment records for the loan
2. Sums the `amount` field from all repayments
3. Returns the total amount paid

```python
# From reports/calculation_service.py
def calculate_amount_paid(loan) -> Decimal:
    total_paid = loan.repayments.aggregate(
        total=Sum('amount')
    )['total']
    return total_paid if total_paid is not None else Decimal('0.00')
```

## Deployment

### Files to Upload
1. **reports/views.py** (already modified for rollover fix)

### Steps
1. Upload the modified `reports/views.py`
2. Restart application: `touch tmp/restart.txt`
3. Verify amount_paid displays correctly

### Verification
1. Go to `/reports/loans-due/enhanced/`
2. Check loans that have received payments
3. Verify "Amount Paid" shows actual payment amounts (not KSh 0)

## SQL Verification

To verify payments exist in the database:

```sql
-- Check repayments for specific loans
SELECT 
    l.loan_number,
    COUNT(r.id) as payment_count,
    SUM(r.amount) as total_paid
FROM loans l
LEFT JOIN repayments r ON l.id = r.loan_id
WHERE l.loan_number IN ('LOAN-000128', 'LOAN-000127', 'LOAN-000110')
GROUP BY l.loan_number, l.id;
```

## Combined with Rollover Fix

This fix is included in the same file (`reports/views.py`) as the rollover exclusion fix, so:
- Upload `reports/views.py` once
- Both fixes will be applied together
- No separate deployment needed

## Notes

- This was a display issue, not a data issue
- Repayment records were stored correctly in the database
- The calculation service was working correctly
- Only the view-to-template data mapping was wrong

## Testing

After deployment, test with loans that have known payments:
1. Find a loan with repayments in the database
2. Note the total amount paid from the database
3. Check the report displays the same amount
4. Verify Outstanding = Total - Amount Paid

## Backward Compatibility

Both `amount_paid` and `last_payment_amount` keys are provided in the dictionary to ensure any templates using either key will work correctly.
