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

Rename admission_date to encounter_date and clean column #1728

Merged
merged 22 commits into from
Dec 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
6 changes: 3 additions & 3 deletions care/abdm/utils/fhir.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@
title="Care Plan",
description="This includes Treatment Summary, Prescribed Medication, General Notes and Special Instructions",
period=Period(
start=self.consultation.admission_date.isoformat(),
start=self.consultation.encounter_date.isoformat(),
end=self.consultation.discharge_date.isoformat()
if self.consultation.discharge_date
else None,
Expand Down Expand Up @@ -355,7 +355,7 @@

id = str(self.consultation.external_id)
status = "finished" if self.consultation.discharge_date else "in-progress"
period_start = self.consultation.admission_date.isoformat()
period_start = self.consultation.encounter_date.isoformat()

Check warning on line 358 in care/abdm/utils/fhir.py

View check run for this annotation

Codecov / codecov/patch

care/abdm/utils/fhir.py#L358

Added line #L358 was not covered by tests
period_end = (
self.consultation.discharge_date.isoformat()
if self.consultation.discharge_date
Expand Down Expand Up @@ -463,7 +463,7 @@
def _medication_request(self, medicine):
id = str(uuid())
prescription_date = (
self.consultation.admission_date.isoformat()
self.consultation.encounter_date.isoformat()
) # TODO: change to the time of prescription
status = "unknown" # TODO: get correct status active | on-hold | cancelled | completed | entered-in-error | stopped | draft | unknown
dosage_text = f"{medicine['dosage_new']} / {medicine['dosage']} for {medicine['days']} days"
Expand Down
5 changes: 1 addition & 4 deletions care/facility/api/serializers/bed.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,10 +235,7 @@ def validate(self, attrs):
raise ValidationError(
{"end_date": "End date cannot be before the start date"}
)
if (
consultation.admission_date
and consultation.admission_date > current_start_date
):
if consultation.encounter_date > current_start_date:
raise ValidationError(
{"start_date": "Start date cannot be before the admission date"}
)
Expand Down
34 changes: 12 additions & 22 deletions care/facility/api/serializers/patient_consultation.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@
and last_consultation.suggestion == SuggestionChoices.A
and last_consultation.discharge_date
and last_consultation.discharge_date + timedelta(days=30)
> consultation.admission_date
> consultation.encounter_date
):
consultation.is_readmission = True
consultation.save()
Expand Down Expand Up @@ -473,6 +473,13 @@

return value

def validate_encounter_date(self, value):
if value > now():
raise ValidationError(

Check warning on line 478 in care/facility/api/serializers/patient_consultation.py

View check run for this annotation

Codecov / codecov/patch

care/facility/api/serializers/patient_consultation.py#L478

Added line #L478 was not covered by tests
{"encounter_date": "This field value cannot be in the future."}
)
return value

def validate(self, attrs):
validated = super().validate(attrs)
# TODO Add Bed Authorisation Validation
Expand Down Expand Up @@ -524,17 +531,6 @@
validated["referred_to"] = None
elif validated.get("referred_to"):
validated["referred_to_external"] = None
if validated["suggestion"] is SuggestionChoices.A:
if not validated.get("admission_date"):
raise ValidationError(
{
"admission_date": "This field is required as the patient has been admitted."
}
)
if validated["admission_date"] > now():
raise ValidationError(
{"admission_date": "This field value cannot be in the future."}
)

if "action" in validated:
if validated["action"] == PatientRegistration.ActionEnum.REVIEW:
Expand Down Expand Up @@ -634,13 +630,10 @@
raise ValidationError(
{"death_datetime": "This field value cannot be in the future."}
)
if (
self.instance.admission_date
and attrs.get("death_datetime") < self.instance.admission_date
):
if attrs.get("death_datetime") < self.instance.encounter_date:
raise ValidationError(
{
"death_datetime": "This field value cannot be before the admission date."
"death_datetime": "This field value cannot be before the encounter date."
}
)
if not attrs.get("death_confirmed_doctor"):
Expand All @@ -654,13 +647,10 @@
raise ValidationError(
{"discharge_date": "This field value cannot be in the future."}
)
elif (
self.instance.admission_date
and attrs.get("discharge_date") < self.instance.admission_date
):
elif attrs.get("discharge_date") < self.instance.encounter_date:
raise ValidationError(
{
"discharge_date": "This field value cannot be before the admission date."
"discharge_date": "This field value cannot be before the encounter date."
}
)
return attrs
Expand Down
6 changes: 3 additions & 3 deletions care/facility/api/viewsets/patient.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,8 @@ def filter_by_category(self, queryset, name, value):
last_consultation_kasp_enabled_date = filters.DateFromToRangeFilter(
field_name="last_consultation__kasp_enabled_date"
)
last_consultation_admission_date = filters.DateFromToRangeFilter(
field_name="last_consultation__admission_date"
last_consultation_encounter_date = filters.DateFromToRangeFilter(
field_name="last_consultation__encounter_date"
)
last_consultation_discharge_date = filters.DateFromToRangeFilter(
field_name="last_consultation__discharge_date"
Expand Down Expand Up @@ -332,7 +332,7 @@ class PatientViewSet(
"date_declared_positive",
"date_of_result",
"last_vaccinated_date",
"last_consultation_admission_date",
"last_consultation_encounter_date",
"last_consultation_discharge_date",
"last_consultation_symptoms_onset_date",
]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Generated by Django 4.2.5 on 2023-11-27 07:00

import django.utils.timezone
from django.db import migrations, models
from django.db.models import F


class Migration(migrations.Migration):
dependencies = [
("facility", "0402_patientconsultation_new_discharge_reason"),
]

def clean_encounter_date(apps, schema_editor):
PatientConsultation = apps.get_model("facility", "PatientConsultation")

# Set `encounter_date` to `created_date` for all consultations with
# suggestions that are not Admission, Domiciliary Care.
#
# Reason:
# We were not capturing `admission_date` (now `encounter_date`) for
# these consultations earlier, but could still be set by mistake.
#
# Example:
# Edit Consultation allowed changing suggestion to non Admission/Domiciliary Care
# without clearing `admission_date` (now `encounter_date`).
PatientConsultation.objects.exclude(suggestion__in=["A", "DC"]).update(
encounter_date=F("created_date")
)

# Set `encounter_date` to `created_date` for all consultations with
# `encounter_date` as `null`.
#
# Reason:
# We were not capturing `encounter_date` for these consultations as
# it was not set for these.
PatientConsultation.objects.filter(encounter_date=None).update(
encounter_date=F("created_date")
)

def reverse_clean_encounter_date(apps, schema_editor):
PatientConsultation = apps.get_model("facility", "PatientConsultation")

# Set `encounter_date` to `null` for all consultations with suggestions
# that are not Admission/Domiciliary Care.
PatientConsultation.objects.exclude(suggestion__in=["A", "DC"]).update(
encounter_date=None
)

operations = [
migrations.RemoveConstraint(
model_name="patientconsultation",
name="if_admitted",
),
migrations.RenameField(
model_name="patientconsultation",
old_name="admission_date",
new_name="encounter_date",
),
migrations.RunPython(
clean_encounter_date,
reverse_code=reverse_clean_encounter_date,
),
migrations.AlterField(
model_name="patientconsultation",
name="encounter_date",
field=models.DateTimeField(
db_index=True, default=django.utils.timezone.now
),
),
]
11 changes: 4 additions & 7 deletions care/facility/models/patient_consultation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from django.core.validators import MinValueValidator
from django.db import models
from django.db.models import JSONField
from django.utils import timezone
from multiselectfield import MultiSelectField
from multiselectfield.utils import get_max_length

Expand Down Expand Up @@ -127,7 +128,7 @@ class PatientConsultation(PatientBaseModel, ConsultationRelatedPermissionMixin):
referred_by_external = models.TextField(default="", null=True, blank=True)
is_readmission = models.BooleanField(default=False)
admitted = models.BooleanField(default=False) # Deprecated
admission_date = models.DateTimeField(null=True, blank=True) # Deprecated
encounter_date = models.DateTimeField(default=timezone.now, db_index=True)
icu_admission_date = models.DateTimeField(null=True, blank=True)
discharge_date = models.DateTimeField(null=True, blank=True)
discharge_reason = models.CharField(
Expand Down Expand Up @@ -236,7 +237,7 @@ def get_related_consultation(self):

CSV_MAPPING = {
"consultation_created_date": "Date of Consultation",
"admission_date": "Date of Admission",
"encounter_date": "Date of Admission",
"symptoms_onset_date": "Date of Onset of Symptoms",
"symptoms": "Symptoms at time of consultation",
"deprecated_covid_category": "Covid Category",
Expand All @@ -256,7 +257,7 @@ def get_related_consultation(self):
}

# CSV_DATATYPE_DEFAULT_MAPPING = {
# "admission_date": (None, models.DateTimeField(),),
# "encounter_date": (None, models.DateTimeField(),),
# "symptoms_onset_date": (None, models.DateTimeField(),),
# "symptoms": ("-", models.CharField(),),
# "category": ("-", models.CharField(),),
Expand Down Expand Up @@ -286,10 +287,6 @@ class Meta:
| models.Q(referred_to__isnull=False)
| models.Q(referred_to_external__isnull=False),
),
models.CheckConstraint(
name="if_admitted",
check=models.Q(admitted=False) | models.Q(admission_date__isnull=False),
),
]

@staticmethod
Expand Down
4 changes: 2 additions & 2 deletions care/facility/models/patient_icmr.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,8 @@ def lab_pincode(self):
@property
def hospitalization_date(self):
return (
self.consultation.admission_date.date()
if self.consultation and self.consultation.admission_date
self.consultation.encounter_date.date()
if self.consultation and self.consultation.encounter_date
else None
)

Expand Down
4 changes: 2 additions & 2 deletions care/facility/tests/test_consultation_bed_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,8 +242,8 @@ def test_start_date_before_end_date(self):
{"end_date": ["End date cannot be before the start date"]},
)

def test_start_date_before_consultation_admission_date(self):
self.consultation.admission_date = timezone.now()
def test_start_date_before_consultation_encounter_date(self):
self.consultation.encounter_date = timezone.now()
self.consultation.save()
response = self.client.post(
"/api/v1/consultationbed/",
Expand Down
6 changes: 3 additions & 3 deletions care/facility/tests/test_patient_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def setUpTestData(cls) -> None:
facility=cls.facility,
created_by=cls.user,
suggestion="A",
admission_date=now(),
encounter_date=now(),
)

def setUp(self):
Expand Down Expand Up @@ -235,7 +235,7 @@ def setUpTestData(cls):
facility=cls.facility,
created_by=cls.user,
suggestion="A",
admission_date=now(),
encounter_date=now(),
)
cls.bed = cls.create_bed(cls.facility, cls.location)
cls.consultation_bed = cls.create_consultation_bed(cls.consultation, cls.bed)
Expand Down Expand Up @@ -287,7 +287,7 @@ def setUpTestData(cls):
facility=cls.facility,
created_by=cls.user,
suggestion="A",
admission_date=now(),
encounter_date=now(),
discharge_date=None, # Patient is currently admitted
discharge_reason=None,
)
Expand Down
Loading
Loading