Skip to content

Commit

Permalink
Merge branch 'develop' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasbpro committed May 9, 2021
2 parents 458f478 + 6a5a372 commit 4d6ebc7
Show file tree
Hide file tree
Showing 6 changed files with 166 additions and 1 deletion.
4 changes: 4 additions & 0 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 Down Expand Up @@ -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
Binary file modified data.db
Binary file not shown.
54 changes: 54 additions & 0 deletions models/product.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# 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)
last_update = db.Column(db.String(constants['MEDIUM_LENGTH']))

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

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

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

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()]

def get_stock_amount(self):
return self.json().stock_amt
2 changes: 2 additions & 0 deletions models/recipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ class RecipeModel(db.Model):
creation_date = db.Column(db.String(constants['MEDIUM_LENGTH']))
last_update = db.Column(db.String(constants['MEDIUM_LENGTH']))

products = db.relationship('ProductModel', lazy='dynamic')

def __init__(self, description, labor_cost, supply_cost, productivity):
self.description = description
self.labor_cost = labor_cost or 5
Expand Down
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
105 changes: 105 additions & 0 deletions resources/product.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# 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=='stock_amt' and data['stock_amt']:
product.stock_amt = data['stock_amt']
product.last_update = datetime.now().strftime("%d/%m/%Y %H:%M")
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.last_update = 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)
parser.add_argument('stock_amt',type=int,required=False)

# 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()

# checks if material exists in database
product = ProductModel.find_by_recipe_id(data['recipe_id'])

# in case it exists, returns a message and HTTP 400 code (BAD REQUEST)
if product:
return {'message': "A product related to recipe_id '{}' already exists.".format(data['recipe_id'])}, 400

# in case it does not exist, creates a new material using data passed
# along with the HTTP request
product = ProductModel(data['recipe_id'], data['stock_amt'])

# 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

0 comments on commit 4d6ebc7

Please sign in to comment.