Example #1
0
    def get(self, request):
        try:
            params = request.GET
            assert 'customer_id' in params and params[
                'customer_id'] != '', "parameter customer_id not found::404"
            customer_id = params['customer_id']
            customer = checkIsExists(Customers, id=int(customer_id))
            assert customer, "customer not found::404"

            carts = Carts.objects.filter(customer_id=customer_id)
            data = getPaginate(request,
                               carts,
                               pageQueryName='page',
                               sizeQueryName='page_size')
            return SuccessResponse({
                'data':
                CartSerializer(data['data'], many=True).data,
                'meta':
                data['meta']
            })

        except AssertionError as error:
            return AssertionErrorResponse(str(error))

        except Exception as error:
            print(error)
            return ErrorResponse("Internal Server Error", 500)
Example #2
0
    def post(self, request):
        try:
            data = request.data
            customer = checkIsExists(Customers, id=data['customer_id'])
            product = checkIsExists(Products, id=data['product_id'])

            assert customer, "customer not found::404"
            assert product, "product not found::404"

            already_exist = checkIsExists(Carts,
                                          customer_id=customer.id,
                                          product_id=product.id)
            if already_exist:
                varian_exist = json.loads(already_exist.varian)
                varian_data = data['varian']
                # check if data already exist with the same varian
                if self.checkVarianExist(varian_data, varian_exist):
                    current_quantity = already_exist.quantity
                    already_exist.quantity += current_quantity
                    already_exist.save()

                else:
                    self.saveData(data, product)

            else:
                self.saveData(data, product)

            return SuccessResponse({'message': 'data successfully added!'})

        except AssertionError as error:
            return AssertionErrorResponse(str(error))

        except Exception as error:
            print(error)
            return ErrorResponse("Internal Server Error", 500)
Example #3
0
    def get(self, request):
        try:
            data_raw = Merchants.objects.all()
            data = MerchantSerializer(data_raw, many=True).data
            return SuccessResponse({"data": data})

        except AssertionError as error:
            return AssertionErrorResponse(str(error))
Example #4
0
    def post(self, request, id):
        try:
            data = request.data
            merchant = checkIsExists(Merchants, id=id)
            assert merchant, "merchant id is not found::404"
            saved = Categories.objects.create(merchant_id=id,
                                              name=data['name'])
            return SuccessResponse({"message": "data successfully created!"})

        except AssertionError as error:
            return AssertionErrorResponse(str(error))
Example #5
0
    def post(self, request):
        # try:
            data = request.data
            is_customer_exist = checkIfExist(Customers, id = int(data['customer_id']))
            if not is_customer_exist:
                return AssertionErrorResponse("customer id not found, please check your customer id::404")
            serializer = ShopSerializer(data = data)
            if serializer.is_valid():
                saved = serializer.save()
                is_customer_exist.is_shop_owner = True
                is_customer_exist.save()
                return Response({"status":"success", "message":"data successfully craeted"})

        # except:
        #     return BadRequestResponse()
Example #6
0
    def get(self, request, id):
        try:
            params = request.GET
            if 'ouput' in params and params['ouput'] == 'data':
                pass

            categories = Categories.objects.filter(merchant_id=id)
            paginated = getPaginate(request,
                                    categories,
                                    pageQueryName='page',
                                    sizeQueryName='page_size')
            data = CategorySerializer(paginated['data'], many=True).data
            return SuccessResponse({"data": data, "meta": paginated['meta']})

        except AssertionError as error:
            return AssertionErrorResponse(str(error))
Example #7
0
    def get(self, request):
        try:
            params = request.GET
            products = Products.objects.all()
            paginated = getPaginate(request,
                                    products,
                                    pageQueryName='page',
                                    sizeQueryName='page_size')
            return SuccessResponse({
                "data":
                ProductSerializer(paginated['data'], many=True).data,
                "meta":
                paginated['meta']
            })

        except AssertionError as error:
            return AssertionErrorResponse(str(error))
Example #8
0
    def post(self, request):
        try:
            data = request.data
            serializer = MerchantSerializer(data=data)
            if serializer.is_valid():
                is_exist = checkIsExists(Sellers,
                                         customer_id=data['customer_id'])
                assert is_exist, "customer not found::404"
                saved = serializer.save()
                return SuccessResponse(
                    {"data": MerchantSerializer(saved).data})

            else:
                raise AssertionError("invalid data::400")

        except AssertionError as error:
            return AssertionErrorResponse(str(error))
Example #9
0
    def post(self, request):
        try:
            data = request.data
            data_length = data['length']
            path = []
            for i in range(int(data_length)):
                attribute = 'file_{}'.format(i + 1)
                file = data[attribute]
                print(file)
                saved = saveFile(file)
                print('saved file -> ', saved)
                if saved:
                    path.append(saved)

            return SuccessResponse({"data": path})

        except AssertionError as error:
            return AssertionErrorResponse(str(error))
