# Product Discounts - Quick Start Guide

## Overview
Complete discount system for NexusMart with support for percentage/fixed discounts, date ranges, usage limits, and promo codes.

## What Was Added

### New Files
1. **`shop/discount_views.py`** - Discount utility functions and views
2. **`shop/management/commands/discount_manager.py`** - CLI tool for managing discounts
3. **`DISCOUNT_SYSTEM.md`** - Complete documentation
4. **`DISCOUNT_TEMPLATES.md`** - Template examples and snippets
5. **`shop/migrations/0016_discount_model.py`** - Database migration

### Updated Files
1. **`shop/models.py`** - Added `Discount` model, updated `Order` and `CartItem`
2. **`shop/admin.py`** - Added `DiscountAdmin` interface
3. **`shop/forms.py`** - Added discount-related forms
4. **`shop/urls.py`** - Added discount endpoints

## Step-by-Step Setup

### Step 1: Run Migration
```bash
cd C:\Users\Imokeuklemi\development_projects\nexusmart
python manage.py migrate shop
```

This creates the `shop_discount` table and adds columns to orders.

### Step 2: Access Admin Panel
1. Go to `http://localhost:8000/admin/`
2. Navigate to **Shop > Discounts**
3. Click "Add Discount"

### Step 3: Create Your First Discount

**Example 1: Summer Sale (No Code)**
- Name: "Summer Sale 2026"
- Code: (leave empty - auto-applied)
- Type: Percentage (%)
- Value: 20
- Applicable to: All products (leave empty)
- Active: ✓ Check
- Start Date: Today
- End Date: 30 days from now
- Usage Limit: (leave empty for unlimited)

**Example 2: First Purchase Code**
- Name: "Welcome Bonus"
- Code: "WELCOME500"
- Type: Fixed Amount
- Value: 500
- Applicable to: All products
- Min Purchase: 5000
- Limit per User: 1
- Start Date: Today
- End Date: 90 days from now

### Step 4: Test with CLI Tool
```bash
# See all active discounts
python manage.py discount_manager --action=report

# Create discount via command line
python manage.py discount_manager --action=create \
    --name="Flash Sale" \
    --code="FLASH15" \
    --type=percentage \
    --value=15

# Expire old discounts
python manage.py discount_manager --action=expire
```

## Integration Guide

### For Displaying Discounts on Product Pages

Add this to your product template:

```html
{% with discount=product.get_active_discount %}
    {% if discount %}
        <div class="discount-badge">
            <span>Save {{ discount.discount_value }}%</span>
        </div>
        <p class="original-price">₦{{ product.price }}</p>
        <p class="sale-price">₦{{ discount.calculate_discounted_price }}</p>
    {% endif %}
{% endwith %}
```

### For Discount Code at Checkout

Add form to your checkout page:

```html
<form method="post" action="{% url 'shop:apply_discount_code' %}">
    {% csrf_token %}
    <input type="text" name="code" placeholder="Discount code">
    <button type="submit">Apply</button>
</form>

{% if applied_discount %}
    <div class="alert alert-success">
        Saved ₦{{ discount_amount }} with {{ applied_discount.name }}
    </div>
{% endif %}
```

### For Order Confirmation

Show discount in order details:

```html
<table>
    <tr>
        <td>Subtotal:</td>
        <td>₦{{ order.subtotal }}</td>
    </tr>
    {% if order.discount %}
    <tr>
        <td>Discount ({{ order.discount.name }}):</td>
        <td style="color: green;">-₦{{ order.discount_amount }}</td>
    </tr>
    {% endif %}
    <tr style="font-weight: bold;">
        <td>Total:</td>
        <td>₦{{ order.total }}</td>
    </tr>
</table>
```

## Backend Integration

### In Views (cart_views.py)

Update your checkout view to apply discounts:

```python
from shop.discount_views import calculate_cart_totals, get_applied_discount

@login_required
def checkout(request):
    cart = Cart.objects.get(user=request.user)
    discount = get_applied_discount(request)  # Get discount from session
    totals = calculate_cart_totals(cart, discount)  # Calculate with discount
    
    context = {
        'subtotal': totals['subtotal'],
        'discount_amount': totals['discount_amount'],
        'total': totals['total'],
        'discount': discount,
    }
    return render(request, 'checkout.html', context)
```

### When Creating Orders (order_views.py)

