28 lines
959 B
Python
28 lines
959 B
Python
#python imports
|
|
from typing import List
|
|
from dataclasses import dataclass, field
|
|
|
|
#dependency imports
|
|
from .cart_item import CartItem
|
|
from .product import Product
|
|
|
|
@dataclass
|
|
class Cart:
|
|
items: List[CartItem]
|
|
total_price: float = field(init=False, default=0.0)
|
|
|
|
def add_item(self, product: Product, quantity: int):
|
|
for item in self.items:
|
|
if item.product.id == product.id:
|
|
item.quantity += quantity
|
|
return
|
|
self.items.append(CartItem(product=product, quantity=quantity))
|
|
|
|
def remove_item(self, product_id: str):
|
|
self.items = [item for item in self.items if item.product.id != product_id]
|
|
|
|
def calculate_total_price(self) -> float:
|
|
self.total_price = sum(item.calculate_total_price() for item in self.items)
|
|
|
|
def list_items(self) -> List[str]:
|
|
return [f"{item.quantity} x {item.product.name} - {item.calculate_total_price()} EUR" for item in self.items] |