# M-Pesa Integration - cPanel Deployment Guide

## 🚀 Quick Deployment Steps

### 1. Upload Files to cPanel
Upload all the modified files to your cPanel server:
- `loans/models.py`
- `loans/views.py` 
- `loans/admin.py`
- `users/models.py`
- `users/views.py`
- `users/admin.py`
- `templates/users/branch_form.html`
- `templates/loans/repayments.html`
- `templates/loans/dashboard.html`
- `templates/base.html`
- `payments/branch_mpesa_service.py`
- `payments/management/commands/setup_production_mpesa.py`
- `payments/management/commands/simulate_mpesa_payment.py`

### 2. Fix Migration Conflicts (if needed)

**Option A: Quick Fix (for simple conflicts)**
```bash
# Quick fix for migration conflicts
python quick_fix_migration.py
```

**Option B: Comprehensive Fix (for complex conflicts)**
```bash
# Comprehensive migration conflict fix
python fix_all_migrations.py
```

**Option C: Skip Migrations Entirely (if all else fails)**
```bash
# Skip problematic migrations and focus on M-Pesa setup
python skip_problematic_migrations.py
```

### 3. Run the Deployment Script

**Option A: Interactive Script (with confirmation prompt)**
```bash
# SSH into your cPanel server or use Terminal in cPanel
cd /home/yourusername/public_html/yourproject
python deploy_mpesa_production.py
```

**Option B: Auto Script (no user input required)**
```bash
# For non-interactive environments or automated deployment
cd /home/yourusername/public_html/yourproject
python deploy_mpesa_production_auto.py
```

**Option C: No Migrations Script (if migrations keep failing)**
```bash
# Deploy M-Pesa without running migrations
cd /home/yourusername/public_html/yourproject
python deploy_mpesa_no_migrations.py
```

**Option D: Complete Deployment Script (handles all scenarios)**
```bash
# Complete deployment that handles missing fields and all issues
cd /home/yourusername/public_html/yourproject
python deploy_mpesa_complete.py
```

**The script will:**
- Apply database migrations
- Set up M-Pesa configuration
- Attempt to register C2B URLs
- Display callback URLs for manual registration

### 3. Manual Steps (if needed)

**Note:** The deployment script handles these automatically, but you can run them manually if needed:

#### A. Apply Database Migrations
```bash
python manage.py migrate
```

#### B. Set up M-Pesa Configuration
```bash
python manage.py setup_production_mpesa --update-branches
```

#### C. Register C2B URLs in M-Pesa Portal
Go to your M-Pesa Daraja portal and register these URLs:

**Confirmation URL:**
```
https://branchbusinessadvance.co.ke/payments/callback/confirmation/
```

**Validation URL:**
```
https://branchbusinessadvance.co.ke/payments/callback/validation/
```

**Response Type:** `Completed`

### 4. Test the Integration

#### A. Test with Simulation
```bash
python manage.py simulate_mpesa_payment --amount 1 --customer-id 22812438
```

#### B. Test with Real Payment
1. Send 1 KSH to paybill: `4159523`
2. Use account number: `22812438` (Aaron Carlson's ID Number)
3. Check the repayments page to see if payment appears

### 5. Verify Everything Works

1. **Check Repayments Page:**
   - Go to `/loans/repayments/`
   - Use "Payment Source" filter to view "Automatic M-Pesa" payments
   - You should see the test payment

2. **Check Branch Configuration:**
   - Go to branch management
   - Edit a branch to see M-Pesa configuration section
   - Only shortcode should be configurable

3. **Check Admin Interface:**
   - Go to Django admin
   - Check M-Pesa transactions and repayments
   - Should see automatic vs manual payment distinction

## 🔧 Production Configuration

### M-Pesa Credentials (Already Set)
- **Consumer Key:** `9mD1A3H1qw5grqdqkZ4X1G9zbNxioydHXL5An4nkUGRlNRKr`
- **Consumer Secret:** `C2dqBSaGFUIporfYYuyhQgnfPEqLvCS3GvfAJ91ENkXI2bhqptlVXAqMelsEpLQR`
- **Shortcode:** `4159523`

### Branch Configuration
- Each branch can have its own shortcode
- Other credentials are shared across all branches
- Default shortcode is `4159523`

## 🚨 Important Notes

1. **Domain:** Your domain is already configured as `branchbusinessadvance.co.ke`
2. **HTTPS Required:** M-Pesa requires HTTPS for production callbacks
3. **Firewall:** Ensure your server can receive incoming requests from M-Pesa
4. **Logs:** Check server logs if payments don't appear

## 🆘 Troubleshooting

### Migration Issues
- **"Duplicate column name" error:** Run `python quick_fix_migration.py`
- **"Can't DROP index" error:** Run `python fix_all_migrations.py`
- **All migration fixes fail:** Run `python deploy_mpesa_no_migrations.py`
- **"Unknown column" error:** Run `python deploy_mpesa_complete.py`

### Payment Not Appearing?
1. Check server logs for M-Pesa callback errors
2. Verify C2B URLs are registered correctly
3. Test with simulation first
4. Check database for M-Pesa transactions

### C2B Registration Failed?
1. Register URLs manually in M-Pesa portal
2. Ensure URLs are accessible from internet
3. Check SSL certificate is valid

### Deployment Script Issues
- **EOF Error:** Use `deploy_mpesa_production_auto.py` instead of the interactive version
- **Migration conflicts:** Use `deploy_mpesa_no_migrations.py` to skip migrations entirely
- **Permission errors:** Ensure your user has write permissions to the Django project directory
- **C2B URL registration fails:** Use `python test_mpesa_integration.py` to test and get manual steps
- **400 Bad Request errors:** Use `python check_mpesa_credentials.py` to verify credentials

### Access Token Issues?
1. Verify consumer key and secret are correct
2. Check network connectivity to M-Pesa API
3. Ensure production environment is set

## ✅ Deployment Successful!

If you see "Complete deployment successful!" in your output, your M-Pesa integration is ready! The only remaining step is manual C2B URL registration.

### Final Steps After Successful Deployment:

1. **Register C2B URLs manually in M-Pesa portal:**
   - Go to https://developer.safaricom.co.ke/
   - Navigate to C2B API section
   - Register these URLs:
     - Confirmation URL: `https://branchbusinessadvance.co.ke/payments/callback/confirmation/`
     - Validation URL: `https://branchbusinessadvance.co.ke/payments/callback/validation/`
     - Response Type: `Completed`

2. **Test the integration:**
   ```bash
   # Test the integration
   python test_mpesa_integration.py
   ```

3. **Test with real payment:**
   - Send 1 KSH to PayBill: `4159523`
   - Use Account Number: `22812438` (Aaron Carlson's ID)
   - Check repayments page for automatic payment

## 📞 Support

If you encounter issues:
1. Check the deployment script output
2. Review server error logs
3. Test with simulation before real payments
4. Verify all URLs are accessible

---

**Ready to deploy? Run the deployment script and follow the prompts!**
