Skip to content

Commit

Permalink
Updated the logic of Health Details API
Browse files Browse the repository at this point in the history
* Switched to serializer to create/update health details record
* Added create/update method in health details serializer
* Added auth while creating health details record
* Switched to validated_data for health details data
* Reformatted the code
  • Loading branch information
aeswibon committed Oct 3, 2022
1 parent ba0c283 commit f018999
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 111 deletions.
188 changes: 79 additions & 109 deletions care/facility/api/serializers/patient_consultation.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,12 @@
from care.facility.api.serializers.bed import ConsultationBedSerializer
from care.facility.api.serializers.daily_round import DailyRoundSerializer
from care.facility.api.serializers.facility import FacilityBasicInfoSerializer
from care.facility.models import (
CATEGORY_CHOICES,
COVID_CATEGORY_CHOICES,
Facility,
PatientRegistration,
)
from care.facility.api.serializers.patient_health_details import (
PatientHealthDetailsSerializer,
)
from care.facility.models import (
CATEGORY_CHOICES,
COVID_CATEGORY_CHOICES,
Facility,
PatientRegistration,
)
Expand All @@ -44,9 +39,7 @@

class PatientConsultationSerializer(serializers.ModelSerializer):
id = serializers.CharField(source="external_id", read_only=True)
facility_name = serializers.CharField(
source="facility.name", read_only=True
)
facility_name = serializers.CharField(source="facility.name", read_only=True)
suggestion_text = ChoiceField(
choices=PatientConsultation.SUGGESTION_CHOICES,
read_only=True,
Expand All @@ -65,14 +58,10 @@ class PatientConsultationSerializer(serializers.ModelSerializer):
referred_to = ExternalIdSerializerField(
queryset=Facility.objects.all(), required=False
)
patient = ExternalIdSerializerField(
queryset=PatientRegistration.objects.all()
)
patient = ExternalIdSerializerField(queryset=PatientRegistration.objects.all())
facility = ExternalIdSerializerField(read_only=True)

assigned_to_object = UserAssignedSerializer(
source="assigned_to", read_only=True
)
assigned_to_object = UserAssignedSerializer(source="assigned_to", read_only=True)

assigned_to = serializers.PrimaryKeyRelatedField(
queryset=User.objects.all(), required=False, allow_null=True
Expand All @@ -89,14 +78,21 @@ class PatientConsultationSerializer(serializers.ModelSerializer):
required=False,
)

review_time = serializers.IntegerField(
default=-1, write_only=True, required=False
)
review_time = serializers.IntegerField(default=-1, write_only=True, required=False)

last_edited_by = UserBaseMinimumSerializer(read_only=True)
created_by = UserBaseMinimumSerializer(read_only=True)
last_daily_round = DailyRoundSerializer(read_only=True)
last_health_details = PatientHealthDetailsSerializer(read_only=True)
health_details = ExternalIdSerializerField(
queryset=PatientHealthDetails.objects.all(), required=False
)

health_details_object = PatientHealthDetailsSerializer(
source="last_health_details",
read_only=True,
)

new_health_details = PatientHealthDetailsSerializer(required=False)

current_bed = ConsultationBedSerializer(read_only=True)

Expand All @@ -121,9 +117,7 @@ def get_icd11_diagnoses_objects_by_ids(self, diagnoses_ids):
return diagnosis_objects

def get_icd11_diagnoses_object(self, consultation):
return self.get_icd11_diagnoses_objects_by_ids(
consultation.icd11_diagnoses
)
return self.get_icd11_diagnoses_objects_by_ids(consultation.icd11_diagnoses)

def get_icd11_provisional_diagnoses_object(self, consultation):
return self.get_icd11_diagnoses_objects_by_ids(
Expand All @@ -139,7 +133,7 @@ class Meta:
"created_by",
"kasp_enabled_date",
)
exclude = ("deleted", "external_id")
exclude = ("deleted", "external_id", "last_health_details")

def validate_bed_number(self, bed_number):
try:
Expand All @@ -155,11 +149,7 @@ def update(self, instance, validated_data):

if instance.discharge_date:
raise ValidationError(
{
"consultation": [
"Discharged Consultation data cannot be updated"
]
}
{"consultation": ["Discharged Consultation data cannot be updated"]}
)

if instance.suggestion == SuggestionChoices.OP:
Expand Down Expand Up @@ -190,52 +180,44 @@ def update(self, instance, validated_data):
validated_data["kasp_enabled_date"] = localtime(now())

_temp = instance.assigned_to
health_details_data = validated_data.pop("new_health_details", None)

consultation = super().update(instance, validated_data)

try:
health_details_data = self.context["request"].data[
"new_health_details"
]
vaccination_history = health_details_data.pop(
"vaccination_history", []
vaccination_history = health_details_data.pop("vaccination_history", [])

serializer = PatientHealthDetailsSerializer(
data={
"patient": consultation.patient.external_id.hex,
"facility": consultation.facility.external_id.hex,
"consultation": consultation.external_id.hex,
**health_details_data,
},
context={
"request": self.context["request"],
},
)
PatientHealthDetails.objects.filter(
id=consultation.last_health_details.id
).update(**self.context["request"].data["new_health_details"])
serializer.is_valid(raise_exception=True)
serializer.save()

consultation.last_health_details = (
PatientHealthDetails.objects.get(
id=consultation.last_health_details.id
)
)
health_details = PatientHealthDetails.objects.filter(
consultation=consultation
).latest("external_id")

consultation.health_details = health_details

vaccines = []
for vaccine in vaccination_history:
vaccines.append(
Vaccine(
health_details=consultation.last_health_details,
**vaccine,
)
)
vaccines.append(Vaccine(health_details=health_details, **vaccine))
if vaccines:
Vaccine.objects.bulk_create(vaccines, ignore_conflicts=True)
consultation.save(update_fields=["last_health_details"])

NotificationGenerator(
event=Notification.Event.PATIENT_HEALTH_DETAILS_UPDATED,
caused_by=self.context["request"].user,
caused_object=consultation.last_health_details,
facility=consultation.facility,
).generate()
except KeyError:
pass

if "assigned_to" in validated_data:
if (
validated_data["assigned_to"] != _temp
and validated_data["assigned_to"]
):
if validated_data["assigned_to"] != _temp and validated_data["assigned_to"]:
NotificationGenerator(
event=Notification.Event.PATIENT_CONSULTATION_ASSIGNMENT,
caused_by=self.context["request"].user,
Expand Down Expand Up @@ -267,16 +249,12 @@ def create(self, validated_data):

# Authorisation Check

allowed_facilities = get_home_facility_queryset(
self.context["request"].user
)
allowed_facilities = get_home_facility_queryset(self.context["request"].user)
if not allowed_facilities.filter(
id=self.validated_data["patient"].facility.id
).exists():
raise ValidationError(
{
"facility": "Consultation creates are only allowed in home facility"
}
{"facility": "Consultation creates are only allowed in home facility"}
)

# End Authorisation Checks
Expand All @@ -295,16 +273,15 @@ def create(self, validated_data):
if validated_data["patient"].last_consultation:
if not validated_data["patient"].last_consultation.discharge_date:
raise ValidationError(
{
"consultation": "Exists please Edit Existing Consultation"
}
{"consultation": "Exists please Edit Existing Consultation"}
)

if "is_kasp" in validated_data:
if validated_data["is_kasp"]:
validated_data["kasp_enabled_date"] = localtime(now())

bed = validated_data.pop("bed", None)
health_details_data = validated_data.pop("new_health_details", None)

validated_data["facility_id"] = validated_data[
"patient"
Expand All @@ -315,47 +292,50 @@ def create(self, validated_data):
consultation.save()

try:
health_details_data = self.context["request"].data[
"new_health_details"
]
vaccination_history = health_details_data.pop(
"vaccination_history", []
vaccination_history = health_details_data.pop("vaccination_history", [])

serializer = PatientHealthDetailsSerializer(
data={
"patient": consultation.patient.external_id.hex,
"facility": consultation.facility.external_id.hex,
"consultation": consultation.external_id.hex,
**health_details_data,
},
context={
"request": self.context["request"],
},
)
serializer.is_valid(raise_exception=True)
serializer.save()

health_details = PatientHealthDetails(
patient=consultation.patient,
facility=consultation.facility,
consultation=consultation,
**health_details_data,
)
health_details.save()
health_details = PatientHealthDetails.objects.filter(
consultation=consultation
).latest("external_id")

consultation.health_details = health_details

vaccines = []
for vaccine in vaccination_history:
vaccines.append(
Vaccine(health_details=health_details, **vaccine)
)
vaccines.append(Vaccine(health_details=health_details, **vaccine))
if vaccines:
Vaccine.objects.bulk_create(vaccines, ignore_conflicts=True)

consultation.last_health_details = health_details
consultation.save(update_fields=["last_health_details"])

NotificationGenerator(
event=Notification.Event.PATIENT_HEALTH_DETAILS_CREATED,
caused_by=self.context["request"].user,
caused_object=health_details,
facility=consultation.facility,
).generate()
except KeyError as error:
if consultation.patient.last_consultation is None:
raise ValidationError(
{
"last_health_details": [
"health_details": [
"Please provide the health details of the patient"
]
}
) from error

else:
consultation.last_health_details = (
consultation.patient.last_consultation.last_health_details
)
consultation.save(update_fields=["last_health_details"])

if bed:
consultation_bed = ConsultationBed(
bed=bed,
Expand All @@ -379,9 +359,7 @@ def create(self, validated_data):
if action != -1:
patient.action = action
if review_time > 0:
patient.review_time = localtime(now()) + timedelta(
minutes=review_time
)
patient.review_time = localtime(now()) + timedelta(minutes=review_time)

patient.save()
NotificationGenerator(
Expand Down Expand Up @@ -410,9 +388,9 @@ def validate(self, attrs):
# TODO Add Bed Authorisation Validation

if "suggestion" in validated:
if validated[
"suggestion"
] is SuggestionChoices.R and not validated.get("referred_to"):
if validated["suggestion"] is SuggestionChoices.R and not validated.get(
"referred_to"
):
raise ValidationError(
{
"referred_to": [
Expand Down Expand Up @@ -445,11 +423,7 @@ def validate(self, attrs):
)
if validated["review_time"] <= 0:
raise ValidationError(
{
"review_time": [
"This field value is must be greater than 0."
]
}
{"review_time": ["This field value is must be greater than 0."]}
)
from care.facility.static_data.icd11 import ICDDiseases

Expand Down Expand Up @@ -483,12 +457,8 @@ def validate(self, attrs):


class PatientConsultationIDSerializer(serializers.ModelSerializer):
consultation_id = serializers.UUIDField(
source="external_id", read_only=True
)
patient_id = serializers.UUIDField(
source="patient.external_id", read_only=True
)
consultation_id = serializers.UUIDField(source="external_id", read_only=True)
patient_id = serializers.UUIDField(source="patient.external_id", read_only=True)

class Meta:
model = PatientConsultation
Expand Down
33 changes: 31 additions & 2 deletions care/facility/api/serializers/patient_health_details.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from care.facility.models.facility import Facility
from care.facility.models.patient import Vaccine
from care.facility.models.patient_base import BLOOD_GROUP_CHOICES, VACCINE_CHOICES
from care.utils.queryset.facility import get_home_facility_queryset
from care.utils.serializer.external_id_field import ExternalIdSerializerField


Expand All @@ -30,8 +31,12 @@ class PatientHealthDetailsSerializer(serializers.ModelSerializer):

id = serializers.CharField(source="external_id", read_only=True)

patient = ExternalIdSerializerField(queryset=PatientRegistration.objects.all())
facility = ExternalIdSerializerField(queryset=Facility.objects.all())
patient = ExternalIdSerializerField(
queryset=PatientRegistration.objects.all(), required=False
)
facility = ExternalIdSerializerField(
queryset=Facility.objects.all(), required=False
)
consultation = ExternalIdSerializerField(
queryset=PatientConsultation.objects.all(), required=False
)
Expand All @@ -44,3 +49,27 @@ class PatientHealthDetailsSerializer(serializers.ModelSerializer):
class Meta:
model = PatientHealthDetails
exclude = ("deleted", "external_id")

def create(self, validated_data):
consultation = validated_data["consultation"]
allowed_facilities = get_home_facility_queryset(self.context["request"].user)
if not allowed_facilities.filter(
id=self.validated_data["patient"].facility.id
).exists():
raise serializers.ValidationError(
{
"patient": "Patient Health Details creates are only allowed in home facility"
}
)

health_details = super().create(validated_data)
consultation.last_health_details = health_details
consultation.save(update_fields=["last_health_details"])
return health_details

def update(self, instance, validated_data):
consultation = validated_data["consultation"]
health_details = super().update(instance, validated_data)
consultation.last_health_details = health_details
consultation.save(update_fields=["last_health_details"])
return health_details

0 comments on commit f018999

Please sign in to comment.