diff --git a/open_prices/api/prices/serializers.py b/open_prices/api/prices/serializers.py index ec5537bc..ba8dea2f 100644 --- a/open_prices/api/prices/serializers.py +++ b/open_prices/api/prices/serializers.py @@ -46,7 +46,11 @@ class PriceCreateSerializer(serializers.ModelSerializer): class Meta: model = Price - fields = Price.CREATE_FIELDS # + ["type"] + fields = Price.CREATE_FIELDS + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["type"].required = False class PriceUpdateSerializer(serializers.ModelSerializer): diff --git a/open_prices/api/prices/tests.py b/open_prices/api/prices/tests.py index fee16e02..af7cd2b5 100644 --- a/open_prices/api/prices/tests.py +++ b/open_prices/api/prices/tests.py @@ -465,6 +465,27 @@ def test_price_create_with_location_id(self): ) self.assertEqual(response.status_code, 201) + def test_price_create_with_type(self): + data = self.data.copy() + # without type? see other tests + # correct type + response = self.client.post( + self.url, + {**data, "type": price_constants.TYPE_PRODUCT}, + headers={"Authorization": f"Bearer {self.user_session.token}"}, + content_type="application/json", + ) + self.assertEqual(response.status_code, 201) + self.assertEqual(response.data["type"], price_constants.TYPE_PRODUCT) + # wrong type + response = self.client.post( + self.url, + {**data, "type": price_constants.TYPE_CATEGORY}, + headers={"Authorization": f"Bearer {self.user_session.token}"}, + content_type="application/json", + ) + self.assertEqual(response.status_code, 400) + def test_price_create_with_app_name(self): for params, result in [ ("?", "API"), diff --git a/open_prices/api/prices/views.py b/open_prices/api/prices/views.py index e3483373..0bebf2de 100644 --- a/open_prices/api/prices/views.py +++ b/open_prices/api/prices/views.py @@ -58,7 +58,7 @@ def create(self, request: Request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) # get type - type = ( + type = serializer.validated_data.get("type") or ( price_constants.TYPE_PRODUCT if serializer.validated_data.get("product_code") else price_constants.TYPE_CATEGORY diff --git a/open_prices/prices/models.py b/open_prices/prices/models.py index c7937f6f..da152611 100644 --- a/open_prices/prices/models.py +++ b/open_prices/prices/models.py @@ -68,6 +68,7 @@ class Price(models.Model): "receipt_quantity", ] CREATE_FIELDS = UPDATE_FIELDS + [ + "type", # optional in the serializer "product_code", "product_name", "category_tag",