# Mwamba Loan Calculation Fix - Complete Summary

## 🔍 Issue Identified

**Loan**: LOAN-000131 (PETER IRUNGU MAINA)  
**Product**: Mwamba (90 days, 10% monthly interest, 5% processing fee)

### Current (Wrong) Values:
```
Principal Amount:     KES 20,000.00 ✓
Interest Amount:      KES  6,000.00 ✓ (30% for 90 days)
Processing Fee:       KES  1,000.00 ✓ (5% of principal)
─────────────────────────────────────
Total Amount:         KES 22,400.00 ✗ WRONG!
Amount Paid:          KES  3,200.00 ✓
Outstanding Balance:  KES 19,200.00 ✗ WRONG!
```

### Correct Values Should Be:
```
Principal Amount:     KES 20,000.00 ✓
Interest Amount:      KES  6,000.00 ✓
Processing Fee:       KES  1,000.00 ✓
─────────────────────────────────────
Total Amount:         KES 27,000.00 ✓ (20,000 + 6,000 + 1,000)
Amount Paid:          KES  3,200.00 ✓
Outstanding Balance:  KES 23,800.00 ✓ (27,000 - 3,200)
```

### Discrepancy:
- **Total Amount**: Off by KES 4,600.00
- **Outstanding Balance**: Off by KES 4,600.00

## 🎯 Root Cause

The `total_amount` field in the `loans` table contains **incorrect data** (22,400 instead of 27,000).

This is **NOT a code bug** - the calculation logic in the codebase is correct:

### Code Analysis:

1. **LoanApplication.save()** (loans/models.py, lines 360-375):
   ```python
   if not self.total_amount:
       self.total_amount = self.requested_amount + self.interest_amount + self.processing_fee_amount
   ```
   ✓ Correct logic

2. **LoanApplication.approve()** (loans/models.py, lines 413-415):
   ```python
   calculated_total = self.requested_amount + self.interest_amount + self.processing_fee_amount
   loan = Loan.objects.create(..., total_amount=calculated_total, ...)
   ```
   ✓ Correct logic

3. **LoanCalculationService.calculate_outstanding_amount()** (reports/calculation_service.py):
   ```python
   outstanding = total_amount + total_penalties - amount_paid
   ```
   ✓ Correct logic (but uses the wrong stored value)

### Likely Causes of Bad Data:
1. Manual database edit
2. A bug that existed when this loan was created (now fixed in code)
3. Data migration issue
4. Direct SQL insert with wrong calculation

## 💊 Solution

### Quick Fix (SQL - Recommended):

Run the provided SQL script:
```bash
mysql -u your_user -p your_database < fix_mwamba_loan_totals.sql
```

Or execute in phpMyAdmin/MySQL client:
```sql
-- Fix LOAN-000131
UPDATE loans 
SET total_amount = principal_amount + interest_amount + processing_fee
WHERE loan_number = 'LOAN-000131';

-- Fix the application too
UPDATE loan_applications la
INNER JOIN loans l ON l.application_id = la.id
SET la.total_amount = l.principal_amount + l.interest_amount + l.processing_fee
WHERE l.loan_number = 'LOAN-000131';
```

### Python Script (Alternative):

```bash
python diagnose_and_fix_mwamba_loan_131.py
```

This will:
- Diagnose the issue
- Show before/after comparison
- Ask for confirmation
- Fix LOAN-000131 and all other affected loans

## 📊 Impact Analysis

### Affected Areas:
1. ✗ **Loan Detail Page** - Shows wrong outstanding balance
2. ✗ **Principal Amount Display** - May show incorrect breakdown
3. ✗ **Payment Progress** - Shows incorrect percentage
4. ✗ **Reports & Analytics** - All financial reports are inaccurate
5. ✗ **Dashboard Statistics** - Portfolio totals are wrong
6. ✗ **Borrower Portal** - Borrower sees wrong amount owed

### Financial Impact:
- Borrower owes **KES 23,800** but system shows **KES 19,200**
- Difference: **KES 4,600** underreported

## ✅ Verification Steps

After applying the fix, verify with:

```sql
SELECT 
    loan_number,
    principal_amount,
    interest_amount,
    processing_fee,
    total_amount,
    (principal_amount + interest_amount + processing_fee) as calculated,
    (SELECT SUM(amount) FROM repayments WHERE loan_id = loans.id) as paid,
    (total_amount - (SELECT COALESCE(SUM(amount), 0) FROM repayments WHERE loan_id = loans.id)) as outstanding
FROM loans
WHERE loan_number = 'LOAN-000131';
```

**Expected Output:**
```
loan_number: LOAN-000131
principal_amount: 20000.00
interest_amount: 6000.00
processing_fee: 1000.00
total_amount: 27000.00
calculated: 27000.00
paid: 3200.00
outstanding: 23800.00
```

## 🔒 Prevention

### 1. Add Database Constraint (Optional):
```sql
ALTER TABLE loans ADD CONSTRAINT chk_total_amount 
CHECK (ABS(total_amount - (principal_amount + interest_amount + processing_fee)) < 0.01);
```

### 2. Add Automated Test:
```python
def test_loan_total_amount_integrity():
    """Ensure all loans have correct total_amount"""
    from loans.models import Loan
    from decimal import Decimal
    
    for loan in Loan.objects.all():
        calculated = loan.principal_amount + loan.interest_amount + loan.processing_fee
        assert abs(loan.total_amount - calculated) < Decimal('0.01'), \
            f"Loan {loan.loan_number} has incorrect total_amount"
```

### 3. Add Admin Warning:
Display a warning in the admin panel if total_amount doesn't match the sum.

## 📝 Files Created

1. **FIX_MWAMBA_CALCULATION_ISSUE.md** - Detailed analysis and fix guide
2. **fix_mwamba_loan_totals.sql** - SQL script to fix the issue
3. **diagnose_and_fix_mwamba_loan_131.py** - Python diagnostic and fix script
4. **MWAMBA_CALCULATION_FIX_SUMMARY.md** - This summary document

## 🚀 Action Required

**IMMEDIATE ACTION NEEDED:**

1. ✅ Run `fix_mwamba_loan_totals.sql` on production database
2. ✅ Verify LOAN-000131 is fixed
3. ✅ Check if other loans are affected
4. ✅ Inform borrower of correct outstanding balance
5. ✅ Update any reports that were generated with wrong data

## 📞 Support

If you need help applying this fix:
1. Review the SQL script before running
2. Backup your database first
3. Run the diagnostic queries to see affected loans
4. Apply the fix
5. Verify the results

---

**Status**: Ready to deploy  
**Risk Level**: Low (only fixes data, no code changes)  
**Estimated Time**: 5 minutes  
**Rollback**: Restore from backup if needed
