예제 #1
0
    def post(self, request):
        """

        @api {POST} /api/v1/baskets Create a Basket
        @apiVersion 1.0.0

        @apiName CreateBasket
        @apiGroup Baskets

        @apiDescription  The endpoint is responsible for creation of a new basket in the database.

        @apiSuccess {String}   basket.id       Basket's id.

        @apiSuccessExample {json} Success-Response:
        HTTP/1.1 200 OK
        {
           "basket_id": "5f841f73-6096-4b78-b660-a830ee6e59bf"
         }

        @apiError (InternalServerError 500) {Object} InternalServerError

        """
        try:

            basket = Basket.objects.create()

            return JsonResponse({"basket_id": basket.id})
        except Exception as e:
            print(e)
            return JsonResponse500().json_response()
예제 #2
0
    def delete(self, request, basket_id, item_id):
        """

        @api {DELETE} /api/v1/baskets/<basket_id>/items/<item_id> Delete Item
        @apiVersion 1.0.0

        @apiName DeleteItem
        @apiGroup Baskets

        @apiDescription  The endpoint is responsible for removal of the Item from the Basket.


        @apiSuccessExample {json} Success-Response:
        HTTP/1.1 200 OK
            { }

        @apiError (Bad Request 400)         {Object}    InvalidItemId           Please provide a valid item id.
        @apiError (Bad Request 400)         {Object}    InvalidBasketId         Please provide a valid basket id.
        @apiError (Bad Request 400)         {Object}    InvalidQuantity         Please provide a valid quantity value.
        @apiError (InternalServerError 500) {Object}    InternalServerError

        """
        try:

            # raises an error if a value is not provided.
            if not basket_id:
                return JsonResponse400(
                    'InvalidBasketId',
                    'Please provide a valid basket id.').json_response()

            if not item_id:
                return JsonResponse400(
                    'InvalidItemId',
                    'Please provide a valid item id.').json_response()

            basket = Basket.objects.get(pk=basket_id)

            basket_item = BasketItem.objects.get(basket=basket, pk=item_id)

            if not basket_item:
                return JsonResponse400(
                    'BasketItemNotFound',
                    'This basket does not contain such an item').json_response(
                    )

            basket_item.delete()

            return JsonResponse({})
        except Exception as e:
            print(e)
            return JsonResponse500().json_response()
예제 #3
0
    def get(self, request, user_id):

        """
        @api {GET} api/v1/user/<user_id>/address/ Address Fetch
        @apiVersion 1.0.0

        @apiName    AddressFetch
        @apiGroup   Users

        @apiDescription  The endpoint is responsible for retrieving the user's address information.

        @apiSuccessExample {json} Success-Response:
        HTTP/1.1 200 OK
        {
            'address': {'apt_nr': 21,
                        'city': 'Stockholm',
                        'country': 'Sweden',
                        'first_name': 'cristina',
                        'id': 1,
                        'last_name': 'garbuz',
                        'street': 'street',
                        'user': 1,
                        'zip_code': 14}
        }

        @apiError (Bad Request 400)             {Object}        UserDoesNotExist        Please complete the fields for delivery address.
        @apiError (InternalServerError 500)     {Object}        InternalServerError

        """

        try:
            user = User.objects.get(pk=user_id)

            delivery_address = DeliveryAddress.objects.filter(user=user).last()
            address_dict = model_to_dict(delivery_address)

            return JsonResponse({
                'address': address_dict
            }, status=200)

        except User.DoesNotExist:
            return JsonResponse400('UserDoesNotExist', 'Such a user does not exist').json_response()
        except IntegrityError:
            return JsonResponse({}, status=200)
        except Exception as e:
            print(e)
            return JsonResponse500().json_response()
