Example #1
0
 def delete(self, request, id):
     """
     Delete particular store
     :param request:
     :param id:
     :return:
     """
     try:
         user = User.objects.get(id=id)
         user.delete()
         return Utils.dispatch_success(request, "SUCCESS")
     except User.DoesNotExist:
         return Utils.dispatch_failure(request, 'OBJECT_RESOURCE_NOT_FOUND')
     except Exception as e:
         print(e)
         return Utils.dispatch_failure(request, 'INTERNAL_SERVER_ERROR', {"error": str(e)})
Example #2
0
 def get(self, request, product_id):
     """
     Returns a particular product based on sub_category id
     :param request:
     :param product_id: product_id
     :return:
     """
     try:
         product = Product.objects.get(id=product_id)
         serializer = serializers.ProductSerializer(product)
         return Utils.dispatch_success(request, serializer.data)
     except Product.DoesNotExist:
         return Utils.dispatch_failure(request, 'OBJECT_RESOURCE_NOT_FOUND')
     except Exception as e:
         print(e)
         return Utils.dispatch_failure(request, 'INTERNAL_SERVER_ERROR', {"error": str(e)})
Example #3
0
    def get(self, request):
        """
        returns the list all the  productsbased on queryset
        :param request:
        :note:
        for not published -  not_published=true query param
        for published -  published=true query param
        pagination added use - page_number = 1
        Page size is customizable - page_size = 10
        :return:
        """
        try:
            if request.GET.get('not_published'):
                queryset = Product.objects.filter(is_drafted=True, is_published=False).order_by('-updated_at')
            elif request.GET.get('published'):
                queryset = Product.objects.filter(is_published=True).order_by('-updated_at')
            else:
                queryset = Product.objects.all().order_by('-updated_at')
            page_size = request.GET.get('page_size')
            if page_size:
                page_size = int(page_size)
            else:
                page_size = 10

            page_number = request.GET.get('page_number')
            if page_number:
                page_number = int(page_number)
            else:
                page_number = 1

            if queryset:
                paginator = Paginator(queryset, per_page=page_size)

                queryset = paginator.page(page_number)

                serializer = serializers.ProductSerializer(queryset, many=True)
            response_data = {
                "data": serializer.data if queryset else [],
                "current_page": page_number,
                "page_size": page_size,
                "total_pages": paginator.num_pages if queryset else 1
            }
            return Utils.dispatch_success(request, response_data)

        except Exception as e:
            print(e)
            return Utils.dispatch_failure(request, 'INTERNAL_SERVER_ERROR', {"error": str(e)})
Example #4
0
 def put(self, request):
     """
     To Update Buyed need to send response
     {
     "order_products" : [1,2,3,4,5,6,7,8,9,10]
     }
     note: These id's are ordered_products
     :param request:
     :return:
     """
     try:
         data = request.data
         OrderedProducts.objects.filter(id__in=data['order_products']).update(is_admin_buyed=True)
         return Utils.dispatch_success(request, 'SUCCESS')
     except Exception as e:
         print(e)
         return Utils.dispatch_failure(request, 'INTERNAL_SERVER_ERROR', {"error": str(e)})
Example #5
0
    def get(self, request):
        """
        pagination added use - page_number = 1
        Page size is customizable - page_size = 10

        param = is_available = true

        :param request:
        :return:
        """
        try:
            if request.GET.get('is_available'):
                queryset = User.objects.filter(user_type=User.DELIVERY_MAN, is_available=True)
                return Utils.dispatch_success(request, serializers.BasicUserInfoSerializer(queryset, many=True).data)
            else:
                queryset = User.objects.filter(user_type=User.DELIVERY_MAN)
            page_size = request.GET.get('page_size')
            if page_size:
                page_size = int(page_size)
            else:
                page_size = 10

            page_number = request.GET.get('page_number')
            if page_number:
                page_number = int(page_number)
            else:
                page_number = 1

            if queryset:
                paginator = Paginator(queryset, per_page=page_size)

                queryset = paginator.page(page_number)

                serializer = serializers.UserManagementSerializer(queryset, many=True)
            response_data = {
                "data": serializer.data if queryset else [],
                "current_page": page_number,
                "page_size": page_size,
                "total_pages": paginator.num_pages if queryset else 1
            }
            return Utils.dispatch_success(request, response_data)

        except Exception as e:
            print(e)
            return Utils.dispatch_failure(request, 'INTERNAL_SERVER_ERROR', {"error": str(e)})
