# Fix Inconsistent Application Issue

## Problem

Application shows error: **"This application has already been approved and a loan exists"**

But when you check the loan, it's not actually approved or doesn't exist properly.

## Root Cause

The application got stuck in an "approved" state during failed approval attempts, but no loan was actually created. This creates a data inconsistency:

- Application status = "approved"
- But no Loan record exists linked to it

## Solution

Run the fix script on the **production server** to reset the application status.

---

## Step 1: Upload Fix Script to Production

```bash
scp fix_application_loan_issue.py user@server:/home/xygbfpsg/phingrazuri/
```

---

## Step 2: SSH into Production Server

```bash
ssh user@server
cd /home/xygbfpsg/phingrazuri
```

---

## Step 3: Run the Fix Script

### Option A: Fix Specific Application

```bash
python fix_application_loan_issue.py c39d3e10-8c36-4db6-a758-aa5963b1bb40
```

This will:
1. Check if the application is in an inconsistent state
2. If yes, reset status to 'pending'
3. Clear reviewed_by and reviewed_at
4. Allow you to approve it properly

### Option B: Scan and Fix All Inconsistent Applications

```bash
python fix_application_loan_issue.py --all
```

This will:
1. Scan ALL applications marked as "approved"
2. Find ones that have no loan
3. Ask for confirmation
4. Fix them all at once

---

## Step 4: Re-Approve the Application

After running the fix:

1. Go to: `https://grazuri.uzuriapps.xyz/loans/applications/c39d3e10.../`
2. Status should now show "Pending" again
3. Click "Approve" button
4. **IMPORTANT:** Make sure the application has:
   - ✅ Loan product selected
   - ✅ Loan amount entered
   - ✅ Duration (days) entered
5. Click "Approve Application"
6. Should now create loan successfully!

---

## What the Fix Script Does

```python
# For each inconsistent application:
app.status = 'pending'           # Reset to pending
app.reviewed_by = None           # Clear reviewer
app.reviewed_at = None           # Clear review date
app.approval_notes = ''          # Clear notes
app.save()                       # Save changes
```

---

## Preventing This in the Future

This happened because:
1. Application was missing required data
2. Approval process started but failed midway
3. Status got set to "approved" before loan was created
4. Transaction didn't roll back properly

**The fixes I made today will prevent this:**
- ✅ Added upfront validation (checks data before approving)
- ✅ Better error handling (shows errors instead of silent failures)
- ✅ Transaction safety (all-or-nothing approval)

---

## Verification After Fix

After running the fix and re-approving:

```bash
# Check application status
python manage.py shell

from loans.models import LoanApplication, Loan
app = LoanApplication.objects.get(pk='c39d3e10-8c36-4db6-a758-aa5963b1bb40')
print(f"Status: {app.status}")

# Check if loan exists
try:
    loan = app.loan
    print(f"Loan: {loan.loan_number}")
    print(f"Loan Status: {loan.status}")
except Loan.DoesNotExist:
    print("No loan exists")
```

Expected output after proper approval:
```
Status: approved
Loan: 11112026-000001  (or similar)
Loan Status: active
```

---

## Quick Reference Commands

```bash
# Upload fix script
scp fix_application_loan_issue.py user@server:/home/xygbfpsg/phingrazuri/

# SSH into server
ssh user@server
cd /home/xygbfpsg/phingrazuri

# Fix specific application
python fix_application_loan_issue.py c39d3e10-8c36-4db6-a758-aa5963b1bb40

# OR fix all inconsistent applications
python fix_application_loan_issue.py --all

# Verify fix worked
python manage.py shell
from loans.models import LoanApplication
app = LoanApplication.objects.get(pk='c39d3e10-8c36-4db6-a758-aa5963b1bb40')
print(f"Status: {app.status}")  # Should be 'pending' now
```

---

## Summary

**Problem:** Application stuck in "approved" state without a loan

**Solution:** Reset application to "pending" and re-approve properly

**Files to upload:**
1. `fix_application_loan_issue.py` - The fix script

**Time to fix:** ~2 minutes

**After fix:** Application can be approved normally

---

**Created:** November 12, 2026  
**Status:** ✅ Ready to use  
**Safe:** Yes - only resets status, doesn't delete data