Example #10
0
    def post(self, request):
        try:
            data = request.data
            serializer = CustomerSerializer(data=data)
            if serializer.is_valid():
                saved = serializer.save()
                saved.password = generateHash(data['password'])
                saved.save()

                include_address = False
                address_saved = None

                if 'address' in data and data['address'] != {}:
                    address = data['address']
                    if not isinstance(address, dict):
                        temp = json.dumps(address)
                        address = json.loads(temp)
                    address_serializer = CustomerAddressSerializer(
                        data=address)
                    if address_serializer.is_valid():
                        address_saved = address_serializer.save()
                        address_saved.default = True
                        address_saved.customer_id = saved.id
                        address_saved.save()
                        include_address = True
                resp = {
                    "message": "data successfully added!",
                    "data": CustomerSerializer(saved, many=False).data
                }
                if include_address:
                    resp['address'] = CustomerAddressSerializer(
                        address_saved, many=False).data
                return SuccessResponse(resp)

            else:
                raise

        except AssertionError as error:
            return AssertionErrorResponse(str(error))

        except:
            return ErrorResponse("Bad Request")
Example #11
0
    def post(self, request):
        try:
            data = request.data
            customer_id = data['customer_id']
            customer = checkIsExists(Customers, id=customer_id)
            assert customer, "customer_id not found::404"
            serializer = SellerSerializer(data=data)
            if serializer.is_valid():
                saved = serializer.save()
                customer.is_seller = True
                customer.save()
                return SuccessResponse({"message": "data successfully added!"})
            else:
                raise

        except AssertionError as error:
            return AssertionErrorResponse(str(error))

        except:
            return ErrorResponse("Bad Request")
Example #12
0
    def get(self, request, id):
        try:
            sql = """
				SELECT products.id, products.name, products.description, products.price, products.stocks, products.varian, products.media, products.date_created, products.time_created,
						merchants.id as merchant_id, merchants.name as merchant_name, merchants.address as merchant_address, product_categories.id as category_id, product_categories.name as categories
				FROM ((products INNER JOIN merchants ON products.merchant_id = merchants.id) INNER JOIN product_categories ON products.category_id = product_categories.id)
				WHERE products.id = '{}'
			""".format(id)
            result = query(sql, False)
            result['varian'] = json.loads(result['varian'])
            result['media'] = json.loads(result['media'])

            spec_sql = """
				SELECT * FROM product_specifications WHERE product_id = '{}'
			""".format(id)
            result['specifications'] = query(spec_sql)
            result['tags'] = query(
                "SELECT * FROM product_tags WHERE product_id = '{}'".format(
                    id))
            return SuccessResponse({'data': result})

        except AssertionError as error:
            return AssertionErrorResponse(str(error))
Example #13
0
    def post(self, request):
        try:
            data = request.data
            merchant = checkIsExists(Merchants, id=data['merchant_id'])
            category = checkIsExists(Categories, id=data['category_id'])

            assert merchant, "merchant_id is not found::404"
            assert category, "caregory_id is not found::404"

            product = None
            product_spec = []
            product_tags = []
            try:
                product = Products.objects.create(
                    merchant_id=data['merchant_id'],
                    name=data['name'],
                    description=data['description'],
                    price=data['price'],
                    stocks=data['stocks'],
                    category_id=data['category_id'],
                    varian=json.dumps(data['varian']),
                    media=json.dumps(data['media']))

                if 'specifications' in data:
                    specifications = data['specifications']
                    if not isinstance(specifications, list):
                        specifications = json.loads(specifications)
                    for spec in specifications:
                        try:
                            temp = ProductSpecifications.objects.create(
                                product_id=product.id,
                                name=spec['name'],
                                value=spec['value'])
                            product_spec.append(temp)
                        except:
                            pass

                if 'tags' in data:
                    tags = data['tags']
                    if not isinstance(tags, list):
                        tags = json.loads(tags)
                    for tag in tags:
                        try:
                            temp = ProductTags.objects.create(
                                product_id=product.id,
                                # name = tag['name']
                                name=tag)
                            product_tags.append(temp)

                        except:
                            pass

                return SuccessResponse(
                    {"message": "data successfully created"})

            except Exception as error:
                if product != None:
                    product.delete()

                if len(product_spec) > 0:
                    for i in product_spec:
                        i.delete()

                if len(product_tags) > 0:
                    for i in product_tags:
                        i.delete()

                print(str(error))
                raise AssertionError("error while submitting data::400")

        except AssertionError as error:
            return AssertionErrorResponse(str(error))

        except:
            return ErrorResponse("BadRequest")