Example #6
0
    def get(self, request, *args, **kwargs):
        """
        :param request:
        :param args:
        :param kwargs:
        send ?text="searchtext" as param
        pagination added use - page_number = 1
        Page size is customizable - page_size = 10
        :return:
        """
        try:
            search = request.GET.get('text', '')
            queryset = Product.objects.filter(is_published=True,
                                              name__icontains=search)
            page_size = request.GET.get('page_size', None)
            if page_size:
                page_size = int(page_size)
            else:
                page_size = 10

            page_number = request.GET.get('page_number', None)
            if page_number:
                page_number = int(page_number)
            else:
                page_number = 1

            if queryset:
                paginator = Paginator(queryset, per_page=page_size)

                queryset = paginator.page(page_number)

                serializer = serializers.CustomerProductSerializer(queryset,
                                                                   many=True)
            response_data = {
                "data": serializer.data if queryset else [],
                "current_page": page_number,
                "page_size": page_size,
                "total_pages": paginator.num_pages if queryset else 1
            }
            return Utils.dispatch_success(request, response_data)
        except Exception as e:
            print(e)
            return Utils.dispatch_failure(request, 'INTERNAL_SERVER_ERROR',
                                          {"error": str(e)})
Example #7
0
    def post(self, request, *args, **kwargs):
        """
        Uploads the file and return the uploaded file details
        :param request:
        :return:
        """
        try:
            print(f'request data - {request.data}')
            key = request.data.get('key', None)

            if key is not None:
                FileUploadUtils.deleteFile(key)

            print(f'request file - {request.FILES}')

            file = request.FILES['file']
            filename = file.name
            file_extension = filename.split('.')[1]

            extension = FileUploadUtils.getContentType(file_extension)

            session = Session(aws_access_key_id=settings.AWS_ACCESS_KEY,
                              aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
                              region_name=settings.AWS_REGION_NAME)

            s3 = session.resource('s3')

            file_key = FileUploadUtils.getFileKey()

            res = s3.Bucket(settings.AWS_BUCKET_NAME).put_object(Key=file_key, Body=file, ContentType=extension,
                                                                 ACL='public-read')

            data = {'key': file_key, 'file_name': filename}
            serializer = serializers.CreateFileUploadSerializer(data=data)
            if serializer.is_valid():
                serializer.save()

            media = Media.objects.get(key=file_key)
            media_serializer = serializers.GetFileSerializer(media)
            return Utils.dispatch_success(request, media_serializer.data)
        except Exception as e:
            print(e)
            return Utils.dispatch_failure(request, 'FILE_UPLOAD_FAILED', {"error": str(e)})
Example #8
0
 def get(self, request):
     try:
         cart_items = Cart.objects.filter(customer=request.user)
         total = 0.0
         for cart_item in cart_items:
             total += float(cart_item.product.sbs_price) * float(
                 cart_item.quantity)
         delivery_charge = 50
         response_data = {
             "data": serializers.CartSerializer(cart_items, many=True).data,
             "delivery_charge": delivery_charge,
             "total": total,
             "total_with_delivery_charge": total + delivery_charge
         }
         return Utils.dispatch_success(request, response_data)
     except Exception as e:
         print(e)
         return Utils.dispatch_failure(request, 'INTERNAL_SERVER_ERROR',
                                       {"error": str(e)})
Example #9
0
 def get(self, request):
     try:
         pending_orders = Order.objects.filter(order_status=Order.PENDING)
         data = {}
         for pending_order in pending_orders:
             for order_item in OrderedProducts.objects.filter(order=pending_order):
                 product = order_item.product
                 product_data = {'id': order_item.id,
                                 'name': product.name,
                                 'quantity': order_item.quantity,
                                 'per_item_price': order_item.price_per_item,
                                 'total_price': order_item.total_price,
                                 'is_admin_buyed': order_item.is_admin_buyed
                                 }
                 data.setdefault(order_item.product.wholesaler.first_name, []).append(product_data)
         return Utils.dispatch_success(request, data)
     except Exception as e:
         print(e)
         return Utils.dispatch_failure(request, 'INTERNAL_SERVER_ERROR', {"error": str(e)})
