async def get_password(email: str): """ Validate in database if user exist and change password """ try: template = EMAIL_CONFIGURATIONS['forgot'] except KeyError: return HTTPException(HTTP_404_NOT_FOUND, detail='Configuration key not found') query_path = path.join("users", "user_id.sql") user_id = execute_query(query_name=query_path, fetch_one=True, email=email) grant_key = create_password_grant() query_path = path.join("password", "create_grant.sql") execute_query(query_name=query_path, user_id=user_id['user_id'], grant_key=grant_key) send_dynamic_email(email, template, link=PASSWORD_LINK + grant_key) response = jsonable_encoder({ "message": "Se han enviado instrucciones para restablecer tu contraseña." }) return JSONResponse(content=response)
async def get_all_products(): query_path = path.join("products", "get_all_activated_categories.sql") categories = execute_query(query_name=query_path, fetch_data=True) if len(categories) > 0: for categories_index in range(len(categories)): query_path = path.join( "products", "get_all_activated_products_by_category_id.sql") products = execute_query( query_name=query_path, fetch_data=True, category_id=categories[categories_index]['id']) categories[categories_index]["products"] = products for product_index in range(len(products)): query_path = path.join( "products", "get_all_activated_products_configurations.sql") products_configuration = execute_query( query_name=query_path, fetch_data=True, product_id=products[product_index]['id']) categories[categories_index]["products"][product_index][ "configurations"] = products_configuration return {"categories": categories} else: return HTTPException(status_code=HTTP_404_NOT_FOUND, detail="No products have been published")
async def reset_password(request: ForgotPassword): """ Validate in database if user exist and change password """ query_path = path.join("users", "user_id.sql") user_id = execute_query(query_name=query_path, fetch_one=True, email=request.email) query_path = path.join("password", "get_grant.sql") grant = execute_query(query_name=query_path, fetch_one=True, user_id=user_id['user_id']) current_date = datetime.utcnow() if current_date < grant['expire_at'] and grant['grant_key'] == request.code: query_path = path.join("password", "update.sql") execute_query(query_path, user_id=user_id['user_id'], password=request.password) response = jsonable_encoder( {"message": "Contraseña restablecida correctamente"}) return JSONResponse(content=response) else: return HTTPException(HTTP_401_UNAUTHORIZED, detail='El codigo expiro o no es correcto')
async def product_configuration(request: ProductConfiguration): query_path = path.join("products", "create_product_configuration.sql") try: execute_query(query_path, False, **request.dict()) response = jsonable_encoder({"message": "success"}) return JSONResponse(content=response) except IntegrityError: return HTTPException(status_code=HTTP_424_FAILED_DEPENDENCY, detail="Error de integridad de llaves") except Exception: return HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR, detail="Error interno del servidor")
async def delete_category(current_id: int): query_path = path.join("products", "update_category_status.sql") try: execute_query(query_path, False, id=current_id) response = jsonable_encoder({"message": "success"}) except IntegrityError: return HTTPException( status_code=HTTP_424_FAILED_DEPENDENCY, detail="Database error, probably foreing key dependency error") except: return HTTPException(status_code=HTTP_404_NOT_FOUND, detail="No products have been found") return JSONResponse(content=response)
async def create_bill(request: List[BillFront], token: str = Depends( JWTBearer(['Usuario Registrado', 'Administrador']))): email = JWTBearer.get_email(token) query_path = path.join("users", "user_id.sql") user_id = execute_query(query_name=query_path, fetch_one=True, email=email)['user_id'] query_path = path.join("bill", "create_bill.sql") execute_query(query_path, id_user=user_id, total_quantity=0, total_price=0) #Traer ID de la factura, ordenado por fecha en orden descendente, se trae la fecha actual query_path = path.join("bill", "select_bill.sql") id_bill = execute_query(query_name=query_path, fetch_one=True, id_user=user_id)['id'] if id_bill: # Crear BillDescription, Validar si se puede enviar todo, restar en stock de Product_configuration total_quantity = 0 total_price = 0 for x in range(len(request)): product_configuration = request[x].dict() query_path = path.join("bill", "create_bill_description.sql") execute_query(query_path, True, id_bill=id_bill, **product_configuration) total_quantity += product_configuration["quantity"] total_price += product_configuration["price"] query_path = path.join("products", "update_product_configuration_stock.sql") execute_query(query_path, False, id=product_configuration["id_product_config"], stock=product_configuration["quantity"]) query_path = path.join("bill", "update_bill_total.sql") execute_query(query_path, False, id_bill=id_bill, total_quantity=total_quantity, total_price=total_price) return HTTPException(status_code=HTTP_200_OK, detail="The bill has created success") else: return HTTPException(status_code=HTTP_404_NOT_FOUND, detail="It was not found a bill")
async def get_all_products(): query_path = path.join("products", "get_all_activated_products.sql") data = execute_query(query_name=query_path, fetch_data=True) if len(data) > 0: return {"products": data} else: return HTTPException(status_code=HTTP_404_NOT_FOUND, detail="No products have been published")
async def get_bills_by_user_id(token: str = Depends( JWTBearer(['Usuario Registrado', 'Administrador']))): email = JWTBearer.get_email(token) query_path = path.join("users", "user_id.sql") user_id = execute_query(query_name=query_path, fetch_one=True, email=email)['user_id'] query_path = path.join("bill", "get_history_bill_by_user_id.sql") data = execute_query(query_name=query_path, fetch_data=True, id_user=user_id) if len(data) > 0: return {"bill_description": data} else: return HTTPException( status_code=HTTP_404_NOT_FOUND, detail="No bill descriptions have been published for this user")
async def get_all_bill_description(): query_path = path.join("bill", "get_all_bill_description.sql") data = execute_query(query_name=query_path, fetch_data=True) if len(data) > 0: return {"bill_description": data} else: return HTTPException(status_code=HTTP_404_NOT_FOUND, detail="No bill descriptions have been published")
async def create_configuration(request: Configuration): query_path = path.join("products", "product", "configuration", "get_configuration_id_by_name.sql") configuration_id = execute_query(query_path, True, **request.dict()) # VALIDATE IF THE CONFIGURATION EXIST if len(configuration_id) > 0: return HTTPException(HTTP_409_CONFLICT, detail='Already exist') # IF THE CATEGORY DOES NOT EXIST, IT IS CREATED else: query_path = path.join("products", "create_configuration.sql") execute_query(query_path, False, **request.dict()) response = jsonable_encoder({ "message": "success" }) # Return message return JSONResponse(content=response)
async def get_category_by_id(current_id: int): query_path = path.join("products", "category", "get_category_by_id.sql") data = execute_query(query_name=query_path, fetch_data=True, id=current_id) if len(data) > 0: return {"category": data} else: return HTTPException(status_code=HTTP_404_NOT_FOUND, detail="No category have been published")
async def get_all_categories(): query_path = path.join("products", "get_all_categories.sql") data = execute_query(query_name=query_path, fetch_data=True) if len(data) > 0: return { "categories": data # TODO RETURN TOKEN } else: return HTTPException(status_code=HTTP_404_NOT_FOUND, detail="No categories have been published")
async def create_category(request: Category): category = request.dict() query_path = path.join("products", "get_categoryID_by_name.sql") category_id = execute_query(query_path, True, **category) # VALIDATE IF THE CATEGORY EXIST if category_id: query_path = path.join("products", "get_category_status_by_id.sql") status = execute_query(query_path, fetch_one=True, **category_id[0]) # IF THE CATEGORY EXIST, THE STATUS IS VALIDATED TO CHANGE THE STATUS IN CASE IT IS DISABLED if status["status"] == 1: return HTTPException(HTTP_409_CONFLICT, detail='Already exist') # update status to enable if the category exist but it is disabled else: query_path = path.join("products", "update_category_status.sql") new_category = {"id": category_id[0]['id'], "status": 1} execute_query(query_path, False, **new_category) response = jsonable_encoder({"message": "Re-activated"}) # IF THE CATEGORY DOES NOT EXIST, IT IS CREATED else: query_path = path.join("products", "create_category.sql") execute_query(query_path, False, **request.dict()) response = jsonable_encoder({"message": "success"}) # Return message return JSONResponse(content=response, )
async def login(request: LoginUser): """ Authenticate user via OAUTH2 and validate if user have access to the application. """ query_path = path.join("auth", "login.sql") data = execute_query(query_name=query_path, fetch_one=True, **request.dict()) if data: token = sign_jwt(data['email'], data['role_type']) response = jsonable_encoder({"token": token}) return JSONResponse(content=response) else: return HTTPException(status_code=HTTP_404_NOT_FOUND, detail="User not found or incorrect password")
async def create_users(request: NormalUserRegister): query_path = path.join("users", "user_email.sql") user = request.dict() email = execute_query(query_name=query_path, fetch_data=True, email=user['email']) if not email: query_path = path.join("users", "role_get.sql") role = execute_query(query_name=query_path, fetch_one=True, role_type='Usuario Registrado') user['is_active'] = True user['role_id'] = role['role_id'] query_path = path.join("users", "user_create.sql") execute_query(query_name=query_path, fetch_data=False, **user) query_path = path.join("users", "user_id.sql") user_id = execute_query(query_name=query_path, fetch_one=True, email=user['email']) try: template = EMAIL_CONFIGURATIONS['welcome'] except KeyError: return HTTPException(HTTP_404_NOT_FOUND, detail='The user already exists') grant_key = create_password_grant() query_path = path.join("password", "create_grant.sql") execute_query(query_name=query_path, user_id=user_id['user_id'], grant_key=grant_key) send_dynamic_email(user['email'], template, link=PASSWORD_LINK + grant_key) return JSONResponse( content={ "status_code": HTTP_201_CREATED, "message": "User created successfully" }) else: return HTTPException(HTTP_409_CONFLICT, detail='The user already exists')
def migrate(is_production: bool): mysql.sql_conn = mysql.db_connection(is_migrate=True) mysql.execute_query(MIGRATE_FILE, is_production) mysql.sql_conn.close()
async def update_bill_status(request: BillUpdateStatus): query_path = path.join("bill", "update_bill_status.sql") execute_query(query_path, False, **request.dict()) return HTTPException(status_code=HTTP_200_OK, detail="The bill has updated success")
async def update_product_configuration(request: Product): query_path = path.join("products", "update_product_configuration.sql") execute_query(query_path, False, **request.dict()) return {"message": "Operation successful"}
async def update_category(request: Category): query_path = path.join("products", "category", "update_category.sql") execute_query(query_path, **request.dict()) return {"message": "Operation successful"}