2023-05-28 15:06:50 +00:00
|
|
|
from typing import Any, Dict
|
|
|
|
|
|
|
|
from django.views.generic import TemplateView
|
|
|
|
from rest_framework.viewsets import ViewSet
|
|
|
|
from rest_framework.decorators import action
|
|
|
|
from rest_framework.response import Response
|
|
|
|
|
|
|
|
from store.cart import SessionCart
|
|
|
|
from store.serializers import (
|
|
|
|
CartProductSerializer,
|
|
|
|
CartProductAddSerializer
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class CartView(TemplateView):
|
|
|
|
"""
|
|
|
|
This view should simply render cart with initial data, it'll do that each refresh, for
|
|
|
|
making actions on cart (using jquery) we will use CartActionView, which will
|
|
|
|
be prepared to return JsonResponse.
|
|
|
|
"""
|
2023-05-25 01:16:01 +00:00
|
|
|
template_name = 'store/cart.html'
|
|
|
|
|
|
|
|
|
2023-05-28 15:06:50 +00:00
|
|
|
def get_context_data(self, **kwargs: Any) -> Dict[str, Any]:
|
|
|
|
context = super().get_context_data(**kwargs)
|
|
|
|
context["cart"] = SessionCart(self.request)
|
|
|
|
return context
|
|
|
|
|
|
|
|
|
|
|
|
class CartActionView(ViewSet):
|
|
|
|
|
|
|
|
@action(detail=False, methods=["get"], url_path="list-products")
|
|
|
|
def list_products(self, request):
|
|
|
|
# get cart items
|
|
|
|
cart = SessionCart(self.request)
|
|
|
|
items = cart.get_items()
|
2023-05-28 16:35:08 +00:00
|
|
|
serializer = CartProductSerializer(instance=items, many=True)
|
|
|
|
return Response(serializer.data)
|
2023-05-28 15:06:50 +00:00
|
|
|
|
|
|
|
@action(detail=False, methods=["post"])
|
|
|
|
def add_product(self, request):
|
|
|
|
cart = SessionCart(self.request)
|
|
|
|
serializer = CartProductAddSerializer(data=request.POST)
|
2023-05-28 16:35:08 +00:00
|
|
|
if not serializer.is_valid():
|
2023-05-28 15:06:50 +00:00
|
|
|
return Response(serializer.errors, status=400)
|
|
|
|
serializer.save(cart)
|
|
|
|
|
|
|
|
items = cart.get_items()
|
2023-05-28 16:35:08 +00:00
|
|
|
serializer = CartProductSerializer(instance=items, many=True)
|
|
|
|
return Response(serializer.data, status=201)
|
2023-05-28 15:06:50 +00:00
|
|
|
|
2023-05-28 16:35:08 +00:00
|
|
|
@action(detail=False, methods=["post"])
|
|
|
|
def remove_product(self, request):
|
|
|
|
cart = SessionCart(self.request)
|
|
|
|
product_id = request.POST.get("product_id")
|
|
|
|
cart.remove_item(product_id)
|
|
|
|
|
|
|
|
items = cart.get_items()
|
|
|
|
serializer = CartProductSerializer(instance=items, many=True)
|
|
|
|
return Response(serializer.data, status=201)
|