Skip to content

Commit

Permalink
data authorization v1
Browse files Browse the repository at this point in the history
  • Loading branch information
marceloarocha committed Jun 13, 2024
1 parent 495662c commit b2ac591
Show file tree
Hide file tree
Showing 11 changed files with 320 additions and 79 deletions.
2 changes: 2 additions & 0 deletions models/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ class RoleEnum(Enum):
SUMMARY = "summary"
UNLOCK_CHECKED_PRESCRIPTION = "unlock-checked-prescription"
CPOE = "cpoe"
PRESMED_FORM = "presmed-form"


class FeatureEnum(Enum):
Expand All @@ -60,6 +61,7 @@ class FeatureEnum(Enum):
DISABLE_SOLUTION_TAB = "DISABLE_SOLUTION_TAB"
PATIENT_REVISION = "PATIENT_REVISION"
INTERVENTION_V2 = "INTERVENTION_V2"
AUTHORIZATION_SEGMENT = "AUTHORIZATION_SEGMENT"


class PrescriptionAuditTypeEnum(Enum):
Expand Down
38 changes: 30 additions & 8 deletions routes/prescription.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
intervention_service,
patient_service,
alert_service,
data_authorization_service,
)
from converter import prescription_converter
from models.enums import (
Expand Down Expand Up @@ -639,13 +640,21 @@ def setPrescriptionData(idPrescription):
dbSession.setSchema(user.schema)
os.environ["TZ"] = "America/Sao_Paulo"

p = Prescription.query.get(idPrescription)
p = db.session.query(Prescription).filter(Prescription.id == idPrescription).first()
if p is None:
return {
"status": "error",
"message": "Prescrição Inexistente!",
}, status.HTTP_400_BAD_REQUEST

if not data_authorization_service.has_segment_authorization(
id_segment=p.idSegment, user=user
):
return {
"status": "error",
"message": "Usuário não autorizado neste segmento",
}, status.HTTP_401_UNAUTHORIZED

if "notes" in data.keys():
p.notes = data.get("notes", None)
p.notes_at = datetime.today()
Expand Down Expand Up @@ -770,6 +779,7 @@ def getDrugPeriod(idPrescriptionDrug):
return {"status": "success", "data": periodList}, status.HTTP_200_OK


# TODO: REFACTOR
@app_pres.route("/prescriptions/drug/<int:idPrescriptionDrug>", methods=["PUT"])
@jwt_required()
def setPrescriptionDrugNote(idPrescriptionDrug):
Expand All @@ -778,6 +788,25 @@ def setPrescriptionDrugNote(idPrescriptionDrug):
dbSession.setSchema(user.schema)
os.environ["TZ"] = "America/Sao_Paulo"

drug = (
db.session.query(PrescriptionDrug)
.filter(PrescriptionDrug.id == idPrescriptionDrug)
.first()
)
if drug is None:
return {
"status": "error",
"message": "Prescrição Inexistente!",
}, status.HTTP_400_BAD_REQUEST

if not data_authorization_service.has_segment_authorization(
id_segment=drug.idSegment, user=user
):
return {
"status": "error",
"message": "Usuário não autorizado neste segmento",
}, status.HTTP_401_UNAUTHORIZED

if "notes" in data:
notes = data.get("notes", None)
idDrug = data.get("idDrug", None)
Expand All @@ -801,13 +830,6 @@ def setPrescriptionDrugNote(idPrescriptionDrug):
db.session.add(note)

if "form" in data:
drug = PrescriptionDrug.query.get(idPrescriptionDrug)
if drug is None:
return {
"status": "error",
"message": "Prescrição Inexistente!",
}, status.HTTP_400_BAD_REQUEST

drug.form = data.get("form", None)
drug.update = datetime.today()
drug.user = user.id
Expand Down
75 changes: 21 additions & 54 deletions routes/segment.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
from utils import status
from models.main import *
from models.appendix import *
from models.prescription import *
from flask import Blueprint, request
from markupsafe import escape as escape_html
from flask_jwt_extended import (
Expand All @@ -10,7 +6,14 @@
)
from sqlalchemy import asc, func
from .utils import tryCommit
from datetime import date, datetime, timedelta
from datetime import date, timedelta

from utils import status
from models.main import *
from models.appendix import *
from models.prescription import *
from services import exams_service
from exception.validation_error import ValidationError

app_seg = Blueprint("app_seg", __name__)

Expand Down Expand Up @@ -205,39 +208,15 @@ def setExams(idSegment):
user = User.find(get_jwt_identity())
dbSession.setSchema(user.schema)
data = request.get_json()
typeExam = data.get("type", None)

segExam = SegmentExam.query.get((idSegment, typeExam))

newSegExam = False
if segExam is None:
newSegExam = True
segExam = SegmentExam()
segExam.idSegment = idSegment
segExam.typeExam = typeExam

if "initials" in data.keys():
segExam.initials = data.get("initials", None)
if "name" in data.keys():
segExam.name = data.get("name", None)
if "min" in data.keys():
segExam.min = data.get("min", None)
if "max" in data.keys():
segExam.max = data.get("max", None)
if "ref" in data.keys():
segExam.ref = data.get("ref", None)
if "order" in data.keys():
segExam.order = data.get("order", None)
if "active" in data.keys():
segExam.active = bool(data.get("active", False))

segExam.update = datetime.today()
segExam.user = user.id

if newSegExam:
db.session.add(segExam)
try:
result = exams_service.upsert_seg_exam(
data=data, id_segment=idSegment, user=user
)
except ValidationError as e:
return {"status": "error", "message": str(e), "code": e.code}, e.httpStatus

return tryCommit(db, escape_html(typeExam))
return tryCommit(db, escape_html(result.typeExam))


@app_seg.route("/segments/<int:idSegment>/exams-order", methods=["PUT"])
Expand All @@ -247,23 +226,11 @@ def setExamsOrder(idSegment):
dbSession.setSchema(user.schema)
data = request.get_json()

examsOrder = data.get("exams", None)
if not examsOrder:
return {
"status": "error",
"message": "Sem exames para ordenar!",
}, status.HTTP_400_BAD_REQUEST

segExams = (
SegmentExam.query.filter(SegmentExam.idSegment == idSegment)
.order_by(asc(SegmentExam.order))
.all()
)

result = {}
for s in segExams:
if s.typeExam in examsOrder:
s.order = examsOrder.index(s.typeExam)
result[s.typeExam] = s.order
try:
result = exams_service.exams_reorder(
exams=data.get("exams", None), id_segment=idSegment, user=user
)
except ValidationError as e:
return {"status": "error", "message": str(e), "code": e.code}, e.httpStatus

return tryCommit(db, result)
27 changes: 27 additions & 0 deletions services/data_authorization_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from models.main import db, UserAuthorization, User
from models.enums import FeatureEnum
from services import memory_service, permission_service


def has_segment_authorization(id_segment: int, user: User):
if id_segment == None:
# some cases dont have a segment defined
return True

if permission_service.has_maintainer_permission(user):
return True

if memory_service.has_feature(FeatureEnum.AUTHORIZATION_SEGMENT.value):
auth = (
db.session.query(UserAuthorization)
.filter(UserAuthorization.idUser == user.id)
.filter(UserAuthorization.idSegment == id_segment)
.first()
)

if auth != None:
return True

return False

return True
20 changes: 19 additions & 1 deletion services/drug_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from models.appendix import *
from models.prescription import *
from models.enums import DrugAdminSegment
from services import permission_service
from services import permission_service, data_authorization_service
from exception.validation_error import ValidationError


Expand Down Expand Up @@ -102,6 +102,15 @@ def drug_config_to_generate_score(
status.HTTP_400_BAD_REQUEST,
)

if not data_authorization_service.has_segment_authorization(
id_segment=id_segment, user=user
):
raise ValidationError(
"Usuário não autorizado neste segmento",
"errors.businessRules",
status.HTTP_401_UNAUTHORIZED,
)

if measure_unit_list:
for m in measure_unit_list:
_setDrugUnit(id_drug, m["idMeasureUnit"], id_segment, m["fator"])
Expand Down Expand Up @@ -195,6 +204,15 @@ def save_attributes(id_segment, id_drug, data, user):
status.HTTP_400_BAD_REQUEST,
)