Example #10
0
 def put(self, request, id):
     """
     Update particular store
     :param request:
     :param id:
     :return:
     """
     try:
         user = User.objects.get(id=id)
         data = request.data
         serializer = serializers.BasicUserInfoSerializer(user, data=data, partial=True)
         if serializer.is_valid():
             serializer.save()
             return Utils.dispatch_success(request, serializer.data)
         return Utils.dispatch_failure(request, 'VALIDATION_ERROR', serializer.errors)
     except User.DoesNotExist:
         return Utils.dispatch_failure(request, 'OBJECT_RESOURCE_NOT_FOUND')
     except Exception as e:
         print(e)
         return Utils.dispatch_failure(request, 'INTERNAL_SERVER_ERROR', {"error": str(e)})
Example #11
0
    def get(self, request):
        """
        Returns the list of users
        :param request:
        :return:
        """
        try:
            user_type_list = request.GET.getlist('user_type', [])
            queryset = User.objects.filter(is_active=True)

            if user_type_list:
                queryset = queryset.filter(user_type__in=user_type_list).order_by('id')

            if queryset:
                serializer = serializers.BasicUserInfoSerializer(queryset, many=True)
                return Utils.dispatch_success(request, serializer.data)
            return Utils.dispatch_success(request, 'DATA_NOT_FOUND')
        except Exception as e:
            print(e)
            return Utils.dispatch_failure(request, 'INTERNAL_SERVER_ERROR', {"error": str(e)})
Example #12
0
 def put(self, request):
     """
     :param request:
     :return:
     """
     try:
         user = request.user
         data = request.data
         serializer = serializers.UpdateDeliveryBoyDetailsSerializer(
             user, data=data, partial=True)
         if serializer.is_valid():
             serializer.save()
             return Utils.dispatch_success(
                 request,
                 serializers.DeliveryBoyDetailsSerializer(user).data)
         return Utils.dispatch_failure(request, serializer.errors)
     except Exception as e:
         print(e)
         return Utils.dispatch_failure(request, 'INTERNAL_SERVER_ERROR',
                                       {"error": str(e)})
Example #13
0
 def post(self, request):
     """
     To verify the authorized user and login them to the application
     :param request:
     :return:
     """
     validate_user = serializers.LoginSerializer(data=request.data)
     if validate_user.is_valid():
         user = validate_user.validated_data
         # old_tokens = AuthUser.objects.filter(user=user, is_expired=True)
         # if old_tokens:
         #     old_tokens.delete()
         #
         # AuthUser.objects.filter(user=user).update(is_expired=True)
         new_session = AuthUser(user=user)
         new_session.token = Utils.generate_token()
         new_session.save()
         serializer = serializers.AuthUserSerializer(new_session)
         return Utils.dispatch_success(request, serializer.data)
     else:
         return Utils.dispatch_failure(request, "UNAUTHORIZED_ACCESS", validate_user.errors)
Example #14
0
    def get(self, request):
        try:
            queryset = User.objects.filter(is_active=True, user_type=User.WHOLESALER).order_by('first_name')
            page_number = request.GET.get('page_number', 1)
            page_size = request.GET.get('page_size', 10)

            if queryset:
                paginator = Paginator(queryset, per_page=page_size)

                queryset = paginator.page(page_number)

                serializer = serializers.UserManagementSerializer(queryset, many=True)
            response_data = {
                "data": serializer.data if queryset else [],
                "current_page": page_number,
                "page_size": page_size,
                "total_pages": paginator.num_pages if queryset else 1
            }
            return Utils.dispatch_success(request, response_data)
        except Exception as e:
            print(e)
            return Utils.dispatch_failure(request, 'INTERNAL_SERVER_ERROR', {"error": str(e)})
