Ejemplo n.º 1
0
def ajax_cart_update(request):
    """
    This method is called from JQuery.  it updates the Cart
    When 
    """
    response = HttpResponseBadRequest()
    result = {}
    request_is_valid = len(request.POST) > 0
    if request_is_valid:

        postdata = request.POST.copy()
        product_id = int(postdata['product_id'])
        quantity = int(postdata['quantity'])
        if product_id is not None and quantity is not None:
            user_cart = CartService.get_user_cart(request)
            result = user_cart.update_cart(item_id=product_id,
                                           quantity=quantity)
            result['count'] = CartService.items_count(user_cart.id)
            result['total'] = CartService.get_subtotal(user_cart.id)
            response = result

        else:
            return HttpResponseBadRequest()
    else:
        return HttpResponseBadRequest()
    return HttpResponse(json.dumps(response), content_type="application/json")
Ejemplo n.º 2
0
def show_cart(request):
    template_name = "cart/cart_flat.html"
    user_cart = CartService.get_user_cart(request)
    # checkout_url = checkout.get_checkout_url(request)
    match = resolve('/order/checkout/')

    if request.method == "POST":
        postdata = request.POST.copy()
        item_id = postdata['item_id']
        quantity = postdata['quantity']
        if postdata['submit'] == 'Supprimer':
            user_cart.remove_from_cart(item_id)
        elif postdata['submit'] == 'Actualiser':
            user_cart.update_quantity(item_id=item_id, quantity=int(quantity))

    cart_items = user_cart.get_items()
    page_title = 'Panier' + " - " + settings.SITE_NAME
    cart_subtotal = CartService.get_subtotal(user_cart.id)
    cart_item_count = CartService.items_count(user_cart.id)

    context = {
        'cart_items': cart_items,
        'page_title': page_title,
        'cart_item_count': cart_item_count,
        'cart_subtotal': cart_subtotal,
        'checkout_url': match.url_name,
    }

    return render(request=request,
                  template_name=template_name,
                  context=context)
Ejemplo n.º 3
0
def cart_box(request):
    context = {}
    if request.user.is_authenticated():
        cart = CartService.get_cart(request.user)
        count = CartService.items_count(cart.id)
        cartItems = cart.get_items()
    else:
        count = 0
        cartItems = None
    context = {'count': count, 'cartItems': cartItems}
    return context
Ejemplo n.º 4
0
    def add_to_cart(self, product, quantity=1):
        """
        Add a new product into the Shopping Cart.
        If the product is already in the cart then
        update the quantity.
        If not then create a new CartItem and set
        appropriate value for its variable and save.
        This method does nothing when 'quantity' <  1
        """
        added = False
        if quantity >= 0:
            if CartService.contains_item(self.id, product.id):
                print("Product Already in Cart")
                # ci = CartItem.objects.get(product=product)
                # ci = CartItem.objects.get(cart=self, product=product)
                ci = self.cartitem_set.get(product=product)
                added = self.update_quantity(ci.id, quantity)

            # check if this product is already in the cart.
            # if yes, then check if 'quantity' is not greater than
            # that we have in stock.
            # if it is lower then update the quantity in stock

            else:
                # create and save a new cart item
                if (quantity <= (product.quantity - product.sell_quantity)):
                    item = CartItem()
                    item.set_product(product)
                    # this might throw an exception
                    item.set_quantity(quantity)
                    item.set_cart(self)
                    item.save()
                    added = True
        return added
Ejemplo n.º 5
0
def ajax_add_to_cart(request):

    response = {}
    response['state'] = False
    added = False
    request_is_valid = len(request.POST) > 0
    if request_is_valid:
        postdata = request.POST.copy()
        product_id = postdata['product_id']
        quantity = postdata['quantity']
        if product_id:
            user_cart = CartService.get_user_cart(request)
            p = Product.objects.get(pk=product_id)
            added = user_cart.add_to_cart(product=p, quantity=int(quantity))
            if added is True:
                response['state'] = True
                response['count'] = CartService.items_count(user_cart.id)
                response['total'] = CartService.get_subtotal(user_cart.id)
            else:
                return HttpResponseBadRequest()
    return HttpResponse(json.dumps(response), content_type="application/json")
Ejemplo n.º 6
0
    def items_count(self):
        """
        Return the number of items present in the Cart.
        Deprecated : use CartService.items_count()
        from cart.cart_service instead
        """
        """
        count = 0
        start_time = datetime.datetime.now()
        items = self.get_items()
        for item in items:
            count += item.quantity

        end_time = datetime.datetime.now()
        elapsed_time = end_time - start_time
        print("Cart : items_count() processing time : {0} ms".format(elapsed_time.microseconds / 1000))
        """
        return CartService.items_count(self.id)
