Skip to content

Commit

Permalink
Merge pull request #408 from noharm-ai/develop
Browse files Browse the repository at this point in the history
v4.07-beta
  • Loading branch information
marceloarocha authored Nov 7, 2024
2 parents a743a33 + c9b9236 commit 15c3fc8
Show file tree
Hide file tree
Showing 13 changed files with 77 additions and 79 deletions.
2 changes: 1 addition & 1 deletion config.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@


class Config:
VERSION = "v4.06-beta"
VERSION = "v4.07-beta"
FRONTEND_VERSION = "4.0.5"
ENV = getenv("ENV") or NoHarmENV.DEVELOPMENT.value
SECRET_KEY = getenv("SECRET_KEY") or "secret_key"
Expand Down
58 changes: 0 additions & 58 deletions models/prescription.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@
from sqlalchemy import case, cast, literal, and_, func, desc, asc, or_
from sqlalchemy.sql.expression import literal_column, case
from sqlalchemy.dialects import postgresql
from sqlalchemy.dialects.postgresql import INTERVAL

from .main import db, User, DrugAttributes, Outlier, Substance, Drug
from .appendix import Department, Notes, MeasureUnit, Frequency, MeasureUnitConvert
from .segment import Segment
from utils import prescriptionutils


Expand Down Expand Up @@ -49,62 +47,6 @@ def getFuturePrescription(idPrescription, admissionNumber):
.first()
)

def lastDeptbyAdmission(idPrescription, admissionNumber, ref_date):
return (
db.session.query(Department.name)
.select_from(Prescription)
.outerjoin(
Department,
and_(
Department.id == Prescription.idDepartment,
Department.idHospital == Prescription.idHospital,
),
)
.filter(Prescription.admissionNumber == admissionNumber)
.filter(Prescription.id < idPrescription)
.filter(
Prescription.date
> (func.date(ref_date) - func.cast("1 month", INTERVAL))
)
.order_by(desc(Prescription.id))
.first()
)

def getPrescriptionBasic():
return (
db.session.query(
Prescription,
Patient,
literal("0"),
literal("0"),
Department.name.label("department"),
Segment.description,
Patient.observation,
Prescription.notes,
Patient.alert,
Prescription.prescriber,
User.name,
Prescription.insurance,
)
.outerjoin(Patient, Patient.admissionNumber == Prescription.admissionNumber)
.outerjoin(
Department,
and_(
Department.id == Prescription.idDepartment,
Department.idHospital == Prescription.idHospital,
),
)
.outerjoin(Segment, Segment.id == Prescription.idSegment)
.outerjoin(User, Prescription.user == User.id)
)

def getPrescription(idPrescription):
return (
Prescription.getPrescriptionBasic()
.filter(Prescription.id == idPrescription)
.first()
)

def getHeaders(admissionNumber, aggDate, idSegment, is_pmc=False, is_cpoe=False):
q = (
db.session.query(Prescription, Department.name, User.name)
Expand Down
2 changes: 1 addition & 1 deletion services/admin/admin_drug_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@

from models.main import db, User, PrescriptionAgg
from models.prescription import (
Segment,
MeasureUnit,
MeasureUnitConvert,
Outlier,
Drug,
DrugAttributes,
Substance,
)
from models.segment import Segment
from models.enums import DrugAdminSegment, DrugAttributesAuditTypeEnum
from services.admin import admin_ai_service
from services import drug_service as main_drug_service
Expand Down
1 change: 0 additions & 1 deletion services/admin/admin_exam_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from markupsafe import escape as escape_html

from models.main import db, User
from models.prescription import Segment
from models.segment import Segment, SegmentExam, Exams
from services.admin import admin_integration_service
from services import data_authorization_service
Expand Down
3 changes: 1 addition & 2 deletions services/admin/admin_integration_status_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from models.main import db, User, PrescriptionAgg
from models.prescription import (
Segment,
Outlier,
Drug,
DrugAttributes,
Expand All @@ -14,7 +13,7 @@
SegmentDepartment,
InterventionReason,
)
from models.segment import SegmentExam
from models.segment import SegmentExam, Segment
from models.enums import MemoryEnum
from services.admin import admin_memory_service
from exception.validation_error import ValidationError
Expand Down
4 changes: 2 additions & 2 deletions services/admin/admin_segment_service.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from sqlalchemy import func, and_, asc

from models.main import db, User
from models.prescription import Segment, Department
from models.prescription import Department
from models.appendix import SegmentDepartment
from models.segment import Hospital
from models.segment import Hospital, Segment
from models.enums import IntegrationStatusEnum
from services.admin import admin_integration_status_service
from decorators.has_permission_decorator import has_permission, Permission
Expand Down
2 changes: 1 addition & 1 deletion services/admin/admin_unit_conversion_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
Drug,
MeasureUnit,
Substance,
Segment,
)
from models.segment import Segment
from models.enums import IntegrationStatusEnum
from services import drug_service as main_drug_service
from services.admin import (
Expand Down
10 changes: 9 additions & 1 deletion services/cache_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,15 @@ def get_range(key: str, days_ago: int):
now = time.time()
min_date = now - (days_ago * 24 * 60 * 60)

cache_data = redis_client.zrangebyscore(key, min=min_date, max=now)
try:
cache_data = redis_client.zrangebyscore(key, min=min_date, max=now)
except TimeoutError:
logging.basicConfig()
logger = logging.getLogger("noharm.backend")
logger.error(
f"redis timeout error: {key}",
)
return None

if cache_data:
result = []
Expand Down
2 changes: 1 addition & 1 deletion services/drug_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
DrugAttributes,
MeasureUnitConvert,
Substance,
Segment,
)
from models.segment import Segment
from models.enums import DrugAdminSegment, DrugAttributesAuditTypeEnum
from services import data_authorization_service
from exception.validation_error import ValidationError
Expand Down
56 changes: 52 additions & 4 deletions services/prescription_agg_service.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from sqlalchemy import desc, text, select, func, and_
from flask_sqlalchemy.session import Session
from datetime import date, datetime
from datetime import date, datetime, timedelta

