Coverage for cart/cart.py: 0.00%
42 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-02 20:31 -0700
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-02 20:31 -0700
1from decimal import Decimal
3from django.conf import settings
5from shop.models import Product
8class Cart:
9 def __init__(self, request):
10 """
11 Initialize the cart.
12 """
13 self.session = request.session
14 cart = self.session.get(settings.CART_SESSION_ID)
15 if not cart:
16 # save an empty cart in the session
17 cart = self.session[settings.CART_SESSION_ID] = {}
18 self.cart = cart
20 def __iter__(self):
21 """
22 Iterate over the items in the cart and get the products
23 from the database.
24 """
25 product_ids = self.cart.keys()
26 # get the product objects and add them to the cart
27 products = Product.objects.filter(id__in=product_ids)
28 cart = self.cart.copy()
29 for product in products:
30 cart[str(product.id)]["product"] = product
31 for item in cart.values():
32 item["price"] = Decimal(item["price"])
33 item["total_price"] = item["price"] * item["quantity"]
34 yield item
36 def __len__(self):
37 """
38 Count all items in the cart.
39 """
40 return sum(item["quantity"] for item in self.cart.values())
42 def add(self, product, quantity=1, override_quantity=False):
43 """
44 Add a product to the cart or update its quantity.
45 """
46 product_id = str(product.id)
47 if product_id not in self.cart:
48 self.cart[product_id] = {"quantity": 0, "price": str(product.price)}
49 if override_quantity:
50 self.cart[product_id]["quantity"] = quantity
51 else:
52 self.cart[product_id]["quantity"] += quantity
53 self.save()
55 def save(self):
56 # mark the session as "modified" to make sure it gets saved
57 self.session.modified = True
59 def remove(self, product):
60 """
61 Remove a product from the cart.
62 """
63 product_id = str(product.id)
64 if product_id in self.cart:
65 del self.cart[product_id]
66 self.save()
68 def clear(self):
69 # remove cart from session
70 del self.session[settings.CART_SESSION_ID]
71 self.save()
73 def get_total_price(self):
74 return sum(
75 Decimal(item["price"]) * item["quantity"] for item in self.cart.values()
76 )