```python
from shop.discount_views import get_applied_discount

def create_order(request):
    # ... order creation logic ...
    
    cart = Cart.objects.get(user=request.user)
    discount = get_applied_discount(request)
    totals = calculate_cart_totals(cart, discount)
    
    order = Order.objects.create(
        user=request.user,
        subtotal=totals['subtotal'],
        discount=discount,
        discount_amount=totals['discount_amount'],
        total=totals['total'],
        # ... other fields ...
    )
    
    # Mark discount as used
    if discount:
        discount.apply()
    
    return order
```

## Usage Examples

### Get Discount Info
```python
from shop.discount_views import get_product_discount_info

info = get_product_discount_info(product)
if info['has_discount']:
    print(f"Original: ₦{info['original_price']}")
    print(f"Sale: ₦{info['discounted_price']}")
    print(f"Save: ₦{info['discount_amount']} ({info['discount_percent']}%)")
```

### Calculate Cart Totals
```python
from shop.discount_views import calculate_cart_totals
from shop.models import Discount

cart = Cart.objects.get(user=request.user)
discount = Discount.objects.get(code='SAVE20')

totals = calculate_cart_totals(cart, discount)
# {
#   'subtotal': Decimal('100000.00'),
#   'discount_amount': Decimal('20000.00'),
#   'total': Decimal('80000.00'),
#   'items_count': 5,
#   'discount': <Discount: SAVE20 - 20%>
# }
```

### Check Discount Validity
```python
discount = Discount.objects.get(id=1)

if discount.is_valid():
    print("Discount is currently active")

if discount.can_user_use(request.user):
    print("User can use this discount")

if discount.is_applicable_to_product(product):
    print("Discount applies to this product")
```

## Common Discount Scenarios

### Black Friday Sale
```
Name: Black Friday 2026
Code: BLACK2026
Type: 30% off
Valid: Nov 1-30, 2026
Applies to: All products
Usage: Unlimited
```

### New Customer Welcome
```
Name: Welcome 500
Code: WELCOME500
Type: ₦500 fixed
Min Purchase: ₦5,000
Usage per User: 1 time only
```

### Category Flash Sale
```
Name: Electronics Flash
Code: (auto-apply)
Type: 15% off
Applies to: Electronics category only
Duration: 24 hours
```

### Loyalty Reward
```
Name: VIP Discount
Code: VIP2026
Type: ₦2,000 off
Min Purchase: ₦50,000
Usage per User: 1 per month (set limit)
```

## Best Practices

✓ **DO:**
- Set realistic discount values
- Set usage limits to control costs
- Use codes for promotional campaigns
- Monitor usage in admin
- Test before going live
- Combine with stock management

✗ **DON'T:**
- Create unlimited 50%+ discounts
- Forget to set end dates
- Allow unlimited uses by default
- Apply contradictory discounts
- Display confusing savings messages
- Let discounts go negative

## Troubleshooting

### Discount not showing in admin
```bash
python manage.py migrate shop
```

### Code not applying
- Check code exists in database
- Check if discount is `is_active=True`
- Check date range
- Check min_purchase requirement

### Wrong discount selected
System picks highest savings; check product/category applicability

## Management Command

```bash
# View all active discounts
python manage.py discount_manager --action=report

# Create discount
python manage.py discount_manager --action=create \
    --name="Test" --code="TEST" --type=percentage --value=10

# Expire old discounts
python manage.py discount_manager --action=expire

# Clean up very old discounts
python manage.py discount_manager --action=cleanup
```

## Next Steps

1. ✓ Run migrations
2. ✓ Create test discount in admin
3. ✓ Update cart templates
4. ✓ Update checkout templates
5. ✓ Update order confirmation templates
6. ✓ Test discount application flow
7. ✓ Test discount codes
8. ✓ Monitor in admin dashboard

## Support Files

- **DISCOUNT_SYSTEM.md** - Complete technical documentation
- **DISCOUNT_TEMPLATES.md** - HTML/template examples
- **shop/discount_views.py** - Core discount logic
- **shop/management/commands/discount_manager.py** - CLI tools

## Questions?

Check the code comments or the complete documentation in:
- `DISCOUNT_SYSTEM.md` - Full feature documentation
- `shop/models.py` - Discount model definition
- `shop/discount_views.py` - Utility function implementations
