Exemplo n.º 1
0
    def get_products(product_ids: list) -> dict:
        r"""
        Get all the products of perticular secondary category
        """

        # All the products of perticular secondary category
        products = ProductDB.objects(product_id__in=product_ids).all()
        # List of marshmallows of ProductDB objects
        data = []
        for product in products:
            product_data = get_product_json(product, product_resource_fields)
            data.append(product_data)

        return data
    def get_products(product_ids: list) -> dict:
        r"""
        Get all the sproducts of perticular secondary category
        """

        # All the sproducts of perticular secondary category
        products = ProductDB.objects(product_id__in=product_ids).all()
        # List of marshmallows of ProductDB objects
        product_marshal = [
            get_product_json(product, product_resource_fields)
            for product in products
        ]

        return product_marshal
    def get(self):
        args = parser.parse_args()
        response = {}

        log_info(args)

        try:
            category_ids = args['category_id']
            min_max_price = args['price']

            if not (isinstance(category_ids, list)
                    and isinstance(min_max_price, list)
                    and len(category_ids) > 0 and len(min_max_price) == 2):
                return {'status': 'fail', 'msg': 'Bad Request'}, 400

            category_ids = list(map(int, category_ids))
            min_max_price = list(map(int, min_max_price))
            min_price, max_price = min(min_max_price), max(min_max_price)

            # SELECT * FROM SecondaryCategoryDB
            category_docs = (SecondaryCategoryDB.objects(
                category_id__in=category_ids).all())
            product_docs = (ProductDB.objects(
                category__in=category_docs,
                discounted_price__gt=min_price,
                discounted_price__lt=max_price).all())

            if len(product_docs) == 0:
                data = []
            else:
                data = [
                    get_product_json(doc, product_resource_fields)
                    for doc in product_docs
                ]

            response['status'] = 'success'
            response['msg'] = {'data': data}
            return response, 200

        except Exception as e:
            response['status'] = 'fail'
            response['msg'] = str(e)

            return response, 500
Exemplo n.º 4
0
    def get(self, id=None):

        if id is None:
            return {'status': 'success', 'msg': {'data': None}}, 204

        args = parser.parse_args()
        response = {}

        try:
            # SELECT * FROM ProductDB WHERE product_id=id
            product = ProductDB.objects(product_id=id).first()

            if product is None:
                response['status'] = 'fail'
                response['msg'] = f'product_id {id} not available in db'
                return response, 404

            # Marshmallow-ing product object
            product_marshal = get_product_json(product,
                                               product_resource_fields)

            # Get corresponding category from SecondaryCategoryDB
            # SELECT * FROM SecondaryCategoryDB WHERE category_id=parent_category_id
            parent_category_id = product.category.category_id
            category_doc = (SecondaryCategoryDB.objects(
                category_id=parent_category_id).first())

            if category_doc is not None:
                # Marshmallow-ing category object
                category_data = get_secondary_category_json(
                    category_doc, secondary_category_resource_fields)
                product_marshal['category_data'] = category_data

            response['status'] = 'success'
            response['msg'] = {'data': product_marshal}
            return response, 200

        except Exception as e:
            # log_info(e)
            response['status'] = 'fail'
            response['msg'] = str(e)

            return response, 500
    def get_products(product_ids: list) -> dict:
        r"""
        Get all the sproducts of perticular secondary category
        """

        # All the sproducts of perticular secondary category
        products = ProductDB.objects(product_id__in=product_ids).all()
        parent_category_ids = [
            product.category.category_id for product in products
        ]

        # Get corresponding all categories from SecondaryCategoryDB
        # SELECT * FROM SecondaryCategoryDB WHERE category_id in parent_category_ids
        category_docs = (SecondaryCategoryDB.objects(
            category_id__in=parent_category_ids).all())

        # List of product marshmallows
        products_marshal = []

        for product in products:
            # Marshmallow-ing product object
            product_marshal = get_product_json(product,
                                               product_resource_fields)

            for category_doc in category_docs:
                if product.category.category_id == category_doc['category_id']:
                    # Marshmallow-ing category object and then
                    # break the inner for-loop
                    category_data = get_secondary_category_json(
                        category_doc, secondary_category_resource_fields)
                    product_marshal['category_data'] = category_data
                    break

            products_marshal.append(product_marshal)

        return products_marshal
