Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refactor attributes validation
Marcin Gębala98b48ba84c53
diff --git a/saleor/graphql/product/descriptions.py b/saleor/graphql/product/descriptions.pynew file mode 100644index 0000000000..c1ad39a6b5--- /dev/null+++ b/saleor/graphql/product/descriptions.py@@ -0,0 +1,13 @@+class AttributeDescriptions:+ NAME = 'Name of an attribute displayed in the interface.'+ SLUG = 'Internal representation of an attribute name.'+ VALUES = 'List of attribute\'s values.'+++class AttributeValueDescriptions:+ NAME = 'Name of a value displayed in the interface.'+ SLUG = 'Internal representation of a value (unique per attribute).'+ TYPE = '''Type of value (used only when `value` field is set).'''+ VALUE = '''Special value other than a textual name. Possible types are:+ string (default), CSS color property, CSS gradient property, URL+ (e.g. link to an image).'''diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.pyindex dedfcc37ca..1775f67de4 100644--- a/saleor/graphql/product/mutations/attributes.py+++ b/saleor/graphql/product/mutations/attributes.py@@ -5,36 +5,66 @@ from django.template.defaultfilters import slugifyfrom graphql_jwt.decorators import permission_requiredfrom ....product import models-from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation+from ...core.mutations import ModelDeleteMutation, ModelMutationfrom ...product.types import ProductType-from ..types import Attribute, AttributeTypeEnum, AttributeValue+from ..types import Attribute, AttributeTypeEnum+from ..descriptions import AttributeDescriptions, AttributeValueDescriptions-class AttributeCreateValueInput(graphene.InputObjectType):+class AttributeValueCreateInput(graphene.InputObjectType):name = graphene.String(- required=True, description='Name displayed in the interface.')- value = graphene.String(- description='''Value different than a textual name e.g. color- in a hexadecimal format.''')+ required=True, description=AttributeValueDescriptions.NAME)+ value = graphene.String(description=AttributeValueDescriptions.VALUE)class AttributeCreateInput(graphene.InputObjectType):name = graphene.String(- required=True, description='Name displayed in the interface.')+ required=True, description=AttributeDescriptions.NAME)values = graphene.List(- AttributeCreateValueInput,- description='Attribute values to be created for this attribute.')+ AttributeValueCreateInput, description=AttributeDescriptions.VALUES)+++class AttributeUpdateInput(graphene.InputObjectType):+ name = graphene.String(description=AttributeDescriptions.NAME)+ remove_values = graphene.List(+ graphene.ID, name='removeValues',+ description='IDs of values to be removed from this attribute.')+ add_values = graphene.List(+ AttributeValueCreateInput, name='addValues',+ description='New values to be created for this attribute.')class AttributeMixin:@classmethod- def clean_attribute_values(cls, values, errors):- """Validates if a valid AttributeValue instance can be created using- the data provided.+ def check_unique_values(cls, values_input, attribute, errors):+ # Check values uniqueness in case of creating new attribute.+ existing_values = attribute.values.values_list('slug', flat=True)+ for value_data in values_input:+ slug = slugify(value_data['name'])+ if slug in existing_values:+ msg = 'Value %s already exists within this attribute.' % value_data['name']+ cls.add_error(errors, cls.ATTRIBUTE_VALUES_FIELD, msg)++ new_slugs = [+ slugify(value_data['name']) for value_data in values_input]+ if len(set(new_slugs)) != len(new_slugs):+ cls.add_error(+ errors, cls.ATTRIBUTE_VALUES_FIELD,+ 'Provided values are not unique.')++ @classmethod+ def clean_values(cls, cleaned_input, attribute, errors):+ """Clean attribute values.++ Transforms AttributeValueCreateInput into AttributeValue instances.+ Slugs are created from given names and checked for uniqueness within+ an attribute."""- for value_data in values:+ values_input = cleaned_input[cls.ATTRIBUTE_VALUES_FIELD]+ for value_data in values_input:value_data['slug'] = slugify(value_data['name'])- attribute_value = models.AttributeValue(**value_data)+ attribute_value = models.AttributeValue(+ **value_data, attribute=attribute)try:attribute_value.full_clean()except ValidationError as validation_errors:@@ -42,33 +72,13 @@ class AttributeMixin:if field == 'attribute':continuefor message in validation_errors.message_dict[field]:- error_field = '%(values_field)s:%(field)s' % {- 'values_field': cls.ATTRIBUTE_VALUES_FIELD,- 'field': field}- cls.add_error(errors, error_field, message)+ cls.add_error(+ errors, cls.ATTRIBUTE_VALUES_FIELD, message)+ cls.check_unique_values(values_input, attribute, errors)return errors@classmethod- def clean_attribute_uniqueness(- cls, instance, input, errors, product_type=None):- # Slugs are created automatically from the names, but should be unique- # within a product type.- slug = input.get('slug')- if not product_type:- product_type = instance.product_type- query = models.Attribute.objects.filter(slug=slug).filter(- Q(product_type=product_type)- | Q(product_variant_type=product_type))- query = query.exclude(pk=getattr(instance, 'pk', None))- if query.exists():- msg = (- 'Attribute already exists within product type %s.' %- product_type)- cls.add_error(errors, 'name', msg)-- @classmethod- def clean_input(cls, info, instance, input, errors):- cleaned_input = super().clean_input(info, instance, input, errors)+ def clean_attribute(cls, instance, cleaned_input, errors, product_type=None):if 'name' in cleaned_input:slug = slugify(cleaned_input['name'])elif instance.pk:@@ -78,30 +88,30 @@ class AttributeMixin:return cleaned_inputcleaned_input['slug'] = slug- values = cleaned_input.get(cls.ATTRIBUTE_VALUES_FIELD)- if not values:- return cleaned_input+ if not product_type:+ product_type = instance.product_type- slugs = []- for value in values:- value['slug'] = slugify(value['name'])- slugs.append(value['slug'])- cls.clean_attribute_values(values, errors)- return cleaned_input+ query = models.Attribute.objects.filter(slug=slug).filter(+ Q(product_type=product_type)+ | Q(product_variant_type=product_type))+ query = query.exclude(pk=getattr(instance, 'pk', None))+ if query.exists():+ cls.add_error(+ errors, 'name',+ 'Attribute already exists within this product type.')@classmethod- def _save_m2m(cls, info, instance, cleaned_data):- super()._save_m2m(info, instance, cleaned_data)+ def _save_m2m(cls, info, attribute, cleaned_data):+ super()._save_m2m(info, attribute, cleaned_data)values = cleaned_data.get(cls.ATTRIBUTE_VALUES_FIELD) or []for value in values:- instance.values.create(**value)+ attribute.values.create(**value)class AttributeCreate(AttributeMixin, ModelMutation):ATTRIBUTE_VALUES_FIELD = 'values'- attribute = graphene.Field(- Attribute, description='A created Attribute.')+ attribute = graphene.Field(Attribute, description='A created Attribute.')product_type = graphene.Field(ProductType,description='A product type to which an attribute was added.')@@ -113,8 +123,8 @@ class AttributeCreate(AttributeMixin, ModelMutation):type = AttributeTypeEnum(required=True,description=(- 'Type of an Attribute, if should be created for Products'- ' or Variants of this ProductType.'))+ 'Type of an Attribute, if should be created for Products '+ 'or Variants of this ProductType.'))input = AttributeCreateInput(required=True,description='Fields required to create an attribute.')@@ -123,13 +133,6 @@ class AttributeCreate(AttributeMixin, ModelMutation):description = 'Creates an attribute.'model = models.Attribute- @classmethod- def clean_attribute_value_uniqueness(cls, values, errors, error_msg):- """Checks if all provided values are unique."""- if len(set(values)) != len(values):- cls.add_error(errors, cls.ATTRIBUTE_VALUES_FIELD, error_msg)- return errors-@classmethod@permission_required('product.manage_products')def mutate(cls, root, info, id, type, input):@@ -138,23 +141,12 @@ class AttributeCreate(AttributeMixin, ModelMutation):info, id, errors, 'id', ProductType)if not product_type:return AttributeCreate(errors=errors)-instance = models.Attribute()- cleaned_input = cls.clean_input(info, instance, input, errors)- # This check happens here as we need product_type and we cannot get it- # in clean_input.- cls.clean_attribute_uniqueness(+ cleaned_input = cls.clean_input(info, instance, input, errors)+ cls.clean_attribute(instance, cleaned_input, errors, product_type=product_type)-- # Check if unique values were provided- values = cleaned_input.get(cls.ATTRIBUTE_VALUES_FIELD)- slugs = []- for value in values:- value['slug'] = slugify(value['name'])- slugs.append(value['slug'])- cls.clean_attribute_value_uniqueness(- slugs, errors, 'Provided AttributeValue names are not unique.')+ cls.clean_values(cleaned_input, instance, errors)instance = cls.construct_instance(instance, cleaned_input)cls.clean_instance(instance, errors)@@ -171,17 +163,6 @@ class AttributeCreate(AttributeMixin, ModelMutation):attribute=instance, product_type=product_type, errors=errors)-class AttributeUpdateInput(graphene.InputObjectType):- name = graphene.String(- description='Name displayed in the interface.')- remove_values = graphene.List(- graphene.ID, name='removeValues',- description='List of attributes to be removed from this attribute.')- add_values = graphene.List(- AttributeCreateValueInput, name='addValues',- description='Attribute values to be created for this attribute.')--class AttributeUpdate(AttributeMixin, ModelMutation):ATTRIBUTE_VALUES_FIELD = 'add_values'@@ -205,39 +186,12 @@ class AttributeUpdate(AttributeMixin, ModelMutation):Attribute."""remove_values = cleaned_input.get('remove_values', [])- if remove_values:- for value in remove_values:- if value.attribute != instance:- cls.add_error(- errors, 'remove_values:%s' % value,- 'AttributeValue does not belong to this Attribute.')+ for value in remove_values:+ if value.attribute != instance:+ msg = 'Value %s does not belong to this attribute.' % value+ cls.add_error(errors, 'remove_values', msg)return remove_values- @classmethod- def clean_add_values(cls, cleaned_input, instance, errors):- """Check if AttributeValue with the same slug or name already exists.- """- existing_values = instance.values.values_list('slug', 'name')- if existing_values:- existing_slugs, existing_names = zip(*existing_values)- for value in cleaned_input.get('add_values', []):- already_exists = (- value['name'] in existing_names or- value['slug'] in existing_slugs)- if already_exists:- cls.add_error(- errors, 'add_values:%s' % value['name'],- 'Value with given name already exists.')- return errors-- @classmethod- def clean_input(cls, info, instance, input, errors):- cleaned_input = super().clean_input(info, instance, input, errors)- cleaned_input['remove_values'] = cls.clean_remove_values(- cleaned_input, instance, errors)- cls.clean_add_values(cleaned_input, instance, errors)- return cleaned_input-@classmethoddef _save_m2m(cls, info, instance, cleaned_data):super()._save_m2m(info, instance, cleaned_data)@@ -249,11 +203,13 @@ class AttributeUpdate(AttributeMixin, ModelMutation):def mutate(cls, root, info, id, input):errors = []instance = cls.get_node_or_error(info, id, errors, 'id', Attribute)+cleaned_input = cls.clean_input(info, instance, input, errors)product_type = instance.product_type-- cls.clean_attribute_uniqueness(+ cls.clean_attribute(instance, cleaned_input, errors, product_type=product_type)+ cls.clean_values(cleaned_input, instance, errors)+ cls.clean_remove_values(cleaned_input, instance, errors)instance = cls.construct_instance(instance, cleaned_input)cls.clean_instance(instance, errors)@@ -290,17 +246,11 @@ class AttributeDelete(ModelDeleteMutation):return response-class AttributeValueCreateInput(graphene.InputObjectType):- name = graphene.String(- required=True, description='Name displayed in the interface.')- value = graphene.String(description='Real value eg. HEX color.')--class AttributeValueCreate(ModelMutation):attribute = graphene.Field(Attribute, description='A related Attribute.')class Arguments:- id = graphene.ID(+ attribute_id = graphene.ID(required=True, name='attribute',description='Attribute to which value will be assigned.')input = AttributeValueCreateInput(@@ -311,23 +261,33 @@ class AttributeValueCreate(ModelMutation):description = 'Creates a value for an attribute.'model = models.AttributeValue- @classmethod- def user_is_allowed(cls, user, input):- return user.has_perm('product.manage_products')-@classmethoddef clean_input(cls, info, instance, input, errors):cleaned_input = super().clean_input(info, instance, input, errors)cleaned_input['slug'] = slugify(cleaned_input['name'])+ return cleaned_input@classmethod- def success_response(cls, instance):- response = super().success_response(instance)- response.attribute = instance.attribute- return response+ @permission_required('product.manage_products')+ def mutate(cls, root, info, attribute_id, input):+ errors = []+ attribute = cls.get_node_or_error(+ info, attribute_id, errors, 'id', Attribute)++ instance = models.AttributeValue(attribute=attribute)+ cleaned_input = cls.clean_input(info, instance, input, errors)+ instance = cls.construct_instance(instance, cleaned_input)+ cls.clean_instance(instance, errors)+ if errors:+ return cls(errors=errors)++ instance.save()+ cls._save_m2m(info, instance, cleaned_input)+ return AttributeValueCreate(+ attribute=attribute, attributeValue=instance, errors=errors)-class AttributeValueUpdate(AttributeValueCreate):+class AttributeValueUpdate(ModelMutation):attribute = graphene.Field(Attribute, description='A related Attribute.')class Arguments:@@ -342,11 +302,22 @@ class AttributeValueUpdate(AttributeValueCreate):description = 'Updates value of an attribute.'model = models.AttributeValue+ @classmethod+ def user_is_allowed(cls, user, input):+ return user.has_perm('product.manage_products')+@classmethoddef clean_input(cls, info, instance, input, errors):cleaned_input = super().clean_input(info, instance, input, errors)if 'name' in cleaned_input:cleaned_input['slug'] = slugify(cleaned_input['name'])+ return cleaned_input++ @classmethod+ def success_response(cls, instance):+ response = super().success_response(instance)+ response.attribute = instance.attribute+ return responseclass AttributeValueDelete(ModelDeleteMutation):diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.pyindex cb60777a11..36d5cf64e7 100644--- a/saleor/graphql/product/types.py+++ b/saleor/graphql/product/types.py@@ -16,6 +16,7 @@ from ..core.types.common import CountableDjangoObjectTypefrom ..core.types.money import (Money, MoneyRange, TaxedMoney, TaxedMoneyRange, TaxRateType)from ..utils import get_database_id+from .descriptions import AttributeDescriptions, AttributeValueDescriptionsfrom .filters import ProductFilterSetCOLOR_PATTERN = r'^(#[0-9a-fA-F]{3}|#(?:[0-9a-fA-F]{2}){2,4}|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))$' # noqa@@ -58,13 +59,10 @@ def resolve_attribute_value_type(attribute_value):class AttributeValue(CountableDjangoObjectType):- name = graphene.String(description='Visible name for display purposes.')- slug = graphene.String(- description='Internal representation of an attribute name.')- type = AttributeValueType(description='Type of value.')- value = graphene.String(- description='''Value different than a textual name e.g. color- in a hexadecimal format.''')+ name = graphene.String(description=AttributeValueDescriptions.NAME)+ slug = graphene.String(description=AttributeValueDescriptions.SLUG)+ type = AttributeValueType(description=AttributeValueDescriptions.TYPE)+ value = graphene.String(description=AttributeValueDescriptions.VALUE)class Meta:description = 'Represents a value of an attribute.'@@ -77,11 +75,10 @@ class AttributeValue(CountableDjangoObjectType):class Attribute(CountableDjangoObjectType):- name = graphene.String(description='Visible name for display purposes.')- slug = graphene.String(- description='Internal representation of an attribute name.')+ name = graphene.String(description=AttributeDescriptions.NAME)+ slug = graphene.String(description=AttributeDescriptions.SLUG)values = graphene.List(- AttributeValue, description='List of attribute\'s values.')+ AttributeValue, description=AttributeDescriptions.VALUES)class Meta:description = """Custom attribute of a product. Attributes can be@@ -107,8 +104,7 @@ class Margin(graphene.ObjectType):class SelectedAttribute(graphene.ObjectType):attribute = graphene.Field(- Attribute,- default_value=None, description='Name of an attribute')+ Attribute, default_value=None, description=AttributeDescriptions.NAME)value = graphene.Field(AttributeValue,default_value=None, description='Value of an attribute.')diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex a478ff1531..8cbf250226 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -130,12 +130,7 @@ type AttributeCreate {input AttributeCreateInput {name: String!- values: [AttributeCreateValueInput]-}--input AttributeCreateValueInput {- name: String!- value: String+ values: [AttributeValueCreateInput]}type AttributeDelete {@@ -159,8 +154,8 @@ type AttributeUpdate {input AttributeUpdateInput {name: String- removeValues: [ID]!- addValues: [AttributeCreateValueInput]!+ removeValues: [ID]+ addValues: [AttributeValueCreateInput]}type AttributeValue implements Node {@@ -180,11 +175,12 @@ type AttributeValueCreate {input AttributeValueCreateInput {name: String!- value: String!+ value: String}type AttributeValueDelete {errors: [Error]+ attribute: AttributeattributeValue: AttributeValue}diff --git a/saleor/static/dashboard-next/types/globalTypes.ts b/saleor/static/dashboard-next/types/globalTypes.tsindex f8f75e26f6..4fdb0f40e0 100644--- a/saleor/static/dashboard-next/types/globalTypes.ts+++ b/saleor/static/dashboard-next/types/globalTypes.ts@@ -128,10 +128,10 @@ export interface AddressInput {export interface AttributeCreateInput {name: string;- values?: (AttributeCreateValueInput | null)[] | null;+ values?: (AttributeValueCreateInput | null)[] | null;}-export interface AttributeCreateValueInput {+export interface AttributeValueCreateInput {name: string;value?: string | null;}@@ -139,7 +139,7 @@ export interface AttributeCreateValueInput {export interface AttributeUpdateInput {name?: string | null;removeValues: (string | null)[];- addValues: (AttributeCreateValueInput | null)[];+ addValues: (AttributeValueCreateInput | null)[];}export interface AttributeValueInput {diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.pyindex 0fe4c37f8a..84d1e97281 100644--- a/tests/api/test_attributes.py+++ b/tests/api/test_attributes.py@@ -89,7 +89,7 @@ def test_attributes_in_category_query(user_api_client, product):CREATE_ATTRIBUTES_QUERY = """mutation createAttribute(- $name: String!, $values: [AttributeCreateValueInput],+ $name: String!, $values: [AttributeValueCreateInput],$id: ID!, $type: AttributeTypeEnum!) {attributeCreate(id: $id, type: $type, input: {name: $name, values: $values}) {@@ -145,10 +145,10 @@ def test_create_attribute_and_attribute_values('name_1, name_2, error_msg', (('Red color', 'Red color',- 'Duplicated AttributeValue names provided.'),+ 'Provided values are not unique.'),('Red color', 'red color',- 'Provided AttributeValue names are not unique.')))+ 'Provided values are not unique.')))def test_create_attribute_and_attribute_values_errors(staff_api_client, name_1, name_2, error_msg,permission_manage_products, product_type):@@ -203,7 +203,7 @@ def test_create_attribute_incorrect_product_type_id(UPDATE_ATTRIBUTE_QUERY = """mutation updateAttribute(- $id: ID!, $name: String!, $addValues: [AttributeCreateValueInput]!,+ $id: ID!, $name: String!, $addValues: [AttributeValueCreateInput]!,$removeValues: [ID]!) {attributeUpdate(id: $id,@@ -277,10 +277,10 @@ def test_update_attribute_remove_and_add_values('name_1, name_2, error_msg', (('Red color', 'Red color',- 'Duplicated AttributeValue names provided.'),+ 'Provided values are not unique.'),('Red color', 'red color',- 'Provided AttributeValue names are not unique.')))+ 'Provided values are not unique.')))def test_update_attribute_and_add_attribute_values_errors(staff_api_client, name_1, name_2, error_msg, color_attribute,permission_manage_products):@@ -317,10 +317,10 @@ def test_update_attribute_and_remove_others_attribute_value(content = get_graphql_content(response)errors = content['data']['attributeUpdate']['errors']assert errors- assert errors[0]['field'] == 'removeValues:%s' % str(- size_attribute).lower()- assert errors[0]['message'] == (- 'AttributeValue does not belong to this Attribute.')+ assert errors[0]['field'] == 'removeValues'+ err_msg = (+ 'Value %s does not belong to this attribute.' % str(size_attribute))+ assert errors[0]['message'] == err_msgdef test_delete_attribute(@@ -356,9 +356,9 @@ def test_delete_attribute(CREATE_ATTRIBUTE_VALUE_QUERY = """mutation createAttributeValue(- $id: ID!, $name: String!, $value: String!) {+ $attributeId: ID!, $name: String!, $value: String) {attributeValueCreate(- attribute: $id, input: {name: $name, value: $value}) {+ attribute: $attributeId, input: {name: $name, value: $value}) {errors {fieldmessage@@ -386,7 +386,7 @@ def test_create_attribute_value(attribute_id = graphene.Node.to_global_id('Attribute', attribute.id)name = 'test name'value = 'test-string'- variables = {'name': name, 'value': value, 'id': attribute_id}+ variables = {'name': name, 'value': value, 'attributeId': attribute_id}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_products])content = get_graphql_content(response)@@ -408,19 +408,19 @@ def test_create_attribute_value_not_unique_name(attribute_id = graphene.Node.to_global_id('Attribute', attribute.id)value_name = attribute.values.first().namevariables = {- 'name': value_name, 'value': 'test-string', 'id': attribute_id}+ 'name': value_name, 'value': 'test-string',+ 'attributeId': attribute_id}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_products])content = get_graphql_content(response)data = content['data']['attributeValueCreate']assert data['errors']- assert data['errors'][0]['field'] == 'name'- assert data['errors'][0]['message'] == 'Provided name is not unique.'+ assert data['errors'][0]['field'] == 'All'UPDATE_ATTRIBUTE_VALUE_QUERY = """mutation updateChoice(- $id: ID!, $name: String!, $value: String!) {+ $id: ID!, $name: String!, $value: String) {attributeValueUpdate(id: $id, input: {name: $name, value: $value}) {errors {@@ -471,8 +471,7 @@ def test_update_attribute_value_name_not_unique(content = get_graphql_content(response)data = content['data']['attributeValueUpdate']assert data['errors']- assert data['errors'][0]['field'] == 'name'- assert data['errors'][0]['message'] == 'Provided name is not unique.'+ assert data['errors'][0]['field'] == 'All'def test_update_same_attribute_value(