|
| 1 | +from decimal import Decimal |
| 2 | +from django.conf import settings |
| 3 | +from django.shortcuts import get_object_or_404 |
| 4 | +from products.models import Product |
| 5 | + |
| 6 | + |
| 7 | +def bag_contents(request): |
| 8 | + |
| 9 | + bag_items = [] |
| 10 | + total = 0 |
| 11 | + product_count = 0 |
| 12 | + bag = request.session.get('bag', {}) |
| 13 | + |
| 14 | + for item_id, item_data in bag.items(): |
| 15 | + |
| 16 | + if isinstance(item_data, int): |
| 17 | + product = get_object_or_404(Product, pk=item_id) |
| 18 | + total += item_data * product.price |
| 19 | + product_count += item_data |
| 20 | + bag_items.append({ |
| 21 | + 'item_id': item_id, |
| 22 | + 'quantity': item_data, |
| 23 | + 'product': product, |
| 24 | + }) |
| 25 | + |
| 26 | + else: |
| 27 | + product = get_object_or_404(Product, pk=item_id) |
| 28 | + for size, quantity in item_data['items_by_size'].items(): |
| 29 | + total += quantity * product.price |
| 30 | + product_count += quantity |
| 31 | + bag_items.append({ |
| 32 | + 'item_id': item_id, |
| 33 | + 'quantity': quantity, |
| 34 | + 'product': product, |
| 35 | + 'size': size, |
| 36 | + }) |
| 37 | + |
| 38 | + if total < settings.FREE_DELIVERY_THRESHOLD: |
| 39 | + delivery = total * Decimal(settings.STANDARD_DELIVERY_PERCENTAGE / 100) |
| 40 | + free_delivery_delta = settings.FREE_DELIVERY_THRESHOLD - total |
| 41 | + else: |
| 42 | + delivery = 0 |
| 43 | + free_delivery_delta = 0 |
| 44 | + |
| 45 | + grand_total = delivery + total |
| 46 | + |
| 47 | + context = { |
| 48 | + 'bag_items': bag_items, |
| 49 | + 'total': total, |
| 50 | + 'product_count': product_count, |
| 51 | + 'delivery': delivery, |
| 52 | + 'free_delivery_delta': free_delivery_delta, |
| 53 | + 'free_delivery_threshold': settings.FREE_DELIVERY_THRESHOLD, |
| 54 | + 'grand_total': grand_total, |
| 55 | + } |
| 56 | + |
| 57 | + return context |
0 commit comments