Skip to content

Commit

Permalink
Merge pull request #353 from noharm-ai/develop
Browse files Browse the repository at this point in the history
v3.21-beta
  • Loading branch information
marceloarocha authored Aug 13, 2024
2 parents d717fac + fe6f9e0 commit 5daacf9
Show file tree
Hide file tree
Showing 15 changed files with 403 additions and 162 deletions.
2 changes: 1 addition & 1 deletion mobile.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@

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


if __name__ == "__main__":
Expand Down
12 changes: 12 additions & 0 deletions models/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,15 @@ class DrugAlertLevelEnum(Enum):
LOW = "low"
MEDIUM = "medium"
HIGH = "high"


class DrugAttributesAuditTypeEnum(Enum):
UPSERT = 1
UPSERT_BEFORE_GEN_SCORE = 2
UPSERT_UPDATE_SUBSTANCE = 3
INSERT_FROM_REFERENCE = 4
COPY_FROM_REFERENCE = 5


class PatientAuditTypeEnum(Enum):
UPSERT = 1
14 changes: 14 additions & 0 deletions models/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,20 @@ class DrugAttributesReference(db.Model, DrugAttributesBase):
__table_args__ = {"schema": "hsc_test"}


class DrugAttributesAudit(db.Model):
__tablename__ = "medatributos_audit"

id = db.Column(
"idmedatributos_audit", db.BigInteger, nullable=False, primary_key=True
)
auditType = db.Column("tp_audit", db.Integer, nullable=False)
idDrug = db.Column("fkmedicamento", db.BigInteger, nullable=False)
idSegment = db.Column("idsegmento", db.BigInteger, nullable=True)
extra = db.Column("extra", postgresql.JSON, nullable=True)
createdAt = db.Column("created_at", db.DateTime, nullable=False)
createdBy = db.Column("created_by", db.BigInteger, nullable=False)


class Allergy(db.Model):
__tablename__ = "alergia"

Expand Down
15 changes: 0 additions & 15 deletions models/notes.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,21 +129,6 @@ def getComplicationCountIfExists(admissionNumber):
else:
return None

def getExamsIfExists(admissionNumber):
if ClinicalNotes.exists():
return (
ClinicalNotes.query.filter(
ClinicalNotes.admissionNumber == admissionNumber
)
.filter(ClinicalNotes.isExam == True)
.filter(ClinicalNotes.text != None)
.filter(ClinicalNotes.date > (datetime.today() - timedelta(days=90)))
.order_by(desc(ClinicalNotes.date))
.all()
)
else:
return []

def getSigns(admissionNumber):
return (
db.session.query(ClinicalNotes.signsText, ClinicalNotes.date)
Expand Down
11 changes: 11 additions & 0 deletions models/prescription.py
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,17 @@ def getPrevNotes(admissionNumber):
)


class PatientAudit(db.Model):
__tablename__ = "pessoa_audit"

id = db.Column("idpessoa_audit", db.BigInteger, nullable=False, primary_key=True)
auditType = db.Column("tp_audit", db.Integer, nullable=False)
admissionNumber = db.Column("nratendimento", db.BigInteger, nullable=False)
extra = db.Column("extra", postgresql.JSON, nullable=True)
createdAt = db.Column("created_at", db.DateTime, nullable=False)
createdBy = db.Column("created_by", db.BigInteger, nullable=False)


class PrescriptionDrug(db.Model):
__tablename__ = "presmed"

Expand Down
120 changes: 15 additions & 105 deletions routes/patient.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
import os, copy
from utils import status
from sqlalchemy import text
from models.main import *
from models.appendix import *
from models.segment import *
from models.prescription import *
from models.notes import ClinicalNotes
from flask import Blueprint, request
from markupsafe import escape as escape_html
from flask_jwt_extended import (
create_access_token,
create_refresh_token,
jwt_required,
get_jwt_identity,
)

from utils import status
from models.main import *
from models.appendix import *
from models.segment import *
from models.prescription import *
from .utils import *
from datetime import datetime
from services import patient_service
from services import patient_service, exams_service
from converter import patient_converter
from models.enums import RoleEnum
from exception.validation_error import ValidationError

app_pat = Blueprint("app_pat", __name__)

Expand Down Expand Up @@ -179,7 +175,7 @@ def getExamsbyAdmission(admissionNumber):
else:
del results[e]

examsText = ClinicalNotes.getExamsIfExists(admissionNumber)
examsText = exams_service.get_textual_exams(id_patient=patient.idPatient)
resultsText = {}
for e in examsText:
slugExam = slugify(e.prescriber)
Expand Down Expand Up @@ -209,102 +205,16 @@ def getExamsbyAdmission(admissionNumber):
def setPatientData(admissionNumber):
user = User.find(get_jwt_identity())
dbSession.setSchema(user.schema)
data = request.get_json()
os.environ["TZ"] = "America/Sao_Paulo"
roles = user.config["roles"] if user.config and "roles" in user.config else []