if not data_authorization_service.has_segment_authorization(
id_segment=id_segment, user=user
):
raise ValidationError(
"Usuário não autorizado neste segmento",
"errors.businessRules",
status.HTTP_401_UNAUTHORIZED,
)

attr = DrugAttributes.query.get((id_drug, id_segment))
add = False
if attr is None:
Expand Down
92 changes: 91 additions & 1 deletion services/exams_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from models.main import db
from models.appendix import *
from models.prescription import *
from services import memory_service
from services import memory_service, data_authorization_service

from exception.validation_error import ValidationError

Expand Down Expand Up @@ -38,3 +38,93 @@ def get_next_id(schema):
)

return ([row[0] for row in result])[0]


def upsert_seg_exam(data: dict, id_segment: int, user: User):
if id_segment == None:
raise ValidationError(
"Parametros inválidos",
"errors.businessRules",
status.HTTP_400_BAD_REQUEST,
)

if not data_authorization_service.has_segment_authorization(
id_segment=id_segment, user=user
):
raise ValidationError(
"Usuário não autorizado neste segmento",
"errors.businessRules",
status.HTTP_401_UNAUTHORIZED,
)

typeExam = data.get("type", None)
segExam = (
db.session.query(SegmentExam)
.filter(SegmentExam.idSegment == id_segment)
.filter(SegmentExam.typeExam == typeExam)
.first()
)

newSegExam = False
if segExam is None:
newSegExam = True
segExam = SegmentExam()
segExam.idSegment = id_segment
segExam.typeExam = typeExam

if "initials" in data.keys():
segExam.initials = data.get("initials", None)
if "name" in data.keys():
segExam.name = data.get("name", None)
if "min" in data.keys():
segExam.min = data.get("min", None)
if "max" in data.keys():
segExam.max = data.get("max", None)
if "ref" in data.keys():
segExam.ref = data.get("ref", None)
if "order" in data.keys():
segExam.order = data.get("order", None)
if "active" in data.keys():
segExam.active = bool(data.get("active", False))

segExam.update = datetime.today()
segExam.user = user.id

if newSegExam:
db.session.add(segExam)

return segExam


def exams_reorder(exams, id_segment, user: User):
if not exams:
raise ValidationError(
"Parametros inválidos",
"errors.businessRules",
status.HTTP_400_BAD_REQUEST,
)

if not data_authorization_service.has_segment_authorization(
id_segment=id_segment, user=user
):
raise ValidationError(
"Usuário não autorizado neste segmento",
"errors.businessRules",
status.HTTP_401_UNAUTHORIZED,
)

segExams = (
SegmentExam.query.filter(SegmentExam.idSegment == id_segment)
.order_by(asc(SegmentExam.order))
.all()
)

result = {}
for s in segExams:
if s.typeExam in exams:
s.order = exams.index(s.typeExam)
db.session.flush()

result[s.typeExam] = s.order

return result
Loading

0 comments on commit b2ac591

Please sign in to comment.