# Rollover Duplicate Loan Number Fix

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

## Root Cause
The rollover approval process was trying to:
1. Keep the original loan in database with status `rolled_over`
2. Create a new active loan with the **same loan number**

Since `loan_number` has a **UNIQUE constraint** in the database, this caused a duplicate key error.

## Solution
Modified the `RolloverRequest.approve()` method to rename the old loan **before** creating the new one:

### Before (Caused Error)
```python
# Create new loan with original number
new_loan = Loan.objects.create(
    loan_number=original_loan_number,  # '12112026-000003'
    ...
)

# Mark old loan as rolled over (still has same number!)
self.loan.status = 'rolled_over'
self.loan.save()  # ❌ ERROR: Duplicate loan_number!
```

### After (Fix Applied)
```python
# First, rename old loan to free up the number
self.loan.loan_number = f"{original_loan_number}-R"  # '12112026-000003-R'
self.loan.status = 'rolled_over'
self.loan.save()

# Now create new loan with clean original number
new_loan = Loan.objects.create(
    loan_number=original_loan_number,  # '12112026-000003'
    ...
)
# ✅ SUCCESS: No duplicate!
```

## Changes Made

### File: `loans/models.py`
**Method**: `RolloverRequest.approve()` (lines ~1840-1860)

**Change**:
- Reordered operations: Rename old loan FIRST, then create new loan
- Added `-R` suffix to rolled-over loans
- This frees up the original loan number for the new active loan

## Loan Number Convention

After this fix:

| Loan Type | Loan Number Format | Example | Status |
|-----------|-------------------|---------|--------|
| Active Loan | `DDMMYYYY-NNNNNN` | `12112026-000003` | `active` |
| Rolled Over Loan | `DDMMYYYY-NNNNNN-R` | `12112026-000003-R` | `rolled_over` |

**Key Points:**
- Active rollover loans have clean loan numbers (no suffix)
- Historical rolled-over loans have `-R` suffix
- The `-R` suffix clearly identifies rolled-over loans in reports
- Loan number generation remains unchanged (only affected during rollover)

## Deployment

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

### Manual Deploy
1. Upload modified `loans/models.py` to production
2. Restart Django application:
   - Via cPanel: Application → Python Apps → Restart
   - Or: `touch tmp/restart.txt`

## Testing After Deployment

1. **Find a pending rollover request**:
   - Go to Loans → Rollovers
   - Find a pending request

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

3. **Verify loan numbers**:
   - Original loan should have: `XXXXXXX-R` (with -R suffix)
   - New active loan should have: `XXXXXXX` (clean number)

4. **Check loan details**:
   ```sql
   -- Find rollovers for a borrower
   SELECT loan_number, status, is_rolled_over, principal_amount
   FROM loans_loan
   WHERE borrower_id = 'BORROWER_ID'
   ORDER BY created_at DESC;
   ```

## Impact on Existing Data

### Existing Rolled Over Loans (Before Fix)
If you have loans rolled over before this fix, they **don't** have the `-R` suffix. Example:
- Old rolled loan: `12112026-000001` (status: rolled_over)
- New active loan: Had to use a different number due to duplicate error

These old rolled-over loans are fine - they're marked as `rolled_over` in status, just without the suffix.

### New Rollover Loans (After Fix)
All new rollovers will use the `-R` suffix pattern, allowing the active loan to retain the original number.

## Benefits

1. **No more duplicate key errors** on rollover approval
2. **Active loans keep original numbers** for consistency
3. **Clear identification** of rolled-over loans via -R suffix
4. **Better reporting** - can filter by suffix to exclude historical rollovers
5. **Backward compatible** - doesn't break existing loans

## Database Schema
No migration needed - the loan_number field already supports 20 characters:
```python
loan_number = models.CharField(max_length=20, unique=True)
```

The `-R` suffix adds 2 characters:
- Original: `12112026-000003` (14 chars)
- With suffix: `12112026-000003-R` (16 chars)
- Still under 20 char limit ✅

## Rollback Plan
If this fix causes issues (unlikely), revert by:
1. Restore old `loans/models.py` from backup
2. Restart Django application
3. Manually fix any loans with `-R` suffix if needed

## Related Issues
- Initial issue: Rollover approval failing with IntegrityError
- Related to: Loan number generation (DDMMYYYY-NNNNNN format)
- Design decision: Rollovers should preserve original loan numbers

## Questions?
- Check Django error logs if approval still fails
- Verify loan_number field has 20 char capacity
- Ensure both old and new loans are visible in loan lists
