# Rollover Fix: Update Existing Loan Instead of Creating New One

## Problem
When approving rollover requests, the system threw:
```
IntegrityError: (1062, "Duplicate entry '12112026-000003' for key 'loans.loan_number'")
```

## Root Cause
The original rollover implementation tried to **create a new loan record** instead of **updating the existing loan**. This caused:
1. Duplicate loan number errors (unique constraint violation)
2. Two separate loan records for what should be one loan
3. Fragmented payment history across multiple loan records
4. Confusion in reporting (which loan is the "real" one?)

## Solution: Update Instead of Create

Changed `RolloverRequest.approve()` to **update the existing loan** with new terms instead of creating a new database record.

### Before (Wrong Approach)
```python
# Mark old loan as rolled_over
self.loan.status = 'rolled_over'
self.loan.save()

# Create NEW loan record
new_loan = Loan.objects.create(
    loan_number=original_loan_number,  # ❌ Duplicate!
    principal_amount=new_amount,
    ...
)
```

**Problems:**
- ❌ Duplicate loan numbers (IntegrityError)
- ❌ Two loan records in database
- ❌ Payment history split across records
- ❌ Reporting confusion

### After (Correct Approach)
```python
# Update existing loan with new terms
self.loan.principal_amount = new_amount
self.loan.interest_amount = new_interest
self.loan.processing_fee += rollover_fee
self.loan.total_amount = new_total
self.loan.duration_days = new_duration
self.loan.due_date = rollover_date + timedelta(days=new_duration)
self.loan.is_rolled_over = True
self.loan.save()

return self.loan  # Same loan, updated
```

**Benefits:**
- ✅ No duplicate loan numbers
- ✅ One loan record (as it should be)
- ✅ All payments stay with same loan
- ✅ Clean, simple data model

## What Gets Updated

When a rollover is approved, the existing loan is updated with:

| Field | Updated To |
|-------|-----------|
| `principal_amount` | New loan amount |
| `interest_amount` | New interest (calculated or custom) |
| `processing_fee` | Existing fee + rollover fee |
| `total_amount` | New principal + interest + fees |
| `duration_days` | New duration in days |
| `due_date` | Rollover date + new duration |
| `is_rolled_over` | Set to `True` |
| `status` | Stays `active` |
| `loan_number` | **UNCHANGED** - same number! |

## Loan Application Also Updated

The related `LoanApplication` is also updated to reflect new terms:
- `requested_amount`
- `requested_duration`
- `interest_amount`
- `processing_fee_amount`
- `total_amount`
- `approval_notes` (appended with rollover info)

## Impact on Payments

**Before (with separate loans):**
```
Old Loan: 12112026-000003-R
  ├─ Payment 1 (KES 5,000)
  ├─ Payment 2 (KES 5,000)
  └─ Status: rolled_over

New Loan: 12112026-000003
  ├─ (no payments yet)
  └─ Status: active
```
Problem: Payment history fragmented!

**After (with updated loan):**
```
Loan: 12112026-000003
  ├─ Payment 1 (KES 5,000) - before rollover
  ├─ Payment 2 (KES 5,000) - before rollover
  ├─ [ROLLOVER APPROVED - new terms]
  └─ Status: active, is_rolled_over: true
```
✅ Complete payment history in one place!

## Files Modified

### 1. `loans/models.py`
**Method**: `RolloverRequest.approve()` (lines ~1777-1850)

**Changes**:
- Removed `Loan.objects.create()` call
- Removed `LoanApplication.objects.create()` call
- Changed to update existing loan fields directly
- Returns same loan object (not new loan)

### 2. `loans/views.py`
**Function**: `approve_rollover()` (line ~2726)

**Changes**:
- Updated success message: "New active loan created" → "Loan has been updated with new terms"

## Database Impact

### No Migration Needed
All required fields already exist:
- `is_rolled_over` field already exists
- No schema changes required
- Just logic changes in Python code

### Existing Data
If you have already approved rollovers with the old system (separate loan records):
- Those loans will stay as is (two separate records)
- New rollovers will use the update approach (one record)
- No data corruption or issues
- Can optionally clean up old rolled-over loans if needed

## Deployment

### Quick Deploy
```bash
cd ~/public_html
python fix_rollover_update_not_create.py
```

### Manual Deploy
1. Upload modified files:
   - `loans/models.py`
   - `loans/views.py`

2. Restart Django:
   ```bash
   touch tmp/restart.txt
   ```

## Testing After Deployment

1. **Find a pending rollover**:
   ```
   Loans → Rollovers → (select pending request)
   ```

2. **Approve the rollover**:
   - Click "Approve Rollover"
   - Should succeed without IntegrityError

3. **Verify the updated loan**:
   - Go to the loan detail page
   - Check loan number (unchanged)
   - Check amounts (updated to new terms)
   - Check due date (extended)
   - Check payments (all previous payments still there)

4. **Database check**:
   ```sql
   -- Find rolled over loans
   SELECT loan_number, principal_amount, is_rolled_over, status
   FROM loans_loan
   WHERE is_rolled_over = 1;
   
   -- Should see one loan per rollover, not two
   ```

## Rollover History Tracking

Since we update instead of create, how do we track rollover history?

### Current Tracking
- `RolloverRequest` table keeps full history:
  - What was requested
  - Who approved/rejected
  - When it was approved
  - Notes and terms
  
- `Loan` table shows current state:
  - `is_rolled_over` flag = True
  - Current terms reflect rollover

### Future Enhancement (Optional)
Could add a `RolloverHistory` table to track each rollover event:
```python
class RolloverHistory(models.Model):
    loan = models.ForeignKey(Loan)
    rollover_request = models.ForeignKey(RolloverRequest)
    previous_amount = models.DecimalField(...)
    new_amount = models.DecimalField(...)
    previous_due_date = models.DateField(...)
    new_due_date = models.DateField(...)
    rolled_over_at = models.DateTimeField(...)
```
But this is optional - the `RolloverRequest` table already provides this info.

## Benefits Summary

✅ **No Duplicate Errors**: Same loan, same number  
✅ **Clean Data**: One loan record per loan  
✅ **Complete History**: All payments stay with loan  
✅ **Simple Logic**: Update instead of create/delete dance  
✅ **Easy Reporting**: No need to join multiple loan records  
✅ **Better UX**: Loan number never changes  

## Rollback Plan

If you need to rollback (unlikely):

1. Restore old `loans/models.py` and `loans/views.py`
2. Restart Django
3. Note: Any rollovers approved with new code will have updated loans (can't easily "split" them back)

## Questions?

**Q: What happens to previous payments?**  
A: They stay with the same loan - nothing changes for payments!

**Q: Does the loan number change?**  
A: No! The loan keeps its original loan number.

**Q: Can I still see rollover history?**  
A: Yes! Check the `RolloverRequest` table for full history.

**Q: What if I rollover twice?**  
A: Each rollover just updates the loan again with new terms.

**Q: Does this affect reporting?**  
A: Yes - positively! Simpler to report since one loan = one record.