예제 #4
0
    def post(self, request):
        """

        @api {POST} api/v1/user/contact User Communication
        @apiVersion 1.0.0

        @apiName    UserCommunication
        @apiGroup   Users

        @apiDescription  The endpoint is responsible for receiving the emails sent by the users sent by the contact form.

        @apiParam   {String}                    email       The email provided by  the user.
        @apiParam   {String}                    name        The name provided by  the user.
        @apiParam   {String}                    message     The message written by  the user.

        @apiSuccessExample {json} Success-Response:
        HTTP/1.1 200 OK
        { }

        @apiError (Bad Request 400)             {Object}        InvalidPassword             The password should have at least 8 characters and can contain any char except white space.
        @apiError (Bad Request 400)             {Object}        UnavailableUsername         The email already exists in the database.
        @apiError (Bad Request 400)             {Object}        InvalidEmailFormat          The Email should have an "@" sign and a email domain name with a domain ending of at least 2 characters.
        @apiError (InternalServerError 500)     {Object}        InternalServerError

        """

        try:

            payload = json.loads(request.body.decode('UTF-8'))

            email = payload.get('email', '')
            name = payload.get('name', '')
            text = payload.get('message', '')

            contact_support_email(email, text, name)

            return JsonResponse({}, status=200)

        except Exception as e:
            print(e)
            return JsonResponse500().json_response()
예제 #5
0
    def delete(self, request, user_id, address_id):

        """
        @api {DELETE} api/v1/user/<user_id>/address/<address_id>/ Delete Addresses
        @apiVersion 1.0.0

        @apiName    DeleteAddresses
        @apiGroup   Users

        @apiDescription  The endpoint is responsible for removing an address from the database.

        @apiSuccessExample {json} Success-Response:
        HTTP/1.1 200 OK

        { }

        @apiError (Bad Request 400)             {Object}        UserDoesNotExist        Please complete the fields for delivery address.
        @apiError (InternalServerError 500)     {Object}        InternalServerError

        """

        try:
            user = User.objects.get(pk=user_id)
            address = DeliveryAddress.objects.filter(user=user, pk=address_id)

            address.delete()

            return JsonResponse({})

        except User.DoesNotExist:
            return JsonResponse400('UserDoesNotExist', 'Such an user does not exist').json_response()
        except DeliveryAddress.DoesNotExist:
            return JsonResponse400('AddressDoesNotExist', 'Such an address does not exist').json_response()
        except Exception as e:
            print(e)
            return JsonResponse500().json_response()
예제 #6
0
    def post(self, request, user_id):

        """

        @api {POST} api/v1/user/<user_id>/address/ Address Creation
        @apiVersion 1.0.0

        @apiName    AddressCreation
        @apiGroup   Users

        @apiDescription  The endpoint is responsible for saving to the database the address provided by the user.

        @apiParam   {String}      first_name          The provided first name by the user.
        @apiParam   {String}      last_name           The provided last name by the user.
        @apiParam   {String}      street_address      The provided street address by the user.
        @apiParam   {Number}      apt_nr              The provided apartment number by the user.
        @apiParam   {Number}      postal_code         The provided postal code by the user.
        @apiParam   {String}      city                The provided city by the user.
        @apiParam   {String}      country             The provided country by the user.

        @apiSuccessExample {json} Success-Response:
        HTTP/1.1 200 OK
        {}

        @apiError (Bad Request 400)             {Object}        AddressNotProvided      Please complete the fields for delivery address.
        @apiError (Bad Request 400)             {Object}        UserDoesNotExist        Please complete the fields for delivery address.
        @apiError (InternalServerError 500)     {Object}        InternalServerError

        """

        try:

            payload = json.loads(request.body.decode('UTF-8'))

            first_name = payload.get('first_name', '')
            last_name = payload.get('last_name', '')
            street_address = payload.get('street_address', '')
            apt_nr = int(payload.get('apt_nr', ''))
            postal_code = int(payload.get('postal_code', ''))
            city = payload.get('city', '')
            country = payload.get('country', '')

            provided_address = []

            for key in ["first_name", "last_name", "street_address", "apt_nr", "postal_code", "city", "country"]:
                value = payload.get(key, None)

                if value is not None:
                    provided_address.append(value)

            # if no values are provided the Bad Request is risen.
            if len(provided_address) == 0:
                return JsonResponse400('AddressNotProvided',
                                       'Please complete the fields for delivery address.').json_response()

            # Checks if such and address already exists in the database
            user = User.objects.get(pk=user_id)

            DeliveryAddress.objects.create(first_name=first_name, last_name=last_name, user=user,
                                           street=street_address, apt_nr=apt_nr, zip_code=postal_code,
                                           city=city, country=country)
            return JsonResponse({}, status=200)

        except User.DoesNotExist:
            return JsonResponse400('UserDoesNotExist', 'Such a user does not exist').json_response()
        except IntegrityError:
            return JsonResponse({}, status=200)
        except Exception as e:
            print(e)
            return JsonResponse500().json_response()
