diff --git a/src/documents/serialisers.py b/src/documents/serialisers.py index 887cdaf23..42fc1049d 100644 --- a/src/documents/serialisers.py +++ b/src/documents/serialisers.py @@ -533,7 +533,7 @@ class CustomFieldSerializer(serializers.ModelSerializer): if ( "data_type" in attrs and attrs["data_type"] == CustomField.FieldDataType.SELECT - ): + ) or self.instance.data_type == CustomField.FieldDataType.SELECT: if ( "extra_data" not in attrs or "select_options" not in attrs["extra_data"] diff --git a/src/documents/tests/test_api_custom_fields.py b/src/documents/tests/test_api_custom_fields.py index 29f136c86..db9b87306 100644 --- a/src/documents/tests/test_api_custom_fields.py +++ b/src/documents/tests/test_api_custom_fields.py @@ -1,5 +1,6 @@ import json from datetime import date +from unittest.mock import ANY from django.contrib.auth.models import Permission from django.contrib.auth.models import User @@ -144,6 +145,70 @@ class TestCustomFieldsAPI(DirectoriesMixin, APITestCase): ) self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST) + def test_custom_field_select_unique_ids(self): + """ + GIVEN: + - Nothing + - Existing custom field + WHEN: + - API request to create custom field with select options without id + THEN: + - Unique ids are generated for each option + """ + resp = self.client.post( + self.ENDPOINT, + json.dumps( + { + "data_type": "select", + "name": "Select Field", + "extra_data": { + "select_options": [ + {"label": "Option 1"}, + {"label": "Option 2"}, + ], + }, + }, + ), + content_type="application/json", + ) + self.assertEqual(resp.status_code, status.HTTP_201_CREATED) + + data = resp.json() + + self.assertCountEqual( + data["extra_data"]["select_options"], + [ + {"label": "Option 1", "id": ANY}, + {"label": "Option 2", "id": ANY}, + ], + ) + + # Add a new option + resp = self.client.patch( + f"{self.ENDPOINT}{data['id']}/", + json.dumps( + { + "extra_data": { + "select_options": data["extra_data"]["select_options"] + + [{"label": "Option 3"}], + }, + }, + ), + content_type="application/json", + ) + self.assertEqual(resp.status_code, status.HTTP_200_OK) + + data = resp.json() + + self.assertCountEqual( + data["extra_data"]["select_options"], + [ + {"label": "Option 1", "id": ANY}, + {"label": "Option 2", "id": ANY}, + {"label": "Option 3", "id": ANY}, + ], + ) + def test_create_custom_field_monetary_validation(self): """ GIVEN: