diff --git a/care/facility/api/serializers/patient_consultation.py b/care/facility/api/serializers/patient_consultation.py index f3df403581..6b992b414c 100644 --- a/care/facility/api/serializers/patient_consultation.py +++ b/care/facility/api/serializers/patient_consultation.py @@ -519,16 +519,19 @@ def validate(self, attrs): # TODO Add Bed Authorisation Validation if ( - not self.instance - and "suggestion" in validated - and validated["suggestion"] == SuggestionChoices.A - ): + not self.instance or validated.get("patient_no") != self.instance.patient_no + ) and "suggestion" in validated: + suggestion = validated["suggestion"] patient_no = validated.get("patient_no") - if not patient_no: + + if suggestion == SuggestionChoices.A and not patient_no: raise ValidationError( - {"ip_no": ["This field is required for admission."]} + {"patient_no": "This field is required for admission."} ) - if PatientConsultation.objects.filter( + + if ( + suggestion == SuggestionChoices.A or patient_no + ) and PatientConsultation.objects.filter( patient_no=patient_no, facility=( self.instance.facility @@ -537,7 +540,9 @@ def validate(self, attrs): ), ).exists(): raise ValidationError( - "Patient number must be unique within the facility." + { + "patient_no": "Consultation with this IP/OP number already exists within the facility." + } ) if ( diff --git a/care/facility/tests/test_patient_consultation_api.py b/care/facility/tests/test_patient_consultation_api.py index 1fa6f056af..758163f404 100644 --- a/care/facility/tests/test_patient_consultation_api.py +++ b/care/facility/tests/test_patient_consultation_api.py @@ -546,6 +546,7 @@ def test_create_consultations_with_duplicate_patient_no_within_facility(self): ) res = self.client.post(self.get_url(), data, format="json") self.assertEqual(res.status_code, status.HTTP_201_CREATED) + data.update( { "patient_no": "IP1234", @@ -557,6 +558,10 @@ def test_create_consultations_with_duplicate_patient_no_within_facility(self): res = self.client.post(self.get_url(), data, format="json") self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) + data.update({"suggestion": SuggestionChoices.A}) + res = self.client.post(self.get_url(), data, format="json") + self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) + def test_create_consultations_with_same_patient_no_in_different_facilities(self): facility2 = self.create_facility( self.super_user, self.district, self.local_body, name="bar"