Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v3.08-beta #323

Merged
merged 4 commits into from
Jun 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion mobile.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@

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


@app.route("/exc", methods=["GET"])
Expand Down
1 change: 1 addition & 0 deletions models/notes.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class ClinicalNotes(db.Model):
template = deferred(db.Column("template", postgresql.JSON, nullable=True))

summary = deferred(db.Column("sumario", postgresql.JSONB, nullable=True))
annotations = deferred(db.Column("anotacoes", postgresql.JSONB, nullable=True))

def exists():
return True
Expand Down
159 changes: 11 additions & 148 deletions routes/notes.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
import os
from models.main import db, dbSession, User
from models.notes import ClinicalNotes
from models.prescription import Patient
from flask import Blueprint, request
from markupsafe import escape as escape_html
from utils import status
from flask_jwt_extended import jwt_required, get_jwt_identity
from .utils import tryCommit
from sqlalchemy import desc, or_, func
from sqlalchemy.orm import undefer
from datetime import datetime
from services import clinical_notes_service, memory_service

from models.main import db, dbSession, User
from models.notes import ClinicalNotes
from services import clinical_notes_service, memory_service
from .utils import tryCommit
from utils import status
from exception.validation_error import ValidationError

app_note = Blueprint("app_note", __name__)
Expand All @@ -23,148 +20,14 @@
user = User.find(get_jwt_identity())
dbSession.setSchema(user.schema)

has_primary_care = memory_service.has_feature("PRIMARYCARE")
filter_date = request.args.get("date", None)
dates = None
previous_admissions = []

if filter_date is None:
dates = (
db.session.query(
func.date(ClinicalNotes.date),
func.count(),
func.sum(ClinicalNotes.diseases),
func.sum(ClinicalNotes.complication),
func.sum(ClinicalNotes.symptoms),
func.sum(ClinicalNotes.conduct),
func.array_agg(func.distinct(ClinicalNotes.position)),
func.sum(ClinicalNotes.allergy),
func.sum(ClinicalNotes.info),
func.sum(ClinicalNotes.medications),
func.sum(ClinicalNotes.names),
func.sum(ClinicalNotes.signs),
func.sum(ClinicalNotes.dialysis),
)
.select_from(ClinicalNotes)
.filter(ClinicalNotes.admissionNumber == admissionNumber)
.filter(or_(ClinicalNotes.isExam == None, ClinicalNotes.isExam == False))
.group_by(func.date(ClinicalNotes.date))
.order_by(desc(func.date(ClinicalNotes.date)))
.all()
)

if len(dates) > 0:
dates_list = []
for row in range(3):
if len(dates) > row:
dates_list.append(dates[row][0])

notes = get_notes_by_date(admissionNumber, dates_list, has_primary_care)
else:
notes = []

admission = (
db.session.query(Patient)
.filter(Patient.admissionNumber == admissionNumber)
.first()
)

if admission != None:
admission_list = (
db.session.query(Patient)
.filter(Patient.idPatient == admission.idPatient)
.filter(Patient.admissionNumber < admissionNumber)
.order_by(desc(Patient.admissionDate))
.limit(10)
.all()
)

for pa in admission_list:
previous_admissions.append(
{
"admissionNumber": pa.admissionNumber,
"admissionDate": (
pa.admissionDate.isoformat() if pa.admissionDate else None
),
"dischargeDate": (
pa.dischargeDate.isoformat() if pa.dischargeDate else None
),
}
)
else:
notes = get_notes_by_date(admissionNumber, [filter_date], has_primary_care)

noteResults = []
for n in notes:
noteResults.append(convert_notes(n, has_primary_care))

dateResults = []
if dates is not None:
for d in dates:
dateResults.append(
{
"date": d[0].isoformat(),
"count": d[1],
"diseases": d[2],
"complication": d[3],
"symptoms": d[4],
"conduct": d[5],
"roles": d[6],
"allergy": d[7],
"info": d[8],
"medications": d[9],
"names": d[10],
"signs": d[11],
"dialysis": d[12],
}
)

return {
"status": "success",
"data": {
"dates": dateResults,
"notes": noteResults,
"previousAdmissions": previous_admissions,
},
}, status.HTTP_200_OK


def get_notes_by_date(admissionNumber, dateList, has_primary_care):
query = (
ClinicalNotes.query.filter(ClinicalNotes.admissionNumber == admissionNumber)
.filter(or_(ClinicalNotes.isExam == None, ClinicalNotes.isExam == False))
.filter(func.date(ClinicalNotes.date).in_(dateList))
)

if has_primary_care:
query = query.options(
undefer(ClinicalNotes.form), undefer(ClinicalNotes.template)
try:
result = clinical_notes_service.get_notes(
admission_number=admissionNumber, filter_date=request.args.get("date", None)
)
except ValidationError as e:
return {"status": "error", "message": str(e), "code": e.code}, e.httpStatus
Dismissed Show dismissed Hide dismissed

return query.order_by(desc(ClinicalNotes.date)).all()


def convert_notes(notes, has_primary_care):
return {
"id": str(notes.id),
"admissionNumber": notes.admissionNumber,
"text": notes.text,
"form": notes.form if has_primary_care else None,
"template": notes.template if has_primary_care else None,
"date": notes.date.isoformat(),
"prescriber": notes.prescriber,
"position": notes.position,
"medications": notes.medications,
"complication": notes.complication,
"symptoms": notes.symptoms,
"diseases": notes.diseases,
"info": notes.info,
"conduct": notes.conduct,
"signs": notes.signs,
"allergy": notes.allergy,
"names": notes.names,
"dialysis": notes.dialysis,
}
return {"status": "success", "data": result}, status.HTTP_200_OK


@app_note.route("/notes/<int:idNote>", methods=["POST"])
Expand Down
170 changes: 169 additions & 1 deletion services/clinical_notes_service.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from sqlalchemy import text
from sqlalchemy import text, Integer, func, desc
from sqlalchemy.orm import undefer

from models.main import db
from models.appendix import *
Expand Down Expand Up @@ -115,3 +116,170 @@ def remove_annotation(id_clinical_notes: int, annotation_type: str, user: User):
"type": annotation_type,
},
)