예제 #7
0
    def get(self, request, user_id):

        """
        @api {GET} api/v1/user/<user_id>/all_addresses/ Get Addresses
        @apiVersion 1.0.0

        @apiName    GetAddresses
        @apiGroup   Users

        @apiDescription  The endpoint is responsible for retrieving all user's addresses.

        @apiSuccess {Object[]}  addresses               List with the all addresses.
        @apiSuccess {Integer}   address.id              Address's id.
        @apiSuccess {String}    address.first_name      User's first name
        @apiSuccess {Text}      address.last_name       User's last name
        @apiSuccess {Integer}   address.street          User's street information
        @apiSuccess {Integer}   address.apt_nr          User's apartment number.
        @apiSuccess {Integer}   address.zip_code        Zip Code of the address where the user lives.
        @apiSuccess {Integer}   address.city            City name of the address where the user lives.
        @apiSuccess {Integer}   address.country         Country name of the address where the user lives.

        @apiSuccessExample {json} Success-Response:
        HTTP/1.1 200 OK

        {
             'address_list': [
                {
                'apt_nr': 21,
                'city': 'Stockholm',
                'country': 'Sweden',
                'first_name': 'cristina1',
                'id': 1,
                'last_name': 'garbuz',
                'street': 'street',
                'zip_code': 14
                },
                {
                'apt_nr': 21,
                 'city': 'Stockholm',
                 'country': 'Sweden',
                 'first_name': 'cristina2',
                 'id': 2,
                 'last_name': 'garbuz',
                 'street': 'street',
                 'zip_code': 14
                 }
            ]
        }

        @apiError (Bad Request 400)             {Object}        UserDoesNotExist        Please complete the fields for delivery address.
        @apiError (InternalServerError 500)     {Object}        InternalServerError

        """

        try:
            user = User.objects.get(pk=user_id)

            address_qs = DeliveryAddress.objects.filter(user=user)

            address_list = []

            # adding to the product_list the dictionaries with the relevant product information.
            for address in address_qs:
                address_list.append({
                    'id': address.id,
                    'first_name': address.first_name,
                    'last_name': address.last_name,
                    'street': address.street,
                    'apt_nr': address.apt_nr,
                    'zip_code': address.zip_code,
                    'city': address.city,
                    'country': address.country,

                })

            return JsonResponse({
                "address_list": address_list
            })

        except User.DoesNotExist:
            return JsonResponse400('UserDoesNotExist', 'Such a user does not exist').json_response()
        except Exception as e:
            print(e)
            return JsonResponse500().json_response()
