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

Store critical care daily round changes in events #2170

Merged
merged 9 commits into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
8 changes: 8 additions & 0 deletions care/facility/api/serializers/daily_round.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,14 @@ def update(self, instance, validated_data):
facility=instance.consultation.patient.facility,
).generate()

create_consultation_events(
instance.consultation_id,
instance,
instance.created_by_id,
instance.created_date,
fields_to_store=set(validated_data.keys()),
)

return super().update(instance, validated_data)

def update_last_daily_round(self, daily_round_obj):
Expand Down
2 changes: 1 addition & 1 deletion care/facility/api/viewsets/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

class EventTypeViewSet(ReadOnlyModelViewSet):
serializer_class = EventTypeSerializer
queryset = EventType.objects.all()
queryset = EventType.objects.filter(is_active=True)
permission_classes = (IsAuthenticated,)

def get_serializer_class(self) -> type[BaseSerializer]:
Expand Down
59 changes: 31 additions & 28 deletions care/facility/events/handler.py
Original file line number Diff line number Diff line change
@@ -1,60 +1,53 @@
from datetime import datetime

from celery import shared_task
from django.core import serializers
from django.db import models, transaction
from django.db import transaction
from django.db.models import Model
from django.db.models.query import QuerySet
from django.utils.timezone import now

from care.facility.models.events import ChangeType, EventType, PatientConsultationEvent
from care.utils.event_utils import get_changed_fields
from care.utils.event_utils import get_changed_fields, serialize_field


def transform(object_instance: Model, old_instance: Model):
fields = []
def transform(
object_instance: Model,
old_instance: Model,
fields_to_store: set | None = None,
) -> dict:
fields = set()
if old_instance:
changed_fields = get_changed_fields(old_instance, object_instance)
fields = [
fields = {
field
for field in object_instance._meta.fields
if field.name in changed_fields
]
}
else:
fields = object_instance._meta.fields
fields = set(object_instance._meta.fields)

data = {}
for field in fields:
value = getattr(object_instance, field.name)
if isinstance(value, models.Model):
data[field.name] = serializers.serialize("python", [value])[0]["fields"]
elif issubclass(field.__class__, models.Field) and field.choices:
# serialize choice fields with display value
data[field.name] = getattr(
object_instance, f"get_{field.name}_display", lambda: value
)()
else:
data[field.name] = value
return data
if fields_to_store:
fields &= fields_to_store

return {field.name: serialize_field(object_instance, field) for field in fields}


@shared_task
def create_consultation_event_entry(
consultation_id: int,
object_instance: Model,
caused_by: int,
created_date: datetime,
old_instance: Model = None,
fields_to_store: set | None = None,
):
change_type = ChangeType.UPDATED if old_instance else ChangeType.CREATED

data = transform(object_instance, old_instance)
data = transform(object_instance, old_instance, fields_to_store)

fields_to_store = set(data.keys())
fields_to_store = fields_to_store or set(data.keys())

