# M-Pesa Payment Mapping System - How It Works

## 🔍 **Payment Mapping Process**

### 1. **Customer Makes Payment**
- Customer sends money to paybill: `4159523`
- Uses their **ID Number** as account number (e.g., `22812438`)
- M-Pesa sends callback to your system

### 2. **System Receives Payment**
- M-Pesa sends confirmation to: `https://branchbusinessadvance.co.ke/payments/mpesa/confirmation/`
- System creates `MpesaTransaction` record
- `bill_ref_number` = Customer's ID Number (e.g., `22812438`)

### 3. **Customer Matching Process**
The system tries to match the customer in this order:

#### **Step 1: Match by ID Number**
```python
# Primary matching method
borrower = User.objects.get(id_number=bill_ref_number, role='borrower')
```
- Uses the `bill_ref_number` (account number) to find customer by ID number
- This is the **primary method** for new payments

#### **Step 2: Fallback - Match by Phone Number**
```python
# Fallback method
borrower = User.objects.get(phone_number=phone_variant, role='borrower')
```
- If ID number matching fails, tries phone number matching
- Handles different phone number formats (254, +254, 0)

### 4. **Loan Matching Process**
Once customer is found, system finds the loan:

#### **Step 1: Match by Loan Number**
```python
# If bill_ref_number matches a loan number
loan = active_loans.filter(loan_number=bill_ref_number).first()
```

#### **Step 2: Single Active Loan**
```python
# If customer has only one active loan
if active_loans.count() == 1:
    loan = active_loans.first()
```

#### **Step 3: Multiple Loans - Priority by Due Date**
```python
# Order loans by due date (closest deadline first)
active_loans = Loan.active_objects.filter(
    borrower=borrower,
    status='active'
).order_by('due_date')
```

### 5. **Payment Allocation Logic**
For customers with multiple loans:

1. **Pay loan closest to deadline first**
2. **If payment exceeds loan amount:**
   - Pay off the first loan completely
   - Apply remaining amount to next loan
   - Continue until all payment is allocated

3. **Create repayment records:**
   - One repayment per loan paid
   - Mark as "Automatic M-Pesa" source
   - Link to M-Pesa transaction

## 📱 **Example: Aaron Carlson Payment**

### Customer Details:
- **Name:** Aaron Carlson
- **ID Number:** `22812438`
- **Phone:** `+254751703458`
- **Active Loan:** LOAN-003343 (KES 31,799.00, Due: 2025-11-21)

### Payment Process:
1. **Customer sends:** 1 KSH to paybill `4159523`
2. **Account number:** `22812438` (Aaron's ID number)
3. **System matches:** `User.objects.get(id_number='22812438')`
4. **Finds loan:** LOAN-003343 (only active loan)
5. **Creates repayment:** KES 1.00 to LOAN-003343
6. **Updates loan balance:** 31,799.00 - 1.00 = 31,798.00

## 🎯 **Key Benefits**

### **For Customers:**
- **Simple:** Just use their ID number as account number
- **No confusion:** No need to remember database IDs
- **Automatic:** Payment appears in system immediately

### **For System:**
- **Accurate matching:** ID numbers are unique and reliable
- **Smart allocation:** Automatically pays loans by priority
- **Audit trail:** Complete transaction history
- **Error handling:** Fallback to phone number matching

## 🔧 **Configuration**

### **Branch-Specific Settings:**
- Each branch can have its own M-Pesa shortcode
- Default shortcode: `4159523`
- Other credentials shared across branches

### **Payment Sources:**
- **Automatic:** M-Pesa payments (green badge)
- **Manual:** Admin-entered payments (yellow badge)

## 🚨 **Important Notes**

1. **ID Numbers Must Be Unique:** Each customer must have a unique ID number
2. **Phone Number Fallback:** System can still match by phone if ID number fails
3. **Loan Priority:** Always pays loans closest to deadline first
4. **Multiple Repayments:** One payment can create multiple repayments for multiple loans

## 📊 **Monitoring**

### **Check Payment Status:**
1. Go to `/loans/repayments/`
2. Filter by "Payment Source: Automatic M-Pesa"
3. Look for payments with "Automatic" badge

### **View Transaction Details:**
1. Go to Django admin
2. Check `MpesaTransaction` records
3. See processing notes and matching details

---

## 🎉 **Ready for Production!**

**Test Payment Instructions:**
- **Paybill:** `4159523`
- **Account Number:** `22812438` (Aaron Carlson's ID Number)
- **Amount:** 1 KSH (for testing)

The payment will automatically appear in your system! 🚀