예제 #8
0
    def get(self, request):
        """

        @api {GET} /api/v1/products Search Products
        @apiVersion 1.0.0

        @apiName SearchProducts
        @apiGroup Products

        @apiDescription  The endpoint is responsible for getting all the existing products from the database.

        @apiParam   {String}   product_name             User input which will be checked against the product's name.


        @apiSuccess {Object[]}  products                List with products.
        @apiSuccess {Integer}   product.id              Product's id.
        @apiSuccess {String}    product.name            Product's name.
        @apiSuccess {Text}      product.description     Product's description.
        @apiSuccess {Integer}   product.price           Product's price per item.
        @apiSuccess {Integer}   product.quantity        Total available products.
        @apiSuccess {Object[]}  product.photo           Product's photo dictionary.
        @apiSuccess {Integer}   photo.id                Photo's id.
        @apiSuccess {URL}       photo.photo_url         Photo's url.

        @apiSuccessExample {json} Success-Response:

        HTTP/1.1 200 OK
        {
            'products': [
                {
                    'id': 1,
                    'name': 'earings',
                    'description': 'very beautiful',
                    'price': 200,
                    'quantity': 20,
                    'photos': [
                        {
                            'id': 1,
                            'photo_url': 'https://vintage-earrings.s3.eu-north-1.amazonaws.com/static/media/earrings/1.1.jpg',
                            'product_id': 1
                        }
                    ]
                },
                {
                    'id': 2,
                    'name': 'earings2',
                    'description': 'very beautiful',
                    'price': 200,
                    'quantity': 20,
                    'photos': [
                        {
                            'id': 2,
                            'photo_url': 'https://vintage-earrings.s3.eu-north-1.amazonaws.com/static/media/earrings/1.1.jpg',
                            'product_id': 2
                        }
                    ]
                },
            ]
         }

        @apiError (InternalServerError 500) {Object} InternalServerError

        """
        try:

            product_name = request.GET.get('product_name', None)
            product_id = request.GET.get('product_id', None)

            # get a query set with all the products and prefetch the productphoto_set related to the products
            product_qs = Product.objects.prefetch_related('productphoto_set').all()

            if product_name is not None:
                product_qs = product_qs.filter(name__icontains=product_name.lower())

            if product_id is not None:
                product_qs = product_qs.filter(pk=product_id)

            product_list = []

            # adding to the product_list the dictionaries with the relevant product information.
            for product in product_qs:
                product_list.append({
                    'id': product.id,
                    'name': product.name,
                    'description': product.description,
                    'price': product.price,
                    'quantity': product.quantity,
                    'photos': list(product.productphoto_set.all().values())
                })

            return JsonResponse({
                "products": product_list
            })
        except Exception as e:
            print(e)
            return JsonResponse500().json_response()
예제 #9
0
    def get(self, request):
        """

        @api {GET} /api/v1/products/latest Latest Products
        @apiVersion 1.0.0

        @apiName LatestProducts
        @apiGroup Products

        @apiDescription  The endpoint is responsible for getting the latest 6 products added to the database.

        @apiSuccess {Object[]}  products                List with products.
        @apiSuccess {Integer}   products.id             Product's id.
        @apiSuccess {String}    products.name           Product's name.
        @apiSuccess {Text}      products.description    Product's description.
        @apiSuccess {Integer}   products.price          Product's price per item.
        @apiSuccess {Integer}   products.quantity       Total available products.
        @apiSuccess {Object[]}  products.photo          Product's photo dictionary.
        @apiSuccess {Integer}   photo.id                Photo's id.
        @apiSuccess {URL}       photo.photo_url         Photo's url.

        @apiSuccessExample {json} Success-Response:

        HTTP/1.1 200 OK
        {
            'products': [
                {
                    'id': 1,
                    'name': 'earings',
                    'description': 'very beautiful',
                    'price': 200,
                    'quantity': 20,
                    'photos': [
                        {
                            'id': 1,
                            'photo_url': 'https://vintage-earrings.s3.eu-north-1.amazonaws.com/static/media/earrings/1.1.jpg',
                            'product_id': 1
                        }
                    ]
                },
                {
                    'id': 2,
                    'name': 'earings2',
                    'description': 'very beautiful',
                    'price': 200,
                    'quantity': 20,
                    'photos': [
                        {
                            'id': 2,
                            'photo_url': 'https://vintage-earrings.s3.eu-north-1.amazonaws.com/static/media/earrings/1.1.jpg',
                            'product_id': 2
                        }
                    ]
                },
                ...
            ]
         }

        @apiError (InternalServerError 500) {Object} InternalServerError

        """
        try:

            # get a query set with the latest 6 added products and prefetch the productphoto_set related to the products
            product_qs = Product.objects.prefetch_related('productphoto_set').order_by('-id')[:4]

            latestProducts_list = []

            # adding to the product_list the dictionaries with the relevant product information.
            for product in product_qs:
                latestProducts_list.append({
                    'id': product.id,
                    'name': product.name,
                    'description': product.description,
                    'price': product.price,
                    'quantity': product.quantity,
                    'photos': list(product.productphoto_set.all().values())
                })

            return JsonResponse({
                "latestProducts": latestProducts_list
            })
        except Exception as e:
            print(e)
            return JsonResponse500().json_response()