from models.main import db, User, dbSession
from models.prescription import (
Expand Down Expand Up @@ -108,9 +108,13 @@ def create_agg_prescription_by_prescription(
id_prescription=pAgg.id, user_context=user_context
)

pAgg.features = prescriptionutils.getFeatures(
features = prescriptionutils.getFeatures(
result=agg_data, agg_date=pAgg.date, intervals_for_agg_date=True
)
score_variation = _get_score_variation(prescription=pAgg, features=features)
features.update({"scoreVariation": score_variation})

pAgg.features = features
pAgg.aggDrugs = pAgg.features["drugIDs"]
pAgg.aggDeps = pAgg.features["departmentList"]

Expand Down Expand Up @@ -199,10 +203,16 @@ def create_agg_prescription_by_date(
id_prescription=agg_p.id, user_context=user_context
)

agg_p.update = datetime.today()
agg_p.features = prescriptionutils.getFeatures(result=agg_data)
features = prescriptionutils.getFeatures(
result=agg_data, agg_date=agg_p.date, intervals_for_agg_date=True
)
score_variation = _get_score_variation(prescription=agg_p, features=features)
features.update({"scoreVariation": score_variation})

agg_p.features = features
agg_p.aggDrugs = agg_p.features["drugIDs"]
agg_p.aggDeps = agg_p.features["departmentList"]
agg_p.update = datetime.today()

internal_prescription_ids = internal_prescription_ids = (
prescriptionutils.get_internal_prescription_ids(result=agg_data)
Expand Down Expand Up @@ -331,3 +341,41 @@ def _update_patient_conciliation_status(prescription: Prescription):
):
patient.st_conciliation = PatientConciliationStatusEnum.CREATED.value
db.session.flush()


def _get_score_variation(prescription: Prescription, features: dict):
new_score = int(features.get("globalScore", 0))
initial_value = {
"variation": 100,
"currentGlobalScore": new_score,
"previousGlobalScore": 0,
}

previous_prescription = (
db.session.query(Prescription)
.filter(
Prescription.id
== prescriptionutils.gen_agg_id(
admission_number=prescription.admissionNumber,
id_segment=prescription.idSegment,
pdate=prescription.date - timedelta(days=1),
)
)
.first()
)

if not previous_prescription:
return initial_value

previous_score = int(previous_prescription.features.get("globalScore", 0))
if previous_score == 0:
return initial_value

variation = (new_score - previous_score) / previous_score * 100

variation_data = initial_value
variation_data.update(
{"variation": round(variation, 2), "previousGlobalScore": previous_score}
)

return variation_data
9 changes: 4 additions & 5 deletions services/prescription_view_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@
PrescriptionDrug,
PrescriptionAudit,
Department,
Segment,
)
from models.segment import Exams
from models.segment import Exams, Segment
from models.enums import (
MemoryEnum,
FeatureEnum,
Expand Down Expand Up @@ -198,7 +197,7 @@ def _build_headers(
"solution": [],
"procedures": [],
"interventions": drugsInterv,
"alertExams": [],
"alertExams": 0,
"complication": 0,
}
)
Expand All @@ -208,7 +207,7 @@ def _build_headers(
"solution": solutions,
"procedures": [],
"interventions": solutionsInterv,
"alertExams": [],
"alertExams": 0,
"complication": 0,
}
)
Expand All @@ -218,7 +217,7 @@ def _build_headers(
"solution": [],
"procedures": procedures,
"interventions": proceduresInterv,
"alertExams": [],
"alertExams": 0,
"complication": 0,
}
)
Expand Down
3 changes: 2 additions & 1 deletion services/segment_service.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from sqlalchemy import asc, func

from models.main import db
from models.prescription import Department, Segment
from models.prescription import Department
from models.segment import Segment
from models.appendix import SegmentDepartment
from decorators.has_permission_decorator import has_permission, Permission

Expand Down
4 changes: 3 additions & 1 deletion utils/prescriptionutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,6 @@ def getFeatures(result, agg_date: datetime = None, intervals_for_agg_date=False)
drug_attributes[attr] = 0

for d in drugList:

drugIDs.append(d["idDrug"])
if d["idSubstance"] != None:
substanceIDs.append(d["idSubstance"])
Expand Down Expand Up @@ -190,6 +189,8 @@ def getFeatures(result, agg_date: datetime = None, intervals_for_agg_date=False)
if "high" in alert_levels:
alert_level = "high"

global_score = pScore + av + am + exams + alerts + diff

return {
"alergy": allergy,
"allergy": allergy,
Expand Down Expand Up @@ -220,6 +221,7 @@ def getFeatures(result, agg_date: datetime = None, intervals_for_agg_date=False)
"drugAttributes": drug_attributes,
"intervals": intervals,
"departmentList": list(department_list),
"globalScore": global_score,
}


Expand Down

0 comments on commit 15c3fc8

Please sign in to comment.