batch = []
groups = EventType.objects.filter(
model=object_instance.__class__.__name__, fields__len__gt=0
model=object_instance.__class__.__name__, fields__len__gt=0, is_active=True
).values_list("id", "fields")
for group_id, group_fields in groups:
if set(group_fields) & fields_to_store:
Expand Down Expand Up @@ -103,6 +96,7 @@ def create_consultation_events(
caused_by: int,
created_date: datetime = None,
old: Model | None = None,
fields_to_store: list | set | None = None,
):
if created_date is None:
created_date = now()
Expand All @@ -115,9 +109,18 @@ def create_consultation_events(
)
for obj in objects:
create_consultation_event_entry(
consultation_id, obj, caused_by, created_date
consultation_id,
obj,
caused_by,
created_date,
fields_to_store=set(fields_to_store) if fields_to_store else None,
)
else:
create_consultation_event_entry(
consultation_id, objects, caused_by, created_date, old
consultation_id,
objects,
caused_by,
created_date,
old,
fields_to_store=set(fields_to_store) if fields_to_store else None,
)
163 changes: 85 additions & 78 deletions care/facility/management/commands/load_event_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,88 +94,40 @@ class Command(BaseCommand):
"model": "DailyRound",
"children": (
{
"name": "HEALTH",
"name": "DAILY_ROUND_DETAILS",
"fields": (
"taken_at",
"round_type",
"other_details",
"action",
"review_after",
),
"children": (
{
"name": "ROUND_SYMPTOMS", # todo resolve clash with consultation symptoms
"fields": ("additional_symptoms", "other_symptoms"),
"fields": ("additional_symptoms",),
},
{
"name": "PHYSICAL_EXAMINATION",
"fields": ("physical_examination_info",),
},
{"name": "PATIENT_CATEGORY", "fields": ("patient_category",)},
{
"name": "PATIENT_CATEGORY",
"fields": ("patient_category",),
},
),
},
{
"name": "VITALS",
"children": (
{
"name": "TEMPERATURE",
"fields": (
"temperature",
"temperature_measured_at", # todo remove field
),
},
{"name": "TEMPERATURE", "fields": ("temperature",)},
{"name": "SPO2", "fields": ("spo2",)},
{"name": "PULSE", "fields": ("pulse",)},
{"name": "BLOOD_PRESSURE", "fields": ("bp",)},
{"name": "RESPIRATORY_RATE", "fields": ("resp",)},
{"name": "RHYTHM", "fields": ("rhythm", "rhythm_details")},
),
},
{
"name": "RESPIRATORY",
"children": (
{
"name": "BILATERAL_AIR_ENTRY",
"fields": ("bilateral_air_entry",),
},
),
},
{
"name": "INTAKE_OUTPUT",
"children": (
{"name": "INFUSIONS", "fields": ("infusions",)},
{"name": "IV_FLUIDS", "fields": ("iv_fluids",)},
{"name": "FEEDS", "fields": ("feeds",)},
{
"name": "TOTAL_INTAKE",
"fields": ("total_intake_calculated",),
},
{"name": "OUTPUT", "fields": ("output",)},
{
"name": "TOTAL_OUTPUT",
"fields": ("total_output_calculated",),
},
),
},
{
"name": "VENTILATOR_MODES",
"fields": (
"ventilator_interface",
"ventilator_mode",
"ventilator_peep",
"ventilator_pip",
"ventilator_mean_airway_pressure",
"ventilator_resp_rate",
"ventilator_pressure_support",
"ventilator_tidal_volume",
"ventilator_oxygen_modality",
"ventilator_oxygen_modality_oxygen_rate",
"ventilator_oxygen_modality_flow_rate",
"ventilator_fi02",
"ventilator_spo2",
),
},
{
"name": "DIALYSIS",
"fields": (
"pressure_sore",
"dialysis_fluid_balance",
"dialysis_net_balance",
),
},
{
"name": "NEUROLOGICAL",
"fields": (
Expand All @@ -191,40 +143,84 @@ class Command(BaseCommand):
"glasgow_verbal_response",
"glasgow_motor_response",
"glasgow_total_calculated",
"limb_response_upper_extremity_right",
"limb_response_upper_extremity_left",
"limb_response_upper_extremity_right",
"limb_response_lower_extremity_left",
"limb_response_lower_extremity_right",
"consciousness_level",
"consciousness_level_detail",
"in_prone_position",
),
},
{
"name": "BLOOD_GLUCOSE",
"fields": ("blood_sugar_level",),
"name": "RESPIRATORY_SUPPORT",
"fields": (
"bilateral_air_entry",
"etco2",
"ventilator_fi02",
"ventilator_interface",
"ventilator_mean_airway_pressure",
"ventilator_mode",
"ventilator_oxygen_modality",
"ventilator_oxygen_modality_flow_rate",
"ventilator_oxygen_modality_oxygen_rate",
"ventilator_peep",
"ventilator_pip",
"ventilator_pressure_support",
"ventilator_resp_rate",
"ventilator_spo2",
"ventilator_tidal_volume",
),
},
{
"name": "DAILY_ROUND_DETAILS",
"name": "ARTERIAL_BLOOD_GAS_ANALYSIS",
"fields": (
"other_details",
"medication_given",
"in_prone_position",
"etco2",
"pain",
"pain_scale_enhanced",
"ph",
"pco2",
"po2",
"hco3",
"base_excess",
"hco3",
"lactate",
"sodium",
"pco2",
"ph",
"po2",
"potassium",
"sodium",
),
},
{
"name": "BLOOD_GLUCOSE",
"fields": (
"blood_sugar_level",
"insulin_intake_dose",
"insulin_intake_frequency",
"nursing",
),
},
{
"name": "IO_BALANCE",
"children": (
{"name": "INFUSIONS", "fields": ("infusions",)},
{"name": "IV_FLUIDS", "fields": ("iv_fluids",)},
{"name": "FEEDS", "fields": ("feeds",)},
{"name": "OUTPUT", "fields": ("output",)},
{
"name": "TOTAL_INTAKE",
"fields": ("total_intake_calculated",),
},
{
"name": "TOTAL_OUTPUT",
"fields": ("total_output_calculated",),
},
),
},
{
"name": "DIALYSIS",
"fields": (
"dialysis_fluid_balance",
"dialysis_net_balance",
),
"children": (
{"name": "PRESSURE_SORE", "fields": ("pressure_sore",)},
),
},
{"name": "NURSING", "fields": ("nursing",)},
),
},
{
Expand All @@ -239,6 +235,12 @@ class Command(BaseCommand):
},
)

inactive_event_types: Tuple[str, ...] = (
"RESPIRATORY",
"INTAKE_OUTPUT",
"VENTILATOR_MODES",
)

def create_objects(
self, types: Tuple[EventType, ...], model: str = None, parent: EventType = None
):
Expand All @@ -250,6 +252,7 @@ def create_objects(
"parent": parent,
"model": model,
"fields": event_type.get("fields", []),
"is_active": True,
},
)
if children := event_type.get("children"):
Expand All @@ -258,6 +261,10 @@ def create_objects(
def handle(self, *args, **options):
self.stdout.write("Loading Event Types... ", ending="")

EventType.objects.filter(name__in=self.inactive_event_types).update(
is_active=False
)

self.create_objects(self.consultation_event_types)

self.stdout.write(self.style.SUCCESS("OK"))
14 changes: 13 additions & 1 deletion care/utils/event_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
from json import JSONEncoder
from logging import getLogger

from django.db.models import Model
from django.core.serializers import serialize
from django.db.models import Field, Model
from multiselectfield.db.fields import MSFList, MultiSelectField

logger = getLogger(__name__)
Expand All @@ -27,6 +28,17 @@ def get_changed_fields(old: Model, new: Model) -> set[str]:
return changed_fields


def serialize_field(object: Model, field: Field):
value = getattr(object, field.name)
if isinstance(value, Model):
# serialize the fields of the related model
return serialize("python", [value])[0]["fields"]
if issubclass(field.__class__, Field) and field.choices:
# serialize choice fields with display value
return getattr(object, f"get_{field.name}_display", lambda: value)()
return value


def model_diff(old, new):
diff = {}
for field in new._meta.fields:
Expand Down
Loading