Exemplo n.º 1
0
def charge(request):
    """
    This method receive a front-end payment and create a charge.
    """
    user = request.user
    if isinstance(user, AnonymousUser):
        logger.error(errors.USR_10.message)
        return errors.handle(errors.USR_10)

    data = request.data
    order_id = data.get('order_id', '')
    amount = data.get('amount', '')
    currency = data.get('currency', '')
    description = data.get('description', '')

    try:
        Orders.objects.get(pk=order_id)
    except Orders.DoesNotExist:
        return errors.handle(errors.ORD_01)
    response = payments.create(amount=amount,
                               order_id=order_id,
                               currency=currency,
                               description=description)
    if response.status != 'succeeded':
        err_data = response.__dict__
        return Response(data={
            'message': err_data['message'],
            'status': err_data['status']
        },
                        status=err_data['status'])
    response['message'] = 'Payment made successfully!'
    return Response(data=response, status=200)
def update_credit_card(request):
    """    
    Update the credit card from customer
    """
    logger.debug("Updating credit card")
    if 'credit_card' in request.data:

        if not validate_credit_card(request.data.get('credit_card')):
            logger.error(errors.USR_08.message)
            return errors.handle(errors.USR_08)

        try:
            customer = request.user.customer
            customer.credit_card = request.data.get('credit_card', None)
            customer.save()
            serializer_element = CustomerSerializer(customer)
            logger.debug("Success")
            return Response(serializer_element.data)
        except AttributeError:
            logger.error(errors.USR_10.message)
            return errors.handle(errors.USR_10)
        except Exception as error:
            errors.COM_02.message = str(error)
            logger.error(errors.COM_02.message)
            return errors.handle(errors.COM_02)
    else:
        errors.COM_02.field = 'credit_card'
        logger.error(errors.COM_02.message)
        return errors.handle(errors.COM_02)
Exemplo n.º 3
0
 def put(self, request, item_id):
     try:
         cart_item = ShoppingCart.objects.get(item_id=item_id)
         quantity = request.data.get("quantity", None)
         if not quantity:
             return errors.handle(errors.COM_02)
         cart_item.quantity = request.data.get("quantity", None)
         cart_item.save()
         serializer_element = ShoppingcartSerializer(instance=cart_item)
         cart_id_field = {"cart_id": int(cart_item.cart_id)}
         new_dict = serializer_element.data
         new_dict.update(cart_id_field)
         return Response(new_dict, 201)
     except ShoppingCart.DoesNotExist:
         return errors.handle(errors.CRT_03)
Exemplo n.º 4
0
def order(request, order_id):
    """
    Get Info about Order
    """
    user = request.user
    if isinstance(user, AnonymousUser):
        logger.error(errors.USR_10.message)
        return errors.handle(errors.USR_10)
    try:
        order = Orders.objects.get(pk=order_id)
    except Orders.DoesNotExist:
        return errors.handle(errors.ORD_01)
    serializer = OrdersSerializer()
    data = serializer.to_representation(order)
    return Response(data=data, status=status.HTTP_200_OK)
Exemplo n.º 5
0
 def get(self, request, attribute_id):
     try:
         queryset = AttributeValue.objects.filter(attribute_id=attribute_id)
         serializer = AttributeValueSerializer(queryset, many=True)
         return Response(serializer.data)
     except AttributeValue.DoesNotExist:
         return errors.handle(errors.ATR_02)
Exemplo n.º 6
0
 def get(self, request, attribute_id):
     try:
         attribute = Attribute.objects.get(attribute_id=attribute_id)
         serializer_element = AttributeSerializer(instance=attribute)
         return Response(serializer_element.data)
     except Attribute.DoesNotExist:
         return errors.handle(errors.ATR_01)
Exemplo n.º 7
0
 def delete(self, request, item_id):
     try:
         item = ShoppingCart.objects.get(item_id=item_id)
         item.delete()
         return Response({"message": "Item successfully removed from cart!"})
     except ShoppingCart.DoesNotExist:
         return errors.handle(errors.CRT_03)
