Exemple #1
0
    def get_delivery(self, obj):
        request = self.context.get("request")

        cart = Cart(user=request.user)
        seller_delivery_cart_item = CartItem(
            product=obj,
            quantity=1,
            delivery_option_id=DeliveryOption.SELLER,
            cart=cart)

        options = {
            "seller": seller_delivery_cart_item.seller_delivery_fee.netto,
            "pickup": Decimal("0.0"),
        }

        region_settings = get_setting(request.region.id)
        if region_settings.central_logistics_company:
            central_logistics_cart_item = CartItem(
                product=obj,
                quantity=1,
                delivery_option_id=DeliveryOption.CENTRAL_LOGISTICS,
                cart=cart,
            )
            options[
                "logistics"] = central_logistics_cart_item.central_logistic_delivery_fee.netto

        return options
Exemple #2
0
 def create(self, validated_data):
     cart_item = CartItem(
         item=validated_data['item'],
         cart=self.context['request'].user.current_cart,
         quantity=validated_data['quantity'],
         price=validated_data['item'].price,
     )
     cart_item.save()
     return cart_item
Exemple #3
0
 def create(self, validated_data):
     request = self.context.get('request')
     item = Item.objects.get(id=request.data['item'])
     cart = request.user.current_cart
     cart_item = CartItem(
         item=item,
         price=item.price,
         cart_id=cart.id,
         item_id=item.id,
         quantity=request.data['quantity'],
     )
     cart_item.save()
     cart.items.add(item)
     cart.save()
     return cart_item
Exemple #4
0
    def put(self, request, format=None, *args, **kwags):
        itemId = request.POST.get('itemId', 0)
        itemCount = request.POST.get('itemCount', 1)

        itemFound = CartItem.objects.filter(id=itemId)
        if not itemFound:
            return CustomJSONRenderer().render404('Cart Item', None)

        itemFoundFirst = itemFound.first()
        itemFoundFirst.count = itemCount
        try:
            itemFoundFirst.save()
            CartItem().update_price(itemFoundFirst.cart.id)
            cart = Cart.objects.filter(user=request.user)
            return CustomJSONRenderer().render({
                'count':
                cart.count(),
                'result':
                CartSerializer(cart, many=True, context={
                    'request': request
                }).data
            })
        except Exception as e:
            return CustomJSONRenderer().render({
                'success': False,
                'e': str(e)
            },
                                               status=500)
Exemple #5
0
    def delete(self, request, format=None, *args, **kwargs):
        # pId = 0
        # if 'product' not in request.POST:
        #     body_unicode = request.body.decode('utf-8')
        #     body_data = json.loads(body_unicode)
        #     if 'product' in body_data:
        #         pId = body_data['product']
        # else:
        cId = request.POST.get('cart', 0)
        cartItem = CartItem.objects.filter(id=cId)
        if not cartItem.exists():
            return CustomJSONRenderer().render404('cart', '')
        else:
            try:
                idCart = cartItem.first().cart.id
                cartItem.first().delete()
                CartItem().update_price(idCart)

            except Exception as e:
                return CustomJSONRenderer().render500(str(e), '')
            cart = Cart.objects.filter(user=request.user)
            return CustomJSONRenderer().render(
                {
                    'count':
                    cart.count(),
                    'result':
                    CartSerializer(
                        cart, many=True, context={
                            'request': request
                        }).data
                },
                status=200)