예제 #10
0
    def post(self, request, basket_id):
        """

        @api {POST} /api/v1/baskets/<basket_id>/items Add Item to the Basket
        @apiVersion 1.0.0

        @apiName AddItemToBasket
        @apiGroup Baskets

        @apiDescription  The endpoint is responsible for adding an item to the Basket.

        @apiParam   {Integer}   product_id              The product_id passed by the client side.

        @apiSuccess {Object}    item                    Represents the information about the item in the basket and the subsequent information about the product.
        @apiSuccess {Integer}   id                      Id of added item to the basket.
        @apiSuccess {String}    items_quantity          Represents the quantity of added item to the basket.
        @apiSuccess {Object[]}  products                List with products.
        @apiSuccess {Integer}   products.id             Product's id.
        @apiSuccess {String}    products.name           Product's name.
        @apiSuccess {Text}      products.description    Product's description.
        @apiSuccess {Integer}   products.price          Product's price per item.
        @apiSuccess {Integer}   products.quantity       Total available products.
        @apiSuccess {Object[]}  products.photo          Product's photo dictionary.
        @apiSuccess {Integer}   photo.id                Photo's id.
        @apiSuccess {URL}       photo.photo_url         Photo's url.

        @apiSuccessExample {json} Success-Response:
        HTTP/1.1 200 OK

            {
                'id': 1,
                'items_quantity': 1,
                'product':
                {
                    'id': 1,
                    'name': 'earings',
                    'description': 'very beautiful',
                    'price': 200,
                    'quantity': 20,
                    'photos':
                    [
                        {
                            'id': 1,
                            'photo_url': 'https://vintage-earrings.s3.eu-north-1.amazonaws.com/static/media/earrings/1.1.jpg',
                            'product_id': 1
                        }
                    ]
                 }
            }

        @apiError (Bad Request 400)         {Object}    InvalidProductId        Please provide a valid product id.
        @apiError (Bad Request 400)         {Object}    InvalidBasketId         Please provide a valid basket id.
        @apiError (InternalServerError 500) {Object}    InternalServerError

        """
        try:
            payload = json.loads(request.body.decode('UTF-8'))

            product_id = payload.get('product_id', '')

            # raises an error if the basket id or product id is not provided.
            if not product_id:
                return JsonResponse400(
                    'InvalidProductId',
                    'Please provide a valid product id.').json_response()

            if not basket_id:
                return JsonResponse400(
                    'InvalidBasketId',
                    'Please provide a valid basket id.').json_response()

            basket = Basket.objects.get(pk=basket_id)
            product = Product.objects.get(pk=product_id)

            basket_item = BasketItem.objects.filter(basket=basket,
                                                    product=product).exists()

            if basket_item:
                return JsonResponse400(
                    'DuplicateItem',
                    'This item already exists in the basket.').json_response()

            # Adding the new item to the Basket.
            new_item = BasketItem.objects.create(basket=basket,
                                                 product=product,
                                                 items_quantity=1)

            # query set returns the item from the BasketWithItems joined with the Product table on product Foreign Key.
            item = BasketItem.objects.select_related('product').get(
                pk=new_item.id)

            return JsonResponse({
                'id': item.id,
                'items_quantity': item.items_quantity,
                'product': {
                    'id': item.product.id,
                    'name': item.product.name,
                    'description': item.product.description,
                    'price': item.product.price,
                    'quantity': item.product.quantity,
                    'photos':
                    list(item.product.productphoto_set.all().values())
                }
            })
        except Basket.DoesNotExist:
            return JsonResponse400(
                'BasketNotFound',
                'Such basket id does not exist').json_response()
        except Exception as e:
            print(e)
            return JsonResponse500().json_response()