Example #15
0
 def post(self, request):
     """
     request_data = 
     {
     "username" : 9876543210,
     "user_type": "WHOLSESALER", # or 'CUSTOMER'
     "name": "STORE_NAME",
     "password": "******",
     "address":"Address"
     }
     """
     try:
         data = request.data
         try:
             User.objects.get(username=data["username"])
         except User.DoesNotExist:
             user = User(username=data["username"],
                         user_type=data["user_type"],
                         first_name=data["name"],
                         address=data.get("address", ''))
             user.save()
             if data.get('email'):
                 user.email = data['email']
             user.set_password(data['password'])
             if user.user_type == User.CUSTOMER:
                 if data.get('referral_code'):
                     referred_user = User.objects.filter(referral_code=data['referral_code'])
                     if referred_user:
                         user.referred_by = referred_user
                 user.referral_code = f"{user.first_name[:4].upper()}" \
                     f"{(int(hashlib.sha256(user.username.encode('utf-8')).hexdigest(), 16) % 10 ** 6)}"
             user.save()
             return Utils.dispatch_success(request, ['SUCCESS'])
         else:
             return Utils.dispatch_failure(request, 'VALIDATION_ERROR')
     except Exception as e:
         print(e)
         return Utils.dispatch_failure(request, 'INTERNAL_SERVER_ERROR', {"error": str(e)})
Example #16
0
    def post(self, request):
        """
        post_data = { product_id : 1,
        "quantity": 10,
        "comments": "Isdgfsdgdgsdgdsgds",
        "image":3
        },
        send quantity = 0 to remove item from cart
        :param request:
        :return:
        """
        try:
            cart = Cart.objects.filter(
                customer=request.user,
                product=request.data['product_id']).first()
            if cart:
                if request.data['quantity']:
                    cart.quantity = request.data['quantity']
                    cart.save()
                else:
                    cart.delete()
            else:
                cart = Cart(
                    customer=request.user,
                    product=Product.objects.get(id=request.data['product_id']),
                    quantity=request.data['quantity'],
                    image=Media.objects.get(id=request.data['image'])
                    if request.data.get('image') else None,
                    comments=request.data.get('comments', ''),
                )
                cart.save()

            return Utils.dispatch_success(request, 'SUCCESS')
        except Exception as e:
            print(e)
            return Utils.dispatch_failure(request, 'INTERNAL_SERVER_ERROR',
                                          {"error": str(e)})
Example #17
0
    def put(self, request, product_id=None):
        """
        Updates a particular product
        :param request:
        :param product_id: product_id
        For save option used
        {
        "is_drafted":True, # if save
        }
        For publish used
        {
        "is_published":True, # if save and publish
        }
        for price
        {
        "sbs_price" : 11100
        }


        -----------------

        for publish all

        param = publish_all = true
        data = {
                "product_list":[10,11,12,13,14,15]
               }
        :return:
        """
        try:
            if not product_id and request.GET.get('publish_all'):
                for p_id in request.data['product_list']:
                    product = Product.objects.get(id=p_id)
                    product.is_drafted = False
                    product.is_edited = False
                    product.is_published = True
                    product.save()
                return Utils.dispatch_success(request, 'SUCCESS')
            else:
                data = request.data
                product = Product.objects.get(id=product_id)
                if data.get('is_published'):
                    data['is_drafted'] = False
                    data['is_edited'] = False
                if data.get('price'):
                    if request.user.user_type == User.WHOLESALER and product.price != data['price']:
                        data['is_edited'] = True
                        data['is_drafted'] = False
                        data['is_published'] = False

                serializer = serializers.AddProductSerializer(product, data=request.data, partial=True)
                if serializer.is_valid():
                    serializer.save()
                else:
                    print(serializer.errors)
                    return Utils.dispatch_failure(request, 'VALIDATION_ERROR', serializer.errors)
                return Utils.dispatch_success(request, serializer.data)
        except Product.DoesNotExist:
            return Utils.dispatch_failure(request, 'OBJECT_RESOURCE_NOT_FOUND')
        except Exception as e:
            print(e)
            return Utils.dispatch_failure(request, 'INTERNAL_SERVER_ERROR', {"error": str(e)})