# Duplicate Repayment Issue - Complete Fix

## Problem
When adding a repayment through the UI, **two identical repayments** were being created instead of one.

## Root Cause
Two pieces of code were both creating receipts when a repayment was saved:
1. **`loans/signals.py`** - `create_receipt_for_repayment()` signal (fires on `post_save`)
2. **`loans/models.py`** - `Repayment.save()` method calls `create_or_update_receipt()`

Both fired when a new repayment was created, causing duplicates.

## Solution Applied

### 1. Fixed the Code (Prevents Future Duplicates)
**File:** `loans/signals.py`
- Commented out the `create_receipt_for_repayment` signal
- Now only `Repayment.save()` creates receipts
- **Status:** ✅ Tested locally - confirmed working

### 2. Cleanup Script (Removes Existing Duplicates)
**File:** `delete_duplicate_repayments_production.py`

**Features:**
- Direct MySQL connection (no Django required)
- Finds duplicates: same loan, same amount, same method, within 5 seconds
- Keeps FIRST repayment in each group, deletes the rest
- Deletes associated receipts (handles FK constraints)
- Recalculates loan `_amount_paid_cache`
- Uses transactions (rollback on error)
- 5-second countdown with Ctrl+C abort
- Non-interactive (safe for production)

**Status:** ✅ Tested locally with test duplicates - works perfectly

## Deployment Steps

### Step 1: Deploy the Signal Fix
```bash
# Upload loans/signals.py to production
scp loans/signals.py user@server:/path/to/project/loans/

# Restart Django server
systemctl restart phingrazuri  # or your server command
```

### Step 2: Clean Up Existing Duplicates
```bash
# Upload cleanup script
scp delete_duplicate_repayments_production.py user@server:/path/to/

# Run the script
cd /path/to/
python3 delete_duplicate_repayments_production.py
```

The script will:
1. Connect to production database
2. Find all duplicate repayments
3. Show preview of what will be deleted
4. Wait 5 seconds (press Ctrl+C to abort)
5. Delete duplicates and update loan totals
6. Report results

### Step 3: Verify
1. Add a test repayment through the UI
2. Check that only ONE repayment was created
3. Check the repayments list - should see no new duplicates

## Files Changed

### Production Files to Upload:
1. ✅ `loans/signals.py` - Signal fix
2. ✅ `delete_duplicate_repayments_production.py` - Cleanup script

### Test Files (Local Only):
- `test_repayment_no_duplicate.py` - Verification test
- `create_test_duplicates.py` - Test data generator
- `delete_duplicate_repayments.py` - Local Django version

## Expected Results

**Before:**
- Adding 1 repayment → 2 repayments created
- Repayments list shows duplicates

**After:**
- Adding 1 repayment → 1 repayment created ✓
- Existing duplicates cleaned up ✓
- Loan totals recalculated correctly ✓

## Rollback Plan
If issues occur:
1. Restore original `loans/signals.py` from backup
2. Restart Django server
3. Database changes from cleanup script cannot be rolled back (uses commits)
   - Keep database backup before running cleanup script

## Testing Evidence

### Local Test Results:
```
✓ Created 3 duplicate repayments (KES 500 each)
✓ Script identified 1 duplicate group
✓ Kept first repayment (oldest)
✓ Deleted 2 duplicates
✓ Deleted 2 associated receipts
✓ Recalculated loan amount_paid: KES 20,500.00
✓ Verified final state: 2 repayments remain (correct)
```

## Notes
- The duplicate issue only affected repayments created through the UI
- API/automated repayments may not have been affected
- Production may have more duplicates than local
- Script is idempotent - safe to run multiple times
