22
33from django .conf import settings
44
5+ from coupons .models import Coupon
56from shop .models import Product
67
78
@@ -23,6 +24,8 @@ def __init__(self, request):
2324 # save an empty cart in the session
2425 cart = self .session [settings .CART_SESSION_ID ] = {}
2526 self .cart = cart
27+ # store current applied coupon
28+ self .coupon_id = self .session .get ('coupon_id' )
2629
2730 def add (self , product , quantity = 1 , override_quantity = False ):
2831 """
@@ -34,7 +37,7 @@ def add(self, product, quantity=1, override_quantity=False):
3437 override_quantity: If True, replace the current quantity with the given quantity.
3538 If False, increment the current quantity by the given amount.
3639 """
37- product_id = str (product .id )
40+ product_id = str (product .product_id )
3841 if product_id not in self .cart :
3942 self .cart [product_id ] = {
4043 'quantity' : 0 ,
@@ -53,7 +56,7 @@ def remove(self, product):
5356 Args:
5457 product: The product object to remove from the cart.
5558 """
56- product_id = str (product .id )
59+ product_id = str (product .product_id )
5760 if product_id in self .cart :
5861 del self .cart [product_id ]
5962 self .save ()
@@ -66,10 +69,10 @@ def __iter__(self):
6669 """
6770 product_ids = self .cart .keys ()
6871 # get the product objects and add them to the cart
69- products = Product .objects .filter (id__in = product_ids )
72+ products = Product .objects .filter (product_id__in = product_ids )
7073 cart = self .cart .copy ()
7174 for product in products :
72- cart [str (product .id )]['product' ] = product
75+ cart [str (product .product_id )]['product' ] = product
7376 for item in cart .values ():
7477 item ['price' ] = Decimal (item ['price' ])
7578 item ['total_price' ] = item ['price' ] * item ['quantity' ]
@@ -108,3 +111,42 @@ def clear(self):
108111 """
109112 del self .session [settings .CART_SESSION_ID ]
110113 self .save ()
114+
115+ @property
116+ def coupon (self ):
117+ """
118+ Retrieve the currently applied coupon.
119+
120+ Returns:
121+ Coupon: The applied coupon object if it exists and is valid.
122+ None: If no coupon is applied or the coupon does not exist.
123+ """
124+ if self .coupon_id :
125+ try :
126+ return Coupon .objects .get (id = self .coupon_id )
127+
128+ except Coupon .DoesNotExist :
129+ pass
130+ return None
131+
132+ def get_discount (self ):
133+ """
134+ Calculate the discount amount based on the applied coupon.
135+
136+ Returns:
137+ Decimal: The discount amount to be subtracted from the total price.
138+ """
139+ if self .coupon :
140+ return (
141+ self .coupon .discount / Decimal (100 )
142+ ) * self .get_total_price ()
143+ return Decimal (0 )
144+
145+ def get_total_price_after_discount (self ):
146+ """
147+ Calculate the total price of the cart after applying the discount.
148+
149+ Returns:
150+ Decimal: The total price after the discount is applied.
151+ """
152+ return self .get_total_price () - self .get_discount ()
0 commit comments