File size: 1,895 Bytes
985f22c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.utils.timezone import now
from Boxes.models import MysteryBox
from Accounts.models import Profile
from .models import Cart, CartItem, Order, OrderItem, Payment



@login_required
def cart_detail(request):
    """Show all items in the cart"""
    profile = request.user.profile
    cart, created = Cart.objects.get_or_create(user=profile)

    return render(request, "templates/cart.html", {"cart": cart})


@login_required
def cart_add(request, pk):
    """Add an item (MysteryBox) to the cart"""
    profile = request.user.profile
    cart, created = Cart.objects.get_or_create(user=profile)
    box = get_object_or_404(MysteryBox, pk=pk)

    item, created = CartItem.objects.get_or_create(cart=cart, box=box)
    item.quantity += 1 if not created else 1
    item.save()

    return redirect("cart:cart_detail")


@login_required
def cart_remove(request, pk):
    """Remove one item from the cart"""
    profile = request.user.profile
    cart = get_object_or_404(Cart, user=profile)
    item = get_object_or_404(CartItem, cart=cart, pk=pk)
    item.delete()
    return redirect("cart:cart_detail")



@login_required
def checkout(request):
    """Convert cart into an order"""
    profile = request.user.profile
    cart = get_object_or_404(Cart, user=profile)

    if not cart.items.exists():
        return redirect("cart:cart_detail")


    order = Order.objects.create(
        user=profile,
        total_amount=cart.total_amount
    )

    for item in cart.items.all():
        OrderItem.objects.create(
            order=order,
            box=item.box,
            quantity=item.quantity,
            unit_price=item.box.price
        )

    cart.items.all().delete()

    return render(request, "templates/checkout_success.html", {"order": order})