# M-Pesa Integration - Complete Fix

## 🐛 Issues Identified

1. **Callback received but payment not linked** - Phone number format mismatch
2. **Payments not showing in /loans/repayments/** - Because they're not being processed
3. **No M-Pesa indicator** - Need to show payment source clearly

## ✅ How It Should Work

### Current Flow (After Fix)

1. **Customer pays via M-Pesa** → Shortcode 4159523
2. **M-Pesa sends callback** → Your server receives it
3. **System matches borrower** → By phone number (all formats)
4. **System matches loan** → By loan number or automatically
5. **Creates Repayment** → With `payment_method='mpesa'` and `payment_source='automatic'`
6. **Updates loan balance** → Reduces outstanding amount
7. **Sends notifications** → To borrower and loan officer

### Where Payments Appear

After processing, M-Pesa payments will show in:

1. ✅ `/payments/callbacks/` - Raw M-Pesa callbacks
2. ✅ `/payments/transactions/` - M-Pesa transaction details
3. ✅ `/loans/repayments/` - **All repayments including M-Pesa** ⭐
4. ✅ `/loans/` - Loan list (updated balances)
5. ✅ `/loans/view/<id>/` - Loan detail (repayment history)

## 🔧 Files to Upload

### 1. Fixed Phone Matching Logic

**File:** `loans/models.py`

**What it fixes:**
- Matches phone numbers in ANY format
- Tries: `+254...`, `254...`, `0...`, etc.
- Logs all attempted variants for debugging

### 2. Reprocess Command

**File:** `payments/management/commands/reprocess_mpesa_transaction.py`

**What it does:**
- Reprocesses existing unmatched transactions
- Can process single transaction or all pending
- Shows detailed results

### 3. Templates (If Not Uploaded)

**Files:**
- `templates/payments/callbacks.html`
- `templates/payments/transaction_detail.html`
- `templates/payments/reprocess_transaction.html`
- `templates/payments/my_payments.html`

## 🚀 Deployment Steps

### Step 1: Upload Files

Upload to production server:

```
/home/acbptxvs/public_html/branchbusinessadvance.co.ke/
├── loans/models.py (UPDATED)
├── payments/management/commands/
│   └── reprocess_mpesa_transaction.py (NEW)
└── templates/payments/
    ├── callbacks.html (NEW)
    ├── transaction_detail.html (NEW)
    ├── reprocess_transaction.html (NEW)
    └── my_payments.html (NEW)
```

### Step 2: Restart Application

```bash
touch /home/acbptxvs/public_html/branchbusinessadvance.co.ke/passenger_wsgi.py
```

### Step 3: Reprocess Existing Transaction

```bash
cd /home/acbptxvs/public_html/branchbusinessadvance.co.ke
python manage.py reprocess_mpesa_transaction --all-pending
```

**Expected output:**
```
======================================================================
Reprocess All Pending Transactions
======================================================================

Found 1 pending transaction(s)

----------------------------------------------------------------------
Processing: SKH1234567
Amount: KES 100.00
Phone: 254114565176
  ✓ Matched to: Phin Client - LOAN-000123

======================================================================
SUMMARY
======================================================================
Total: 1
Successful: 1
```

### Step 4: Verify Fix

1. **Check M-Pesa Transactions:**
   - Go to: `/payments/transactions/`
   - Transaction should show matched borrower and loan

2. **Check Repayments List:**
   - Go to: `/loans/repayments/`
   - Should see the M-Pesa payment with:
     - Payment Method: **M-Pesa** 📱
     - Payment Source: **Automatic M-Pesa** 🤖
     - Receipt Number: **RCP-000XXX**
     - M-Pesa Transaction ID

3. **Check Loan:**
   - Go to: `/loans/`
   - Loan balance should be reduced
   - Repayment should appear in loan history

## 📊 How M-Pesa Payments Appear

### In /loans/repayments/

M-Pesa payments will show with these indicators:

| Field | Value | Visual |
|-------|-------|--------|
| Payment Method | M-Pesa | 📱 Badge |
| Payment Source | Automatic M-Pesa | 🤖 Badge |
| Receipt Number | RCP-000123 | Standard format |
| M-Pesa Trans ID | SKH1234567 | Link to details |
| Phone Number | 254114565176 | Displayed |

**Filter Options:**
- Filter by Payment Method: **M-Pesa**
- Filter by Payment Source: **Automatic**
- Search by M-Pesa Transaction ID
- Search by phone number

### In /loans/view/<id>/

Loan detail page shows:
- **Repayment History** section
- M-Pesa payments marked with 📱 icon
- "Automatic M-Pesa" badge
- Link to M-Pesa transaction details

## 🎨 Visual Indicators

### Existing Indicators (Already in Code)

The repayment list already shows:

1. **Payment Method Badge:**
   ```html
   {% if repayment.payment_method == 'mpesa' %}
       <span class="badge badge-success">📱 M-Pesa</span>
   {% endif %}
   ```

2. **Payment Source Badge:**
   ```html
   {% if repayment.payment_source == 'automatic' %}
       <span class="badge badge-info">🤖 Automatic</span>
   {% endif %}
   ```

3. **M-Pesa Transaction Link:**
   ```html
   {% if repayment.mpesa_transaction_id %}
       <a href="/payments/transactions/?search={{ repayment.mpesa_transaction_id }}">
           {{ repayment.mpesa_transaction_id }}
       </a>
   {% endif %}
   ```

## 🔍 Troubleshooting

### Issue: Transaction still shows "Not linked"

**Check:**
1. Has `loans/models.py` been uploaded?
2. Has application been restarted?
3. Has reprocess command been run?

**Fix:**
```bash
# Verify file uploaded
ls -la /home/acbptxvs/public_html/branchbusinessadvance.co.ke/loans/models.py

# Restart
touch /home/acbptxvs/public_html/branchbusinessadvance.co.ke/passenger_wsgi.py

# Reprocess
python manage.py reprocess_mpesa_transaction --all-pending
```

### Issue: Payment not in /loans/repayments/

**Reason:** Transaction hasn't been processed yet

**Check:**
```bash
# Django shell
python manage.py shell

from loans.models import MpesaTransaction
t = MpesaTransaction.objects.filter(trans_id='YOUR_TRANS_ID').first()
print(f"Status: {t.status}")
print(f"Borrower: {t.borrower}")
print(f"Loan: {t.loan}")
print(f"Repayment: {t.repayment}")
print(f"Notes: {t.processing_notes}")
```

**If repayment is None:**
```bash
# Reprocess
python manage.py reprocess_mpesa_transaction YOUR_TRANS_ID
```

### Issue: Phone number still not matching

**Check user's phone format:**
```sql
SELECT id, first_name, last_name, phone_number 
FROM users_customuser 
WHERE role='borrower' 
AND phone_number LIKE '%114565176%';
```

**Normalize phone numbers:**
```python
# Django shell
from users.models import User

user = User.objects.get(phone_number='+254114565176')
print(f"Current: {user.phone_number}")

# The new code will match this automatically
# But you can normalize if needed:
user.phone_number = '+254114565176'  # Standard format
user.save()
```

## 📋 Verification Checklist

After deployment:

- [ ] Files uploaded to production
- [ ] Application restarted
- [ ] Reprocess command executed
- [ ] Transaction shows matched borrower
- [ ] Transaction shows matched loan
- [ ] Repayment created (check receipt number)
- [ ] Repayment appears in `/loans/repayments/`
- [ ] Repayment shows "M-Pesa" badge
- [ ] Repayment shows "Automatic" badge
- [ ] Loan balance updated
- [ ] Borrower notified
- [ ] Loan officer notified (if assigned)

## 🎯 Expected Results

### Before Fix
```
/payments/callbacks/     ✓ Shows callback
/payments/transactions/  ✓ Shows transaction (Not linked)
/loans/repayments/       ✗ No repayment
/loans/                  ✗ Balance not updated
```

### After Fix
```
/payments/callbacks/     ✓ Shows callback (Processed)
/payments/transactions/  ✓ Shows transaction (Linked to Phin)
/loans/repayments/       ✓ Shows repayment with M-Pesa badge
/loans/                  ✓ Balance updated
```

## 💡 Future Payments

After this fix, all future M-Pesa payments will:

1. ✅ Automatically match borrower (any phone format)
2. ✅ Automatically match loan
3. ✅ Create repayment record
4. ✅ Update loan balance
5. ✅ Send notifications
6. ✅ Appear in `/loans/repayments/` immediately
7. ✅ Show M-Pesa and Automatic badges

## 📞 Support Commands

### View Unmatched Transactions
```bash
python manage.py shell -c "
from loans.models import MpesaTransaction
unmatched = MpesaTransaction.objects.filter(loan__isnull=True, status='confirmed')
for t in unmatched:
    print(f'{t.trans_id}: {t.phone_number} - {t.processing_notes}')
"
```

### View Recent M-Pesa Repayments
```bash
python manage.py shell -c "
from loans.models import Repayment
mpesa = Repayment.objects.filter(payment_method='mpesa').order_by('-payment_date')[:5]
for r in mpesa:
    print(f'{r.receipt_number}: {r.loan.borrower.get_full_name()} - KES {r.amount}')
"
```

### Check Specific Transaction
```bash
python manage.py shell -c "
from loans.models import MpesaTransaction
t = MpesaTransaction.objects.get(trans_id='YOUR_TRANS_ID')
print(f'Status: {t.status}')
print(f'Borrower: {t.borrower}')
print(f'Loan: {t.loan}')
print(f'Repayment: {t.repayment}')
if t.repayment:
    print(f'Receipt: {t.repayment.receipt_number}')
"
```

---

**Status:** Ready for Production  
**Priority:** Critical - Fixes payment processing  
**Impact:** All M-Pesa payments will work correctly