Ejemplo n.º 7
0
    def subtotal(self):
        """
        Return the subtotal amount for the
        items available in the Cart.
        Deprecated : use CartService.get_subtotal()
        from cart.cart_service instead
        """
        """
        cart_total = 0
        start_time = datetime.datetime.now()
        items = self.get_items()
        for item in items:
            cart_total += item.total_price()

        end_time = datetime.datetime.now()
        elapsed_time = end_time - start_time
        print("Cart : subtotal() processing time : {0} ms".format(elapsed_time.microseconds / 1000))
        """
        return CartService.get_subtotal(self.id)
Ejemplo n.º 8
0
 def contain_item(self, item_id):
     """
     Deprecated : this method is slow on query.
     Use the CartService.contains_items() from 
     cart.cart_service instead
     """
     """
     flag = False
     try:
         start_time = datetime.datetime.now()
         prod = Product.objects.get(pk=int(item_id))
         item = self.cartitem_set.get(product=prod)
         if item is not None:
             flag = True
         end_time = datetime.datetime.now()
         elapsed_time = end_time - start_time
         print("Cart : contain_item() processing time : {0} ms".format(elapsed_time.microseconds / 1000))
     except ObjectDoesNotExist as e:
         flag = False
     """
     return CartService.contains_item(self.id, item_id)
Ejemplo n.º 9
0
    def update_cart(self, item_id, quantity):
        """
        item_id : ID of the Product to be updated
        quantity:  new quantity of the item .
        precondition : quantity >= 0;
        update_cart() updates the quantity value of a CartItem.
        If quantity == 0 then that item will be removed from the cart.
        if quantity < 0 this method returns false.
        On success this method returns True.

        Update :11.03.2018 : this method returns an object which
        contains more infos on the result.
        """
        response = {}
        if (quantity >= 0):
            if (CartService.contains_item(self.id, item_id)):
                prod = Product.objects.get(pk=int(item_id))
                item = self.cartitem_set.get(product=prod)
                # item = self.get_item(item_id)
                # item_quantity = item.get_quantity()
                if quantity > 0:
                    in_stock = prod.quantity - prod.sell_quantity
                    if (quantity <= in_stock):
                        item.set_quantity(quantity)
                        item.save()
                        response['updated'] = True
                        response['quantity'] = quantity
                    else:
                        response['updated'] = False
                        response['quantity_error'] = True
                        response['quantity'] = item.quantity

                else:
                    response['updated'] = self.remove_from_cart(item.id)
                    response['quantity'] = 0
        return response
Ejemplo n.º 10
0
def show_product(request, product_slug, template_name="catalog/product.html"):
    """
        This method displays the Product's information.
        The product is found using the slug attribut.
        This function will be update to query the product based on the 
        product ID.
        It possible for the user to add the displayed product into the cart,
        because of that we have to check whether the user used the GET or POST 
        HTTP method.
        If the user used GET then we just display the product details.
        If the user used POST then if want to add that product into the cart,
        we have to retrieve the product attribut that has been sent through
        a form, get the product and add it into the cart and return a json response.

        For static raison , we are counting the number of time this product
        has been displayed.

        As of now,the product page is served by the Class Based View ProductDetailView(defined above)
    """
    p = get_object_or_404(Product, slug=product_slug)
    categories = p.categories.filter(is_active=True)
    p.view_count = p.view_count + 1
    p.save()
    page_title = p.name + ' | ' + settings.SITE_NAME
    meta_keywords = p.meta_keywords
    meta_description = p.meta_description
    # HTTP methods evaluation:
    if request.method == 'POST':
        # add to cart. create the bound form
        postdata = request.POST.copy()
        form = ProductAddToCartForm(request, postdata)
        # check if the postdata is valid
        if form.is_valid():
            # action = postdata.get('action')
            print("Add to Cart form is Valid")
            # add to cart and redirect to cart page
            user_cart = CartService.get_user_cart(request)
            # get product slug from postdata, return blank if empty
            product_slug = postdata.get('product_slug')
            # get quantity added, return 1 if empty
            quantity = postdata.get('quantity', 1)

            p = get_object_or_404(Product, slug=product_slug)
            # TO-DO Check if the product was added into the Cart
            user_cart.add_to_cart(product=p, quantity=int(quantity))
            # return JsonResponse({'status': 'ok'})
            # if test cookie worked, get rid of it

            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            url = urlresolvers.reverse('cart:show_cart')
            return HttpResponseRedirect(url)

        else:
            #print("Add to Cart form is inValid")
            return JsonResponse({'status': 'error'})
    else:
        form = ProductAddToCartForm(request=request, label_suffix=':')
    # assign the hidden input the product_slug
    form.fields['product_slug'].widget.attrs['value'] = product_slug
    # set the test cookie on our first GET
    request.session.set_test_cookie()
    return render(request, template_name, locals())