forked from divanov11/ecom_steps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm4-p5-s2-cartdatalogic.py
58 lines (44 loc) · 1.47 KB
/
m4-p5-s2-cartdatalogic.py
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
import json
from .models import *
def cookieCart(request):
#Create empty cart for now for non-logged in user
try:
cart = json.loads(request.COOKIES['cart'])
except:
cart = {}
print('CART:', cart)
items = []
order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
cartItems = order['get_cart_items']
for i in cart:
#We use try block to prevent items in cart that may have been removed from causing error
try:
cartItems += cart[i]['quantity']
product = Product.objects.get(id=i)
total = (product.price * cart[i]['quantity'])
order['get_cart_total'] += total
order['get_cart_items'] += cart[i]['quantity']
item = {
'id':product.id,
'product':{'id':product.id,'name':product.name, 'price':product.price,
'imageURL':product.imageURL}, 'quantity':cart[i]['quantity'],
'digital':product.digital,'get_total':total,
}
items.append(item)
if product.digital == False:
order['shipping'] = True
except:
pass
return {'cartItems':cartItems ,'order':order, 'items':items}
def cartData(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
cookieData = cookieCart(request)
cartItems = cookieData['cartItems']
order = cookieData['order']
items = cookieData['items']
return {'cartItems':cartItems ,'order':order, 'items':items}