-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcart.py
87 lines (75 loc) · 1.97 KB
/
cart.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import datetime
import store.models
CART_ID = 'CART-ID'
class ItemAlreadyExists(Exception):
pass
class ItemDoesNotExist(Exception):
pass
class Cart:
def __init__(self, request):
cart_id = request.session.get(CART_ID)
if cart_id:
try:
cart = store.models.Cart.objects.get(id=cart_id, checked_out=False)
except store.models.Cart.DoesNotExist:
cart = self.new(request)
else:
cart = self.new(request)
self.cart = cart
def __iter__(self):
for item in self.cart.item_set.all():
yield item
def new(self, request):
cart = store.models.Cart(creation_date=datetime.datetime.now())
cart.save()
request.session[CART_ID] = cart.id
return cart
def add(self, product, unit_price, quantity=1):
print("Adding %s at quantity %s: total %s" % (product, unit_price, quantity))
try:
item = store.models.Item.objects.get(
cart=self.cart,
product=product,
)
except store.models.Item.DoesNotExist:
item = store.models.Item()
item.cart = self.cart
item.product = product
item.unit_price = unit_price
item.quantity = quantity
item.save()
else: #store.models.ItemAlreadyExists
item.unit_price = unit_price
item.quantity = item.quantity + int(quantity)
item.save()
def remove(self, product):
try:
item = store.models.Item.objects.get(
cart=self.cart,
product=product,
)
except store.models.Item.DoesNotExist:
raise store.models.ItemDoesNotExist
else:
item.delete()
def update(self, product, quantity, unit_price=None):
try:
item = store.models.Item.objects.get(
cart=self.cart,
product=product,
)
except store.models.Item.DoesNotExist:
raise store.models.ItemDoesNotExist
def count(self):
result = 0
for item in self.cart.item_set.all():
result += 1 * item.quantity
return result
def summary(self):
result = 0
for item in self.cart.item_set.all():
result += item.total_price
return result
def clear(self):
for item in self.cart.item_set.all():
item.delete()