diff --git a/care/facility/api/serializers/patient.py b/care/facility/api/serializers/patient.py index 048b3ba715..d46316ae29 100644 --- a/care/facility/api/serializers/patient.py +++ b/care/facility/api/serializers/patient.py @@ -442,6 +442,7 @@ class Meta: "facility", "allow_transfer", "is_active", + "is_expired", ) diff --git a/care/facility/api/viewsets/patient.py b/care/facility/api/viewsets/patient.py index 9e8f6d3cf3..987b64c4c8 100644 --- a/care/facility/api/viewsets/patient.py +++ b/care/facility/api/viewsets/patient.py @@ -565,6 +565,14 @@ def transfer(self, request, *args, **kwargs): patient = PatientRegistration.objects.get(external_id=kwargs["external_id"]) facility = Facility.objects.get(external_id=request.data["facility"]) + if patient.is_expired: + return Response( + { + "Patient": "Patient transfer cannot be completed because the patient is expired" + }, + status=status.HTTP_406_NOT_ACCEPTABLE, + ) + if patient.is_active and facility == patient.facility: return Response( { diff --git a/care/facility/models/patient.py b/care/facility/models/patient.py index 6e8d020f95..b3d42bef01 100644 --- a/care/facility/models/patient.py +++ b/care/facility/models/patient.py @@ -436,6 +436,10 @@ class TestTypeEnum(enum.Enum): objects = BaseManager() + @property + def is_expired(self) -> bool: + return self.death_datetime is not None + def __str__(self): return f"{self.name} - {self.year_of_birth} - {self.get_gender_display()}" diff --git a/care/facility/tests/test_patient_api.py b/care/facility/tests/test_patient_api.py index f52f7deb19..88dba9fb75 100644 --- a/care/facility/tests/test_patient_api.py +++ b/care/facility/tests/test_patient_api.py @@ -509,6 +509,31 @@ def test_transfer_with_active_consultation_same_facility(self): "Patient transfer cannot be completed because the patient has an active consultation in the same facility", ) + def test_transfer_with_expired_patient(self): + # Mocking discharged as expired + self.consultation.new_discharge_reason = NewDischargeReasonEnum.EXPIRED + self.consultation.death_datetime = now() + self.consultation.save() + + # Set the patient's facility to allow transfers + self.patient.allow_transfer = True + self.patient.save() + + # Ensure transfer fails if the patient has an active consultation + self.client.force_authenticate(user=self.super_user) + response = self.client.post( + f"/api/v1/patient/{self.patient.external_id}/transfer/", + { + "year_of_birth": 1992, + "facility": self.facility.external_id, + }, + ) + self.assertEqual(response.status_code, status.HTTP_406_NOT_ACCEPTABLE) + self.assertEqual( + response.data["Patient"], + "Patient transfer cannot be completed because the patient is expired", + ) + def test_transfer_disallowed_by_facility(self): # Set the patient's facility to disallow transfers self.patient.allow_transfer = False