Skip to content

Commit

Permalink
merge with main
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasbpro committed Jun 22, 2021
2 parents a3481ab + a11a0d3 commit b0669f4
Show file tree
Hide file tree
Showing 8 changed files with 186 additions and 11 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
__pycache__/
inserts/
venv/
data.db
data.db
app.py
8 changes: 6 additions & 2 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
# import resorces
from resources.raw_material import *
from resources.recipe import *
from resources.product import *
from resources.customers import *
from resources.orders import *
from resources.recipe_material_amt import *
Expand All @@ -17,9 +18,9 @@
# creates Flask application
app = Flask(__name__)

# sets up production environment
# sets up MAIN environment
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///data.db').replace("://", "ql://", 1)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL').replace("://", "ql://", 1)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'rebequinha'

Expand All @@ -41,6 +42,9 @@
api.add_resource(MaterialList, '/recipe/<int:id>/materials')
api.add_resource(RecipeMaterialAmount,'/recipe/<int:recipe_id>/material/<int:material_id>')

api.add_resource(Product, '/products/<int:id>')
api.add_resource(Products, '/products')

api.add_resource(Customer, '/customers/<int:id>')
api.add_resource(Customers, '/customers')

Expand Down
53 changes: 53 additions & 0 deletions models/product.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# import SQLAlchemy object
from db import db
from constants import constants
from datetime import datetime

# defines the model for 'products' table in db
class ProductModel(db.Model):

# name of the table in database
__tablename__ = 'products'

# define columns in table
id = db.Column(db.Integer, primary_key=True)
recipe_id = db.Column(db.Integer, db.ForeignKey('recipes.id'))
stock_amt = db.Column(db.Integer)
fabrication_date = db.Column(db.String(constants['MEDIUM_LENGTH']))

# define relationships with other tables
recipe = db.relationship('RecipeModel')

def __init__(self, recipe_id):
self.recipe_id = recipe_id
self.fabrication_date = datetime.now().strftime("%d/%m/%Y %H:%M")

def json(self):
return {
'id' : self.id,
'recipe_id' : self.recipe_id,
'fabrication_date' : self.fabrication_date
}

def save_to_db(self):
db.session.add(self)
db.session.commit()

def delete_from_db(self):
db.session.delete(self)
db.session.commit()

@classmethod
def find_by_id(cls, id_):
return cls.query.filter_by(id=id_).first()

@classmethod
def find_by_recipe_id(cls, id_):
return cls.query.filter_by(recipe_id=id_).first()

def get_recipe(self):
return [self.recipe.json()]

@classmethod
def get_stock_amount(cls, id_):
return len(cls.query.filter_by(recipe_id=id_))
3 changes: 2 additions & 1 deletion models/raw_material.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ def json(self):
'package_amt' : self.package_amt,
'unit_material': self.unit_material,
'stock_amt' : self.stock_amt,
'sell_by' : self.sell_by_date
'sell_by' : self.sell_by_date,
'recipes' : [recipe.json()["id"] for recipe in self.recipes]
}

def save_to_db(self):
Expand Down
17 changes: 13 additions & 4 deletions models/recipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,21 @@ class RecipeModel(db.Model):
description = db.Column(db.String(constants['LONG_LENGTH']))
labor_cost = db.Column(db.Float(constants['PRICE_PRECISION']))
supply_cost = db.Column(db.Float(constants['PRICE_PRECISION']))
productivity = db.Column(db.Integer)
creation_date = db.Column(db.String(constants['MEDIUM_LENGTH']))
last_update = db.Column(db.String(constants['MEDIUM_LENGTH']))

def __init__(self, description, labor_cost, supply_cost):
products = db.relationship('ProductModel', lazy='dynamic')

def __init__(self, description, labor_cost, supply_cost, productivity):
self.description = description
self.labor_cost = labor_cost
self.supply_cost = supply_cost
self.labor_cost = labor_cost or 5
self.supply_cost = supply_cost or 0
self.productivity = productivity or 1
self.creation_date = datetime.now().strftime("%d/%m/%Y %H:%M")
self.last_update = self.creation_date


def json(self):
materialList = {}
for material in self.materials:
Expand All @@ -38,6 +43,7 @@ def json(self):
'last_update' : self.last_update,
'labor_cost' : self.labor_cost,
'supply_cost' : self.supply_cost,
'productivity' : self.productivity,
'materials' : materialList
}

Expand All @@ -61,4 +67,7 @@ def get_materials(self):
return [material.json() for material in self.materials]

def get_materials_amount(self):
return [item.json() for item in RecipeMaterialAmountModel.query.all()]
return [item.json() for item in RecipeMaterialAmountModel.query.all()]

def get_products_from_recipe(self):
return [product.json() for product in self.products]
2 changes: 1 addition & 1 deletion resources/customers.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def get(self, id):
if customer:
return customer.json(), 200
else:
return {'Message': constants['ID_NOT_EXIST']}
return {'Message': constants['ID_NOT_FOUND']}

def delete(self, id):
# checks if material exists in database
Expand Down
97 changes: 97 additions & 0 deletions resources/product.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# import flask libs
from flask_restful import Resource, reqparse
from constants import constants
from datetime import datetime

# import model
from models.product import ProductModel
from models.recipe import RecipeModel

