Ejemplo n.º 1
0
    def put(self, client_id):

        data = request.json if request.json else {}

        v = CustomValidator(schema)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document

        client = ModelClient.find_client(client_id)

        if not client:
            return jsonify({"message": "Client not found"}), 404

        if client:

            try:
                client.update_client(**data)
                client.save_client()
                return jsonify({
                    "message": "client updated",
                    "data": client.json_client()
                }), 200

            except:
                return jsonify({"message": "Internal Error"}), 500
Ejemplo n.º 2
0
    def post(self):

        data = request.json if request.json else {}

        v = CustomValidator(schema_stock)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400
        data = v.document

        list_data = []

        for product in data.get("products"):

            if product.get("value"):
                data_product = ModelProducts.find_product_without_stock(
                    product.get("id"))

                if not data_product:
                    return jsonify({"message": "product {} not found or stock already registered".format(product.get("id"))}), 400

                data_product.stock.available_stock = product.get("value")
                data_product.stock.initial_stock = True

                list_data.append(data_product)

        try:
            [data.save_product() for data in list_data]
            return jsonify({"message": "Updated quantities", "data": [{"name": data.name, "qtde": data.stock.available_stock} for data in list_data]}), 200

        except:
            return jsonify({"message": "Internal Error"})
            pass

        return jsonify(data), 200
Ejemplo n.º 3
0
    def put(self, brand_id):

        data = request.json if request.json else{}

        v = CustomValidator(schema)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document

        brand = ModelBrandProduct.find_brand(brand_id)

        if brand:
            try:

                brand.update_brand(**data)
                brand.save_brand()

                return jsonify({"messahe": "Cateory updated", "data": brand.list_brand()}), 200

            except:

                return jsonify({"message": "Internal error"}), 500
        return jsonify({"messahe": "Brand not found"}), 404
Ejemplo n.º 4
0
    def put(self, provider_id):

        data = request.json if request.json else {}

        v = CustomValidator(schema)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document

        provider = ModelProvider.find_provider(provider_id)

        if not provider:
            return jsonify({"message": "Provider not found"}), 404

        if provider:
            try:
                provider.update_provider(**data)
                provider.save_provider()
                return jsonify({
                    "message": "provider updated",
                    "data": provider.json_provider()
                }), 200
            except:
                return jsonify({"message": "Internal Error"}), 500
Ejemplo n.º 5
0
    def put(self, unit_id):

        data = request.json if request.json else {}

        v = CustomValidator(schema)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document

        unit = ModelProductUnit.find_unit(unit_id)

        if not unit:
            return jsonify({"message": "Unit not found"}), 404

        unit_name = ModelProductUnit.find_unit_name(data.get("name"))

        if unit_name:
            if len(unit_name) > 1 or unit_name[0] != unit_id:
                return {"message": "Duplicate name."}, 400

        try:

            unit.update_unit(**data)
            unit.save_unit()
            return {"message": "Unit updated", "data": unit.json_units()}, 200
        except:
            return {"message": "Internal error"}, 500
Ejemplo n.º 6
0
    def post(self):
        """
        Realizar Login para receber o token de acesso
        """

        data = request.json if request.json else {}

        v = CustomValidator(schema_login)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document

        user = ModelsUser.user_login(data.get("username"))

        if not user:
            return jsonify({"message": "User Or Password Error"}), 401

        if not user.check_password(data.get("password")):
            return jsonify({"message": "User Or Password Error"}), 401

        if not user.enable:
            return jsonify(
                {"message": "Usuário desabilitado. Contate o suporte"}), 401

        expire = timedelta(hours=12)
        token = create_access_token(identity=user.list_users(),
                                    expires_delta=expire)
        return jsonify({"data": {"id": user.id_user, "token": token}}), 200
Ejemplo n.º 7
0
    def post(self):
        """ Adicionar ou editar Unidade.
        Para criar envie string vazia em id e para editar envie um int com o ID da unidade """

        data = request.json if request.json else {}

        v = CustomValidator(schema)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document

        unit_name = ModelProductUnit.find_unit_name(data.get("name"))

        if unit_name:
            return {"message": "Duplicate name."}, 400

        try:

            unit = ModelProductUnit(**data)
            unit.save_unit()

            return {"message": "Unit saved", "data": unit.json_units()}, 201

        except:
            return {"message": "Internal error"}, 500
Ejemplo n.º 8
0
    def post(self):
        """
        Adicionar ou Editar novo usuário.
        Para criar envie string vazia em id e para editar envie um int com o ID do usuário
        """
        data = request.json if request.json else {}

        v = CustomValidator(schema)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document

        username = ModelsUser.find_username(data.get("username"))

        if username:
            return jsonify(
                {"message": "Nome de usuário já existe. Tente outro."}), 400

        try:

            user = ModelsUser(**data)
            user.generate_hash()
            user.save_user()

            return jsonify({
                "message": "Usuário criado",
                "data": user.list_users()
            }), 201

        except:

            return jsonify({"message": "Internal Error"}), 500