예제 #11
0
    def get(self, request, basket_id):
        """
        @api {GET} /api/v1/baskets/${basketId}/payment/verify Verify Payment
        @apiVersion 1.0.0

        @apiName PaymentVerify
        @apiGroup Baskets

        @apiDescription  The endpoint is responsible for verifying that the stripe payment was successful.

        @apiSuccessExample {json} Success-Response:

        HTTP/1.1 200 OK

            {
                'payment_status': succeeded
            }

        @apiError (Bad Request 400)         {Object}    InvalidBasketId         Please provide a valid basket id.
        @apiError (Bad Request 402)         {Object}    UnsuccessfulPayment  There was an error processing your payment.
        @apiError (InternalServerError 500) {Object}    InternalServerError

        """
        try:

            if not basket_id:
                return JsonResponse400(
                    'InvalidBasketId',
                    'Please provide a valid basket id.').json_response()

            basket = Basket.objects.get(pk=basket_id)
            stripe_id = basket.stripe_id

            stripe.api_key = settings.STRIPE_API_KEY

            # retrieve a stripe session
            session_response = stripe.checkout.Session.retrieve(stripe_id)

            # retrieve stripe PaymentIntent
            payment_intent = session_response.payment_intent
            payment_intent_response = stripe.PaymentIntent.retrieve(
                payment_intent)
            status = payment_intent_response.status

            # retrieve customer email
            customer_email = session_response.customer_email

            if status != 'succeeded':
                return JsonResponse402(
                    'There was an error processing your payment.'
                ).json_response()

            # establish a connection with RabbitMQ server.

            params = pika.URLParameters(settings.CLOUDAMQP_URL)
            connection = pika.BlockingConnection(params)
            channel = connection.channel()

            # make sure the recipient queue exists.
            # The durability options let the tasks survive even if RabbitMQ is restarted.
            channel.queue_declare(queue='order', durable=True)
            """
            A message can never be sent directly to the queue, it always needs to go through an exchange. 
            A default exchange is identified by an empty string. This exchange is special ‒ it allows us to specify 
            exactly to which queue the message should go. The queue name needs to be specified in the routing_key.
            """

            body = [basket_id, customer_email]

            channel.basic_publish(
                exchange='',
                routing_key='order',
                body=json.dumps(body),
                properties=pika.BasicProperties(
                    delivery_mode=2,  # make message persistent
                ))
            print("Message sent")
            connection.close()

            return JsonResponse({'payment_status': status})
        except Exception as e:
            print(e)
            return JsonResponse500().json_response()
