# INSTALLMENT PAYMENT SYSTEM - QUICK START

## What You Get

A complete automatic installment payment system where:
- Customers choose to pay in 3, 6, or 12 months
- They enter their card ONCE and authorize recurring charges
- Your system automatically charges their card monthly
- Failed payments retry automatically
- Customers can manage payments from their dashboard

**Example**: $600 phone → $100/month for 6 months (automatic)

---

## Quick Setup (5 Steps)

### Step 1: Update Django URLs

Add to `nexusmart/urls.py`:

```python
urlpatterns = [
    # ... existing patterns ...
    path('installment/', include('shop.installment_urls')),
]
```

### Step 2: Add Automatic Payment Processing

Choose one method:

**Option A: Celery (Production)**
```python
# shop/tasks.py
from celery import shared_task
from django.core.management import call_command

@shared_task
def process_monthly_payments():
    call_command('process_installment_payments')

# settings.py - Add to CELERY_BEAT_SCHEDULE:
'process-installment-payments': {
    'task': 'shop.tasks.process_monthly_payments',
    'schedule': crontab(hour=2, minute=0),  # Daily at 2 AM
}
```

**Option B: Simple Cron (Development)**
```bash
# Run this daily (add to crontab)
python manage.py process_installment_payments

# Test it with:
python manage.py process_installment_payments --dry-run
```

### Step 3: Update Order Views

Link your checkout to installment flow. Update your checkout view:

```python
def checkout(request):
    num_installments = request.POST.get('num_installments', '1')
    if int(num_installments) > 1:
        return redirect('installment:checkout')
    # ... rest of checkout
```

### Step 4: Add Navigation Link

In `navbar.html`, add:
```html
<a href="{% url 'installment:checkout' %}" class="nav-link">
    <i class="fas fa-credit-card"></i> Payment Plans
</a>
```

### Step 5: Test It

```bash
# Create a test order in admin
# Set it to installment (3 months)
# Manually run:
python manage.py process_installment_payments

# Or use --dry-run first:
python manage.py process_installment_payments --dry-run
```

---

## Customer Experience

### 1. Browse and Add to Cart
Customer shops normally

### 2. Checkout with Payment Plan
- Click "Checkout"
- Select "6 Monthly Payments"
- See: $100/month
- Click "Continue"

### 3. Authorize Card (One Time)
- Redirected to Flutterwave
- Enters card details
- Card is tokenized
- Returns to confirmation

### 4. First Payment
- Order is confirmed
- First payment charged immediately

### 5. Automatic Monthly Charges
- System charges $100 on day 1 of months 2-6
- Customer receives email confirmation each time
- If card fails, system retries automatically
- Customer can update card anytime

### 6. View Payment Schedule
- Customer goes to their order
- Sees all payments (paid, upcoming, failed)
- Can retry failed payments
- Can update payment method

---

## File Structure

```
shop/
├── installment_views.py          ← NEW: All checkout & payment logic
├── installment_urls.py           ← NEW: URL patterns
├── installment_forms.py          ← NEW: Form validation
├── management/
│   └── commands/
│       └── process_installment_payments.py  ← NEW: Automatic charging
└── models.py                     ← Already has InstallmentSchedule, etc.

templates/
└── shop/
    ├── checkout_installment.html           ← NEW
    ├── setup_installment.html              ← NEW
    ├── installment_schedule.html           ← NEW
    ├── retry_payment.html                  ← NEW
    ├── update_payment_method.html          ← NEW
    └── emails/
        ├── payment_success.html            ← NEW
        ├── payment_failure.html            ← NEW
        └── payment_suspended.html          ← NEW
```

---

## How Automatic Charging Works