Exemplo n.º 8
0
 def delete(self, request, cart_id):
     cart = ShoppingCart.objects.filter(cart_id=cart_id)
     if not cart:
         return errors.handle(errors.CRT_01)
     for item in cart:
         item.delete()
     return Response([], 200)
Exemplo n.º 9
0
def update_quantity(request, item_id):
    """
    Update the cart by item
    """
    logger.debug("Updating quantity")
    error = None
    quantity = request.data.get('quantity', '')
    error = errors.handle(
        errors.Error(code="COM_10",
                     message="Quantity must be a number not less than 1",
                     _status=400)) if not isinstance(
                         quantity, int) or quantity < 1 else error
    invalid_qty = validate_field_required(request.data, 'quantity', 'COM_01')
    invalid_id = validate_cart_ids(item_id, 'item_id')
    error = invalid_qty if invalid_qty else error
    error = invalid_id if invalid_id else error
    if error:
        return error
    cart = ShoppingCart.objects.get(item_id=item_id)
    serializer_class = UpdateShoppingcartSerializer(
        cart,
        data=request.data,
        partial=True,
    )
    serializer_class.is_valid(raise_exception=True)
    serializer_class.update(cart, request.data)
    import pdb
    pdb.set_trace()
    return Response(serializer_class.data, status=status.HTTP_200_OK)
Exemplo n.º 10
0
def create_order(request):
    """
    Create a Order
    """
    user = request.user
    data = request.data
    if isinstance(user, AnonymousUser):
        logger.error(errors.USR_10.message)
        return errors.handle(errors.USR_10)
    error = validate_order_input(request.data)
    if error:
        return error
    data['customer_id'] = user.customer_id
    data['created_on'] = timezone.now()
    data['status'] = 0
    total = 0
    for item in ShoppingCart.objects.filter(cart_id=data['cart_id']).all():
        product = Product.objects.get(product_id=item.product_id)
        total += product.price * item.quantity if \
            float(product.discounted_price) == 0 else \
            product.discounted_price * item.quantity
    data['total_amount'] = total
    serializer = OrdersSerializer(data=data)
    serializer.is_valid(raise_exception=True)
    return Response(data={'order_id': serializer.save().pk}, status=status.HTTP_201_CREATED)
Exemplo n.º 11
0
 def get(self, request, shipping_region_id):
     shipping = Shipping.objects.filter(
         shipping_region_id=shipping_region_id)
     if not shipping:
         return errors.handle(errors.SHP_02)
     serializer = ShippingSerializer(shipping, many=True)
     return Response(serializer.data)
Exemplo n.º 12
0
 def get(self, request, tax_id):
     try:
         tax = Tax.objects.get(tax_id=tax_id)
         serializer = TaxSerializer(instance=tax)
         return Response(serializer.data)
     except Tax.DoesNotExist:
         return errors.handle(errors.TAX_01)
Exemplo n.º 13
0
 def get(self, request, department_id):
     try:
         department = Department.objects.get(department_id=department_id)
         serializer_element = DepartmentSerializer(instance=department)
         return Response(serializer_element.data)
     except Department.DoesNotExist:
         return errors.handle(errors.DEP_02)
Exemplo n.º 14
0
 def get(self, request, category_id):
     try:
         category = Category.objects.get(category_id=category_id)
         serializer_element = CategorySerializer(instance=category)
         return Response(serializer_element.data)
     except Category.DoesNotExist:
         return errors.handle(errors.CAT_01)
Exemplo n.º 15
0
 def get(self, request, order_id):
     try:
         order = Orders.objects.get(order_id=order_id)
         cart_items = ShoppingCart.objects.filter(cart_id=order.reference)
         details_list = list()
         for item in cart_items:
             product = Product.objects.get(product_id=item.product_id)
             details_dict = {
                 "order_id":
                 order.order_id,
                 "total_amount":
                 str(order.total_amount),
                 "created_on":
                 order.created_on,
                 "shipped_on":
                 order.shipped_on if order.shipped_on is not None else "",
                 "status":
                 order.status,
                 "name":
                 product.name,
             }
             details_list.append(details_dict)
         return Response(details_list)
     except Orders.DoesNotExist:
         return errors.handle(errors.ORD_01)