예제 #12
0
    def post(self, request, basket_id):
        """

        @api {POST} /api/v1/baskets/<basket_id>/checkout Checkout Basket
        @apiVersion 1.0.0

        @apiName CheckoutBasket
        @apiGroup Baskets

        @apiDescription  The endpoint is responsible for creating a stripe payment session and returning the stripe session id.

        @apiParam   {String}   email              The email passed by the client side.

        @apiSuccess {String}   sessionId          Represents the stripe session id.


         @apiSuccessExample {json} Success-Response:

        HTTP/1.1 200 OK

            {
                'sessionId': 329e-4913-ae15-e9242451f698
            }

        @apiError (Bad Request 400)         {Object}    InvalidBasketId         Please provide a valid basket id.
        @apiError (Bad Request 400)         {Object}    InvalidEmail            Please provide a valid email.
        @apiError (InternalServerError 500) {Object}    InternalServerError

        """
        try:

            payload = json.loads(request.body.decode('UTF-8'))

            email = payload.get('email', '')

            try:
                validate_email(email)
            except ValidationError as ve:
                print('error message:', ','.join(ve.messages))
                return JsonResponse400('InvalidEmail',
                                       ','.join(ve.messages)).json_response()

            if not basket_id:
                return JsonResponse400(
                    'InvalidBasketId',
                    'Please provide a valid basket id.').json_response()

            basket = Basket.objects.get(pk=basket_id)
            stripe_id = basket.stripe_id

            if not stripe_id or True:

                basket_items_list = BasketItem.objects.prefetch_related(
                    'product').filter(basket=basket)

                # creating the list with all the products' information to be passed to stripe
                line_items = []

                for item in basket_items_list:
                    line_items.append({
                        "name":
                        item.product.name,
                        "currency":
                        'eur',
                        "amount":
                        item.product.price * 100,
                        "quantity":
                        item.items_quantity,
                        'images': [
                            product_image.photo_url for product_image in
                            item.product.productphoto_set.all()
                        ]
                    })

                # stripe payment
                stripe.api_key = settings.STRIPE_API_KEY

                stripe_response = stripe.checkout.Session.create(
                    success_url=f"{settings.HOST}/success/{basket_id}",
                    cancel_url=f"{settings.HOST}/cancel/{basket_id}",
                    customer_email=email,
                    payment_method_types=["card"],
                    line_items=line_items,
                    mode='payment')

                # Getting the data from the stripe response that is important for the client
                stripe_id = stripe_response['id']

                # saving the stripe_id to the Basket
                basket.stripe_id = stripe_id
                basket.save()

            return JsonResponse({'sessionId': stripe_id})
        except Exception as e:
            print(e)
            return JsonResponse500().json_response()
