Skip to content

Commit

Permalink
Merge branch 'develop' into sainak/fix/atomicity-of-consultations
Browse files Browse the repository at this point in the history
  • Loading branch information
vigneshhari authored Aug 16, 2024
2 parents 2b13232 + e95d98d commit 9d1c835
Show file tree
Hide file tree
Showing 26 changed files with 423 additions and 109 deletions.
3 changes: 3 additions & 0 deletions care/abdm/api/viewsets/health_facility.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@

@shared_task
def register_health_facility_as_service(facility_external_id):
if settings.ENABLE_ABDM:
return [False, "ABDM Services are currently disabled"]

health_facility = HealthFacility.objects.filter(
facility__external_id=facility_external_id
).first()
Expand Down
1 change: 1 addition & 0 deletions care/facility/api/serializers/daily_round.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ def create(self, validated_data):
daily_round_obj,
daily_round_obj.created_by_id,
daily_round_obj.created_date,
taken_at=daily_round_obj.taken_at,
)
return daily_round_obj

Expand Down
14 changes: 9 additions & 5 deletions care/facility/api/serializers/facility.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import boto3
from django.conf import settings
from django.contrib.auth import get_user_model
from rest_framework import serializers

Expand Down Expand Up @@ -168,11 +169,14 @@ def save(self, **kwargs):
config, bucket_name = get_client_config(BucketType.FACILITY)
s3 = boto3.client("s3", **config)
image_location = f"cover_images/{facility.external_id}_cover.{image_extension}"
s3.put_object(
Bucket=bucket_name,
Key=image_location,
Body=image.file,
)
boto_params = {
"Bucket": bucket_name,
"Key": image_location,
"Body": image.file,
}
if settings.BUCKET_HAS_FINE_ACL:
boto_params["ACL"] = "public-read"
s3.put_object(**boto_params)
facility.cover_image_url = image_location
facility.save()
return facility
21 changes: 21 additions & 0 deletions care/facility/api/serializers/file_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from care.facility.api.serializers.shifting import has_facility_permission
from care.facility.models.facility import Facility
from care.facility.models.file_upload import FileUpload
from care.facility.models.notification import Notification
from care.facility.models.patient import PatientRegistration
from care.facility.models.patient_consultation import (
PatientConsent,
Expand All @@ -14,6 +15,7 @@
from care.facility.models.patient_sample import PatientSample
from care.users.api.serializers.user import UserBaseMinimumSerializer
from care.users.models import User
from care.utils.notification_handler import NotificationGenerator
from config.serializers import ChoiceField


Expand Down Expand Up @@ -156,12 +158,31 @@ def create(self, validated_data):
internal_id = check_permissions(
validated_data["file_type"], validated_data["associating_id"], user
)
associating_id = validated_data["associating_id"]
validated_data["associating_id"] = internal_id
validated_data["uploaded_by"] = user
validated_data["internal_name"] = validated_data["original_name"]
del validated_data["original_name"]
file_upload: FileUpload = super().create(validated_data)
file_upload.signed_url = file_upload.signed_url(mime_type=mime_type)
if validated_data["file_type"] == FileUpload.FileType.CONSULTATION.value:
consultation = PatientConsultation.objects.get(external_id=associating_id)
NotificationGenerator(
event=Notification.Event.CONSULTATION_FILE_UPLOAD_CREATED,
caused_by=user,
caused_object=consultation,
facility=consultation.facility,
generate_for_facility=True,
).generate()
if validated_data["file_type"] == FileUpload.FileType.PATIENT.value:
patient = PatientRegistration.objects.get(external_id=associating_id)
NotificationGenerator(
event=Notification.Event.PATIENT_FILE_UPLOAD_CREATED,
caused_by=user,
caused_object=patient,
facility=patient.facility,
generate_for_facility=True,
).generate()
return file_upload


Expand Down
6 changes: 3 additions & 3 deletions care/facility/api/serializers/patient_consultation.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ def update(self, instance, validated_data):
consultation,
self.context["request"].user.id,
consultation.modified_date,
old_instance,
old=old_instance,
)

if "assigned_to" in validated_data:
Expand Down Expand Up @@ -798,7 +798,7 @@ def update(self, instance: PatientConsultation, validated_data):
ConsultationBed.objects.filter(
consultation=self.instance, end_date__isnull=True
).update(end_date=now())
if patient.abha_number:
if settings.ENABLE_ABDM and patient.abha_number:
abha_number = patient.abha_number
try:
AbdmGateway().fetch_modes(
Expand All @@ -818,7 +818,7 @@ def update(self, instance: PatientConsultation, validated_data):
instance,
self.context["request"].user.id,
instance.modified_date,
old_instance,
old=old_instance,
)

return instance
Expand Down
35 changes: 34 additions & 1 deletion care/facility/api/viewsets/consultation_diagnosis.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
from copy import copy