Exemple #6
0
def product_detail(request, slug):
    instance = get_object_or_404(Product, slug=slug)
    menu_categories, cart, cart_items = initial_data(request)
    images = ProductPhotos.objects.filter(product=instance)
    seo_title = '%s' % instance.title
    if instance.size:
        form = CartItemCreateWithAttrForm(instance_related=instance)
    else:
        form = CartItemCreate()
    if request.POST:
        if instance.size:
            form = CartItemCreateWithAttrForm(instance, request.POST)
            if form.is_valid():
                qty = form.cleaned_data.get('qty', 1)
                attribute = form.cleaned_data.get('attribute')
                cart = check_or_create_cart(request)
                cart_item = CartItem.create_cart_item(request,
                                                      order=cart,
                                                      product=instance,
                                                      qty=qty,
                                                      size=attribute)
                cart.refresh_from_db()
                CartGiftItem.check_cart(cart)
                return HttpResponseRedirect(
                    reverse('product_page', kwargs={'slug': instance.slug}))
        else:
            form = CartItemCreate(request.POST)
            if form.is_valid():
                qty = form.cleaned_data.get('qty', 1)
                cart = check_or_create_cart(request)
                cart_item = CartItem.create_cart_item(request,
                                                      order=cart,
                                                      product=instance,
                                                      qty=qty)
                cart.refresh_from_db()
                CartGiftItem.check_cart(cart)
                return HttpResponseRedirect(
                    reverse('product_page', kwargs={'slug': instance.slug}))

    context = locals()
    return render(request, 'my_site/product_page.html', context)
Exemple #7
0
    def get(self, request, *args, **kwargs):
        cart = self.get_object()
        item_id = request.GET.get("item")
        delete_item = request.GET.get("delete", False)
        flash_message = ""
        message_type = "info"
        item_added = False
        if item_id:
            item_instance = get_object_or_404(Variation, id=item_id)
            qty = 1
            try:
                qty = int(request.GET.get("qty"))
                if qty < 1:
                    delete_item = True
            except:
                raise Http404
            try:
                cart_item, created = CartItem.objects.get_or_create(
                    cart=cart, item=item_instance)
            except:
                cart_item = CartItem.objects.filter(cart=cart,
                                                    item=item_instance)
                if cart_item.exists():
                    cart_item = cart_item.first()
                    created = False
                else:
                    cart_item = CartItem(cart=cart, item=item_instance)
                    created = True

            if created:
                flash_message = "Successfully added to the Cart"
                message_type = "success"
                item_added = True
            if delete_item:
                flash_message = "Item removed Successfully."
                cart_item.delete()
                message_type = "danger"
            else:
                if not created:
                    flash_message = "Quantity has been updated Successfully."
                    message_type = "info"
                cart_item.quantity = qty
                cart_item.save()
            if not request.is_ajax():
                return HttpResponseRedirect(reverse("cart"))

        if request.is_ajax():
            try:
                line_total = cart_item.line_item_total
            except:
                line_total = None
            try:
                subtotal = cart_item.cart.subtotal
                tax_total = cart_item.cart.tax_total
                total = cart_item.cart.total
                # print(subtotal)
            except:
                subtotal = None
                tax_total = None
                total = None

            try:
                total_items = cart_item.cart.cartitem_set.count()
            except:
                total_items = 0

            data = {
                "deleted": delete_item,
                "item_added": item_added,
                "line_total": line_total,
                "subtotal": subtotal,
                "flash_message": flash_message,
                "message_type": message_type,
                "total_items": total_items,
                "tax_total": tax_total,
                "total": total
            }
            return JsonResponse(data)

        context = {
            "object": self.get_object(),
        }
        template = self.template_name

        return render(request, template, context)