Ejemplo n.º 9
0
    def put(self, client_id, address_id):
        """ Atualiza endereço de entrega cadastrador"""

        data = request.json if request.json else {}

        v = CustomValidator(schema_address)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document

        address = ModelDelivereAdrressClient.query.filter_by(
            id=address_id).filter_by(client=client_id).first()

        if address:

            try:
                address.update_address(**data)
                address.save_address()

                return jsonify({
                    "message": "address updated",
                    "data": address.list_address()
                }), 200
            except:

                return jsonify({"message": "Internal error"}), 500

        return jsonify({"message": "Address not found"}), 404
Ejemplo n.º 10
0
    def post(self):
        """ Adicionar ou editar produto.
        Para criar envie string vazia em id e para editar envie um int com o ID do produto"""

        data = request.json if request.json else{}

        v = CustomValidator(schema)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document

        product_code = ModelProducts.find_internal_code(
            data.get("internal_code"))
        if product_code:
            return jsonify({"message": "Product Code in use to other product"}), 400

        # Check if category exist
        if not ModelCategoryProduct.find_category(data.get("category")):
            return jsonify({"message": "Category id {} not found".format(data.get("category"))}), 400

        # Check if provider exist
        lst_provider = []

        for id_provider in data.get("provider"):
            provider = ModelProvider.find_provider(id_provider)
            if not provider:
                return jsonify({"message": "provider id {} not found".format(id_provider)}), 400

            lst_provider.append(provider)

        try:

            b64_cover = data.get("cover")

            if b64_cover:
                data["cover"] = upload_image(b64_cover)

            product = ModelProducts(**data)

            # Appending Images
            for images in data.get("images"):
                product.images.append(ModelImagesProduct(
                    upload_image(images), product))

            # Appending provider

            [product.providers.append(provider) for provider in lst_provider]

            # Save Product
            product.save_product()

            return jsonify({"message": "product created", "data": product.get_product()}), 201

        except Exception as err:
            print(err)

            return jsonify({"message": "Internal error"}), 500
Ejemplo n.º 11
0
    def put(self, product_id):

        data = request.json if request.json else{}

        v = CustomValidator(schema)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document

        product = ModelProducts.find_product(product_id)

        # Check if category exist
        if not ModelCategoryProduct.find_category(data.get("category")):
            return jsonify({"message": "Category id {} not found".format(data.get("category"))}), 400

        # Check if provider exist
        lst_provider = []
        for id_provider in data.get("provider"):
            provider = ModelProvider.find_provider(id_provider)
            if not provider:
                return jsonify({"message": "provider id {} not found".format(id_provider)}), 400

            lst_provider.append(provider)

        product_code = ModelProducts.find_internal_code(
            data.get("internal_code"))

        if product_code:
            if len(product_code) > 1:
                return jsonify({"message": "Product Code in use to other product"}), 400
            if product_code[0] != int(product_id):
                return jsonify({"message": "Product Code in use to other product"}), 400

        try:
            if data.get("cover"):
                data["cover"] = upload_image(data.get("cover"))

            product.update_product(**data)
            # Appending Images
            for images in data.get("images"):
                product.images.append(ModelImagesProduct(
                    upload_image(images), product))

            # Appending provider
            [product.providers.append(provider) for provider in lst_provider]

            # Save Prodict
            product.save_product()

            return jsonify({"message": "Product Updated", "data": product.get_product()}), 200
        except Exception as err:
            print(err)
            return {"message": "internal error"}, 500
Ejemplo n.º 12
0
    def post(self):
        """ Adicionar ou editar cliente.
        Para criar envie string vazia em id e para editar envie um int com o ID do cliente
        """
        data = request.json if request.json else {}

        v = CustomValidator(schema)
        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document

        # Check if delivery_addres has one current selected
        current = len([
            address.get("current")
            for address in data.get("delivery_address", "{}")
            if address.get("current")
        ])
        if len(data.get("delivery_address")) > 1:
            if current != 1:
                return jsonify(
                    {"message": "Only one address current required"}), 400
        else:
            data["delivery_address"][0]["current"] = True
        # End check current address

        try:
            client = ModelClient(**data)

            for address in data.get("delivery_address"):
                client.delivery_address.append(
                    ModelDelivereAdrressClient(client=client, **address))

            client.save_client()

            return jsonify({
                "message": "Client created",
                "data": client.json_client()
            }), 201
        except:

            return jsonify({"message": "Internal error"}), 500
Ejemplo n.º 13
0
    def post(self, client_id):
        """ Adiciona endereço de entrega """

        data = request.json if request.json else {}

        v = CustomValidator(schema_address)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document

        client = ModelClient.find_client(client_id)

        if not client:
            return jsonify({"message": "Client not found"}), 400

        address = [
            address.list_address() for address in client.delivery_address
        ]

        if not address:
            data["current"] = True
        else:
            if data.get("current"):
                for new in address:
                    address = ModelDelivereAdrressClient.find_address(
                        new.get("id"))
                    address.current = False
                    address.save_address()

        try:
            address = ModelDelivereAdrressClient(**data, client=client_id)
            address.save_address()

            return jsonify({
                "message": "address created",
                "data": address.list_address()
            }), 201
        except:
            return jsonify({"message": "internal error"}), 200