Exemplo n.º 16
0
    def put(self, request):
        customer = request.user
        shipping_id = request.data.get("shipping_region_id", None)

        if shipping_id is None:
            errors.COM_01.message = "The field shipping_region_id is required"
            return errors.handle(errors.COM_01)

        if not isinstance(shipping_id, int):
            return errors.handle(errors.USR_09)
        for field, value in request.data.items():
            setattr(customer, field, value)

        customer.save()
        serializer_element = CustomerSerializer(instance=customer)
        return Response(serializer_element.data, status.HTTP_200_OK)
Exemplo n.º 17
0
 def create_customer(self, *args, **kwargs):
     email = kwargs.get("email", None)
     normalized_email = self.normalize_email(email)
     if not re.match(r"[^@]+@[^@]+\.[^@]+", normalized_email):
         errors.handle(errors.USR_03)
     try:
         customer = self.model.objects.get(email=normalized_email)
         if customer:
             errors.handle(errors.USR_04)
     except self.model.DoesNotExist:
         kwargs.pop("email", None)
         password = kwargs.pop("password", None)
         customer = self.model(email=normalized_email, **kwargs)
         if password is not None:
             customer.set_password(password)
         customer.save()
         return customer
Exemplo n.º 18
0
 def get(self, request, product_id):
     try:
         prod_category = ProductCategory.objects.get(product_id=product_id)
         category = Category.objects.get(category_id=prod_category.category_id)
         serializer_element = ProductCategorySerializer(instance=category)
         return Response(serializer_element.data)
     except ProductCategory.DoesNotExist:
         return errors.handle(errors.PRO_02)
Exemplo n.º 19
0
 def get(self, request, product_id):
     try:
         product = Product.objects.get(product_id=product_id)
         serializer_element = SingleProductSerializer(instance=product)
         data = self.truncate_description(request, serializer_element.data)
         return Response(data)
     except Product.DoesNotExist:
         return errors.handle(errors.PRO_01)
Exemplo n.º 20
0
    def get(self, request, department_id):
        _categories = Category.objects.filter(department_id=department_id)
        if not _categories:
            errors.handle(errors.DEP_02)

        _products_list = list()
        for category in _categories:
            prod_category = ProductCategory.objects.filter(
                category_id=category.category_id)
            for item in prod_category:
                product = Product.objects.get(product_id=item.product_id)
                _products_list.append(product)
        paginated_data = self.paginate_queryset(_products_list)
        products_list = list()
        for product in paginated_data:
            serializer_element = ProductSerializer(instance=product)
            products_list.append(serializer_element.data)
        return self.get_paginated_response(products_list)
Exemplo n.º 21
0
def webhooks(request):
    """
    Endpoint that provide a synchronization
    """
    user = request.user
    if isinstance(user, AnonymousUser):
        logger.error(errors.USR_10.message)
        return errors.handle(errors.USR_10)
    response = payments.create_webhook()
    return Response(data=response, status=201)
Exemplo n.º 22
0
    def details(self, request, pk):
        """
        Get details of a Product
        """
        product = Product.objects.get(product_id=pk)
        if not product:
            return errors.handle(errors.PRO_01)

        return Response(self.serializer_class(product).data,
                        status=status.HTTP_200_OK)
Exemplo n.º 23
0
 def get(self, request, product_id):
     try:
         product = Product.objects.get(product_id=product_id)
         review = Review.objects.get(product_id=product_id)
         serializer_element = ReviewSerializer(instance=review)
         holding_dict = serializer_element.data
         return_dict = {"name": product.name, **holding_dict}
         return Response(return_dict, 201)
     except Product.DoesNotExist:
         return errors.handle(errors.PRO_01)