Exemple #8
0
    def post(self, request, format=None, *args, **kwargs):
        # body_unicode = request.body.decode('utf-8')
        # body_data = json.loads(body_unicode)
        pId = request.POST.get('product', 0)
        # check exists Product
        product = Product.objects.filter(id=pId)
        if not product.exists():
            return CustomJSONRenderer().render404('product', '')
        product = product.first()
        if product.is_free or product.price == 0:
            return Response(
                {'message': 'Product Is Free, can not add to cart'},
                status=400)
        mutable = request.POST._mutable
        request.POST._mutable = True
        # if request.user:
        #     request.data.update('user', 1)
        # else:
        #     request.data.update('user', None)
        print('user', str(request.user))
        request.data.update(user=request.user.pk)
        request.data.update(price=product.price)
        request.data.update(total_price=product.price)
        request.POST._mutable = mutable
        cart = Cart.objects.filter(user=request.user).filter(status=1)
        if cart.count() == 0:
            cart = self.create(request, *args, **kwargs)
        else:
            cart = CartSerializer(cart.first(),
                                  many=False,
                                  context={'request': request})

        print(str(cart.data['id']))
        try:
            cItem = CartItem.objects.filter(cart__id=cart.data['id'])

            if cItem.filter(product__id=product.id).count() > 0:
                cItem = cItem.first()
                cItem.count = cItem.count + 1
                cItem.total_price = cItem.total_price + cItem.product.price
                cItem.save()
            else:
                cartCreate = CartItem.objects.create(
                    product=product,
                    price=product.price,
                    total_price=product.price,
                    cart=Cart.objects.get(pk=int(cart.data['id'])),
                    count=1)
        except Exception as e:
            raise e
            # Cart.objects.filter(id=cart.data['id']).delete()
            print('error when create item', str(e))
            return Response(
                {'message': 'Problem When Add product To Cart Try Again.'})
        # Create Item Product
        # cart = Cart.objects.get(pk=cart.data['id'])
        CartItem().update_price(Cart.objects.get(pk=int(cart.data['id'])).id)

        cart = Cart.objects.filter(user=request.user)

        return CustomJSONRenderer().render(
            {
                'count':
                cart.count(),
                'result':
                CartSerializer(cart, many=True, context={
                    'request': request
                }).data
            },
            status=201)