Ejemplo n.º 14
0
    def patch(self, purchase_id):
        """ Atualizar status da entrega.
        1: Pendente
        2: Em Trânsito
        3: Entregue (Dar entrada do produto no estoque)
        """

        data = request.json if request.json else {}

        v = CustomValidator(schema_delivery)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document

        purchase = ModelPurchase.find_purchase(purchase_id)

        if purchase:

            delivery_status = purchase.delivery_status

            if delivery_status == 3:
                return jsonify(
                    {"message": "Delivered purchase cannot be changed"}), 400

            if data.get("delivery_status") == delivery_status:
                return jsonify({"message": "No changes to make"}), 400

            try:
                purchase.update_delivery_status(data.get("delivery_status"))
                purchase.save_purchase()
                return jsonify({
                    "message": "Updated delivery status",
                    "status": purchase.delivery_status_name.name
                }), 200
            except Exception as err:
                print(err)
                return jsonify({"message": "internal error"}), 400

        return {"message": "purchase not found"}, 404
Ejemplo n.º 15
0
    def post(self):
        """ Adicionar ou editar categoria.
        Para criar envie string vazia em id e para editar envie um int com o ID da categoria"""

        data = request.json if request.json else{}

        v = CustomValidator(schema)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document
        try:

            brand = ModelBrandProduct(**data)
            brand.save_brand()

            return jsonify({"message": "brand saved", "data": brand.list_brand()}), 201

        except:
            return jsonify({"message": "Internal error"}), 500
Ejemplo n.º 16
0
    def post(self):
        """  Create or Updated provider """

        data = request.json if request.json else {}

        v = CustomValidator(schema)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document

        try:
            provider = ModelProvider(**data)
            provider.save_provider()

            return jsonify({
                "message": "provided created",
                "data": provider.json_provider()
            }), 201
        except Exception as err:
            print(err)
            return jsonify({"message": "Internal error"}), 500
Ejemplo n.º 17
0
    def put(self, user_id):

        data = request.json if request.json else {}

        v = CustomValidator(schema)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document

        user = ModelsUser.find_user(user_id)

        if not user:
            return jsonify({"message": "user not Found"}), 404

        username = ModelsUser.find_username(data.get("username"))

        if username:
            if len(username) > 1 or username[0] != user_id:
                return jsonify(
                    {"message":
                     "Nome de usuário já existe. Tente outro."}), 400

        try:
            user.update_user(**data)
            user.generate_hash()
            user.save_user()

            return jsonify({
                "message": "User Updated",
                "data": user.list_users()
            }), 200

        except:

            return jsonify({"message": "Internal error"})
Ejemplo n.º 18
0
    def put(self, category_id):

        data = request.json if request.json else {}

        v = CustomValidator(schema)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document
        category = ModelCategoryProduct.find_category(category_id)

        if category:
            try:
                category.update_category(**data)
                category.save_category()
                return jsonify({
                    "messahe": "cateory updated",
                    "data": category.list_category()
                }), 200
            except:
                return jsonify({"message": "Internal error"}), 500

        return jsonify({"message": "Category not found"}), 404
Ejemplo n.º 19
0
    def put(self, purchase_id):

        data = request.json if request.json else {}

        v = CustomValidator(schema)

        if not v.validate(data):
            return jsonify({"message": v.errors}), 400

        data = v.document

        purchase = ModelPurchase.find_purchase(purchase_id)

        if not purchase:
            return jsonify({"message": "Purchase  not found"}), 404

        if purchase.delivery_status == 1:
            return jsonify({"message":
                            "Delivered purchase cannot be changed"}), 400

        provider = ModelProvider.find_provider(data.get("provider_id"))

        if not provider:
            return jsonify({"message": "Provider not found"}), 400

        total = []
        for itens in data.get("itens"):

            item = ModelProducts.find_product(itens.get("product_id"))

            if not item:
                return jsonify({
                    "message": "Item Not Found",
                    "item": itens
                }), 400

            if not itens.get("unit_price") * itens.get("qtde") == itens.get(
                    "total_price"):
                return jsonify({
                    "message":
                    "Total value of item: {} does not check".format(item.name)
                }), 400

            total.append(itens.get("total_price"))

        if sum(total) != data.get("value"):
            return jsonify({"message": "Value does not check"}), 400

        total_check = sum(total) + data.get("freight") - data.get("discount")

        if total_check != data.get("total_value"):
            return jsonify({"message": "total value does not check "}), 400

        try:
            purchase.update_purchase(**data)

            for itens in data.get("itens"):
                purchase.itens.append(
                    ModelPurchaseItem(**itens,
                                      id_purchase=purchase,
                                      provider_id=provider.provider_id))

            purchase.save_purchase()

            return jsonify({
                "message": "Purchase updated",
                "data": purchase.json_purchase()
            }), 200
        except Exception as err:
            print(err)
            return jsonify({"message": "Internal error"}), 500