Exemplo n.º 6
0
    def delete(self, id):
        args = parser.parse_args()
        response = {}

        try:
            content, status_code = (Product.decode_token(
                token=args['Authorization']))

            if content['status'] == 'success':
                # Authorized seller

                # SELECT * FROM ProductDB WHERE product_id=id
                product = ProductDB.objects(product_id=id).first()

                if product is None:
                    response['status'] = 'fail'
                    response['msg'] = f'product_id {id} not available in db'
                    return response, 404

                # SELECT * FROM Seller2Products WHERE seller_id=product.seller_id
                s2p = (Seller2Products.objects(
                    seller_id=product.seller_id).first())

                if s2p is None or id not in s2p.product_ids:
                    # This seller has not has any product yet, or
                    # This product was added by another seller
                    response['status'] = 'fail'
                    response[
                        'msg'] = f'product_id {id} was not added by seller id {product.seller_id}'
                else:
                    # If seller already has added few products
                    # then remove product.product_id from the
                    # same category's product_ids list and
                    # add product.product_id to the
                    # same category's archive_product_ids list
                    s2p.update(pull__product_ids=product.product_id)
                    s2p.update(
                        add_to_set__archive_product_ids=[product.product_id])

                # Get corresponding category from SecondaryCategoryDB
                # SELECT * FROM SecondaryCategoryDB WHERE category_id=parent_category_id
                parent_category_id = product.category.category_id
                category_doc = (SecondaryCategoryDB.objects(
                    category_id=parent_category_id).first())

                if category_doc is not None:
                    # Remove product.product_id from the
                    # same category's product_ids list
                    category_doc.update(pull__product_ids=product.product_id)

                # Delete the product
                product.delete()

                response['status'] = 'success'
                response['msg'] = f'product_id {id} has deleted from db'

                return response, 200

            elif content['status'] == 'fail':
                return content, status_code

        except Exception as e:
            # log_info(e)
            response['status'] = 'fail'
            response['msg'] = str(e)

            return response, 500
Exemplo n.º 7
0
    def put(self, id):
        args = parser.parse_args()
        response = {}

        try:
            content, status_code = (Product.decode_token(
                token=args['Authorization']))

            if content['status'] == 'success':
                # Authorized seller

                product_args = {
                    'product_name':
                    args['product_name'],
                    'short_description':
                    args['short_description'],
                    'long_description':
                    args['long_description'],
                    'quantity':
                    args['quantity'],
                    'discount':
                    args['discount'],
                    'features': [
                        feature.strip()
                        for feature in args['features'].split(',')
                    ],
                    'colors':
                    [color.strip() for color in args['colors'].split(',')],
                    'sizes':
                    [size.strip() for size in args['sizes'].split(',')],
                    'img_base_url':
                    args['img_base_url'],
                    'img_aux_urls':
                    list(
                        filter(lambda x: x is not None, [
                            args.get('aux_img_url_1'),
                            args.get('aux_img_url_2'),
                            args.get('aux_img_url_3')
                        ]))
                }
                if current_app.config['DEBUG'] == True:
                    log_info(args)
                    log_info(product_args)

                # SELECT * FROM ProductDB WHERE product_id=id
                product = ProductDB.objects(product_id=id).first()

                # Update values
                setattr(product.date, 'date_last_update', datetime.utcnow())
                # product.extra = {}
                for key, value in product_args.items():
                    if hasattr(product, key):
                        setattr(product, key, value)
                    elif hasattr(product.description, key):
                        setattr(product.description, key, value)

                # Marshmallow-ing product object
                product_marshal = get_product_json(product,
                                                   product_resource_fields)

                # Get corresponding category from SecondaryCategoryDB
                # SELECT * FROM SecondaryCategoryDB WHERE category_id=parent_category_id
                parent_category_id = product.category.category_id
                category_doc = (SecondaryCategoryDB.objects(
                    category_id=parent_category_id).first())

                if category_doc is not None:
                    # Marshmallow-ing category object
                    category_data = object_to_json(
                        category_doc, secondary_category_resource_fields)
                    product_marshal['category_data'] = category_data

                product.save()

                response['status'] = 'success'
                response['msg'] = {'data': product_marshal}

                return response, 200

            elif content['status'] == 'fail':
                return content, status_code

        except KeyError as e:
            # log_info(e)
            response['status'] = 'fail'
            response['msg'] = str(e) + " is not available in json data"

            return response, 400

        except ValidationError as e:
            # log_info(e)
            response['status'] = 'fail'
            response['msg'] = str(e)

            return response, 400

        except Exception as e:
            # log_info(e)
            response['status'] = 'fail'
            response['msg'] = str(e)

            return response, 500