# Branch PayBill Configuration Guide

## Overview
This system now supports **branch-specific M-Pesa PayBill configurations**. Each branch can have its own PayBill number with unique API credentials. The system will automatically route payments to the correct branch based on the borrower's branch assignment.

## 🔴 Important: NO Default Credentials

**ALL branches (including the main branch) MUST be configured manually by the admin.**

There are no hardcoded or default credentials in the system. Every branch requires:
- M-Pesa Shortcode (PayBill number)
- Consumer Key
- Consumer Secret
- Passkey (for STK Push)

### Example Branch Configurations

**Branch 1 (Main Branch):**
- **PayBill:** `4086675`
- **Consumer Key:** `L00rQYgBd5WrsGYI4a0Agb9P8SSCgaYGA3uF0Dme0IgKsAN5`
- **Consumer Secret:** `nuHpJxybEO0eh3qAlpckBFPzveHEV3A6LUNOl5gUwqIU53I03aIGY4VM1vVHRJDC`

**Branch 2:**
- **PayBill:** `4159523`
- **Consumer Key:** `9mD1A3H1qw5grqdqkZ4X1G9zbNxioydHXL5An4nkUGRlNRKr`
- **Consumer Secret:** `C2dqBSaGFUIporfYYuyhQgnfPEqLvCS3GvfAJ91ENkXI2bhqptlVXAqMelsEpLQR`

## Setup Instructions

### Step 1: Configure Branch M-Pesa Settings

1. **Access Django Admin Panel**
   - Navigate to `/admin/`
   - Go to **Users → Branches**

2. **Edit or Create a Branch**
   - For the main branch, ensure "Is main branch" is checked
   - **REQUIRED:** Fill in ALL M-Pesa Configuration fields:
     - **M-Pesa Shortcode:** Your PayBill number (e.g., 4086675)
     - **M-Pesa Consumer Key:** Your Safaricom API Consumer Key
     - **M-Pesa Consumer Secret:** Your Safaricom API Consumer Secret
     - **M-Pesa Passkey:** (Required for STK Push payments)

3. **Save the Branch**
   - The system will show a 🔴 CRITICAL ERROR if M-Pesa configuration is incomplete
   - **NO branch can process payments without complete configuration**
   - This applies to ALL branches including the main branch

### Step 2: Warning System

The admin interface displays clear warnings for branches without M-Pesa configuration:

- **✓ Configured** (Green) - Branch has complete M-Pesa setup
- **🔴 NOT CONFIGURED** (Red) - Branch cannot process payments (applies to ALL branches)

### Step 3: Assign Borrowers to Branches

1. Go to **Users → Custom users**
2. Edit a borrower/client
3. Set their **Branch** field
4. This ensures their payments go to the correct PayBill

## Payment Processing

### How Branch-Specific Payments Work

1. **Customer makes M-Pesa payment** to their branch's PayBill
2. **System receives callback** with PayBill number and transaction details
3. **System matches customer** by ID number (not phone number)
4. **Payment is processed** only if:
   - Customer's ID number matches a borrower in the system
   - Customer is assigned to a branch
   - Branch has valid M-Pesa configuration

### Payment Routing Logic

```
Payment Received → Match by ID Number → Check Borrower's Branch → Use Branch PayBill Config → Process Payment
```

## Admin Features

### Branch Management Dashboard
- **User Count:** Shows number of users per branch
- **M-Pesa Status:** Visual indicator of configuration status
- **Quick Warnings:** Red badges for unconfigured branches

### Loan Application Preview & Editing
Admins can now **review and edit loan applications before approval**:

1. Go to **Loans → Loan Applications**
2. Click **"Review & Edit"** on pending applications
3. **Preview Panel** shows:
   - Principal Amount
   - Interest Amount
   - Processing Fee
   - Total Amount
   - Duration
   - Borrower Information

4. **Edit as Needed:**
   - Adjust requested amount
   - Change duration
   - Modify interest/fees
   - Add approval notes

5. **Approve or Reject** after review

## Security & Best Practices

### ⚠️ Important Security Notes

1. **Never share API credentials** publicly
2. **Each branch should have unique credentials**
3. **Main branch defaults are pre-configured** - other branches MUST be configured manually
4. **Test in sandbox first** before going live

### Configuration Checklist

- [ ] **EVERY branch** configured with its PayBill credentials
- [ ] **NO default credentials** - Every branch must be manually configured by admin
- [ ] All borrowers assigned to correct branches
- [ ] Test payment from each branch's PayBill
- [ ] Verify NO red "NOT CONFIGURED" warnings in admin

## Troubleshooting

### Branch Shows "NOT CONFIGURED" Warning

**Problem:** Branch cannot process payments
**Solution:** 
1. Go to branch settings in admin
2. Fill in all M-Pesa Configuration fields
3. Ensure credentials are correct
4. Save the branch

### Payment Not Processing

**Problem:** Payment received but not applied to loan
**Solution:**
1. Check borrower has ID number in system
2. Verify borrower is assigned to a branch
3. Confirm branch has M-Pesa configuration
4. Check M-Pesa transaction logs in admin

### Wrong PayBill Receiving Payments

**Problem:** Payments going to wrong branch
**Solution:**
1. Verify borrower's branch assignment
2. Check branch M-Pesa shortcode configuration
3. Ensure C2B URLs are registered for correct PayBill

## Migration from Old System

If you're upgrading from a system with hardcoded credentials:

1. **Identify all active branches**
2. **Configure M-Pesa settings for each branch**
3. **Assign all existing borrowers to branches**
4. **Test payment flow for each branch**
5. **Monitor transactions for first few days**

## API Integration Points

### Files Modified
- `users/models.py` - Branch model with M-Pesa configuration
- `users/admin.py` - Branch admin with warnings and validation
- `payments/branch_mpesa_service.py` - Branch-specific payment processing
- `loans/admin.py` - Loan application preview and editing

### Key Methods
- `Branch.get_mpesa_shortcode()` - Gets branch PayBill
- `Branch.get_mpesa_consumer_key()` - Gets branch API key
- `Branch.get_mpesa_consumer_secret()` - Gets branch API secret
- `Branch.has_mpesa_config()` - Validates branch configuration
- `BranchMpesaService` - Processes payments for specific branch

## Support

For technical support or questions:
1. Check admin warnings and error messages
2. Review M-Pesa transaction logs
3. Verify branch configurations
4. Test with small amounts first

---

**Last Updated:** November 10, 2025
**System Version:** Branch-Specific PayBill v1.0
