# Quick Fix Commands for M-Pesa Payments

## 🚀 Easiest Method (Recommended)

### Fix All Unmatched Payments
```bash
cd /home/acbptxvs/public_html/branchbusinessadvance.co.ke
python manage.py fix_mpesa_payments
```

This will:
- Find all unmatched M-Pesa transactions
- Show you what will be processed
- Ask for confirmation
- Process all transactions
- Show detailed results

### Dry Run (See What Would Happen)
```bash
python manage.py fix_mpesa_payments --dry-run
```

---

## 📋 Alternative Methods

### Method 1: Reprocess All Pending
```bash
python manage.py reprocess_mpesa_transaction --all-pending
```

### Method 2: Reprocess Specific Transaction
```bash
# By Transaction ID
python manage.py reprocess_mpesa_transaction <TRANSACTION_ID>

# Example:
python manage.py reprocess_mpesa_transaction 1020ad2a-9134-4735-b5be-c55dd653deb8
```

---

## 🔍 Check Status Commands

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

### 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')[:10]
print(f'Recent M-Pesa repayments:')
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.filter(trans_id='YOUR_TRANS_ID').first()
if t:
    print(f'Transaction: {t.trans_id}')
    print(f'Status: {t.status}')
    print(f'Borrower: {t.borrower or \"Not matched\"}')
    print(f'Loan: {t.loan or \"Not matched\"}')
    print(f'Repayment: {t.repayment or \"Not created\"}')
    if t.repayment:
        print(f'Receipt: {t.repayment.receipt_number}')
    print(f'Notes: {t.processing_notes}')
else:
    print('Transaction not found')
"
```

---

## 📤 Files to Upload

Before running commands, upload these files:

1. **`loans/models.py`** (fixed phone matching)
2. **`payments/management/commands/reprocess_mpesa_transaction.py`** (reprocess command)
3. **`payments/management/commands/fix_mpesa_payments.py`** (easy fix command)

---

## 🔄 Complete Fix Workflow

### Step 1: Upload Files
```bash
# Via cPanel File Manager or SCP
# Upload the 3 files above
```

### Step 2: Restart Application
```bash
touch /home/acbptxvs/public_html/branchbusinessadvance.co.ke/passenger_wsgi.py
```

### Step 3: Check What Needs Fixing
```bash
python manage.py fix_mpesa_payments --dry-run
```

### Step 4: Fix All Unmatched Payments
```bash
python manage.py fix_mpesa_payments
# Type 'yes' when prompted
```

### Step 5: Verify Results
```bash
# Check repayments page
# Visit: https://branchbusinessadvance.co.ke/loans/repayments/
# Filter by: Payment Method = M-Pesa
```

---

## ✅ Success Indicators

After running the fix command, you should see:

```
======================================================================
SUMMARY
======================================================================
Total Transactions: 1
Successfully Processed: 1
Failed/Partial: 0

✓ Payments have been processed!

You can now view them at:
  • /loans/repayments/ - All repayments including M-Pesa
  • /payments/transactions/ - M-Pesa transaction details
  • /loans/ - Updated loan balances
```

---

## 🆘 If Something Goes Wrong

### Error: "No module named 'loans'"
**Fix:** Make sure you're in the correct directory
```bash
cd /home/acbptxvs/public_html/branchbusinessadvance.co.ke
```

### Error: "Transaction not found"
**Fix:** Check the transaction ID is correct
```bash
# List all unmatched transactions
python manage.py shell -c "
from loans.models import MpesaTransaction
for t in MpesaTransaction.objects.filter(loan__isnull=True):
    print(t.id, t.trans_id)
"
```

### Error: "Could not match phone number"
**Fix:** Check the user's phone number format
```bash
python manage.py shell -c "
from users.models import User
# Replace with the phone number from M-Pesa
phone = '254114565176'
users = User.objects.filter(phone_number__contains='114565176')
for u in users:
    print(f'{u.get_full_name()}: {u.phone_number}')
"
```

---

## 📞 Quick Support Snippets

### Normalize All Phone Numbers
```python
# Django shell
from users.models import User

borrowers = User.objects.filter(role='borrower')
for b in borrowers:
    if b.phone_number:
        clean = ''.join(filter(str.isdigit, b.phone_number))
        if clean.startswith('0'):
            b.phone_number = '+254' + clean[1:]
        elif clean.startswith('254'):
            b.phone_number = '+' + clean
        else:
            b.phone_number = '+254' + clean
        b.save()
        print(f"Updated: {b.get_full_name()} -> {b.phone_number}")
```

### Force Reprocess Specific Transaction
```python
# Django shell
from loans.models import MpesaTransaction

t = MpesaTransaction.objects.get(trans_id='YOUR_TRANS_ID')
t.borrower = None
t.loan = None
t.processing_notes = ''
t.save()
success = t.process_payment()
print(f"Success: {success}")
print(f"Borrower: {t.borrower}")
print(f"Loan: {t.loan}")
print(f"Repayment: {t.repayment}")
```

---

## 🎯 Most Common Command

For 99% of cases, just run:

```bash
cd /home/acbptxvs/public_html/branchbusinessadvance.co.ke
python manage.py fix_mpesa_payments
```

That's it! ✅