```
Daily at 2 AM:
  ├─ System checks for payments due today
  ├─ For each payment:
  │  ├─ Verify customer's saved card token exists
  │  ├─ Call Flutterwave API to charge card
  │  ├─ If successful:
  │  │  ├─ Mark payment as successful
  │  │  ├─ Send success email
  │  │  └─ Update schedule progress
  │  └─ If failed:
  │     ├─ Retry in 5 mins (if first failure)
  │     ├─ Retry in 15 mins (if second failure)
  │     ├─ Retry in 60 mins (if third failure)
  │     └─ After 3 failures: Suspend + Email customer
  └─ Done

Customer can also:
  - Manually retry from dashboard
  - Update card to fix failures
  - View full payment history
```

---

## Database Models (Already Exist)

```python
# Order model has:
- payment_type = 'full' or 'installment'
- total_installments = number of months
- installments_paid = how many paid
- flutterwave_token = saved card token

# InstallmentSchedule tracks:
- order
- payment_token (saved card)
- installment_amount (monthly charge)
- total_installments
- paid_installments
- status (active/completed/suspended)
- next_payment_date

# ScheduledPayment is each individual payment:
- installment_number (1st, 2nd, 3rd...)
- amount
- due_date
- status (pending/successful/failed)
- retry_count
- error_message (if failed)
```

---

## Key Features

✅ **Fully Automatic** - No manual intervention needed  
✅ **Retry Logic** - Handles failed cards automatically  
✅ **Secure** - Card details never stored on your server  
✅ **Customer Dashboard** - Track all payments  
✅ **Email Notifications** - Keep customers informed  
✅ **Admin Control** - Manage schedules from admin  
✅ **Flexible** - 1, 3, 6, or 12 month options  
✅ **Flutterwave Ready** - Uses your existing gateway  

---

## Common Questions

**Q: Where is the customer's card stored?**
A: Only on Flutterwave servers. You store a token pointing to it.

**Q: What if a payment fails?**
A: System retries automatically (5 min, 15 min, 60 min). Customer gets emails.

**Q: Can customers cancel?**
A: They can suspend the schedule from dashboard (implement in next version).

**Q: What about failed cards?**
A: Customer updates payment method from dashboard. New card used for future payments.

**Q: How often does it charge?**
A: Every month on the same day they signed up (handles different month lengths).

**Q: Can I charge more or less?**
A: Yes, you can customize in admin - change installment_amount before next charge.

---

## Testing Commands

```bash
# See what would be charged (no actual charges)
python manage.py process_installment_payments --dry-run

# Process only specific order
python manage.py process_installment_payments --order-id=5

# Process only specific schedule
python manage.py process_installment_payments --schedule-id=3

# Enable verbose output
python manage.py process_installment_payments --verbose

# Run in production
python manage.py process_installment_payments
```

---

## Production Deployment

1. Update URLs ✓
2. Set up daily cron/celery task ✓
3. Test with dry-run ✓
4. Monitor first few days ✓
5. Check logs regularly ✓
6. Email admin on failures ✓

---

## Next Steps

1. ✅ Review the implementation files
2. ✅ Update URLs in your main Django config
3. ✅ Set up automated payment processing
4. ✅ Test with a test order
5. ✅ Update your navbar with link to installment checkout
6. ✅ Create admin dashboard for monitoring

---

## Troubleshooting

**Payments not processing?**
- Run: `python manage.py process_installment_payments --dry-run`
- Check: Is the scheduled_payment due_date <= today?
- Check: Does the payment_token exist and is_authorized=True?
- Check: Are your Flutterwave API keys correct?

**Customer not receiving emails?**
- Verify EMAIL_BACKEND in settings.py is configured
- Check if email templates exist
- Test: `python manage.py shell` → `send_mail(...)`

**Card declined?**
- Customer needs to update payment method
- Redirect them: `installment/payment/update-method/{order_id}/`

---

## Support

Read the full guide: `INSTALLMENT_SYSTEM_GUIDE.md`

For Flutterwave issues: https://developer.flutterwave.com
For Django issues: https://docs.djangoproject.com
