Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Improvements
Piotr Grundasba4ff17faab4
diff --git a/saleor/attribute/__init__.py b/saleor/attribute/__init__.pyindex 8dbccf8eac..484e4a6e6a 100644--- a/saleor/attribute/__init__.py+++ b/saleor/attribute/__init__.py@@ -15,7 +15,7 @@ class AttributeInputType:(TEXT, "Text"),]# list of the input types that can be used in variant selection- ALLOWED_IN_VARIANT_SELECTION = [DROPDOWN, TEXT]+ ALLOWED_IN_VARIANT_SELECTION = [DROPDOWN]class AttributeType:diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.pyindex 618e321c5d..b0065d55e5 100644--- a/saleor/graphql/attribute/utils.py+++ b/saleor/graphql/attribute/utils.py@@ -4,7 +4,6 @@ from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple, Unionimport graphenefrom django.core.exceptions import ValidationError-from django.db import DataErrorfrom django.db.models import Qfrom django.utils.text import slugifyfrom graphql.error import GraphQLError@@ -187,9 +186,9 @@ class AttributeAssignmentMixin:if not file_url:return tuple()name = file_url.split("/")[-1]- # don't create ne value when assignment already exists+ # don't create new value when assignment already existsvalue = cls._get_assigned_attribute_value_if_exists(- instance, attribute, attr_value.file_url+ instance, attribute, "file_url", attr_value.file_url)if value is None:value = attribute_models.AttributeValue(@@ -204,15 +203,19 @@ class AttributeAssignmentMixin:@classmethoddef _get_assigned_attribute_value_if_exists(- cls, instance: T_INSTANCE, attribute: attribute_models.Attribute, file_url+ cls,+ instance: T_INSTANCE,+ attribute: attribute_models.Attribute,+ lookup_field: str,+ value,):assignment = instance.attributes.filter(- assignment__attribute=attribute, values__file_url=file_url+ assignment__attribute=attribute, **{f"values__{lookup_field}": value}).first()return (Noneif assignment is None- else assignment.values.filter(file_url=file_url).first()+ else assignment.values.filter(**{lookup_field: value}).first())@classmethod@@ -253,6 +256,30 @@ class AttributeAssignmentMixin:if errors:raise ValidationError(errors)+ @classmethod+ def _pre_save_text_values(+ cls,+ instance: T_INSTANCE,+ attribute: attribute_models.Attribute,+ attr_values: AttrValuesInput,+ ):+ """Lazy-retrieve or create the database object from the supplied raw value."""+ value_model = attribute.values.model+ text = attr_values.values[0] if attr_values.values else ""+ # don't create ne value when assignment already exists+ value = cls._get_assigned_attribute_value_if_exists(+ instance, attribute, "name", text+ )++ if value is None:+ value = value_model.objects.create(+ attribute=attribute,+ name=text,+ slug=slugify(text, allow_unicode=True),+ )++ return (value,)+@classmethoddef clean_input(cls,@@ -371,36 +398,26 @@ class AttributeAssignmentMixin::param instance: the product or variant to associate the attribute against.:param cleaned_input: the cleaned user input (refer to clean_attributes)"""- errors = []-for attribute, attr_values in cleaned_input:- try:- if attribute.input_type == AttributeInputType.FILE:- attribute_values = cls._pre_save_file_value(- instance, attribute, attr_values- )- elif attribute.input_type == AttributeInputType.REFERENCE:- attribute_values = cls._pre_save_reference_values(- instance, attribute, attr_values- )- else:- attribute_values = cls._pre_save_values(attribute, attr_values)-- associate_attribute_values_to_instance(- instance, attribute, *attribute_values- )- except DataError as e:- errors.append(- ValidationError(- str(e),- code=ProductErrorCode.INVALID.value,- params={"attributes": [attr_values.global_id]},- )+ if attribute.input_type == AttributeInputType.FILE:+ attribute_values = cls._pre_save_file_value(+ instance, attribute, attr_values+ )+ elif attribute.input_type == AttributeInputType.REFERENCE:+ attribute_values = cls._pre_save_reference_values(+ instance, attribute, attr_values)+ elif attribute.input_type == AttributeInputType.TEXT:+ attribute_values = cls._pre_save_text_values(+ instance, attribute, attr_values+ )+ else:+ attribute_values = cls._pre_save_values(attribute, attr_values)- if errors:- raise ValidationError({"attributes": errors})+ associate_attribute_values_to_instance(+ instance, attribute, *attribute_values+ )def get_variant_selection_attributes(qs: "QuerySet"):@@ -442,6 +459,12 @@ class AttributeInputErrors:"REQUIRED",)+ # text errors+ ERROR_MAX_LENGTH = (+ "Attribute value length is exceeded.",+ "INVALID",+ )+def validate_attributes_input(input_data: List[Tuple["Attribute", "AttrValuesInput"]],@@ -469,6 +492,8 @@ def validate_attributes_input(validate_file_attributes_input(*attrs)elif attribute.input_type == AttributeInputType.REFERENCE:validate_reference_attributes_input(*attrs)+ elif attribute.input_type == AttributeInputType.TEXT:+ validate_text_attributes_input(*attrs)# validation for other input typeselse:validate_standard_attributes_input(*attrs)@@ -548,6 +573,20 @@ def validate_standard_attributes_input()+def validate_text_attributes_input(+ attribute: "Attribute",+ attr_values: "AttrValuesInput",+ attribute_errors: T_ERROR_DICT,+ variant_validation: bool,+):+ name_field = attribute.values.model.name.field # type: ignore+ attribute_id = attr_values.global_id+ text = attr_values.values[0] if attr_values.values else ""++ if len(text) > name_field.max_length:+ attribute_errors[AttributeInputErrors.ERROR_MAX_LENGTH].append(attribute_id)++def is_variant_selection_attribute(attribute: attribute_models.Attribute):return attribute.input_type in AttributeInputType.ALLOWED_IN_VARIANT_SELECTIONdiff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex 01cb6a49ce..4323885d29 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -3267,6 +3267,66 @@ def test_create_product_with_product_reference_attribute_required_no_references(]+def test_create_product_with_text_attribute(+ staff_api_client,+ product_type,+ category,+ text_attribute,+ color_attribute,+ permission_manage_products,+ product,+):+ query = CREATE_PRODUCT_MUTATION++ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)+ category_id = graphene.Node.to_global_id("Category", category.pk)+ product_name = "test name"+ product_slug = "product-test-slug"++ # Add second attribute+ product_type.product_attributes.add(text_attribute)+ text_attribute_id = graphene.Node.to_global_id("Attribute", text_attribute.id)++ # test creating root product+ variables = {+ "input": {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name,+ "slug": product_slug,+ "attributes": [{"id": text_attribute_id, "values": ["Cool text"]}],+ }+ }++ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ data = content["data"]["productCreate"]+ assert data["productErrors"] == []+ assert data["product"]["name"] == product_name+ assert data["product"]["slug"] == product_slug+ assert data["product"]["productType"]["name"] == product_type.name+ assert data["product"]["category"]["name"] == category.name+ _, product_id = graphene.Node.from_global_id(data["product"]["id"])+ expected_attributes_data = [+ {+ "attribute": {"slug": "text"},+ "values": [+ {+ "slug": "cool-text",+ "name": "Cool text",+ "reference": None,+ "file": None,+ }+ ],+ },+ {"attribute": {"slug": color_attribute.slug}, "values": []},+ ]+ for attr_data in data["product"]["attributes"]:+ assert attr_data in expected_attributes_data++def test_create_product_no_values_given(staff_api_client,product_type,diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.pyindex 942ddbd6f2..c702ea4b80 100644--- a/saleor/graphql/product/tests/test_variant.py+++ b/saleor/graphql/product/tests/test_variant.py@@ -1050,6 +1050,59 @@ def test_create_variant_invalid_variant_attributes(assert error in errors+@patch("saleor.plugins.manager.PluginsManager.product_variant_created")+def test_create_variant_with_text_attribute(+ created_webhook_mock,+ permission_manage_products,+ product,+ product_type,+ staff_api_client,+ text_attribute,+ warehouse,+):+ product_type.variant_attributes.add(text_attribute)+ query = CREATE_VARIANT_MUTATION+ product_id = graphene.Node.to_global_id("Product", product.pk)+ sku = "1"+ price = 1.32+ cost_price = 3.22+ weight = 10.22+ attr_id = graphene.Node.to_global_id("Attribute", text_attribute.id)+ text = "Sample text"+ stocks = [+ {+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),+ "quantity": 20,+ }+ ]+ variables = {+ "productId": product_id,+ "sku": sku,+ "stocks": stocks,+ "costPrice": cost_price,+ "price": price,+ "weight": weight,+ "attributes": [+ {"id": attr_id, "values": text},+ ],+ "trackInventory": True,+ }++ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)["data"]["productVariantCreate"]+ flush_post_commit_hooks()+ data = content["productVariant"]++ assert not content["productErrors"]+ assert data["name"] == sku+ assert data["sku"] == sku+ assert data["attributes"][-1]["attribute"]["slug"] == text_attribute.slug+ assert data["attributes"][-1]["values"][0]["name"] == text+ created_webhook_mock.assert_called_once_with(product.variants.last())++def test_create_variant_attributes_save_error(permission_manage_products,product,@@ -1401,6 +1454,50 @@ def test_update_product_variant_with_current_attribute(assert variant.attributes.last().values.first().slug == "small"+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+def test_update_variant_with_text_attribute(+ product_variant_updated,+ permission_manage_products,+ product,+ product_type,+ staff_api_client,+ text_attribute,+ warehouse,+):+ product_type.variant_attributes.add(text_attribute)+ query = QUERY_UPDATE_VARIANT_ATTRIBUTES+ variant = product.variants.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ sku = "123"+ attr_id = graphene.Node.to_global_id("Attribute", text_attribute.id)+ text = text_attribute.values.first().name+ variables = {+ "id": variant_id,+ "sku": sku,+ "attributes": [+ {"id": attr_id, "values": text},+ ],+ }+ associate_attribute_values_to_instance(+ variant, text_attribute, text_attribute.values.first()+ )+ values_count = text_attribute.values.count()++ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)["data"]["productVariantUpdate"]+ variant.refresh_from_db()+ data = content["productVariant"]++ assert not content["productErrors"]+ assert data["sku"] == sku+ assert data["attributes"][-1]["attribute"]["slug"] == text_attribute.slug+ assert data["attributes"][-1]["values"][0]["name"] == text+ assert text_attribute.values.count() == values_count+ product_variant_updated.assert_called_once_with(product.variants.last())++def test_update_product_variant_with_new_attribute(staff_api_client,product_with_variant_with_two_attributes,diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 0ec1bd5c93..d536bba2f4 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -759,7 +759,7 @@ def shipping_method_channel_PLN(shipping_zone, channel_PLN):@pytest.fixture-def color_attribute(db): # pylint: disable=W0613+def color_attribute(db):attribute = Attribute.objects.create(slug="color",name="Color",@@ -774,11 +774,12 @@ def color_attribute(db): # pylint: disable=W0613@pytest.fixture-def text_attribute(db): # pylint: disable=W0613+def text_attribute(db):attribute = Attribute.objects.create(slug="text",name="Text",type=AttributeInputType.TEXT,+ input_type=AttributeInputType.TEXT,filterable_in_storefront=True,filterable_in_dashboard=True,available_in_grid=True,