from django.shortcuts import get_object_or_404
from django_filters import rest_framework as filters
from dry_rest_permissions.generics import DRYPermissions
from rest_framework import mixins
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from care.facility.api.serializers.consultation_diagnosis import (
ConsultationDiagnosisSerializer,
)
from care.facility.events.handler import create_consultation_events
from care.facility.models import (
ConditionVerificationStatus,
ConsultationDiagnosis,
Expand Down Expand Up @@ -52,4 +56,33 @@ def get_queryset(self):

def perform_create(self, serializer):
consultation = self.get_consultation_obj()
serializer.save(consultation=consultation, created_by=self.request.user)
diagnosis = serializer.save(
consultation=consultation, created_by=self.request.user
)
create_consultation_events(
consultation.id,
diagnosis,
caused_by=self.request.user.id,
created_date=diagnosis.created_date,
)

def perform_update(self, serializer):
return serializer.save()

def update(self, request, *args, **kwargs):
partial = kwargs.pop("partial", False)
instance = self.get_object()
old_instance = copy(instance)
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
instance = self.perform_update(serializer)

create_consultation_events(
instance.consultation_id,
instance,
caused_by=self.request.user.id,
created_date=instance.created_date,
old=old_instance,
)

return Response(serializer.data)
15 changes: 12 additions & 3 deletions care/facility/api/viewsets/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,20 @@ def roots(self, request):


class PatientConsultationEventFilterSet(filters.FilterSet):
ordering = filters.OrderingFilter(
fields=(
"created_date",
"taken_at",
)
)

class Meta:
model = PatientConsultationEvent
fields = {
"event_type": ["exact"],
}
fields = [
"event_type",
"caused_by",
"is_latest",
]


class PatientConsultationEventViewSet(ReadOnlyModelViewSet):
Expand Down
17 changes: 17 additions & 0 deletions care/facility/api/viewsets/prescription.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@
PrescriptionType,
generate_choices,
)
from care.facility.models.notification import Notification
from care.facility.static_data.medibase import MedibaseMedicine
from care.utils.filters.choicefilter import CareChoiceFilter
from care.utils.filters.multiselect import MultiSelectFilter
from care.utils.notification_handler import NotificationGenerator
from care.utils.queryset.consultation import get_consultation_queryset
from care.utils.static_data.helpers import query_builder, token_escaper

Expand Down Expand Up @@ -120,6 +122,13 @@ def get_queryset(self):

def perform_create(self, serializer):
consultation_obj = self.get_consultation_obj()
NotificationGenerator(
event=Notification.Event.PATIENT_PRESCRIPTION_CREATED,
caused_by=self.request.user,
caused_object=consultation_obj,
facility=consultation_obj.facility,
generate_for_facility=True,
).generate()
serializer.save(prescribed_by=self.request.user, consultation=consultation_obj)

@extend_schema(tags=["prescriptions"])
Expand All @@ -133,6 +142,14 @@ def discontinue(self, request, *args, **kwargs):
prescription_obj.discontinued_reason = request.data.get(
"discontinued_reason", None
)
consultation_obj = self.get_consultation_obj()
NotificationGenerator(
event=Notification.Event.PATIENT_PRESCRIPTION_UPDATED,
caused_by=self.request.user,
caused_object=consultation_obj,
facility=consultation_obj.facility,
generate_for_facility=True,
).generate()
prescription_obj.save()
return Response({}, status=status.HTTP_200_OK)

Expand Down
58 changes: 25 additions & 33 deletions care/facility/events/handler.py
Original file line number Diff line number Diff line change
@@ -1,71 +1,56 @@
from contextlib import suppress
from datetime import datetime

from django.core.exceptions import FieldDoesNotExist
from django.db import transaction
from django.db.models import Field, Model
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, serialize_field


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

if fields_to_store:
fields = {field for field in fields if field.name in fields_to_store}

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


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

data = transform(object_instance, old_instance, fields_to_store)
fields_to_store = fields_to_store or set(data.keys())
fields: set[str] = (
get_changed_fields(old_instance, object_instance)
if old_instance
else {field.name for field in object_instance._meta.fields}
)

fields_to_store = fields_to_store & fields if fields_to_store else fields

batch = []
groups = EventType.objects.filter(
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:
if fields_to_store & {field.split("__", 1)[0] for field in group_fields}:
value = {}
for field in group_fields:
try:
value[field] = data[field]
except KeyError:
value[field] = getattr(object_instance, field, None)
# if all values in the group are Falsy, skip creating the event for this group
with suppress(FieldDoesNotExist):
value[field] = serialize_field(object_instance, field)

if all(not v for v in value.values()):
continue

PatientConsultationEvent.objects.select_for_update().filter(
consultation_id=consultation_id,
event_type=group_id,
is_latest=True,
object_model=object_instance.__class__.__name__,
object_id=object_instance.id,
created_date__lt=created_date,
taken_at__lt=taken_at,
).update(is_latest=False)
batch.append(
PatientConsultationEvent(
Expand All @@ -74,6 +59,7 @@ def create_consultation_event_entry(
event_type_id=group_id,
is_latest=True,
created_date=created_date,
taken_at=taken_at,
object_model=object_instance.__class__.__name__,
object_id=object_instance.id,
value=value,
Expand All @@ -93,13 +79,17 @@ def create_consultation_events(
consultation_id: int,
objects: list | QuerySet | Model,
caused_by: int,
created_date: datetime = None,
created_date: datetime | None = None,
taken_at: datetime | None = None,
old: Model | None = None,
fields_to_store: list[str] | set[str] | None = None,
):
if created_date is None:
created_date = now()

if taken_at is None:
taken_at = created_date

with transaction.atomic():
if isinstance(objects, (QuerySet, list, tuple)):
if old is not None:
Expand All @@ -112,6 +102,7 @@ def create_consultation_events(
obj,
caused_by,
created_date,
taken_at,
fields_to_store=set(fields_to_store) if fields_to_store else None,
)
else:
Expand All @@ -120,6 +111,7 @@ def create_consultation_events(
objects,
caused_by,
created_date,
taken_at,
old,
fields_to_store=set(fields_to_store) if fields_to_store else None,
)
Loading

0 comments on commit 9d1c835

Please sign in to comment.