예제 #13
0
    def get(self, request, basket_id):
        """

        @api {GET} /api/v1/baskets/<basket_id>/items Get Items from the Basket
        @apiVersion 1.0.0

        @apiName GetItemsFromBasket
        @apiGroup Baskets

        @apiDescription  The endpoint is responsible for getting the Items from the Basket.

        @apiSuccess {Object[]}  items                   Represents all the existing items in the Basket.
        @apiSuccess {Integer}   id                      Id of added item to the basket.
        @apiSuccess {Integer}   items_quantity          Represents the quantity of added item to the basket.
        @apiSuccess {Object[]}  products                List with products.
        @apiSuccess {Integer}   products.id             Product's id.
        @apiSuccess {String}    products.name           Product's name.
        @apiSuccess {Text}      products.description    Product's description.
        @apiSuccess {Integer}   products.price          Product's price per item.
        @apiSuccess {Integer}   products.quantity       Total available products.
        @apiSuccess {Object[]}  products.photo          Product's photo dictionary.
        @apiSuccess {Integer}   photo.id                Photo's id.
        @apiSuccess {URL}       photo.photo_url         Photo's url.

         @apiSuccessExample {json} Success-Response:

        HTTP/1.1 200 OK

            {
             'items': [
                {
                    'id': 1,
                    'items_quantity': 1,
                    'product': {
                        'description': 'product1.description',
                        'id': 'product1.id',
                        'name': 'product1.name',
                        'photos': [
                            {
                                'id': photo1.id,
                                'photo_url': 'https://vintage-earrings.s3.eu-north-1.amazonaws.com/static/media/earrings/1.1.jpg',
                                'product_id': product1.id
                            }
                        ],
                        'price': 'product1.price',
                        'quantity': 'product1.quantity'
                    }
                },
                {
                    'id': 2,
                    'items_quantity': 1,
                    'product': {
                        'description': 'product2.description',
                        'id': 'product2.id',
                        'name': 'product2.name',
                        'photos': [
                            {
                                'id': 'photo2.id',
                                'photo_url': 'https://vintage-earrings.s3.eu-north-1.amazonaws.com/static/media/earrings/1.1.jpg',
                                'product_id': 'product2.id'
                            }
                        ],
                        'price': 'product2.price',
                        'quantity': 'product2.quantity'
                    }
                }
            ]
            }

        @apiError (Bad Request 400)         {Object}    InvalidBasketId         Please provide a valid basket id.
        @apiError (InternalServerError 500) {Object}    InternalServerError

        """
        try:

            # raises an error if no basked id is provided.
            if not basket_id:
                return JsonResponse400(
                    'InvalidBasketId',
                    'Please provide a valid basket id.').json_response()

            # get a query set that returns all the items from a specific basket joined with the Product table on
            # product's Foreign Key.

            basket = Basket.objects.get(pk=basket_id)
            items_qs = BasketItem.objects.select_related('product').filter(
                basket=basket)

            items_list = []

            # adding to the product_list the dictionaries with the relevant product information.
            for item in items_qs:
                items_list.append({
                    'id': item.id,
                    'items_quantity': item.items_quantity,
                    'product': {
                        'id':
                        item.product.id,
                        'name':
                        item.product.name,
                        'description':
                        item.product.description,
                        'price':
                        item.product.price,
                        'quantity':
                        item.product.quantity,
                        'photos':
                        list(item.product.productphoto_set.all().values())
                    }
                })

            return JsonResponse({"items": items_list})
        except Exception as e:
            print(e)
            return JsonResponse500().json_response()
예제 #14
0
    def patch(self, request, basket_id, item_id):
        """

        @api {PATCH} /api/v1/baskets/<basket_id>/items/<item_id> Update the items_quantity
        @apiVersion 1.0.0

        @apiName UpdateItemNumber
        @apiGroup Baskets

        @apiDescription  The endpoint is responsible for updating the number of items in the basket.

        @apiParam   {Integer}   quantity              The product_id passed by the client side.

        @apiSuccessExample {json} Success-Response:
        HTTP/1.1 200 OK
            { }

        @apiError (Bad Request 400)         {Object}    InvalidItemId        Please provide a valid item id.
        @apiError (Bad Request 400)         {Object}    InvalidBasketId         Please provide a valid basket id.
        @apiError (Bad Request 400)         {Object}    InvalidQuantity         Please provide a valid quantity value.
        @apiError (InternalServerError 500) {Object}    InternalServerError

        """
        try:
            payload = json.loads(request.body.decode('UTF-8'))

            item_quantity = payload.get('quantity', '')

            # raises an error if a value is not provided.
            if not item_id:
                return JsonResponse400(
                    'InvalidItemId',
                    'Please provide a valid item id.').json_response()

            if not basket_id:
                return JsonResponse400(
                    'InvalidBasketId',
                    'Please provide a valid basket id.').json_response()

            if not item_quantity:
                return JsonResponse400(
                    'InvalidQuantity',
                    'Please provide a valid quantity value.').json_response()

            basket = Basket.objects.get(pk=basket_id)

            basket_item = BasketItem.objects.get(basket=basket, pk=item_id)

            if not basket_item:
                return JsonResponse400(
                    'BasketItemNotFound',
                    'This basked does not contain such an item').json_response(
                    )

            basket_item.items_quantity = item_quantity
            basket_item.save()

            return JsonResponse({})
        except Exception as e:
            print(e)
            return JsonResponse500().json_response()