# Loan Number Duplicate Error - FIXED

## The Error

```
This application has already been approved and a loan exists. 
(Error: (1062, "Duplicate entry '12112026-000001' for key 'loans.loan_number'"))
```

## Root Cause

The loan number generation code had a **critical bug**:

1. It was looking for existing loan numbers with the **old format** (`LOAN-000001`)
2. But we changed the format to **new format** (`DDMMYYYY-NNNNNN`)
3. So it couldn't find any existing loans for today
4. Always started at number `1` for each day
5. Tried to create `12112026-000001` again and again → **Duplicate error!**

### The Problematic Code

**BEFORE (Broken):**
```python
# Was looking for old format "LOAN-NNNNNN"
for loan_number in Loan.objects.values_list('loan_number', flat=True):
    if loan_number and loan_number.startswith('LOAN-'):  # ← WRONG PREFIX!
        try:
            num = int(loan_number.split('-')[1])
            existing_numbers.add(num)
        except (IndexError, ValueError):
            continue

# Would always find NO existing numbers for today
# So next_num would always be 1
# Causing duplicate: 12112026-000001, 12112026-000001, ...
```

## The Fix

**AFTER (Fixed):**
```python
# Get today's date first
date_part = datetime.now().strftime('%d%m%Y')  # e.g., 12112026
today_prefix = f"{date_part}-"  # e.g., "12112026-"

# Look for existing loan numbers for TODAY specifically
existing_numbers = set()
for loan_number in Loan.objects.values_list('loan_number', flat=True):
    if loan_number and loan_number.startswith(today_prefix):  # ← CORRECT!
        try:
            num = int(loan_number.split('-')[1])
            existing_numbers.add(num)
        except (IndexError, ValueError):
            continue

# Find next available number FOR TODAY
next_num = 1
while next_num in existing_numbers:
    next_num += 1

# Generate: 12112026-000001, 12112026-000002, 12112026-000003, etc.
self.loan_number = f"{date_part}-{next_num:06d}"
```

## How It Works Now

**Scenario: Creating loans on November 12, 2026**

1. **First loan:**
   - Checks existing loans starting with `12112026-`
   - Finds: none
   - Generates: `12112026-000001` ✅

2. **Second loan (same day):**
   - Checks existing loans starting with `12112026-`
   - Finds: `12112026-000001`
   - Generates: `12112026-000002` ✅

3. **Third loan (same day):**
   - Checks existing loans starting with `12112026-`
   - Finds: `12112026-000001`, `12112026-000002`
   - Generates: `12112026-000003` ✅

**No more duplicates!**

## File Modified

**`loans/models.py`** - Lines ~832-863
- Fixed loan number generation logic
- Now correctly finds existing numbers for today's date
- Properly increments the sequential number

## Deployment

```bash
# Upload fixed file
scp loans/models.py user@server:/home/xygbfpsg/phingrazuri/loans/

# Restart server
sudo systemctl restart gunicorn
# OR
sudo systemctl restart lsws
```

## Testing

After deployment, create multiple loans on the same day:

1. **Loan 1:** Should get `12112026-000002` (next after existing 000001)
2. **Loan 2:** Should get `12112026-000003`
3. **Loan 3:** Should get `12112026-000004`

Each loan number should be **unique** - no more duplicates!

## What About Tomorrow?

**November 13, 2026:**
- First loan: `13112026-000001` ✅
- Second loan: `13112026-000002` ✅
- etc.

The counter **resets each day** as intended, but now it correctly finds existing loans for that day.

## Additional Notes

### Why This Bug Happened

When we changed the loan number format from `LOAN-NNNNNN` to `DDMMYYYY-NNNNNN`, we updated the **generation logic** but forgot to update the **existing number detection logic**. So the old detection code kept looking for `LOAN-` prefix instead of the new date prefix.

### Why It Affects All Applications

Every application you tried to approve today was trying to create loan `12112026-000001`, which already exists from the first (or an earlier) approval attempt. That's why ALL applications were failing with the same error.

### The Existing Loan

There's now a loan `12112026-000001` in the database. That's fine - leave it there. The next loan will be `12112026-000002`.

---

**Fixed:** November 12, 2026  
**File:** `loans/models.py`  
**Status:** ✅ Ready to deploy  
**Priority:** CRITICAL - Blocks all loan approvals