def get_tags():
return [
{"name": "dados", "column": "info"},
{"name": "acesso", "column": None},
{"name": "germes", "column": None},
{"name": "sinais", "column": "signs"},
{"name": "alergia", "column": "allergy"},
{"name": "conduta", "column": "conduct"},
{"name": "dialise", "column": "dialysis"},
{"name": "diliexc", "column": None},
{"name": "doencas", "column": "diseases"},
{"name": "resthid", "column": None},
{"name": "gestante", "column": None},
{"name": "sintomas", "column": "symptoms"},
{"name": "complicacoes", "column": "complication"},
{"name": "medicamentos", "column": "medications"},
]


def get_notes(admission_number: int, filter_date: str):
has_primary_care = memory_service.has_feature("PRIMARYCARE")
dates = None
previous_admissions = []

tags = get_tags()

if filter_date is None:
dates_query = (
db.session.query(
func.date(ClinicalNotes.date).label("date"),
func.count().label("total"),
func.array_agg(func.distinct(ClinicalNotes.position)).label("roles"),
)
.select_from(ClinicalNotes)
.filter(ClinicalNotes.admissionNumber == admission_number)
.filter(or_(ClinicalNotes.isExam == None, ClinicalNotes.isExam == False))
.group_by(func.date(ClinicalNotes.date))
.order_by(desc(func.date(ClinicalNotes.date)))
)

for tag in tags:
if tag["column"] != None:
dates_query = dates_query.add_columns(
func.sum(getattr(ClinicalNotes, tag["column"])).label(tag["name"])
)
else:
column_name = tag["name"] + "_count"
dates_query = dates_query.add_columns(
func.sum(
func.cast(
func.coalesce(
ClinicalNotes.annotations[column_name].astext, "0"
),
Integer,
)
).label(tag["name"])
)

dates = dates_query.all()

if len(dates) > 0:
dates_list = []
for row in range(3):
if len(dates) > row:
dates_list.append(dates[row][0])

notes = get_notes_by_date(admission_number, dates_list, has_primary_care)
else:
notes = []

admission = (
db.session.query(Patient)
.filter(Patient.admissionNumber == admission_number)
.first()
)

if admission != None:
admission_list = (
db.session.query(Patient)
.filter(Patient.idPatient == admission.idPatient)
.filter(Patient.admissionNumber < admission_number)
.order_by(desc(Patient.admissionDate))
.limit(10)
.all()
)

for pa in admission_list:
previous_admissions.append(
{
"admissionNumber": pa.admissionNumber,
"admissionDate": (
pa.admissionDate.isoformat() if pa.admissionDate else None
),
"dischargeDate": (
pa.dischargeDate.isoformat() if pa.dischargeDate else None
),
}
)
else:
notes = get_notes_by_date(admission_number, [filter_date], has_primary_care)

noteResults = []
for n in notes:
noteResults.append(convert_notes(n, has_primary_care, tags))

dateResults = []
if dates is not None:
for d in dates:
d_dict = {"date": d.date.isoformat(), "count": d.total, "roles": d.roles}

for tag in tags:
if tag["column"] != None:
d_dict[tag["column"]] = getattr(d, tag["name"])
else:
d_dict[tag["name"]] = getattr(d, tag["name"])

dateResults.append(d_dict)

return {
"dates": dateResults,
"notes": noteResults,
"previousAdmissions": previous_admissions,
}


def get_notes_by_date(admission_number, dateList, has_primary_care):
query = (
ClinicalNotes.query.filter(ClinicalNotes.admissionNumber == admission_number)
.filter(or_(ClinicalNotes.isExam == None, ClinicalNotes.isExam == False))
.filter(func.date(ClinicalNotes.date).in_(dateList))
)

query = query.options(undefer(ClinicalNotes.annotations))

if has_primary_care:
query = query.options(
undefer(ClinicalNotes.form), undefer(ClinicalNotes.template)
)

return query.order_by(desc(ClinicalNotes.date)).all()


def convert_notes(notes, has_primary_care, tags):
obj = {
"id": str(notes.id),
"admissionNumber": notes.admissionNumber,
"text": notes.text,
"form": notes.form if has_primary_care else None,
"template": notes.template if has_primary_care else None,
"date": notes.date.isoformat(),
"prescriber": notes.prescriber,
"position": notes.position,
}

for tag in tags:
if tag["column"] != None:
obj[tag["column"]] = getattr(notes, tag["column"])
else:
obj[tag["name"]] = (
notes.annotations[tag["name"] + "_count"]
if notes.annotations != None
else 0
)

return obj
5 changes: 4 additions & 1 deletion services/intervention_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,10 @@ def save_intervention(
if expended_dose != -1:
i.expended_dose = expended_dose

if memory_service.has_feature(FeatureEnum.INTERVENTION_V2.value):
if (
memory_service.has_feature(FeatureEnum.INTERVENTION_V2.value)
and id_prescription == 0
):
economy_type = None
reasons = (
db.session.query(InterventionReason)
Expand Down
Loading