Skip to content

Commit

Permalink
Merge pull request #267 from noharm-ai/develop
Browse files Browse the repository at this point in the history
v2.05-beta
  • Loading branch information
marceloarocha authored Nov 21, 2023
2 parents f77aee8 + 4cb99ec commit c49c5c1
Show file tree
Hide file tree
Showing 17 changed files with 424 additions and 92 deletions.
4 changes: 3 additions & 1 deletion mobile.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from routes.admin.drug import app_admin_drug
from routes.admin.integration import app_admin_integration
from routes.admin.segment import app_admin_segment
from routes.admin.exam import app_admin_exam
import os
import logging
from models.enums import NoHarmENV
Expand Down Expand Up @@ -85,6 +86,7 @@
app.register_blueprint(app_admin_drug)
app.register_blueprint(app_admin_integration)
app.register_blueprint(app_admin_segment)
app.register_blueprint(app_admin_exam)

CORS(app, origins=[Config.MAIL_HOST], supports_credentials=True)

Expand All @@ -95,7 +97,7 @@

@app.route("/version", methods=["GET"])
def getVersion():
return {"status": "success", "data": "v2.04-beta"}, status.HTTP_200_OK
return {"status": "success", "data": "v2.05-beta"}, status.HTTP_200_OK


if __name__ == "__main__":
Expand Down
1 change: 1 addition & 0 deletions models/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class MemoryEnum(Enum):
SUMMARY_CONFIG = "summary-config"
MAP_TUBE = "map-tube"
MAP_IV = "map-iv"
MAP_ROUTES = "map-routes"
MAP_ORIGIN_DRUG = "map-origin-drug"
MAP_ORIGIN_SOLUTION = "map-origin-solution"
MAP_ORIGIN_PROCEDURE = "map-origin-procedure"
Expand Down
20 changes: 20 additions & 0 deletions models/prescription.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,26 @@ def findRelation(

interaction = relation.filter(Relation.kind.in_(["it", "dt", "dm", "iy"]))

# if is_cpoe:
# interaction = relation.filter(
# or_(
# Relation.kind.in_(["it", "dt", "dm", "iy"]),
# and_(Relation.kind == "sl", pd1.cpoe_group == pd2.cpoe_group),
# )
# )
# else:
# interaction = relation.filter(
# or_(
# Relation.kind.in_(["it", "dt", "dm", "iy"]),
# (
# and_(
# Relation.kind == "sl",
# pd1.solutionGroup == pd2.solutionGroup,
# )
# ),
# )
# )

q_allergy = (
db.session.query(Allergy.idDrug.label("idDrug"))
.select_from(Allergy)
Expand Down
69 changes: 69 additions & 0 deletions routes/admin/exam.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import os
from flask import Blueprint, request
from flask_jwt_extended import jwt_required, get_jwt_identity

from models.main import *
from models.appendix import *
from models.segment import *
from models.prescription import *
from services.admin import exam_service
from exception.validation_error import ValidationError

app_admin_exam = Blueprint("app_admin_exam", __name__)


@app_admin_exam.route("/admin/exam/copy", methods=["POST"])
@jwt_required()
def copy_exams():
user = User.find(get_jwt_identity())
dbSession.setSchema(user.schema)
os.environ["TZ"] = "America/Sao_Paulo"
data = request.get_json()

try:
result = exam_service.copy_exams(
id_segment_origin=data.get("idSegmentOrigin", None),
id_segment_destiny=data.get("idSegmentDestiny", None),
user=user,
)
except ValidationError as e:
return {"status": "error", "message": str(e), "code": e.code}, e.httpStatus

return tryCommit(db, result.rowcount)


@app_admin_exam.route("/admin/exam/most-frequent", methods=["GET"])
@jwt_required()
def get_most_frequent():
user = User.find(get_jwt_identity())
dbSession.setSchema(user.schema)

try:
list = exam_service.get_most_frequent(user=user)
except ValidationError as e:
return {"status": "error", "message": str(e), "code": e.code}, e.httpStatus

return {
"status": "success",
"data": list,
}, status.HTTP_200_OK


@app_admin_exam.route("/admin/exam/most-frequent/add", methods=["POST"])
@jwt_required()
def add_most_frequent():
user = User.find(get_jwt_identity())
dbSession.setSchema(user.schema)
os.environ["TZ"] = "America/Sao_Paulo"
data = request.get_json()

try:
exam_service.add_most_frequent(
id_segment=data.get("idSegment", None),
exam_types=data.get("examTypes", None),
user=user,
)
except ValidationError as e:
return {"status": "error", "message": str(e), "code": e.code}, e.httpStatus

return tryCommit(db, True)
34 changes: 17 additions & 17 deletions routes/admin/frequency.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os
from flask import Blueprint, request
from flask_jwt_extended import (jwt_required, get_jwt_identity)
from flask_jwt_extended import jwt_required, get_jwt_identity

from flask_api import status
from models.main import *
Expand All @@ -10,39 +10,39 @@
from services.admin import frequency_service
from exception.validation_error import ValidationError

app_admin_freq = Blueprint('app_admin_freq',__name__)
app_admin_freq = Blueprint("app_admin_freq", __name__)

@app_admin_freq.route('/admin/frequency', methods=['GET'])

@app_admin_freq.route("/admin/frequency/list", methods=["POST"])
@jwt_required()
def get_frequencies():
user = User.find(get_jwt_identity())
dbSession.setSchema(user.schema)
request_data = request.get_json()

list = frequency_service.get_frequencies()
list = frequency_service.get_frequencies(
has_daily_frequency=request_data.get("hasDailyFrequency", None),
)

return {
'status': 'success',
'data': frequency_service.list_to_dto(list)
"status": "success",
"data": frequency_service.list_to_dto(list),
}, status.HTTP_200_OK


@app_admin_freq.route('/admin/frequency', methods=['PUT'])

@app_admin_freq.route("/admin/frequency", methods=["PUT"])
@jwt_required()
def update_frequency():
data = request.get_json()
user = User.find(get_jwt_identity())
dbSession.setSchema(user.schema)
os.environ['TZ'] = 'America/Sao_Paulo'
os.environ["TZ"] = "America/Sao_Paulo"

try:
freq = frequency_service.update_daily_frequency(\
data.get('id', None), data.get('dailyFrequency', None), user\
freq = frequency_service.update_daily_frequency(
data.get("id", None), data.get("dailyFrequency", None), user
)
except ValidationError as e:
return {
'status': 'error',
'message': str(e),
'code': e.code
}, e.httpStatus
return {"status": "error", "message": str(e), "code": e.code}, e.httpStatus

return tryCommit(db, frequency_service.list_to_dto([freq]))
return tryCommit(db, frequency_service.list_to_dto([freq]))
39 changes: 19 additions & 20 deletions routes/admin/memory.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os
from flask import Blueprint, request
from flask_jwt_extended import (jwt_required, get_jwt_identity)
from flask_jwt_extended import jwt_required, get_jwt_identity

from flask_api import status
from models.main import *
Expand All @@ -10,39 +10,38 @@
from services.admin import memory_service
from exception.validation_error import ValidationError

app_admin_memory = Blueprint('app_admin_memory',__name__)
app_admin_memory = Blueprint("app_admin_memory", __name__)

@app_admin_memory.route('/admin/memory', methods=['GET'])

@app_admin_memory.route("/admin/memory/list", methods=["POST"])
@jwt_required()
def get_memory_itens():
def get_admin_memory_itens():
data = request.get_json()
user = User.find(get_jwt_identity())
dbSession.setSchema(user.schema)

list = memory_service.get_admin_memory_itens(user)
list = memory_service.get_admin_entries(user, kinds=data.get("kinds", []))

return {"status": "success", "data": list}, status.HTTP_200_OK

return {
'status': 'success',
'data': list
}, status.HTTP_200_OK


@app_admin_memory.route('/admin/memory', methods=['PUT'])
@app_admin_memory.route("/admin/memory", methods=["PUT"])
@jwt_required()
def update_memory_item():
data = request.get_json()
user = User.find(get_jwt_identity())
dbSession.setSchema(user.schema)
os.environ['TZ'] = 'America/Sao_Paulo'
os.environ["TZ"] = "America/Sao_Paulo"

try:
key = memory_service.update_memory(\
data.get('key', None), data.get('kind', None), data.get('value', None), user\
key = memory_service.update_memory(
key=data.get("key", None),
kind=data.get("kind", None),
value=data.get("value", None),
user=user,
unique=data.get("unique", False),
)
except ValidationError as e:
return {
'status': 'error',
'message': str(e),
'code': e.code
}, e.httpStatus
return {"status": "error", "message": str(e), "code": e.code}, e.httpStatus

return tryCommit(db, key)
return tryCommit(db, key)
23 changes: 22 additions & 1 deletion routes/admin/segment.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,27 @@
app_admin_segment = Blueprint("app_admin_segment", __name__)


@app_admin_segment.route("/admin/segments", methods=["POST"])
@jwt_required()
def upsert_segment():
data = request.get_json()
user = User.find(get_jwt_identity())
dbSession.setSchema(user.schema)
os.environ["TZ"] = "America/Sao_Paulo"

try:
segment_service.upsert_segment(
id_segment=data.get("idSegment", None),
description=data.get("description", None),
active=data.get("active", None),
user=user,
)
except ValidationError as e:
return {"status": "error", "message": str(e), "code": e.code}, e.httpStatus

return tryCommit(db, data.get("idSegment"))


@app_admin_segment.route(
"/admin/segments/departments/<int:id_segment>", methods=["GET"]
)
Expand All @@ -28,7 +49,7 @@ def get_departments(id_segment):

@app_admin_segment.route("/admin/segments/departments", methods=["POST"])
@jwt_required()
def upsert_record():
def upsert_department():
data = request.get_json()
user = User.find(get_jwt_identity())
dbSession.setSchema(user.schema)
Expand Down
7 changes: 6 additions & 1 deletion routes/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,16 @@ def auth():
password = data.get("password", None)
schema = data.get("schema", None)
default_roles = data.get("defaultRoles", [])
run_as_basic_user = data.get("runAsBasicUser", False)
refresh_token = None

try:
auth_data = auth_service.auth_local(
email, password, force_schema=schema, default_roles=default_roles
email,
password,
force_schema=schema,
default_roles=default_roles,
run_as_basic_user=run_as_basic_user,
)

refresh_token = auth_data["refresh_token"]
Expand Down
22 changes: 11 additions & 11 deletions routes/outlier_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,17 +79,17 @@ def generateOutliers(idSegment, fold=None, idDrug=None, clean=None):
result = db.engine.execute(queryDelete)
print("RowCount Delete Drug", result.rowcount)

queryRefresh = text(
f"""
insert into {user.schema}.prescricaoagg
select * from {user.schema}.prescricaoagg where fkmedicamento = :idDrug and idsegmento = :idSegment
"""
)

result = db.engine.execute(
queryRefresh, {"idSegment": idSegment, "idDrug": idDrug}
)
print("RowCount Refresg Agg", result.rowcount)
# queryRefresh = text(
# f"""
# insert into {user.schema}.prescricaoagg
# select * from {user.schema}.prescricaoagg where fkmedicamento = :idDrug and idsegmento = :idSegment
# """
# )

# result = db.engine.execute(
# queryRefresh, {"idSegment": idSegment, "idDrug": idDrug}
# )
# print("RowCount Refresg Agg", result.rowcount)

queryInsert = text(
"""
Expand Down
3 changes: 2 additions & 1 deletion routes/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ def interactionsList(drugList, splitStr):
typeRelations["it"] = "Interação Medicamentosa"
typeRelations["iy"] = "Incompatibilidade em Y"
typeRelations["rx"] = "Reatividade Cruzada"
typeRelations["sl"] = "Incompatibilidade em Solução"

examEmpty = {"value": None, "alert": False, "ref": None, "name": None}
mdrdEmpty = dict(
Expand Down Expand Up @@ -404,7 +405,7 @@ def tryCommit(db, recId, allow=True):

return {
"status": "error",
"message": str(e),
"message": "Ocorreu um erro inesperado.",
}, status.HTTP_500_INTERNAL_SERVER_ERROR


Expand Down
9 changes: 8 additions & 1 deletion services/admin/drug_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ def copy_drug_attributes(
overwrite_all=False,
):
roles = user.config["roles"] if user.config and "roles" in user.config else []
if RoleEnum.ADMIN.value not in roles:
if RoleEnum.ADMIN.value not in roles and RoleEnum.TRAINING.value not in roles:
raise ValidationError(
"Usuário não autorizado",
"errors.unauthorizedUser",
Expand All @@ -443,6 +443,13 @@ def copy_drug_attributes(
status.HTTP_400_BAD_REQUEST,
)

if overwrite_all and RoleEnum.ADMIN.value not in roles:
raise ValidationError(
"Usuário não autorizado",
"errors.unauthorizedUser",
status.HTTP_401_UNAUTHORIZED,
)

origin_schema = "hsc_test" if from_admin_schema else user.schema
schema = user.schema

Expand Down
Loading

0 comments on commit c49c5c1

Please sign in to comment.