Exemplo n.º 24
0
 def post(self, request):
     try:
         product_id = request.data.get("product_id", None)
         product = Product.objects.get(product_id=product_id)
         customer_id = request.user.customer_id
         review = Review()
         for field, value in request.data.items():
             setattr(review, field, value)
         customer_review = Review.objects.filter(customer_id=customer_id,
                                                 product_id=product_id)
         if customer_review:
             return errors.handle(errors.USR_11)
         review.customer_id = customer_id
         review.save()
         serializer_element = ReviewSerializer(instance=review)
         holding_dict = serializer_element.data
         return_dict = {"name": product.name, **holding_dict}
         return Response(return_dict, 201)
     except Product.DoesNotExist:
         return errors.handle(errors.PRO_01)
Exemplo n.º 25
0
 def get(self, request):
     """
     Get a customer by ID. The customer is getting by token
     """
     customer_id = decode_token_from_request(request)
     if isinstance(request.user, AnonymousUser):
         logger.error(errors.USR_10.message)
         return errors.handle(errors.USR_10)
     customer = Customer.objects.get(customer_id=customer_id)
     serializer_element = CustomerSerializer(customer)
     return Response(serializer_element.data)
Exemplo n.º 26
0
    def put(self, request):

        if "credit_card" in request.data:
            credit_card = request.data.get("credit_card")
            if not validate_credit_card(credit_card):
                return errors.handle(errors.USR_08)
            customer = request.user
            customer.credit_card = credit_card
            customer.save()
            last_digits = credit_card.split("-")[-1]
            serializer_element = CustomerSerializer(customer)
            credit_field = {"credit_card": "xxxxxxxxxxxx" + str(last_digits)}
            return_dict = dict()
            return_dict.update(serializer_element.data)
            return_dict.update(credit_field)
            return Response(return_dict)

        else:
            errors.COM_01.message = "The field credit_card is required"
            return errors.handle(errors.COM_01)
Exemplo n.º 27
0
def customer(request):
    """
    Get a customer by ID. The customer is getting by token
    """
    logger.debug("Getting customer")
    user = request.user
    if isinstance(user, AnonymousUser):
        logger.error(errors.USR_10.message)
        return errors.handle(errors.USR_10)
    serializer_element = CustomerSerializer(user.customer)
    logger.debug("Success")
    return Response(serializer_element.data)
Exemplo n.º 28
0
 def get_values_from_attribute(self, request, *args, **kwargs):
     """
     Get Values Attribute from Attribute ID
     """
     serializer_class = AttributeValueSerializer
     attribute_id = kwargs.get('attribute_id', '')
     if not Attribute.objects.filter(attribute_id=attribute_id):
         return errors.handle(errors.ATT_01)
     attribute_value = AttributeValue.objects.filter(
         attribute_id=attribute_id).all()
     data = serializer_class(attribute_value, many=True).data
     return Response(data, status=200)
Exemplo n.º 29
0
    def get(self, request):
        user = request.user
        if isinstance(user, AnonymousUser):
            logger.error(errors.USR_10.message)
            return errors.handle(errors.USR_10)
        try:
            customer = request.user
        except Customer.DoesNotExist:
            raise exceptions.APIException(detail='Customer does not exist',
                                          code=404)
        serializer = self.serializer_class(customer)

        return Response(serializer.data, status=status.HTTP_200_OK)
Exemplo n.º 30
0
 def reviews(self, request, pk):
     """Return a list of reviews
     Args:
         request (obj): request onject
         pk (int): product id
     Returns:
         list of the product's reviews
     """
     serializer_class = ReviewSerializer
     if not Product.objects.filter(product_id=pk):
         return errors.handle(errors.PRO_01)
     return Response(serializer_class(
         Review.objects.filter(product_id=pk).all(), many=True).data,
                     status=status.HTTP_200_OK)