p = Patient.findByAdmission(admissionNumber)
if p is None:
first_prescription = (
db.session.query(Prescription)
.filter(Prescription.admissionNumber == admissionNumber)
.filter(Prescription.agg == None)
.filter(Prescription.concilia == None)
.filter(Prescription.idSegment != None)
.order_by(asc(Prescription.date))
.first()
try:
result = patient_service.save_patient(
request_data=request.get_json(), admission_number=admissionNumber, user=user
)
except ValidationError as e:
return {"status": "error", "message": str(e), "code": e.code}, e.httpStatus

if first_prescription == None:
return {
"status": "error",
"message": "Paciente Inexistente!",
}, status.HTTP_400_BAD_REQUEST

p = Patient()
p.admissionNumber = admissionNumber
p.admissionDate = first_prescription.date
p.idHospital = first_prescription.idHospital
p.idPatient = first_prescription.idPatient
db.session.add(p)

updateWeight = False

if RoleEnum.READONLY.value in roles and not (
RoleEnum.ADMIN.value in roles or RoleEnum.TRAINING.value in roles
):
return {
"status": "error",
"message": "Permissão inválida",
}, status.HTTP_401_UNAUTHORIZED

if RoleEnum.SUPPORT.value not in roles and RoleEnum.READONLY.value not in roles:
if "weight" in data.keys():
weight = data.get("weight", None)

if weight != p.weight:
p.weightDate = datetime.today()
p.weight = weight
updateWeight = True

alertExpire = data.get("alertExpire", None)
if alertExpire and alertExpire != p.alertExpire:
p.alert = data.get("alert", None)
p.alertExpire = alertExpire
p.alertDate = datetime.today()
p.alertBy = user.id

if "height" in data.keys():
p.height = data.get("height", None)
if "dialysis" in data.keys():
p.dialysis = data.get("dialysis", None)
if "lactating" in data.keys():
p.lactating = data.get("lactating", None)
if "pregnant" in data.keys():
p.pregnant = data.get("pregnant", None)
if "observation" in data.keys():
p.observation = data.get("observation", None)
if "skinColor" in data.keys():
p.skinColor = data.get("skinColor", None)
if "gender" in data.keys():
p.gender = data.get("gender", None)
if "birthdate" in data.keys():
p.birthdate = data.get("birthdate", None)

if RoleEnum.ADMIN.value in roles or RoleEnum.TRAINING.value in roles:
if "dischargeDate" in data.keys():
p.dischargeDate = data.get("dischargeDate", None)

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

if "idPrescription" in data.keys() and updateWeight:
idPrescription = data.get("idPrescription")

query = text(
"INSERT INTO "
+ user.schema
+ ".presmed \
SELECT *\
FROM "
+ user.schema
+ ".presmed\
WHERE fkprescricao = :idPrescription ;"
)

db.session.execute(query, {"idPrescription": idPrescription})

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


@app_pat.route("/patient", methods=["GET"])
Expand Down
11 changes: 9 additions & 2 deletions routes/prescription.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,12 +428,19 @@ def getPrescription(

for a in allergies:
notesAllergies.append(
{"date": a[1].isoformat(), "text": a[0], "source": "care", "id": a[2]}
{
"date": a[1].isoformat(),
"text": a[0],
"source": "care",
"id": str(a[2]),
}
)

notesDialysis = []
for a in dialysis:
notesDialysis.append({"date": a[1].isoformat(), "text": a[0], "id": a[3]})
notesDialysis.append(
{"date": a[1].isoformat(), "text": a[0], "id": str(a[3])}
)

_log_perf(start_date, "GET CLINICAL NOTES")

Expand Down
1 change: 1 addition & 0 deletions routes/support.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def create_ticket():
user=user,
from_url=request.form.get("fromUrl", None),
category=request.form.get("category", None),
title=request.form.get("title", None),
description=request.form.get("description", None),
filelist=request.files.getlist("fileList[]"),
)
Expand Down
38 changes: 34 additions & 4 deletions services/admin/drug_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from models.main import *
from models.appendix import *
from models.segment import *
from models.enums import RoleEnum, DrugAdminSegment
from models.enums import RoleEnum, DrugAdminSegment, DrugAttributesAuditTypeEnum
from services.admin import ai_service
from services import drug_service as main_drug_service, permission_service

Expand Down Expand Up @@ -370,14 +370,14 @@ def copy_drug_attributes(
"gestante",
"fkunidademedidacusto",
"custo",
"jejum",
]
set_attributes = []
for a in attributes:
if a in base_attributes:
set_attributes.append(f"{a} = destino.{a},")

query = text(
f"""
query = f"""
with modelo as (
select
m.sctid,
Expand All @@ -397,6 +397,7 @@ def copy_drug_attributes(
coalesce(ma.naopadronizado, false) as naopadronizado,
coalesce(ma.linhabranca, false) as linhabranca,
coalesce(ma.dialisavel, false) as dialisavel,
coalesce(ma.jejum, false) as jejum,
ma.fkunidademedidacusto,
ma.custo
from
Expand All @@ -419,6 +420,35 @@ def copy_drug_attributes(
ma.idsegmento = :idSegmentDestiny
{only_support_filter if not overwrite_all else ''}
)
"""

audit_stmt = text(
f"""
{query}
insert into
{schema}.medatributos_audit
(tp_audit, fkmedicamento, idsegmento, extra, created_at, created_by)
select
{DrugAttributesAuditTypeEnum.COPY_FROM_REFERENCE.value}, d.fkmedicamento, d.idsegmento, :extra, now(), :idUser
from
destino d
"""
)

db.session.execute(
audit_stmt,
{
"idSegmentOrigin": id_segment_origin,
"idSegmentDestiny": id_segment_destiny,
"supportRole": f"%{RoleEnum.SUPPORT.value}%",
"idUser": user.id,
"extra": '{"attributes": "' + ",".join(attributes) + '"}',
},
)

update_stmt = text(
f"""
{query}
update
{schema}.medatributos origem
set
Expand All @@ -434,7 +464,7 @@ def copy_drug_attributes(
)

return db.session.execute(
query,
update_stmt,
{
"idSegmentOrigin": id_segment_origin,
"idSegmentDestiny": id_segment_destiny,
Expand Down
Loading

0 comments on commit 5daacf9

Please sign in to comment.