Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix reusing attribute values in product mutations
Marcin Gębala921813e0d166
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex e8c0cd05be..145df34bb1 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -10,24 +10,8 @@ from ...core.types.common import Decimal, SeoInputfrom ...core.utils import clean_seo_fieldsfrom ...file_upload.types import Uploadfrom ...shipping.types import WeightScalar-from ...utils import get_attributes_dict_from_listfrom ..types import Collection, Product, ProductImage, ProductVariant---def update_variants_names(instance, saved_attributes):- initial_attributes = set(instance.variant_attributes.all())- attributes_changed = initial_attributes.intersection(saved_attributes)- if not attributes_changed:- return- variants_to_be_updated = models.ProductVariant.objects.filter(- product__in=instance.products.all(),- product__product_type__variant_attributes__in=attributes_changed)- variants_to_be_updated = variants_to_be_updated.prefetch_related(- 'product__product_type__variant_attributes__values').all()- attributes = instance.variant_attributes.all()- for variant in variants_to_be_updated:- variant.name = get_name_from_attributes(variant, attributes)- variant.save()+from ..utils import attributes_to_hstore, update_variants_namesclass CategoryInput(graphene.InputObjectType):@@ -262,11 +246,13 @@ class ProductCreate(ModelMutation):if instance.pk else cleaned_input.get('product_type'))if attributes and product_type:- slug_to_id_map = dict(- product_type.product_attributes.values_list('slug', 'id'))- attributes = get_attributes_dict_from_list(- attributes, slug_to_id_map)- cleaned_input['attributes'] = attributes+ try:+ attributes = attributes_to_hstore(+ attributes, product_type.product_attributes.all())+ except ValueError as e:+ cls.add_error(errors, 'attributes', str(e))+ else:+ cleaned_input['attributes'] = attributesclean_seo_fields(cleaned_input)return cleaned_input@@ -353,11 +339,13 @@ class ProductVariantCreate(ModelMutation):product_type = product.product_typeif attributes and product_type:- slug_to_id_map = dict(- product_type.variant_attributes.values_list('slug', 'id'))- attributes = get_attributes_dict_from_list(- attributes, slug_to_id_map)- cleaned_input['attributes'] = attributes+ try:+ attributes = attributes_to_hstore(+ attributes, product_type.variant_attributes.all())+ except ValueError as e:+ cls.add_error(errors, 'attributes', str(e))+ else:+ cleaned_input['attributes'] = attributesreturn cleaned_input@classmethod@@ -575,7 +563,7 @@ class ProductImageReorder(BaseMutation):cls.add_error(errors, 'order',"Image with id %r does not belong to product %r" % (- image_id, product_id))+ image.id, product_id))if not errors:for order, image in enumerate(images):image.sort_order = orderdiff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.pynew file mode 100644index 0000000000..1b735c1767--- /dev/null+++ b/saleor/graphql/product/utils.py@@ -0,0 +1,62 @@+from django.utils.text import slugify++from ...product.models import (+ AttributeChoiceValue, ProductAttribute, ProductVariant)+from ...product.utils.attributes import get_name_from_attributes+++def attributes_to_hstore(attribute_value_input, attributes_queryset):+ """Transform attributes to the HStore representation.++ Attributes configuration per product is stored in a HStore field as+ a dict of IDs. This function transforms the list of `AttributeValueInput`+ objects to this format.+ """+ attributes_map = dict(attributes_queryset.values_list('slug', 'id'))++ attributes_hstore = {}+ values_map = dict(+ AttributeChoiceValue.objects.values_list('slug', 'id'))++ for attribute in attribute_value_input:+ attr_slug = attribute.get('slug')+ if attr_slug not in attributes_map:+ raise ValueError(+ 'Attribute %r doesn\'t belong to given product type.' % (+ attr_slug,))++ value = attribute.get('value')+ if not value:+ continue++ attribute_id = attributes_map[attr_slug]+ value_id = values_map.get(value)++ if value_id is None:+ # `value_id` was not found; create a new AttributeChoiceValue+ # instance from the provided `value`.+ attr_instance = ProductAttribute.objects.get(slug=attr_slug)+ obj = AttributeChoiceValue.objects.get_or_create(+ attribute_id=attr_instance.pk, name=value,+ slug=slugify(value))[0]+ value_id = obj.pk++ attributes_hstore[str(attribute_id)] = str(value_id)++ return attributes_hstore+++def update_variants_names(instance, saved_attributes):+ initial_attributes = set(instance.variant_attributes.all())+ attributes_changed = initial_attributes.intersection(saved_attributes)+ if not attributes_changed:+ return+ variants_to_be_updated = ProductVariant.objects.filter(+ product__in=instance.products.all(),+ product__product_type__variant_attributes__in=attributes_changed)+ variants_to_be_updated = variants_to_be_updated.prefetch_related(+ 'product__product_type__variant_attributes__values').all()+ attributes = instance.variant_attributes.all()+ for variant in variants_to_be_updated:+ variant.name = get_name_from_attributes(variant, attributes)+ variant.save()diff --git a/saleor/graphql/utils.py b/saleor/graphql/utils.pyindex 49604aa589..0453720dbf 100644--- a/saleor/graphql/utils.py+++ b/saleor/graphql/utils.py@@ -1,12 +1,9 @@import graphenefrom django.db.models import Q-from django.utils.encoding import smart_text-from django.utils.text import slugifyfrom graphene_django.registry import get_global_registryfrom graphql.error import GraphQLErrorfrom graphql_relay import from_global_id-from ..product.models import AttributeChoiceValue, ProductAttributefrom .core.types.common import PermissionDisplayregistry = get_global_registry()@@ -63,39 +60,6 @@ def get_nodes(ids, graphene_type=None):return nodes-def get_attributes_dict_from_list(attributes, slug_to_id_map):- """- :param attributes: list- :return: dict- Takes list on form [{"slug": "attr_slug", "value": "attr_value"}, {...}]- and converts into dictionary {attr_pk: value_pk}- """- attr_ids = {}- value_slug_id = dict(- AttributeChoiceValue.objects.values_list('name', 'id'))- for attribute in attributes:- attr_slug = attribute.get('slug')- if attr_slug not in slug_to_id_map:- raise ValueError(- 'Attribute %r doesn\'t belong to given product type.' % (- attr_slug,))- value = attribute.get('value')- if not value:- continue-- if not value_slug_id.get(value):- attr = ProductAttribute.objects.get(slug=attr_slug)- value = AttributeChoiceValue(- attribute_id=attr.pk, name=value, slug=slugify(value))- value.save()- attr_ids[smart_text(- slug_to_id_map.get(attr_slug))] = smart_text(value.pk)- else:- attr_ids[smart_text(slug_to_id_map.get(attr_slug))] = smart_text(- value_slug_id.get(value))- return attr_ids--def filter_by_query_param(queryset, query, search_fields):"""Filter queryset according to given parameters.diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.pyindex d74f240f15..455fbd69e2 100644--- a/tests/api/test_attributes.py+++ b/tests/api/test_attributes.py@@ -4,6 +4,89 @@ import grapheneimport pytestfrom django.shortcuts import reversefrom tests.utils import get_graphql_content+from saleor.product.models import (+ Category, ProductAttribute, AttributeChoiceValue)+from saleor.graphql.product.utils import attributes_to_hstore+++def test_attributes_to_hstore(product, color_attribute):+ color_value = color_attribute.values.first()++ # test transforming slugs of existing attributes to IDs+ input_data = [{+ 'slug': color_attribute.slug, 'value': color_value.slug}]+ attrs_qs = product.product_type.product_attributes.all()+ ids = attributes_to_hstore(input_data, attrs_qs)+ assert str(color_attribute.pk) in ids+ assert ids[str(color_attribute.pk)] == str(color_value.pk)++ # test creating a new attribute value+ input_data = [{+ 'slug': color_attribute.slug, 'value': 'Space Grey'}]+ ids = attributes_to_hstore(input_data, attrs_qs)+ new_value = AttributeChoiceValue.objects.get(slug='space-grey')+ assert str(color_attribute.pk) in ids+ assert ids[str(color_attribute.pk)] == str(new_value.pk)++ # test passing an attribute that doesn't belong to this product raises+ # an error+ input_data = [{'slug': 'not-an-attribute', 'value': 'not-a-value'}]+ with pytest.raises(ValueError):+ attributes_to_hstore(input_data, attrs_qs)+++def test_attributes_query(user_api_client, product):+ attributes = ProductAttribute.objects.prefetch_related('values')+ query = '''+ query {+ attributes {+ edges {+ node {+ id+ name+ slug+ values {+ id+ name+ slug+ }+ }+ }+ }+ }+ '''+ response = user_api_client.post(reverse('api'), {'query': query})+ content = get_graphql_content(response)+ assert 'errors' not in content+ attributes_data = content['data']['attributes']['edges']+ assert len(attributes_data) == attributes.count()+++def test_attributes_in_category_query(user_api_client, product):+ category = Category.objects.first()+ query = '''+ query {+ attributes(inCategory: "%(category_id)s") {+ edges {+ node {+ id+ name+ slug+ values {+ id+ name+ slug+ }+ }+ }+ }+ }+ ''' % {'category_id': graphene.Node.to_global_id('Category', category.id)}+ response = user_api_client.post(reverse('api'), {'query': query})+ content = get_graphql_content(response)+ assert 'errors' not in content+ attributes_data = content['data']['attributes']['edges']+ assert len(attributes_data) == ProductAttribute.objects.count()def test_create_product_attribute(admin_api_client):diff --git a/tests/api/test_product.py b/tests/api/test_product.pyindex ce15fa2076..07234a1c41 100644--- a/tests/api/test_product.py+++ b/tests/api/test_product.py@@ -10,9 +10,9 @@ from prices import Moneyfrom tests.utils import (create_image, create_pdf_file_with_image_ext, get_graphql_content)-from saleor.graphql.product.mutations.products import update_variants_names+from saleor.graphql.product.utils import update_variants_namesfrom saleor.product.models import (- Category, Collection, Product, ProductAttribute, ProductType, ProductImage)+ Category, Collection, Product, ProductType, ProductImage)from .utils import assert_no_permission, get_multipart_request_body@@ -316,60 +316,6 @@ def test_sort_products(user_api_client, product):assert price_0 > price_1-def test_attributes_query(user_api_client, product):- attributes = ProductAttribute.objects.prefetch_related('values')- query = '''- query {- attributes {- edges {- node {- id- name- slug- values {- id- name- slug- }- }- }- }- }- '''- response = user_api_client.post(reverse('api'), {'query': query})- content = get_graphql_content(response)- assert 'errors' not in content- attributes_data = content['data']['attributes']['edges']- assert len(attributes_data) == attributes.count()---def test_attributes_in_category_query(user_api_client, product):- category = Category.objects.first()- query = '''- query {- attributes(inCategory: "%(category_id)s") {- edges {- node {- id- name- slug- values {- id- name- slug- }- }- }- }- }- ''' % {'category_id': graphene.Node.to_global_id('Category', category.id)}- response = user_api_client.post(reverse('api'), {'query': query})- content = get_graphql_content(response)- assert 'errors' not in content- attributes_data = content['data']['attributes']['edges']- assert len(attributes_data) == ProductAttribute.objects.count()--def test_create_product(admin_api_client, product_type, category, size_attribute):query = """@@ -440,9 +386,9 @@ def test_create_product(# Default attribute defined in product_type fixturecolor_attr = product_type.product_attributes.get(name='Color')- color_attr_value = color_attr.values.first().namecolor_value_slug = color_attr.values.first().slugcolor_attr_slug = color_attr.slug+# Add second attributeproduct_type.product_attributes.add(size_attribute)size_attr_slug = product_type.product_attributes.get(name='Size').slug@@ -459,7 +405,7 @@ def test_create_product('taxRate': product_taxRate,'price': product_price,'attributes': [- {'slug': color_attr_slug, 'value': color_attr_value},+ {'slug': color_attr_slug, 'value': color_value_slug},{'slug': size_attr_slug, 'value': non_existent_attr_value}]})response = admin_api_client.post(