class Product(Resource):
# adds a parser to handle PUT HTTP requests
parser = reqparse.RequestParser()
parser.add_argument('recipe_id',type=int,required=False)
parser.add_argument('stock_amt',type=int,required=False)

# to handle HTTP GET /product/<int:id>
def get(self, id):
product = ProductModel.find_by_id(id)
if product:
return product.json(), 200
else:
return {'Message': constants['ID_NOT_FOUND']}

# to handle HTTP DEL /product/<int:id>
def delete(self, id):
# checks if material exists in database
product = ProductModel.find_by_id(id)

# in case it exists, delete it
if product:
product.delete_from_db()

# return message and default HTTP status (200 - OK)
return {'Message': constants['DELETED']}

# to handle HTTP PUT /product/<int:id>
def put(self, id):
# gets parameter from parser
data = Product.parser.parse_args()

# checks if material exists in database
product = ProductModel.find_by_id(id)

# in case it exists, updates it
if product:
for key in data.keys():
if key=='recipe_id' and data['recipe_id']:
recipe = RecipeModel.find_by_id(data['recipe_id'])
if recipe:
product.recipe_id = data['recipe_id']
product.recipe = recipe
product.fabrication_date = datetime.now().strftime("%d/%m/%Y %H:%M")

# in case it does not exist, creates a new material using data passed
# along with the HTTP request
else:
product = ProductModel(**data)

# tries to insert in database, returns 500 (internal server error) in case of database failure
try:
product.save_to_db()
except:
return {"message": "An error occurred with the database."}, 500

# returns
return product.json()

class Products(Resource):
# adds a parser to handle POST HTTP requests
parser = reqparse.RequestParser()
parser.add_argument('recipe_id',type=int,required=True)

# handles HTTP request GET /products
def get(self):
return [x.json() for x in ProductModel.query.all()]

# handles HTTP request POST /products
def post(self):
# gets parameter from parser
data = Products.parser.parse_args()

recipe = RecipeModel.find_by_id(data['recipe_id'])
if recipe:
product = ProductModel(data['recipe_id'])
# in case provided recipe does not exist, throw error message
else:
return {"message": "A recipe with id '{}' does not exist.".format(data['recipe_id'])}, 400

# tries to insert in database
# returns 500 (internal server error) in case of database failure
try:
product.save_to_db()
except:
return {"message": "An error occurred upon inserting the into the database."}, 500

# returns JSON with the created Material and returns CREATED status (201)
return product.json(), 201
14 changes: 12 additions & 2 deletions resources/recipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class Recipe(Resource):
parser.add_argument('description',type=str,required=False)
parser.add_argument('labor_cost',type=float,required=False)
parser.add_argument('supply_cost',type=float,required=False)
parser.add_argument('productivity',type=int,required=False)
parser.add_argument('materials', type=dict, action="append",required=False)

# to handle HTTP GET /recipes/<int:id>
Expand Down Expand Up @@ -55,6 +56,8 @@ def put(self, id):
recipe.labor_cost = data['labor_cost']
if key=='supply_cost':
recipe.supply_cost = data['supply_cost']
if key=='productivity':
recipe.productivity = data['productivity']
if key=='sell_by_date':
recipe.sell_by_date = data['sell_by_date']
if key=='materials':
Expand Down Expand Up @@ -83,7 +86,7 @@ def put(self, id):

# in case not exist, creates a new item
else:
recipe = RecipeModel(data['description'],data['labor_cost'],data['supply_cost'])
recipe = RecipeModel(data['description'],data['labor_cost'],data['supply_cost'], data['productivity'])
materialsDict = data['materials'][0]
for key in materialsDict.keys():
materialId = int(key)
Expand Down Expand Up @@ -118,6 +121,7 @@ class Recipes(Resource):
parser.add_argument('description',type=str,required=True)
parser.add_argument('labor_cost',type=float,required=False)
parser.add_argument('supply_cost',type=float,required=False)
parser.add_argument('productivity',type=int,required=False)
parser.add_argument('materials',type=dict,action="append",required=True)

# handles HTTP request GET /recipes
Expand All @@ -138,7 +142,7 @@ def post(self):

# in case it does not exist, creates a new recipe using data passed
# along with the HTTP request
recipe = RecipeModel(data['description'],data['labor_cost'],data['supply_cost'])
recipe = RecipeModel(data['description'],data['labor_cost'],data['supply_cost'], data['productivity'])
materialsDict = data['materials'][0]
for key in materialsDict.keys():
materialId = int(key)
Expand All @@ -147,6 +151,7 @@ def post(self):
if material:
recipe.materials.append(material)
materialRecipeItem = RecipeMaterialAmountModel.find_by_map(recipe.id, materialId)

# in case recipe-material map already exists, then just updates it
if materialRecipeItem:
materialRecipeItem.amount = materialAmount
Expand All @@ -155,6 +160,11 @@ def post(self):
else:
materialRecipeItem = RecipeMaterialAmountModel(recipe.id, materialId, materialAmount)
materialRecipeItem.save_to_db()

material_unit_price = material.package_price/material.package_amt
recipe.supply_cost += material_unit_price*materialAmount


# in case any materialId provided does not exist
else:
return {"message": constants['MATERIAL_NOT_EXIST'].format(materialId)}, 200
Expand Down

0 comments on commit b0669f4

Please sign in to comment.