Exemple #9
0
def home(request):
    context = {}
    user = request.user
    active_fiscal_year = FiscalYear.get_active_fiscal_year()

    if user.is_authenticated:
        sidebar_obj, new_obj = Sidebar.objects.new_or_get(request)
        if user.is_superuser():
            template_name = 'pages/admin_dashboard.html'
        elif user.is_provider():
            provider = request.user.company_admin.company
            orders = Order.objects.filter(
                is_deleted=False,
                order_items__item__provider=provider).order_by(
                    "-updated_at").distinct()[:5]
            requests = RefundRequest.objects.filter(
                is_deleted=False, order_item__item__provider=provider)[:5]

            context['orders'] = orders
            context['requests'] = requests
            context['provider'] = provider
            template_name = 'pages/provider_dashboard.html'

        elif user.is_customer():
            print(request.user.id)
            cart_id = request.session.get('cart_id', None)
            print(cart_id)
            try:
                cart = Cart.objects.get(id=cart_id, user=None)
            except Cart.DoesNotExist:
                cart = None

            if cart:
                items = cart.cart_items.all()
            else:
                items = None

            try:
                cart_obj = Cart.objects.get(user_id=request.user.id)
                if cart and items.count() > 0:
                    for item in items:
                        try:
                            item_in_cart = CartItem.objects.get(cart=cart_obj,
                                                                item=item.item)
                        except CartItem.DoesNotExist:
                            item_in_cart = None

                        if item_in_cart:
                            item_in_cart.quantity += item.quantity
                            item_in_cart.save()
                        else:
                            cart_item = CartItem()
                            cart_item.cart = cart_obj
                            cart_item.item = item.item
                            cart_item.total = item.total
                            cart_item.quantity = item.quantity
                            cart_item.save()
                            items.delete()
                            cart.delete()

                request.session['cart_id'] = cart_obj.id
                request.session['item_count'] = cart_obj.cart_items.all(
                ).count()
            except Cart.MultipleObjectsReturned:
                qs = Cart.objects.filter(user_id=request.user.id)
                if qs:
                    cart_obj = qs.last()
                    if cart and items.count() > 0:
                        for item in items:
                            try:
                                item_in_cart = CartItem.objects.get(
                                    cart=cart_obj, item=item.item)
                            except CartItem.DoesNotExist:
                                item_in_cart = None
                            if item_in_cart:
                                item_in_cart.quantity += item.quantity
                                item_in_cart.save()
                            else:
                                cart_item = CartItem()
                                cart_item.cart = cart_obj
                                cart_item.item = item.item
                                cart_item.total = item.total
                                cart_item.quantity = item.quantity
                                cart_item.save()
                                items.delete()
                                cart.delete()
                    request.session['cart_id'] = cart_obj.id
                    request.session['item_count'] = cart_obj.cart_items.all(
                    ).count()
            except Cart.DoesNotExist:
                cart_obj, new_obj = Cart.objects.new_or_get(request)
            categories = Category.objects.all_active()
            category_id = request.GET.get('category', 'None')
            if category_id:
                try:
                    category = Category.objects.get(slug=category_id)
                except:
                    category = None

                if category:
                    products = category.items.all()[:6]
                    best_sellers = OrderItem.objects.filter(
                        is_deleted=False,
                        item__category=category).distinct()[:3]
                    latest_products = Item.objects.filter(
                        is_deleted=False,
                        category=category).order_by("-created_at")[:3]
                    top_offers = Item.objects.filter(
                        is_deleted=False,
                        stock_record__discount_percentage__isnull=False,
                        category=category).distinct()[:3]
                else:
                    products = Product.objects.all_active()[:6]
                    best_sellers = OrderItem.objects.filter(
                        is_deleted=False).distinct()[:3]
                    latest_products = Item.objects.filter(
                        is_deleted=False).order_by("-created_at")[:3]
                    top_offers = Item.objects.filter(
                        is_deleted=False,
                        stock_record__discount_percentage__isnull=False
                    ).distinct()[:3]

            else:
                products = Product.objects.all_active()[:6]
                best_sellers = OrderItem.objects.filter(
                    is_deleted=False).distinct()[:3]
                latest_products = Item.objects.filter(
                    is_deleted=False).order_by("-created_at")[:3]
                top_offers = Item.objects.filter(
                    is_deleted=False,
                    stock_record__discount_percentage__isnull=False).distinct(
                    )[:3]

            context['cart'] = cart_obj

            context['products'] = products
            context['categories'] = categories
            context['best_sellers'] = best_sellers
            context['latest_products'] = latest_products
            context['top_offers'] = top_offers
            template_name = 'pages/user_dashboard.html'
        else:
            pass

            # user is not authenticated down from here
    else:
        categories = Category.objects.all_active()
        category_id = request.GET.get('category')
        if category_id:
            try:
                category = Category.objects.get(slug=category_id)
            except:
                category = None

            if category:
                products = category.items.all()[:6]
                best_sellers = OrderItem.objects.filter(
                    is_deleted=False, item__category=category).distinct()[:3]
                latest_products = Item.objects.filter(
                    is_deleted=False,
                    category=category).order_by("-created_at")[:3]
                top_offers = Item.objects.filter(
                    is_deleted=False,
                    stock_record__discount_percentage__isnull=False,
                    category=category).distinct()[:3]
            else:
                products = Product.objects.all_active()[:6]
                best_sellers = OrderItem.objects.filter(
                    is_deleted=False).distinct()[:3]
                latest_products = Item.objects.filter(
                    is_deleted=False).order_by("-created_at")[:3]
                top_offers = Item.objects.filter(
                    is_deleted=False,
                    stock_record__discount_percentage__isnull=False).distinct(
                    )[:3]
        else:
            products = Product.objects.all_active()[:6]
            best_sellers = OrderItem.objects.filter(
                is_deleted=False).distinct()[:3]
            top_offers = Item.objects.filter(
                is_deleted=False,
                stock_record__discount_percentage__isnull=False).distinct()[:3]
            latest_products = Item.objects.filter(
                is_deleted=False).order_by("-created_at")[:3]
        cart_obj, new_obj = Cart.objects.new_or_get(request)
        if cart_obj:
            items = cart_obj.cart_items.filter(is_deleted=False).count()

        context['cart'] = cart_obj
        context['best_sellers'] = best_sellers
        context['latest_products'] = latest_products
        context['top_offers'] = top_offers
        context['item_count'] = items
        context['products'] = products
        context['categories'] = categories
        template_name = 'pages/user_dashboard.html'
    context['year'] = date.today().year
    return render(request, template_name, context)