Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Introduce file attributes (#6568)
Iga Karbowiake6bdeec743fd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 26236b67f8..bd21cfff32 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,7 @@ All notable, unreleased changes to this project will be documented in this file.- Add possibility to exclude products from shipping method - #6506 by @korycins- Add availableShippingMethods to the Shop type - #6551 by @IKarbowiak- Add delivery time to shipping method - #6564 by @IKarbowiak+- Introduce file attributes - #6568 by @IKarbowiak# 2.11.1diff --git a/saleor/attribute/__init__.py b/saleor/attribute/__init__.pyindex ee8fb37023..2c98a3dc64 100644--- a/saleor/attribute/__init__.py+++ b/saleor/attribute/__init__.py@@ -3,13 +3,11 @@ class AttributeInputType:DROPDOWN = "dropdown"MULTISELECT = "multiselect"+ FILE = "file"- CHOICES = [- (DROPDOWN, "Dropdown"),- (MULTISELECT, "Multi Select"),- ]- # list the input types that cannot be assigned to a variant- NON_ASSIGNABLE_TO_VARIANTS = [MULTISELECT]+ CHOICES = [(DROPDOWN, "Dropdown"), (MULTISELECT, "Multi Select"), (FILE, "File")]+ # list of the input types that can be used in variant selection+ ALLOWED_IN_VARIANT_SELECTION = [DROPDOWN]class AttributeType:diff --git a/saleor/attribute/migrations/0003_auto_20201113_1149.py b/saleor/attribute/migrations/0003_auto_20201113_1149.pynew file mode 100644index 0000000000..8ea2c7aef0--- /dev/null+++ b/saleor/attribute/migrations/0003_auto_20201113_1149.py@@ -0,0 +1,51 @@+# Generated by Django 3.1 on 2020-11-13 11:49++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("attribute", "0002_auto_20201030_1141"),+ ]++ operations = [+ migrations.AddField(+ model_name="attributevalue",+ name="content_type",+ field=models.CharField(blank=True, max_length=50, null=True),+ ),+ migrations.AddField(+ model_name="attributevalue",+ name="file_url",+ field=models.URLField(blank=True, null=True),+ ),+ migrations.AlterField(+ model_name="attribute",+ name="input_type",+ field=models.CharField(+ choices=[+ ("dropdown", "Dropdown"),+ ("multiselect", "Multi Select"),+ ("file", "File"),+ ],+ default="dropdown",+ max_length=50,+ ),+ ),+ migrations.AlterField(+ model_name="attribute",+ name="available_in_grid",+ field=models.BooleanField(blank=True, default=False),+ ),+ migrations.AlterField(+ model_name="attribute",+ name="filterable_in_dashboard",+ field=models.BooleanField(blank=True, default=False),+ ),+ migrations.AlterField(+ model_name="attribute",+ name="filterable_in_storefront",+ field=models.BooleanField(blank=True, default=False),+ ),+ ]diff --git a/saleor/attribute/models.py b/saleor/attribute/models.pyindex eaebf66dc8..170d7467f9 100644--- a/saleor/attribute/models.py+++ b/saleor/attribute/models.py@@ -253,11 +253,11 @@ class Attribute(ModelWithMetadata):is_variant_only = models.BooleanField(default=False, blank=True)visible_in_storefront = models.BooleanField(default=True, blank=True)- filterable_in_storefront = models.BooleanField(default=True, blank=True)- filterable_in_dashboard = models.BooleanField(default=True, blank=True)+ filterable_in_storefront = models.BooleanField(default=False, blank=True)+ filterable_in_dashboard = models.BooleanField(default=False, blank=True)storefront_search_position = models.IntegerField(default=0, blank=True)- available_in_grid = models.BooleanField(default=True, blank=True)+ available_in_grid = models.BooleanField(default=False, blank=True)objects = AttributeQuerySet.as_manager()translated = TranslationProxy()@@ -299,6 +299,8 @@ class AttributeValue(SortableModel):name = models.CharField(max_length=250)value = models.CharField(max_length=100, blank=True, default="")slug = models.SlugField(max_length=255, allow_unicode=True)+ file_url = models.URLField(null=True, blank=True)+ content_type = models.CharField(max_length=50, null=True, blank=True)attribute = models.ForeignKey(Attribute, related_name="values", on_delete=models.CASCADE)diff --git a/saleor/csv/tests/export/products_data/test_get_products_data.py b/saleor/csv/tests/export/products_data/test_get_products_data.pyindex 5d121ac136..5c1bcea68e 100644--- a/saleor/csv/tests/export/products_data/test_get_products_data.py+++ b/saleor/csv/tests/export/products_data/test_get_products_data.py@@ -1,6 +1,7 @@from measurement.measures import Weightfrom .....attribute.models import Attribute+from .....attribute.utils import associate_attribute_values_to_instancefrom .....channel.models import Channelfrom .....product.models import Product, ProductVariant, VariantImagefrom .....warehouse.models import Warehouse@@ -225,9 +226,18 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(variant_with_many_stocks,product_with_image,product_with_variant_with_two_attributes,+ file_attribute,):# givenproduct.variants.add(variant_with_many_stocks)+ product.product_type.variant_attributes.add(file_attribute)+ product.product_type.product_attributes.add(file_attribute)+ associate_attribute_values_to_instance(+ variant_with_many_stocks, file_attribute, file_attribute.values.first()+ )+ associate_attribute_values_to_instance(+ product, file_attribute, file_attribute.values.first()+ )products = Product.objects.all()export_fields = {"id", "variants__sku"}diff --git a/saleor/csv/tests/export/products_data/test_handle_relations_data.py b/saleor/csv/tests/export/products_data/test_handle_relations_data.pyindex f6fae7743a..1606f6c4b1 100644--- a/saleor/csv/tests/export/products_data/test_handle_relations_data.py+++ b/saleor/csv/tests/export/products_data/test_handle_relations_data.py@@ -1,10 +1,12 @@from unittest.mock import patchfrom .....attribute.models import Attribute+from .....attribute.utils import associate_attribute_values_to_instancefrom .....product.models import Product, ProductImage, VariantImagefrom .....warehouse.models import Warehousefrom ....utils import ProductExportFieldsfrom ....utils.products_data import (+ AttributeData,add_attribute_info_to_data,add_channel_info_to_data,add_collection_info_to_data,@@ -72,9 +74,15 @@ def test_get_products_relations_data_no_relations_fields(@patch("saleor.csv.utils.products_data.prepare_products_relations_data")def test_get_products_relations_data_attribute_ids(- prepare_products_data_mocked, product_list+ prepare_products_data_mocked, product_list, file_attribute):# given+ product = product_list[0]+ product.product_type.product_attributes.add(file_attribute)+ associate_attribute_values_to_instance(+ product, file_attribute, file_attribute.values.first()+ )+qs = Product.objects.all()export_fields = {"name", "description"}attribute_ids = list(Attribute.objects.values_list("pk", flat=True))@@ -83,7 +91,6 @@ def test_get_products_relations_data_attribute_ids(# whenget_products_relations_data(qs, export_fields, attribute_ids, channel_ids)- # then# thenassert prepare_products_data_mocked.call_count == 1args, kwargs = prepare_products_data_mocked.call_args@@ -116,12 +123,19 @@ def test_get_products_relations_data_channel_ids(def test_prepare_products_relations_data(- product_with_image, collection_list, channel_USD, channel_PLN+ product_with_image, collection_list, channel_USD, channel_PLN, file_attribute):# givenpk = product_with_image.pk++ product_with_image.product_type.product_attributes.add(file_attribute)+ associate_attribute_values_to_instance(+ product_with_image, file_attribute, file_attribute.values.first()+ )+collection_list[0].products.add(product_with_image)collection_list[1].products.add(product_with_image)+qs = Product.objects.all()fields = set(ProductExportFields.HEADERS_TO_FIELDS_MAPPING["product_many_to_many"].values()@@ -288,9 +302,16 @@ def test_get_variants_relations_data_no_relations_fields(@patch("saleor.csv.utils.products_data.prepare_variants_relations_data")def test_get_variants_relations_data_attribute_ids(- prepare_variants_data_mocked, product_list+ prepare_variants_data_mocked, product_list, file_attribute):# given+ product = product_list[0]+ product.product_type.variant_attributes.add(file_attribute)+ variant = product.variants.first()+ associate_attribute_values_to_instance(+ variant, file_attribute, file_attribute.values.first()+ )+qs = Product.objects.all()export_fields = {"name", "variants__sku"}attribute_ids = list(Attribute.objects.values_list("pk", flat=True))@@ -392,8 +413,16 @@ def test_prepare_variants_relations_data(media_root,channel_PLN,channel_USD,+ file_attribute,):# given+ product = product_with_variant_with_two_attributes+ product.product_type.variant_attributes.add(file_attribute)+ variant = product.variants.first()+ associate_attribute_values_to_instance(+ variant, file_attribute, file_attribute.values.first()+ )+qs = Product.objects.all()variant = product_with_variant_with_two_attributes.variants.first()product_image = ProductImage.objects.create(@@ -645,10 +674,9 @@ def test_add_attribute_info_to_data(product):pk = product.pkslug = "test_attribute_slug"value = "test value"- attribute_data = {- "slug": slug,- "value": value,- }+ attribute_data = AttributeData(+ slug=slug, value=value, file_url=None, input_type="dropdown"+ )input_data = {pk: {}}# when@@ -668,10 +696,9 @@ def test_add_attribute_info_to_data_update_attribute_data(product):value = "test value"expected_header = f"{slug} (variant attribute)"- attribute_data = {- "slug": slug,- "value": value,- }+ attribute_data = AttributeData(+ slug=slug, value=value, file_url=None, input_type="dropdown"+ )input_data = {pk: {expected_header: {"value1"}}}# when@@ -686,10 +713,9 @@ def test_add_attribute_info_to_data_update_attribute_data(product):def test_add_attribute_info_to_data_no_slug(product):# givenpk = product.pk- attribute_data = {- "slug": None,- "value": None,- }+ attribute_data = AttributeData(+ slug=None, value=None, file_url=None, input_type="dropdown"+ )input_data = {pk: {}}# when@@ -701,6 +727,26 @@ def test_add_attribute_info_to_data_no_slug(product):assert result == input_data+def test_add_file_attribute_info_to_data(product):+ # given+ pk = product.pk+ slug = "testtxt"+ test_url = "test.txt"+ attribute_data = AttributeData(+ slug=slug, value=None, file_url=test_url, input_type="file"+ )+ input_data = {pk: {}}++ # when+ result = add_attribute_info_to_data(+ product.pk, attribute_data, "product attribute", input_data+ )++ # then+ expected_header = f"{slug} (product attribute)"+ assert result[pk][expected_header] == {"http://mirumee.com/media/" + test_url}++def test_add_warehouse_info_to_data(product):# givenpk = product.pkdiff --git a/saleor/csv/tests/export/products_data/utils.py b/saleor/csv/tests/export/products_data/utils.pyindex 6e90d68b33..0de4552ecf 100644--- a/saleor/csv/tests/export/products_data/utils.py+++ b/saleor/csv/tests/export/products_data/utils.py@@ -1,12 +1,22 @@+from .....attribute import AttributeInputType++def add_product_attribute_data_to_expected_data(data, product, attribute_ids, pk=None):for assigned_attribute in product.attributes.all():if assigned_attribute:header = f"{assigned_attribute.attribute.slug} (product attribute)"if str(assigned_attribute.attribute.pk) in attribute_ids:+ value_instance = assigned_attribute.values.first()+ value = (+ value_instance.slug+ if assigned_attribute.attribute.input_type+ != AttributeInputType.FILE+ else value_instance.file_url+ )if pk:- data[pk][header] = assigned_attribute.values.first().slug+ data[pk][header] = valueelse:- data[header] = assigned_attribute.values.first().slug+ data[header] = valuereturn data@@ -14,10 +24,16 @@ def add_variant_attribute_data_to_expected_data(data, variant, attribute_ids, pkfor assigned_attribute in variant.attributes.all():header = f"{assigned_attribute.attribute.slug} (variant attribute)"if str(assigned_attribute.attribute.pk) in attribute_ids:+ value_instance = assigned_attribute.values.first()+ value = (+ value_instance.slug+ if assigned_attribute.attribute.input_type != AttributeInputType.FILE+ else value_instance.file_url+ )if pk:- data[pk][header] = assigned_attribute.values.first().slug+ data[pk][header] = valueelse:- data[header] = assigned_attribute.values.first().slug+ data[header] = valuereturn datadiff --git a/saleor/csv/utils/__init__.py b/saleor/csv/utils/__init__.pyindex bf6d22af16..4f749b2fe6 100644--- a/saleor/csv/utils/__init__.py+++ b/saleor/csv/utils/__init__.py@@ -22,7 +22,9 @@ class ProductExportFields:PRODUCT_ATTRIBUTE_FIELDS = {"value": "attributes__values__slug",+ "file_url": "attributes__values__file_url","slug": "attributes__assignment__attribute__slug",+ "input_type": "attributes__assignment__attribute__input_type","attribute_pk": "attributes__assignment__attribute__pk",}@@ -44,7 +46,9 @@ class ProductExportFields:VARIANT_ATTRIBUTE_FIELDS = {"value": "variants__attributes__values__slug",+ "file_url": "variants__attributes__values__file_url","slug": "variants__attributes__assignment__attribute__slug",+ "input_type": "variants__attributes__assignment__attribute__input_type","attribute_pk": "variants__attributes__assignment__attribute__pk",}diff --git a/saleor/csv/utils/products_data.py b/saleor/csv/utils/products_data.pyindex 73f95e8ec8..d4ed69e9ee 100644--- a/saleor/csv/utils/products_data.py+++ b/saleor/csv/utils/products_data.py@@ -1,11 +1,12 @@-import os-from collections import defaultdict+from collections import defaultdict, namedtuplefrom typing import TYPE_CHECKING, Dict, List, Optional, Set, Union+from urllib.parse import urljoinfrom django.conf import settingsfrom django.db.models import Case, CharField, Value as V, Whenfrom django.db.models.functions import Concat+from ...attribute import AttributeInputTypefrom ...core.utils import build_absolute_urifrom . import ProductExportFields@@ -278,7 +279,7 @@ def add_image_uris_to_data(absolute uri of given image is added to set with other uris."""if image:- uri = build_absolute_uri(os.path.join(settings.MEDIA_URL, image))+ uri = build_absolute_uri(urljoin(settings.MEDIA_URL, image))if header in result_data[pk]:result_data[pk][header].add(uri)else:@@ -286,6 +287,9 @@ def add_image_uris_to_data(return result_data+AttributeData = namedtuple("AttributeData", ["slug", "file_url", "value", "input_type"])++def handle_attribute_data(pk: int,data: dict,@@ -294,13 +298,13 @@ def handle_attribute_data(attribute_fields: dict,attribute_owner: str,):- attribute_data: dict = {}-attribute_pk = str(data.pop(attribute_fields["attribute_pk"], ""))- attribute_data = {- "slug": data.pop(attribute_fields["slug"], None),- "value": data.pop(attribute_fields["value"], None),- }+ attribute_data = AttributeData(+ slug=data.pop(attribute_fields["slug"], None),+ input_type=data.pop(attribute_fields["input_type"], None),+ file_url=data.pop(attribute_fields["file_url"], None),+ value=data.pop(attribute_fields["value"], None),+ )if attribute_ids and attribute_pk in attribute_ids:result_data = add_attribute_info_to_data(@@ -359,7 +363,7 @@ def handle_warehouse_data(def add_attribute_info_to_data(pk: int,- attribute_data: Dict[str, Optional[Union[str]]],+ attribute_data: AttributeData,attribute_owner: str,result_data: Dict[int, dict],) -> Dict[int, dict]:@@ -370,14 +374,21 @@ def add_attribute_info_to_data(to set with values.It returns updated data."""- slug = attribute_data["slug"]+ slug = attribute_data.slugheader = Noneif slug:header = f"{slug} ({attribute_owner})"+ value = (+ attribute_data.value+ if attribute_data.input_type != AttributeInputType.FILE+ else build_absolute_uri(+ urljoin(settings.MEDIA_URL, attribute_data.file_url)+ )+ )if header in result_data[pk]:- result_data[pk][header].add(attribute_data["value"]) # type: ignore+ result_data[pk][header].add(value) # type: ignoreelse:- result_data[pk][header] = {attribute_data["value"]}+ result_data[pk][header] = {value}return result_datadiff --git a/saleor/graphql/attribute/descriptions.py b/saleor/graphql/attribute/descriptions.pyindex e2d9139c55..9c69b45400 100644--- a/saleor/graphql/attribute/descriptions.py+++ b/saleor/graphql/attribute/descriptions.py@@ -24,3 +24,4 @@ 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)."+ FILE = "Represents file URL and content type (if attribute value is a file)."diff --git a/saleor/graphql/attribute/mutations.py b/saleor/graphql/attribute/mutations.pyindex 72137b2b8e..b61f635a5d 100644--- a/saleor/graphql/attribute/mutations.py+++ b/saleor/graphql/attribute/mutations.py@@ -5,7 +5,7 @@ from django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.db import transactionfrom django.utils.text import slugify-from ...attribute import models as models+from ...attribute import AttributeInputType, models as modelsfrom ...attribute.error_codes import AttributeErrorCodefrom ...core.exceptions import PermissionDeniedfrom ...core.permissions import (@@ -190,10 +190,21 @@ class AttributeMixin:an attribute."""values_input = cleaned_input.get(cls.ATTRIBUTE_VALUES_FIELD)+ attribute_input_type = cleaned_input.get("input_type") or attribute.input_typeif values_input is None:return+ if attribute_input_type == AttributeInputType.FILE and values_input:+ raise ValidationError(+ {+ cls.ATTRIBUTE_VALUES_FIELD: ValidationError(+ "Values cannot be used with input type FILE.",+ code=AttributeErrorCode.INVALID.value,+ )+ }+ )+for value_data in values_input:value_data["slug"] = slugify(value_data["name"], allow_unicode=True)attribute_value = models.AttributeValue(**value_data, attribute=attribute)@@ -215,9 +226,34 @@ class AttributeMixin:except ValidationError as error:error.code = AttributeErrorCode.REQUIRED.valueraise ValidationError({"slug": error})+ cls._clean_attribute_settings(instance, cleaned_input)return cleaned_input+ @classmethod+ def _clean_attribute_settings(cls, instance, cleaned_input):+ """Validate attributes settings.++ Ensure that any invalid operations will be not performed.+ """+ attribute_input_type = cleaned_input.get("input_type") or instance.input_type+ if attribute_input_type != AttributeInputType.FILE:+ return+ errors = {}+ for field in [+ "filterable_in_storefront",+ "filterable_in_dashboard",+ "available_in_grid",+ "storefront_search_position",+ ]:+ if cleaned_input.get(field):+ errors[field] = ValidationError(+ "Cannot set on a file attribute.",+ code=AttributeErrorCode.INVALID.value,+ )+ if errors:+ raise ValidationError(errors)+@classmethoddef _save_m2m(cls, info, attribute, cleaned_data):super()._save_m2m(info, attribute, cleaned_data)diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_create.pyindex 74366f8126..0b760581b1 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py@@ -3,16 +3,13 @@ from django.utils.text import slugifyfrom .....attribute.error_codes import AttributeErrorCodefrom ....tests.utils import get_graphql_content-from ...enums import AttributeTypeEnum+from ...enums import AttributeInputTypeEnum, AttributeTypeEnumCREATE_ATTRIBUTE_MUTATION = """mutation createAttribute(- $name: String!, $slug: String, $type: AttributeTypeEnum!,- $values: [AttributeValueCreateInput]+ $input: AttributeCreateInput!){- attributeCreate(input: {- name: $name, values: $values, slug: $slug, type: $type,- }) {+ attributeCreate(input: $input) {attributeErrors {fieldmessage@@ -22,6 +19,11 @@ CREATE_ATTRIBUTE_MUTATION = """nameslugtype+ inputType+ filterableInStorefront+ filterableInDashboard+ availableInGrid+ storefrontSearchPositionvalues {nameslug@@ -40,7 +42,9 @@ CREATE_ATTRIBUTE_MUTATION = """def test_create_attribute_and_attribute_values(- staff_api_client, permission_manage_product_types_and_attributes+ staff_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_products,):# givenquery = CREATE_ATTRIBUTE_MUTATION@@ -48,14 +52,21 @@ def test_create_attribute_and_attribute_values(attribute_name = "Example name"name = "Value name"variables = {- "name": attribute_name,- "values": [{"name": name}],- "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "input": {+ "name": attribute_name,+ "values": [{"name": name}],+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ }}# whenresponse = staff_api_client.post_graphql(- query, variables, permissions=[permission_manage_product_types_and_attributes]+ query,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],)# then@@ -79,8 +90,57 @@ def test_create_attribute_and_attribute_values(assert data["attribute"]["values"][0]["slug"] == slugify(name)+def test_create_attribute_with_file_input_type(+ staff_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_products,+):+ # given+ query = CREATE_ATTRIBUTE_MUTATION++ attribute_name = "Example name"+ variables = {+ "input": {+ "name": attribute_name,+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "inputType": AttributeInputTypeEnum.FILE.name,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["attributeCreate"]["attributeErrors"]+ data = content["data"]["attributeCreate"]++ # Check if the attribute was correctly created+ assert data["attribute"]["name"] == attribute_name+ assert data["attribute"]["slug"] == slugify(+ attribute_name+ ), "The default slug should be the slugified name"+ assert (+ data["attribute"]["productTypes"]["edges"] == []+ ), "The attribute should not have been assigned to a product type"++ # Check if the attribute values were correctly created+ assert len(data["attribute"]["values"]) == 0+ assert data["attribute"]["type"] == AttributeTypeEnum.PRODUCT_TYPE.name+ assert data["attribute"]["inputType"] == AttributeInputTypeEnum.FILE.name++def test_create_page_attribute_and_attribute_values(- staff_api_client, permission_manage_page_types_and_attributes+ staff_api_client,+ permission_manage_page_types_and_attributes,+ permission_manage_pages,):# givenquery = CREATE_ATTRIBUTE_MUTATION@@ -88,14 +148,21 @@ def test_create_page_attribute_and_attribute_values(attribute_name = "Example name"name = "Value name"variables = {- "name": attribute_name,- "values": [{"name": name}],- "type": AttributeTypeEnum.PAGE_TYPE.name,+ "input": {+ "name": attribute_name,+ "values": [{"name": name}],+ "type": AttributeTypeEnum.PAGE_TYPE.name,+ }}# whenresponse = staff_api_client.post_graphql(- query, variables, permissions=[permission_manage_page_types_and_attributes]+ query,+ variables,+ permissions=[+ permission_manage_page_types_and_attributes,+ permission_manage_pages,+ ],)# then@@ -111,6 +178,10 @@ def test_create_page_attribute_and_attribute_values(assert (data["attribute"]["productTypes"]["edges"] == []), "The attribute should not have been assigned to a product type"+ assert data["attribute"]["filterableInStorefront"] is False+ assert data["attribute"]["filterableInDashboard"] is False+ assert data["attribute"]["availableInGrid"] is False+ assert data["attribute"]["storefrontSearchPosition"] == 0# Check if the attribute values were correctly createdassert len(data["attribute"]["values"]) == 1@@ -119,6 +190,194 @@ def test_create_page_attribute_and_attribute_values(assert data["attribute"]["values"][0]["slug"] == slugify(name)+def test_create_attribute_with_file_input_type_and_values(+ staff_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_products,+):+ # given+ query = CREATE_ATTRIBUTE_MUTATION++ attribute_name = "Example name"+ name = "Value name"+ variables = {+ "input": {+ "name": attribute_name,+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "values": [{"name": name}],+ "inputType": AttributeInputTypeEnum.FILE.name,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeCreate"]+ errors = data["attributeErrors"]++ assert not data["attribute"]+ assert len(errors) == 1+ assert errors[0]["field"] == "values"+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name+++def test_create_attribute_with_file_input_type_correct_attribute_settings(+ staff_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_products,+):+ # given+ query = CREATE_ATTRIBUTE_MUTATION++ attribute_name = "Example name"+ variables = {+ "input": {+ "name": attribute_name,+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "inputType": AttributeInputTypeEnum.FILE.name,+ "filterableInStorefront": False,+ "filterableInDashboard": False,+ "availableInGrid": False,+ "storefrontSearchPosition": 0,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["attributeCreate"]["attributeErrors"]+ data = content["data"]["attributeCreate"]++ # Check if the attribute was correctly created+ assert data["attribute"]["name"] == attribute_name+ assert data["attribute"]["slug"] == slugify(+ attribute_name+ ), "The default slug should be the slugified name"+ assert (+ data["attribute"]["productTypes"]["edges"] == []+ ), "The attribute should not have been assigned to a product type"++ # Check if the attribute values were correctly created+ assert len(data["attribute"]["values"]) == 0+ assert data["attribute"]["type"] == AttributeTypeEnum.PRODUCT_TYPE.name+ assert data["attribute"]["inputType"] == AttributeInputTypeEnum.FILE.name+++def test_create_attribute_with_file_input_type_and_invalid_settings(+ staff_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_products,+):+ # given+ query = CREATE_ATTRIBUTE_MUTATION++ attribute_name = "Example name"+ variables = {+ "input": {+ "name": attribute_name,+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "inputType": AttributeInputTypeEnum.FILE.name,+ "filterableInStorefront": True,+ "filterableInDashboard": True,+ "availableInGrid": True,+ "storefrontSearchPosition": 1,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeCreate"]+ errors = data["attributeErrors"]++ assert not data["attribute"]+ assert len(errors) == 4+ assert {error["field"] for error in errors} == {+ "filterableInStorefront",+ "filterableInDashboard",+ "availableInGrid",+ "storefrontSearchPosition",+ }+ assert {error["code"] for error in errors} == {AttributeErrorCode.INVALID.name}+++ "field, value",+ [+ ("filterableInStorefront", True),+ ("filterableInDashboard", True),+ ("availableInGrid", True),+ ("storefrontSearchPosition", 4),+ ],+)+def test_create_attribute_with_file_input_type_and_invalid_one_settings_value(+ field,+ value,+ staff_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_products,+):+ # given+ query = CREATE_ATTRIBUTE_MUTATION++ attribute_name = "Example name"+ variables = {+ "input": {+ "name": attribute_name,+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "inputType": AttributeInputTypeEnum.FILE.name,+ field: value,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeCreate"]+ errors = data["attributeErrors"]++ assert not data["attribute"]+ assert len(errors) == 1+ assert errors[0]["field"] == field+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name++@pytest.mark.parametrize("input_slug, expected_slug",(@@ -131,6 +390,7 @@ def test_create_page_attribute_and_attribute_values(def test_create_attribute_with_given_slug(staff_api_client,permission_manage_product_types_and_attributes,+ permission_manage_products,input_slug,expected_slug,):@@ -170,21 +430,30 @@ def test_create_attribute_with_given_slug(def test_create_attribute_value_name_and_slug_with_unicode(- staff_api_client, permission_manage_product_types_and_attributes+ staff_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_products,):# givenquery = CREATE_ATTRIBUTE_MUTATIONname = "わたし わ にっぽん です"slug = "わたし-わ-にっぽん-で"variables = {- "name": name,- "slug": slug,- "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "input": {+ "name": name,+ "slug": slug,+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ }}# whenresponse = staff_api_client.post_graphql(- query, variables, permissions=[permission_manage_product_types_and_attributes]+ query,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],)# then@@ -219,19 +488,27 @@ def test_create_attribute_and_attribute_values_errors(error_msg,error_code,permission_manage_product_types_and_attributes,+ permission_manage_products,product_type,):# givenquery = CREATE_ATTRIBUTE_MUTATIONvariables = {- "name": "Example name",- "type": AttributeTypeEnum.PRODUCT_TYPE.name,- "values": [{"name": name_1}, {"name": name_2}],+ "input": {+ "name": "Example name",+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "values": [{"name": name_1}, {"name": name_2}],+ }}# whenresponse = staff_api_client.post_graphql(- query, variables, permissions=[permission_manage_product_types_and_attributes]+ query,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],)# thendiff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_update.pyindex 9720f83b8d..8c9ee0209f 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_update.py@@ -7,13 +7,11 @@ from ....tests.utils import get_graphql_contentUPDATE_ATTRIBUTE_MUTATION = """mutation updateAttribute(- $id: ID!, $name: String!, $addValues: [AttributeValueCreateInput]!,- $removeValues: [ID]!) {+ $id: ID!, $input: AttributeUpdateInput!+ ) {attributeUpdate(id: $id,- input: {- name: $name, addValues: $addValues,- removeValues: $removeValues}) {+ input: $input) {attributeErrors {fieldmessage@@ -48,7 +46,10 @@ def test_update_attribute_name(name = "Wings name"slug = attribute.slugnode_id = graphene.Node.to_global_id("Attribute", attribute.id)- variables = {"name": name, "id": node_id, "addValues": [], "removeValues": []}+ variables = {+ "input": {"name": name, "addValues": [], "removeValues": []},+ "id": node_id,+ }# whenresponse = staff_api_client.post_graphql(@@ -76,10 +77,12 @@ def test_update_attribute_remove_and_add_values(attribute_value_id = attribute.values.first().idvalue_id = graphene.Node.to_global_id("AttributeValue", attribute_value_id)variables = {- "name": name,"id": node_id,- "addValues": [{"name": attribute_value_name}],- "removeValues": [value_id],+ "input": {+ "name": name,+ "addValues": [{"name": attribute_value_name}],+ "removeValues": [value_id],+ },}# when@@ -109,10 +112,12 @@ def test_update_empty_attribute_and_add_values(attribute_value_name = "Yellow Color"node_id = graphene.Node.to_global_id("Attribute", attribute.id)variables = {- "name": name,"id": node_id,- "addValues": [{"name": attribute_value_name}],- "removeValues": [],+ "input": {+ "name": name,+ "addValues": [{"name": attribute_value_name}],+ "removeValues": [],+ },}# when@@ -127,6 +132,117 @@ def test_update_empty_attribute_and_add_values(assert attribute.values.filter(name=attribute_value_name).exists()+def test_update_attribute_with_file_input_type(+ staff_api_client,+ file_attribute_with_file_input_type_without_values,+ permission_manage_product_types_and_attributes,+):+ # given+ query = UPDATE_ATTRIBUTE_MUTATION+ attribute = file_attribute_with_file_input_type_without_values+ name = "Wings name"+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)++ variables = {+ "id": node_id,+ "input": {"name": name, "addValues": [], "removeValues": []},+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )++ # then+ content = get_graphql_content(response)+ attribute.refresh_from_db()+ data = content["data"]["attributeUpdate"]+ assert not data["attributeErrors"]+ assert data["attribute"]["name"] == name == attribute.name+++def test_update_attribute_with_file_input_type_and_values(+ staff_api_client,+ file_attribute_with_file_input_type_without_values,+ permission_manage_product_types_and_attributes,+):+ # given+ query = UPDATE_ATTRIBUTE_MUTATION+ attribute = file_attribute_with_file_input_type_without_values+ name = "Wings name"+ attribute_value_name = "Test file"+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)++ variables = {+ "id": node_id,+ "input": {+ "name": name,+ "addValues": [{"name": attribute_value_name}],+ "removeValues": [],+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )++ # then+ content = get_graphql_content(response)+ attribute.refresh_from_db()+ data = content["data"]["attributeUpdate"]+ errors = data["attributeErrors"]+ assert not data["attribute"]+ assert len(errors) == 1+ assert errors[0]["field"] == "addValues"+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name+++def test_update_attribute_with_file_input_type_invalid_settings(+ staff_api_client,+ file_attribute_with_file_input_type_without_values,+ permission_manage_product_types_and_attributes,+):+ # given+ query = UPDATE_ATTRIBUTE_MUTATION+ attribute = file_attribute_with_file_input_type_without_values+ name = "Wings name"+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)++ variables = {+ "id": node_id,+ "input": {+ "name": name,+ "addValues": [],+ "removeValues": [],+ "filterableInStorefront": True,+ "filterableInDashboard": True,+ "availableInGrid": True,+ "storefrontSearchPosition": 3,+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )++ # then+ content = get_graphql_content(response)+ attribute.refresh_from_db()+ data = content["data"]["attributeUpdate"]+ errors = data["attributeErrors"]+ assert not data["attribute"]+ assert len(errors) == 4+ assert {error["field"] for error in errors} == {+ "filterableInStorefront",+ "filterableInDashboard",+ "availableInGrid",+ "storefrontSearchPosition",+ }+ assert {error["code"] for error in errors} == {AttributeErrorCode.INVALID.name}++UPDATE_ATTRIBUTE_SLUG_MUTATION = """mutation updateAttribute($id: ID!, $slug: String) {@@ -335,10 +451,12 @@ def test_update_attribute_and_add_attribute_values_errors(attribute = color_attributenode_id = graphene.Node.to_global_id("Attribute", attribute.id)variables = {- "name": "Example name","id": node_id,- "removeValues": [],- "addValues": [{"name": name_1}, {"name": name_2}],+ "input": {+ "name": "Example name",+ "removeValues": [],+ "addValues": [{"name": name_1}, {"name": name_2}],+ },}# when@@ -368,10 +486,8 @@ def test_update_attribute_and_remove_others_attribute_value(size_attribute = size_attribute.values.first()attr_id = graphene.Node.to_global_id("AttributeValue", size_attribute.pk)variables = {- "name": "Example name","id": node_id,- "addValues": [],- "removeValues": [attr_id],+ "input": {"name": "Example name", "addValues": [], "removeValues": [attr_id]},}# whendiff --git a/saleor/graphql/attribute/tests/queries/test_attribute_query.py b/saleor/graphql/attribute/tests/queries/test_attribute_query.pyindex 23477505cd..3ded69852a 100644--- a/saleor/graphql/attribute/tests/queries/test_attribute_query.py+++ b/saleor/graphql/attribute/tests/queries/test_attribute_query.py@@ -69,6 +69,10 @@ query($id: ID!) {values {sluginputType+ file {+ url+ contentType+ }}valueRequiredvisibleInStorefront@@ -202,6 +206,49 @@ def test_get_single_page_attribute_by_staff_no_perm(assert_no_permission(response)+def test_get_single_product_attribute_with_file_value(+ staff_api_client, file_attribute, permission_manage_products, media_root+):+ staff_api_client.user.user_permissions.add(permission_manage_products)+ attribute_gql_id = graphene.Node.to_global_id("Attribute", file_attribute.id)+ query = QUERY_ATTRIBUTE+ content = get_graphql_content(+ staff_api_client.post_graphql(query, {"id": attribute_gql_id})+ )+ attribute_data = content["data"]["attribute"]++ assert attribute_data, "Should have found an attribute"+ assert attribute_data["id"] == attribute_gql_id+ assert attribute_data["slug"] == file_attribute.slug+ assert attribute_data["valueRequired"] == file_attribute.value_required+ assert attribute_data["visibleInStorefront"] == file_attribute.visible_in_storefront+ assert (+ attribute_data["filterableInStorefront"]+ == file_attribute.filterable_in_storefront+ )+ assert (+ attribute_data["filterableInDashboard"]+ == file_attribute.filterable_in_dashboard+ )+ assert attribute_data["availableInGrid"] == file_attribute.available_in_grid+ assert (+ attribute_data["storefrontSearchPosition"]+ == file_attribute.storefront_search_position+ )+ assert len(attribute_data["values"]) == file_attribute.values.count()+ attribute_value_data = []+ for value in file_attribute.values.all():+ data = {+ "slug": value.slug,+ "inputType": value.input_type.upper(),+ "file": {"url": value.file_url, "contentType": value.content_type},+ }+ attribute_value_data.append(data)++ for data in attribute_value_data:+ assert data in attribute_data["values"]++QUERY_ATTRIBUTES = """query {attributes(first: 20) {diff --git a/saleor/graphql/attribute/tests/test_utils.py b/saleor/graphql/attribute/tests/test_utils.pynew file mode 100644index 0000000000..ccc72e2af3--- /dev/null+++ b/saleor/graphql/attribute/tests/test_utils.py@@ -0,0 +1,1038 @@+import graphene++from ....attribute import AttributeInputType+from ....page.error_codes import PageErrorCode+from ....product.error_codes import ProductErrorCode+from ...product.mutations.products import AttrValuesInput+from ..utils import validate_attributes_input+++def test_validate_attributes_input_for_product(+ weight_attribute, color_attribute, product_type+):+ # given+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required"])++ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=["a"],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ values=["b"],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ variant_validation=False,+ )++ # then+ assert not errors+++def test_validate_attributes_input_for_product_no_values_given(+ weight_attribute, color_attribute, product_type+):+ # given+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required"])++ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=[],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ values=[],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ variant_validation=False,+ )++ # then+ assert len(errors) == 1+ error = errors[0]+ assert error.code == ProductErrorCode.REQUIRED.value+ assert set(error.params["attributes"]) == {+ graphene.Node.to_global_id("Attribute", attr.pk)+ for attr in [weight_attribute, color_attribute]+ }+++def test_validate_attributes_input_for_product_too_many_values_given(+ weight_attribute, color_attribute, product_type+):+ # given+ color_attribute.input_type = AttributeInputType.DROPDOWN+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required", "input_type"])++ weight_attribute.value_required = True+ weight_attribute.input_type = AttributeInputType.MULTISELECT+ weight_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=["abc", "efg"],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ values=["a", "b"],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ variant_validation=False,+ )++ # then+ assert len(errors) == 1+ error = errors[0]+ assert error.code == ProductErrorCode.INVALID.value+ assert error.params["attributes"] == [+ graphene.Node.to_global_id("Attribute", color_attribute.pk)+ ]+++def test_validate_attributes_input_for_product_empty_values_given(+ weight_attribute, color_attribute, product_type+):+ # given+ color_attribute.input_type = AttributeInputType.DROPDOWN+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required", "input_type"])++ weight_attribute.value_required = True+ weight_attribute.input_type = AttributeInputType.MULTISELECT+ weight_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=["a", None],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ values=[" "],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ variant_validation=False,+ )++ # then+ assert len(errors) == 1+ error = errors[0]+ assert error.code == ProductErrorCode.REQUIRED.value+ assert set(error.params["attributes"]) == {+ graphene.Node.to_global_id("Attribute", attr.pk)+ for attr in [weight_attribute, color_attribute]+ }+++def test_validate_attributes_input_for_product_lack_of_required_attribute(+ weight_attribute, color_attribute, product_type+):+ # given+ product_attributes = product_type.product_attributes.all()+ attr = product_attributes.first()+ attr.value_required = True+ attr.save(update_fields=["value_required"])++ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=["a"],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_attributes,+ is_page_attributes=False,+ variant_validation=False,+ )++ # then+ assert len(errors) == 1+ error = errors[0]+ assert error.code == ProductErrorCode.REQUIRED.value+ assert set(error.params["attributes"]) == {+ graphene.Node.to_global_id("Attribute", attr.pk)+ }+++def test_validate_attributes_input_for_product_multiply_errors(+ weight_attribute, color_attribute, product_type+):+ # given+ color_attribute.input_type = AttributeInputType.DROPDOWN+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required", "input_type"])++ weight_attribute.value_required = True+ weight_attribute.input_type = AttributeInputType.MULTISELECT+ weight_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=[None],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ values=["a", "b"],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ variant_validation=False,+ )++ # then+ assert len(errors) == 2+ assert {error.code for error in errors} == {+ ProductErrorCode.INVALID.value,+ ProductErrorCode.REQUIRED.value,+ }+ assert {attr for error in errors for attr in error.params["attributes"]} == {+ graphene.Node.to_global_id("Attribute", attr.pk)+ for attr in [weight_attribute, color_attribute]+ }+++def test_validate_attributes_input_for_page(+ weight_attribute, color_attribute, page_type+):+ # given+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required"])++ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=["a"],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ values=["b"],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ page_type.page_attributes.all(),+ is_page_attributes=True,+ variant_validation=False,+ )++ # then+ assert not errors+++def test_validate_attributes_input_for_page_no_values_given(+ weight_attribute, color_attribute, page_type+):+ # given+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required"])++ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=[],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ values=[],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ page_type.page_attributes.all(),+ is_page_attributes=True,+ variant_validation=False,+ )++ # then+ assert len(errors) == 1+ error = errors[0]+ assert error.code == PageErrorCode.REQUIRED.value+ assert set(error.params["attributes"]) == {+ graphene.Node.to_global_id("Attribute", attr.pk)+ for attr in [weight_attribute, color_attribute]+ }+++def test_validate_attributes_input_for_page_too_many_values_given(+ weight_attribute, color_attribute, page_type+):+ # given+ color_attribute.input_type = AttributeInputType.DROPDOWN+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required", "input_type"])++ weight_attribute.value_required = True+ weight_attribute.input_type = AttributeInputType.MULTISELECT+ weight_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=["abc", "efg"],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ values=["a", "b"],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ page_type.page_attributes.all(),+ is_page_attributes=True,+ variant_validation=False,+ )++ # then+ assert len(errors) == 1+ error = errors[0]+ assert error.code == PageErrorCode.INVALID.value+ assert error.params["attributes"] == [+ graphene.Node.to_global_id("Attribute", color_attribute.pk)+ ]+++def test_validate_attributes_input_for_page_empty_values_given(+ weight_attribute, color_attribute, page_type+):+ # given+ color_attribute.input_type = AttributeInputType.DROPDOWN+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required", "input_type"])++ weight_attribute.value_required = True+ weight_attribute.input_type = AttributeInputType.MULTISELECT+ weight_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=["a", None],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ values=[" "],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ page_type.page_attributes.all(),+ is_page_attributes=True,+ variant_validation=False,+ )++ # then+ assert len(errors) == 1+ error = errors[0]+ assert error.code == PageErrorCode.REQUIRED.value+ assert set(error.params["attributes"]) == {+ graphene.Node.to_global_id("Attribute", attr.pk)+ for attr in [weight_attribute, color_attribute]+ }+++def test_validate_attributes_input_for_page_lack_of_required_attribute(+ weight_attribute, color_attribute, page_type+):+ # given+ page_attributes = page_type.page_attributes.all()+ attr = page_attributes.first()+ attr.value_required = True+ attr.save(update_fields=["value_required"])++ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=["a"],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data, page_attributes, is_page_attributes=True, variant_validation=False+ )++ # then+ assert len(errors) == 1+ error = errors[0]+ assert error.code == PageErrorCode.REQUIRED.value+ assert set(error.params["attributes"]) == {+ graphene.Node.to_global_id("Attribute", attr.pk)+ }+++def test_validate_attributes_input_for_page_multiply_errors(+ weight_attribute, color_attribute, page_type+):+ # given+ color_attribute.input_type = AttributeInputType.DROPDOWN+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required", "input_type"])++ weight_attribute.value_required = True+ weight_attribute.input_type = AttributeInputType.MULTISELECT+ weight_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=[None],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ values=["a", "b"],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ page_type.page_attributes.all(),+ is_page_attributes=True,+ variant_validation=False,+ )++ # then+ assert len(errors) == 2+ assert {error.code for error in errors} == {+ PageErrorCode.INVALID.value,+ PageErrorCode.REQUIRED.value,+ }+ assert {attr for error in errors for attr in error.params["attributes"]} == {+ graphene.Node.to_global_id("Attribute", attr.pk)+ for attr in [weight_attribute, color_attribute]+ }+++def test_validate_attributes_input(weight_attribute, color_attribute, product_type):+ # given+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required"])++ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=["a"],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ values=["b"],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ attributes = product_type.variant_attributes.all()++ # when+ errors = validate_attributes_input(+ input_data, attributes, is_page_attributes=False, variant_validation=True+ )++ # then+ assert not errors+++def test_validate_attributes_input_no_values_given(+ weight_attribute, color_attribute, product_type+):+ # given+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required"])++ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=[],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ values=[],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ attributes = product_type.variant_attributes.all()++ # when+ errors = validate_attributes_input(+ input_data, attributes, is_page_attributes=False, variant_validation=True+ )++ # then+ assert len(errors) == 1+ error = errors[0]+ assert error.code == ProductErrorCode.REQUIRED.value+ assert set(error.params["attributes"]) == {+ graphene.Node.to_global_id("Attribute", attr.pk)+ for attr in [weight_attribute, color_attribute]+ }+++def test_validate_not_required_variant_selection_attributes_input_no_values_given(+ weight_attribute, color_attribute, product_type+):+ # given+ color_attribute.value_required = False+ color_attribute.input_type = AttributeInputType.MULTISELECT+ color_attribute.save(update_fields=["value_required", "input_type"])++ weight_attribute.value_required = False+ weight_attribute.input_type = AttributeInputType.MULTISELECT+ weight_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=[],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ values=[],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ attributes = product_type.variant_attributes.all()++ # when+ errors = validate_attributes_input(+ input_data, attributes, is_page_attributes=False, variant_validation=True+ )++ # then+ assert not errors+++def test_validate_attributes_input_too_many_values_given(+ weight_attribute, color_attribute, product_type+):+ # given+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required"])++ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=["abc", "efg"],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ values=["a", "b"],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ attributes = product_type.variant_attributes.all()++ # when+ errors = validate_attributes_input(+ input_data, attributes, is_page_attributes=False, variant_validation=True+ )++ # then+ assert len(errors) == 1+ error = errors[0]+ assert error.code == ProductErrorCode.INVALID.value+ assert set(error.params["attributes"]) == {+ graphene.Node.to_global_id("Attribute", attr.pk)+ for attr in [weight_attribute, color_attribute]+ }+++def test_validate_attributes_input_empty_values_given(+ weight_attribute, color_attribute, product_type+):+ # given+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required", "input_type"])++ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=[None],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ values=[" "],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ attributes = product_type.variant_attributes.all()++ # when+ errors = validate_attributes_input(+ input_data, attributes, is_page_attributes=False, variant_validation=True+ )++ # then+ assert len(errors) == 1+ error = errors[0]+ assert error.code == ProductErrorCode.REQUIRED.value+ assert set(error.params["attributes"]) == {+ graphene.Node.to_global_id("Attribute", attr.pk)+ for attr in [weight_attribute, color_attribute]+ }+++def test_validate_attributes_input_multiply_errors(+ weight_attribute, color_attribute, product_type+):+ # given+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required", "input_type"])++ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=[None],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ values=["a", "b"],+ file_url=None,+ content_type=None,+ ),+ ),+ ]++ attributes = product_type.variant_attributes.all()++ # when+ errors = validate_attributes_input(+ input_data, attributes, is_page_attributes=False, variant_validation=True+ )++ # then+ assert len(errors) == 2+ assert {error.code for error in errors} == {+ ProductErrorCode.INVALID.value,+ ProductErrorCode.REQUIRED.value,+ }+ assert {attr for error in errors for attr in error.params["attributes"]} == {+ graphene.Node.to_global_id("Attribute", attr.pk)+ for attr in [weight_attribute, color_attribute]+ }+++def test_validate_attributes_with_file_input_type_for_product(+ weight_attribute, file_attribute, product_type+):+ # given+ file_attribute.value_required = True+ file_attribute.save(update_fields=["value_required"])++ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=["a"],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ file_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", file_attribute.pk),+ values=[],+ file_url="test_file.jpeg",+ content_type="image/jpeg",+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ variant_validation=False,+ )++ # then+ assert not errors+++def test_validate_attributes_with_file_input_type_for_product_no_file_given(+ weight_attribute, file_attribute, product_type+):+ # given+ file_attribute.value_required = True+ file_attribute.save(update_fields=["value_required"])++ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=["a"],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ file_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", file_attribute.pk),+ values=[],+ file_url="",+ content_type="image/jpeg",+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ variant_validation=False,+ )++ # then+ assert len(errors) == 1+ error = errors[0]+ assert error.code == ProductErrorCode.REQUIRED.value+ assert set(error.params["attributes"]) == {+ graphene.Node.to_global_id("Attribute", file_attribute.pk)+ }+++def test_validate_not_required_attrs_with_file_input_type_for_product_no_file_given(+ weight_attribute, file_attribute, product_type+):+ # given+ file_attribute.value_required = False+ file_attribute.save(update_fields=["value_required"])++ weight_attribute.value_required = False+ weight_attribute.save(update_fields=["value_required"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=["a"],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ file_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", file_attribute.pk),+ values=[],+ file_url="",+ content_type="image/jpeg",+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ variant_validation=False,+ )++ # then+ assert not errors+++def test_validate_attributes_with_file_input_type_for_product_empty_file_value(+ weight_attribute, file_attribute, product_type+):+ # given+ file_attribute.value_required = True+ file_attribute.save(update_fields=["value_required"])++ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ values=["a"],+ file_url=None,+ content_type=None,+ ),+ ),+ (+ file_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", file_attribute.pk),+ values=[],+ file_url=" ",+ content_type="image/jpeg",+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ variant_validation=False,+ )++ # then+ assert len(errors) == 1+ error = errors[0]+ assert error.code == ProductErrorCode.REQUIRED.value+ assert set(error.params["attributes"]) == {+ graphene.Node.to_global_id("Attribute", file_attribute.pk)+ }diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.pyindex dfd19355f4..4aadf57486 100644--- a/saleor/graphql/attribute/types.py+++ b/saleor/graphql/attribute/types.py@@ -4,6 +4,7 @@ import graphenefrom ...attribute import modelsfrom ..core.connection import CountableDjangoObjectType+from ..core.types import Filefrom ..decorators import (check_attribute_required_permissions,check_attribute_value_required_permissions,@@ -43,6 +44,9 @@ class AttributeValue(CountableDjangoObjectType):AttributeValueTranslation, type_name="attribute value")input_type = AttributeInputTypeEnum(description=AttributeDescriptions.INPUT_TYPE)+ file = graphene.Field(+ File, description=AttributeValueDescriptions.FILE, required=False+ )class Meta:description = "Represents a value of an attribute."@@ -59,6 +63,12 @@ class AttributeValue(CountableDjangoObjectType):def resolve_input_type(root: models.AttributeValue, *_args):return root.input_type+ @staticmethod+ def resolve_file(root: models.AttributeValue, *_args):+ if not root.file_url:+ return+ return File(url=root.file_url, content_type=root.content_type)+class Attribute(CountableDjangoObjectType):input_type = AttributeInputTypeEnum(description=AttributeDescriptions.INPUT_TYPE)diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.pynew file mode 100644index 0000000000..b56d5967d0--- /dev/null+++ b/saleor/graphql/attribute/utils.py@@ -0,0 +1,488 @@+from collections import defaultdict, namedtuple+from typing import TYPE_CHECKING, Dict, Iterable, List, Tuple, Union++import graphene+from django.core.exceptions import ValidationError+from django.db.models import Q+from django.utils.text import slugify+from graphql_relay import from_global_id++from ...attribute import AttributeInputType, AttributeType, models as attribute_models+from ...attribute.utils import associate_attribute_values_to_instance+from ...core.utils import generate_unique_slug+from ...page import models as page_models+from ...page.error_codes import PageErrorCode+from ...product import models as product_models+from ...product.error_codes import ProductErrorCode++if TYPE_CHECKING:+ from django.db.models import QuerySet+ from ...attribute.models import Attribute+++AttrValuesInput = namedtuple(+ "AttrValuesInput", ["global_id", "values", "file_url", "content_type"]+)+T_INSTANCE = Union[+ product_models.Product, product_models.ProductVariant, page_models.Page+]+T_INPUT_MAP = List[Tuple[attribute_models.Attribute, AttrValuesInput]]+++class AttributeAssignmentMixin:+ """Handles cleaning of the attribute input and creating the proper relations.++ 1. You should first call ``clean_input``, to transform and attempt to resolve+ the provided input into actual objects. It will then perform a few+ checks to validate the operations supplied by the user are possible and allowed.+ 2. Once everything is ready and all your data is saved inside a transaction,+ you shall call ``save`` with the cleaned input to build all the required+ relations. Once the ``save`` call is done, you are safe from continuing working+ or to commit the transaction.++ Note: you shall never call ``save`` outside of a transaction and never before+ the targeted instance owns a primary key. Failing to do so, the relations will+ be unable to build or might only be partially built.+ """++ @classmethod+ def _resolve_attribute_nodes(+ cls,+ qs: "QuerySet",+ *,+ global_ids: List[str],+ pks: Iterable[int],+ slugs: Iterable[str],+ ):+ """Retrieve attributes nodes from given global IDs and/or slugs."""+ qs = qs.filter(Q(pk__in=pks) | Q(slug__in=slugs))+ nodes: List[attribute_models.Attribute] = list(qs)++ if not nodes:+ raise ValidationError(+ (+ f"Could not resolve to a node: ids={global_ids}"+ f" and slugs={list(slugs)}"+ ),+ code=ProductErrorCode.NOT_FOUND.value,+ )++ nodes_pk_list = set()+ nodes_slug_list = set()+ for node in nodes:+ nodes_pk_list.add(node.pk)+ nodes_slug_list.add(node.slug)++ for pk, global_id in zip(pks, global_ids):+ if pk not in nodes_pk_list:+ raise ValidationError(+ f"Could not resolve {global_id!r} to Attribute",+ code=ProductErrorCode.NOT_FOUND.value,+ )++ for slug in slugs:+ if slug not in nodes_slug_list:+ raise ValidationError(+ f"Could not resolve slug {slug!r} to Attribute",+ code=ProductErrorCode.NOT_FOUND.value,+ )++ return nodes++ @classmethod+ def _resolve_attribute_global_id(cls, global_id: str) -> int:+ """Resolve an Attribute global ID into an internal ID (int)."""+ graphene_type, internal_id = from_global_id(global_id) # type: str, str+ if graphene_type != "Attribute":+ raise ValidationError(+ f"Must receive an Attribute id, got {graphene_type}.",+ code=ProductErrorCode.INVALID.value,+ )+ if not internal_id.isnumeric():+ raise ValidationError(+ f"An invalid ID value was passed: {global_id}",+ code=ProductErrorCode.INVALID.value,+ )+ return int(internal_id)++ @classmethod+ def _pre_save_values(+ cls, attribute: attribute_models.Attribute, attr_values: AttrValuesInput+ ):+ """Lazy-retrieve or create the database objects from the supplied raw values."""+ get_or_create = attribute.values.get_or_create+ return tuple(+ get_or_create(+ attribute=attribute,+ slug=slugify(value, allow_unicode=True),+ defaults={"name": value},+ )[0]+ for value in attr_values.values+ )++ @classmethod+ def _pre_save_file_value(+ cls,+ instance: T_INSTANCE,+ attribute: attribute_models.Attribute,+ attr_value: AttrValuesInput,+ ):+ """Create database file attribute value object from the supplied value.++ For every URL new value must be created as file attribute can be removed+ separately from every instance.+ """+ file_url = attr_value.file_url+ if not file_url:+ return tuple()+ name = file_url.split("/")[-1]+ # don't create ne value when assignment already exists+ value = cls._get_assigned_attribute_value_if_exists(+ instance, attribute, attr_value.file_url+ )+ if value is None:+ value = attribute_models.AttributeValue(+ attribute=attribute,+ file_url=file_url,+ name=name,+ content_type=attr_value.content_type,+ )+ value.slug = generate_unique_slug(value, name) # type: ignore+ value.save()+ return (value,)++ @classmethod+ def _get_assigned_attribute_value_if_exists(+ cls, instance: T_INSTANCE, attribute: attribute_models.Attribute, file_url+ ):+ assignment = instance.attributes.filter(+ assignment__attribute=attribute, values__file_url=file_url+ ).first()+ return (+ None+ if assignment is None+ else assignment.values.filter(file_url=file_url).first()+ )++ @classmethod+ def _validate_attributes_input(+ cls,+ cleaned_input: T_INPUT_MAP,+ attribute_qs: "QuerySet",+ *,+ is_variant: bool,+ is_page_attributes: bool+ ):+ """Check the cleaned attribute input.++ An Attribute queryset is supplied.++ - ensure all required attributes are passed+ - ensure the values are correct++ :raises ValidationError: when an invalid operation was found.+ """+ variant_validation = False+ if is_variant:+ qs = get_variant_selection_attributes(attribute_qs)+ if len(cleaned_input) < qs.count():+ raise ValidationError(+ "All variant selection attributes must take a value.",+ code=ProductErrorCode.REQUIRED.value,+ )+ variant_validation = True++ errors = validate_attributes_input(+ cleaned_input,+ attribute_qs,+ is_page_attributes=is_page_attributes,+ variant_validation=variant_validation,+ )++ if errors:+ raise ValidationError(errors)++ @classmethod+ def clean_input(+ cls,+ raw_input: dict,+ attributes_qs: "QuerySet",+ is_variant: bool = False,+ is_page_attributes: bool = False,+ ) -> T_INPUT_MAP:+ """Resolve and prepare the input for further checks.++ :param raw_input: The user's attributes input.+ :param attributes_qs:+ A queryset of attributes, the attribute values must be prefetched.+ Prefetch is needed by ``_pre_save_values`` during save.+ :param page_attributes: Whether the input is for page type or not.+ :param is_variant: Whether the input is for a variant or a product.++ :raises ValidationError: contain the message.+ :return: The resolved data+ """++ # Mapping to associate the input values back to the resolved attribute nodes+ pks = {}+ slugs = {}++ # Temporary storage of the passed ID for error reporting+ global_ids = []++ for attribute_input in raw_input:+ global_id = attribute_input.get("id")+ slug = attribute_input.get("slug")+ values = AttrValuesInput(+ global_id=global_id,+ values=attribute_input.get("values", []),+ file_url=attribute_input.get("file"),+ content_type=attribute_input.get("content_type"),+ )++ if global_id:+ internal_id = cls._resolve_attribute_global_id(global_id)+ global_ids.append(global_id)+ pks[internal_id] = values+ elif slug:+ slugs[slug] = values+ else:+ raise ValidationError(+ "You must whether supply an ID or a slug",+ code=ProductErrorCode.REQUIRED.value,+ )++ attributes = cls._resolve_attribute_nodes(+ attributes_qs, global_ids=global_ids, pks=pks.keys(), slugs=slugs.keys()+ )+ cleaned_input = []+ for attribute in attributes:+ key = pks.get(attribute.pk, None)++ # Retrieve the primary key by slug if it+ # was not resolved through a global ID but a slug+ if key is None:+ key = slugs[attribute.slug]++ cleaned_input.append((attribute, key))+ cls._validate_attributes_input(+ cleaned_input,+ attributes_qs,+ is_variant=is_variant,+ is_page_attributes=is_page_attributes,+ )++ return cleaned_input++ @classmethod+ def save(cls, instance: T_INSTANCE, cleaned_input: T_INPUT_MAP):+ """Save the cleaned input into the database against the given instance.++ Note: this should always be ran inside a transaction.++ :param instance: the product or variant to associate the attribute against.+ :param cleaned_input: the cleaned user input (refer to clean_attributes)+ """+ for attribute, attr_values in cleaned_input:+ if attribute.input_type == AttributeInputType.FILE:+ attribute_values = cls._pre_save_file_value(+ instance, attribute, attr_values+ )+ else:+ attribute_values = cls._pre_save_values(attribute, attr_values)+ associate_attribute_values_to_instance(+ instance, attribute, *attribute_values+ )+++def get_variant_selection_attributes(qs: "QuerySet"):+ return qs.filter(+ input_type__in=AttributeInputType.ALLOWED_IN_VARIANT_SELECTION,+ type=AttributeType.PRODUCT_TYPE,+ )+++class ProductAttributeInputErrors:+ ERROR_NO_VALUE_GIVEN = ValidationError(+ "Attribute expects a value but none were given",+ code=PageErrorCode.REQUIRED.value,+ )+ ERROR_DROPDOWN_GET_MORE_THAN_ONE_VALUE = ValidationError(+ "Attribute must take only one value", code=PageErrorCode.INVALID.value,+ )+ ERROR_BLANK_VALUE = ValidationError(+ "Attribute values cannot be blank", code=PageErrorCode.REQUIRED.value,+ )++ # file errors+ ERROR_NO_FILE_GIVEN = ValidationError(+ "Attribute file url cannot be blank", code=PageErrorCode.REQUIRED.value,+ )+ ERROR_BLANK_FILE_VALUE = ValidationError(+ "Attribute expects a file url but none were given",+ code=PageErrorCode.REQUIRED.value,+ )+++class PageAttributeInputErrors:+ ERROR_NO_VALUE_GIVEN = ValidationError(+ "Attribute expects a value but none were given",+ code=ProductErrorCode.REQUIRED.value,+ )+ ERROR_DROPDOWN_GET_MORE_THAN_ONE_VALUE = ValidationError(+ "Attribute must take only one value", code=ProductErrorCode.INVALID.value,+ )+ ERROR_BLANK_VALUE = ValidationError(+ "Attribute values cannot be blank", code=ProductErrorCode.REQUIRED.value,+ )++ # file errors+ ERROR_NO_FILE_GIVEN = ValidationError(+ "Attribute file url cannot be blank", code=ProductErrorCode.REQUIRED.value,+ )+ ERROR_BLANK_FILE_VALUE = ValidationError(+ "Attribute expects a file url but none were given",+ code=ProductErrorCode.REQUIRED.value,+ )+++def validate_attributes_input(+ input_data: List[Tuple["Attribute", "AttrValuesInput"]],+ attribute_qs: "QuerySet",+ *,+ is_page_attributes: bool,+ variant_validation: bool,+):+ """Validate attribute input.++ - ensure all required attributes are passed+ - ensure the values are correct for a products or a page+ """++ errors_data_structure = (+ PageAttributeInputErrors if is_page_attributes else ProductAttributeInputErrors+ )+ attribute_errors: Dict[ValidationError, List[str]] = defaultdict(list)+ for attribute, attr_values in input_data:+ # validation for file attribute+ if attribute.input_type == AttributeInputType.FILE:+ validate_file_attributes_input(+ attribute,+ attr_values,+ errors_data_structure,+ attribute_errors,+ variant_validation,+ )+ # validation for other input types+ else:+ validate_not_file_attributes_input(+ attribute,+ attr_values,+ errors_data_structure,+ attribute_errors,+ variant_validation,+ )++ errors = prepare_error_list_from_error_attribute_mapping(attribute_errors)+ if not variant_validation:+ errors = validate_required_attributes(+ input_data, attribute_qs, errors, is_page_attributes+ )++ return errors+++def validate_file_attributes_input(+ attribute: "Attribute",+ attr_values: "AttrValuesInput",+ errors_data_structure,+ attribute_errors: Dict[ValidationError, List[str]],+ variant_validation: bool,+):+ attribute_id = attr_values.global_id+ value = attr_values.file_url+ if not value:+ if attribute.value_required or (+ variant_validation and is_variant_selection_attribute(attribute)+ ):+ attribute_errors[errors_data_structure.ERROR_NO_FILE_GIVEN].append(+ attribute_id+ )+ elif not value.strip():+ attribute_errors[errors_data_structure.ERROR_BLANK_FILE_VALUE].append(+ attribute_id+ )+++def validate_not_file_attributes_input(+ attribute: "Attribute",+ attr_values: "AttrValuesInput",+ errors_data_structure,+ attribute_errors: Dict[ValidationError, List[str]],+ variant_validation: bool,+):+ attribute_id = attr_values.global_id+ if not attr_values.values:+ if attribute.value_required or (+ variant_validation and is_variant_selection_attribute(attribute)+ ):+ attribute_errors[errors_data_structure.ERROR_NO_VALUE_GIVEN].append(+ attribute_id+ )+ elif (+ attribute.input_type != AttributeInputType.MULTISELECT+ and len(attr_values.values) != 1+ ):+ attribute_errors[+ errors_data_structure.ERROR_DROPDOWN_GET_MORE_THAN_ONE_VALUE+ ].append(attribute_id)+ for value in attr_values.values:+ if value is None or not value.strip():+ attribute_errors[errors_data_structure.ERROR_BLANK_VALUE].append(+ attribute_id+ )+++def is_variant_selection_attribute(attribute: attribute_models.Attribute):+ return attribute.input_type in AttributeInputType.ALLOWED_IN_VARIANT_SELECTION+++def validate_required_attributes(+ input_data: List[Tuple["Attribute", "AttrValuesInput"]],+ attribute_qs: "QuerySet",+ errors: List[ValidationError],+ is_page_attributes: bool,+):+ """Ensure all required attributes are supplied."""++ supplied_attribute_pk = [attribute.pk for attribute, _ in input_data]+ error_code_enum = PageErrorCode if is_page_attributes else ProductErrorCode++ missing_required_attributes = attribute_qs.filter(+ Q(value_required=True) & ~Q(pk__in=supplied_attribute_pk)+ )++ if missing_required_attributes:+ ids = [+ graphene.Node.to_global_id("Attribute", attr.pk)+ for attr in missing_required_attributes+ ]+ error = ValidationError(+ "All attributes flagged as having a value required must be supplied.",+ code=error_code_enum.REQUIRED.value, # type: ignore+ params={"attributes": ids},+ )+ errors.append(error)++ return errors+++def prepare_error_list_from_error_attribute_mapping(+ attribute_errors: Dict[ValidationError, List[str]]+):+ errors = []+ for error, attributes in attribute_errors.items():+ error.params = {"attributes": attributes}+ errors.append(error)++ return errorsdiff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.pyindex fe6a1f2f23..f31a890c4e 100644--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@ -18,7 +18,7 @@ from ...core.exceptions import PermissionDeniedfrom ...core.permissions import AccountPermissionsfrom ..decorators import staff_member_or_app_requiredfrom ..utils import get_nodes-from .types import Error, Upload, UploadedFile+from .types import Error, File, Uploadfrom .types.common import UploadErrorfrom .utils import from_global_id_strict_type, snake_to_camel_casefrom .utils.error_codes import get_error_code_from_error@@ -624,7 +624,7 @@ class ModelBulkDeleteMutation(BaseBulkMutation):class FileUpload(BaseMutation):- uploaded_file = graphene.Field(UploadedFile)+ uploaded_file = graphene.Field(File)class Arguments:file = Upload(@@ -647,5 +647,5 @@ class FileUpload(BaseMutation):path = default_storage.save(file_data._name, file_data.file)return FileUpload(- uploaded_file=UploadedFile(url=path, content_type=file_data.content_type)+ uploaded_file=File(url=path, content_type=file_data.content_type))diff --git a/saleor/graphql/core/tests/test_file_upload.py b/saleor/graphql/core/tests/test_file_upload.pyindex 51ea405385..9d8b8cef2a 100644--- a/saleor/graphql/core/tests/test_file_upload.py+++ b/saleor/graphql/core/tests/test_file_upload.py@@ -22,7 +22,7 @@ mutation fileUpload($file: Upload!) {"""-def test_file_upload_by_staff(staff_api_client, media_root):+def test_file_upload_by_staff(staff_api_client, site_settings, media_root):# givenimage_file, image_name = create_image()variables = {"image": image_name}@@ -38,11 +38,11 @@ def test_file_upload_by_staff(staff_api_client, media_root):data = content["data"]["fileUpload"]errors = data["uploadErrors"]- expected_path = image_file._name+ expected_path = "http://testserver/media/" + image_file._nameassert not errorsassert data["uploadedFile"]["contentType"] == "image/png"assert data["uploadedFile"]["url"] == expected_path- assert default_storage.exists(expected_path)+ assert default_storage.exists(image_file._name)def test_file_upload_by_customer(user_api_client, media_root):@@ -76,11 +76,11 @@ def test_file_upload_by_app(app_api_client, media_root):data = content["data"]["fileUpload"]errors = data["uploadErrors"]- expected_path = image_file._name+ expected_path = "http://testserver/media/" + image_file._nameassert not errorsassert data["uploadedFile"]["contentType"] == "image/png"assert data["uploadedFile"]["url"] == expected_path- assert default_storage.exists(expected_path)+ assert default_storage.exists(image_file._name)def test_file_upload_by_superuser(superuser_api_client, media_root):@@ -99,8 +99,44 @@ def test_file_upload_by_superuser(superuser_api_client, media_root):data = content["data"]["fileUpload"]errors = data["uploadErrors"]- expected_path = image_file._name+ expected_path = "http://testserver/media/" + image_file._nameassert not errorsassert data["uploadedFile"]["contentType"] == "image/png"assert data["uploadedFile"]["url"] == expected_path- assert default_storage.exists(expected_path)+ assert default_storage.exists(image_file._name)+++def test_file_upload_file_with_the_same_name_already_exists(+ staff_api_client, media_root+):+ """Ensure that when the file with the same name as uploaded file,+ already exists, the file name will be renamed and save as another file.+ """+ # given+ image_file1, image_name1 = create_image()+ path = default_storage.save(image_file1._name, image_file1)++ image_file, image_name = create_image()+ assert image_file1 != image_file+ assert image_name == image_name1+ assert image_file._name == image_file1._name++ variables = {"image": image_name}+ body = get_multipart_request_body(+ FILE_UPLOAD_MUTATION, variables, image_file, image_name+ )++ # when+ response = staff_api_client.post_multipart(body)++ # then+ content = get_graphql_content(response)+ data = content["data"]["fileUpload"]+ errors = data["uploadErrors"]++ assert not errors+ assert data["uploadedFile"]["contentType"] == "image/png"+ file_url = data["uploadedFile"]["url"]+ assert file_url != "http://testserver/media/" + image_file._name+ assert file_url != "http://testserver/media/" + path+ assert default_storage.exists(file_url.replace("http://testserver/media/", ""))diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.pyindex 26a9fe8bf4..fbec73b59f 100644--- a/saleor/graphql/core/types/__init__.py+++ b/saleor/graphql/core/types/__init__.py@@ -2,12 +2,12 @@from .common import (CountryDisplay,Error,+ File,Image,LanguageDisplay,Permission,SeoInput,TaxType,- UploadedFile,Weight,)from .filter_input import ChannelFilterInputObjectType, FilterInputObjectTypediff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.pyindex 3225a3b9c4..365ee5ddb6 100644--- a/saleor/graphql/core/types/common.py+++ b/saleor/graphql/core/types/common.py@@ -1,4 +1,7 @@+from urllib.parse import urljoin+import graphene+from django.conf import settingsfrom ....product.templatetags.product_images import get_thumbnailfrom ...translations.enums import LanguageCodeEnum@@ -337,12 +340,16 @@ class Image(graphene.ObjectType):return Image(url, alt)-class UploadedFile(graphene.ObjectType):- url = graphene.String(required=True, description="The URL of the uploaded file.")+class File(graphene.ObjectType):+ url = graphene.String(required=True, description="The URL of the file.")content_type = graphene.String(- required=True, description="Content type of uploaded file."+ required=False, description="Content type of the file.")+ @staticmethod+ def resolve_url(root, info):+ return info.context.build_absolute_uri(urljoin(settings.MEDIA_URL, root.url))+class PriceRangeInput(graphene.InputObjectType):gte = graphene.Float(description="Price greater than or equal to.", required=False)diff --git a/saleor/graphql/page/mutations/pages.py b/saleor/graphql/page/mutations/pages.pyindex 0383ae2a2b..9d3957d436 100644--- a/saleor/graphql/page/mutations/pages.py+++ b/saleor/graphql/page/mutations/pages.py@@ -10,6 +10,7 @@ from ....attribute import AttributeTypefrom ....core.permissions import PagePermissions, PageTypePermissionsfrom ....page import modelsfrom ....page.error_codes import PageErrorCode+from ...attribute.utils import AttributeAssignmentMixinfrom ...core.mutations import ModelDeleteMutation, ModelMutationfrom ...core.types.common import PageError, SeoInputfrom ...core.utils import (@@ -17,7 +18,7 @@ from ...core.utils import (get_duplicates_ids,validate_slug_and_generate_if_needed,)-from ...product.mutations.products import AttributeAssignmentMixin, AttributeValueInput+from ...product.mutations.products import AttributeValueInputif TYPE_CHECKING:from ....attribute.models import Attributediff --git a/saleor/graphql/page/tests/test_page.py b/saleor/graphql/page/tests/test_page.pyindex 36748c4810..c55de6e691 100644--- a/saleor/graphql/page/tests/test_page.py+++ b/saleor/graphql/page/tests/test_page.py@@ -6,8 +6,9 @@ from django.utils import timezonefrom django.utils.text import slugifyfrom freezegun import freeze_time+from ....attribute.utils import associate_attribute_values_to_instancefrom ....page.error_codes import PageErrorCode-from ....page.models import Page+from ....page.models import Page, PageTypefrom ...tests.utils import get_graphql_contentPAGE_QUERY = """@@ -151,6 +152,11 @@ CREATE_PAGE_MUTATION = """}values {slug+ name+ file {+ url+ contentType+ }}}}@@ -347,6 +353,241 @@ def test_page_create_mutation_empty_attribute_value(]+def test_create_page_with_file_attribute(+ staff_api_client, permission_manage_pages, page_type, page_file_attribute+):+ # given+ page_slug = "test-slug"+ page_content = "test content"+ page_content_json = json.dumps({"content": "test content"})+ page_title = "test title"+ page_is_published = True+ page_type = PageType.objects.create(+ name="Test page type 2", slug="test-page-type-2"+ )+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)++ file_attribute_id = graphene.Node.to_global_id("Attribute", page_file_attribute.pk)+ page_type.page_attributes.add(page_file_attribute)+ attr_value = page_file_attribute.values.first()++ values_count = page_file_attribute.values.count()++ # test creating root page+ variables = {+ "title": page_title,+ "content": page_content,+ "contentJson": page_content_json,+ "isPublished": page_is_published,+ "slug": page_slug,+ "pageType": page_type_id,+ "attributes": [{"id": file_attribute_id, "file": attr_value.file_url}],+ }++ # when+ response = staff_api_client.post_graphql(+ CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["pageCreate"]+ errors = data["pageErrors"]++ assert not errors+ assert data["page"]["title"] == page_title+ assert data["page"]["content"] == page_content+ assert data["page"]["contentJson"] == page_content_json+ assert data["page"]["slug"] == page_slug+ assert data["page"]["isPublished"] == page_is_published+ assert data["page"]["pageType"]["id"] == page_type_id+ assert len(data["page"]["attributes"]) == 1+ expected_attr_data = {+ "attribute": {"slug": page_file_attribute.slug},+ "values": [+ {+ "slug": f"{attr_value.slug}-2",+ "name": attr_value.name,+ "file": {"url": attr_value.file_url, "contentType": None},+ }+ ],+ }+ assert data["page"]["attributes"][0] == expected_attr_data++ page_file_attribute.refresh_from_db()+ assert page_file_attribute.values.count() == values_count + 1+++def test_create_page_with_file_attribute_new_attribute_value(+ staff_api_client, permission_manage_pages, page_type, page_file_attribute+):+ # given+ page_slug = "test-slug"+ page_content = "test content"+ page_content_json = json.dumps({"content": "test content"})+ page_title = "test title"+ page_is_published = True+ page_type = PageType.objects.create(+ name="Test page type 2", slug="test-page-type-2"+ )+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)++ file_attribute_id = graphene.Node.to_global_id("Attribute", page_file_attribute.pk)+ page_type.page_attributes.add(page_file_attribute)+ new_value = "new_test_value.txt"+ new_value_content_type = "text/plain"++ values_count = page_file_attribute.values.count()++ # test creating root page+ variables = {+ "title": page_title,+ "content": page_content,+ "contentJson": page_content_json,+ "isPublished": page_is_published,+ "slug": page_slug,+ "pageType": page_type_id,+ "attributes": [+ {+ "id": file_attribute_id,+ "file": new_value,+ "contentType": new_value_content_type,+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["pageCreate"]+ errors = data["pageErrors"]++ assert not errors+ assert data["page"]["title"] == page_title+ assert data["page"]["content"] == page_content+ assert data["page"]["contentJson"] == page_content_json+ assert data["page"]["slug"] == page_slug+ assert data["page"]["isPublished"] == page_is_published+ assert data["page"]["pageType"]["id"] == page_type_id+ assert len(data["page"]["attributes"]) == 1+ expected_attr_data = {+ "attribute": {"slug": page_file_attribute.slug},+ "values": [+ {+ "slug": slugify(new_value),+ "name": new_value,+ "file": {+ "url": "http://testserver/media/" + new_value,+ "contentType": new_value_content_type,+ },+ }+ ],+ }+ assert data["page"]["attributes"][0] == expected_attr_data++ page_file_attribute.refresh_from_db()+ assert page_file_attribute.values.count() == values_count + 1+++def test_create_page_with_file_attribute_not_required_no_file_url_given(+ staff_api_client, permission_manage_pages, page_type, page_file_attribute+):+ # given+ page_slug = "test-slug"+ page_content = "test content"+ page_content_json = json.dumps({"content": "test content"})+ page_title = "test title"+ page_is_published = True+ page_type = PageType.objects.create(+ name="Test page type 2", slug="test-page-type-2"+ )+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)++ file_attribute_id = graphene.Node.to_global_id("Attribute", page_file_attribute.pk)+ page_type.page_attributes.add(page_file_attribute)++ page_file_attribute.value_required = False+ page_file_attribute.save(update_fields=["value_required"])++ # test creating root page+ variables = {+ "title": page_title,+ "content": page_content,+ "contentJson": page_content_json,+ "isPublished": page_is_published,+ "slug": page_slug,+ "pageType": page_type_id,+ "attributes": [{"id": file_attribute_id, "file": ""}],+ }++ # when+ response = staff_api_client.post_graphql(+ CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]+ )++ content = get_graphql_content(response)+ data = content["data"]["pageCreate"]+ assert data["pageErrors"] == []+ assert data["page"]["title"] == page_title+ assert data["page"]["content"] == page_content+ assert data["page"]["contentJson"] == page_content_json+ assert data["page"]["slug"] == page_slug+ assert data["page"]["isPublished"] == page_is_published+ assert data["page"]["pageType"]["id"] == page_type_id+ assert len(data["page"]["attributes"]) == 1+ assert len(data["page"]["attributes"][0]["values"]) == 0+++def test_create_page_with_file_attribute_required_no_file_url_given(+ staff_api_client, permission_manage_pages, page_type, page_file_attribute+):+ # given+ page_slug = "test-slug"+ page_content = "test content"+ page_content_json = json.dumps({"content": "test content"})+ page_title = "test title"+ page_is_published = True+ page_type = PageType.objects.create(+ name="Test page type 2", slug="test-page-type-2"+ )+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)++ file_attribute_id = graphene.Node.to_global_id("Attribute", page_file_attribute.pk)+ page_type.page_attributes.add(page_file_attribute)++ page_file_attribute.value_required = True+ page_file_attribute.save(update_fields=["value_required"])++ # test creating root page+ variables = {+ "title": page_title,+ "content": page_content,+ "contentJson": page_content_json,+ "isPublished": page_is_published,+ "slug": page_slug,+ "pageType": page_type_id,+ "attributes": [{"id": file_attribute_id, "file": ""}],+ }++ # when+ response = staff_api_client.post_graphql(+ CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]+ )++ content = get_graphql_content(response)+ data = content["data"]["pageCreate"]+ errors = data["pageErrors"]+ assert not data["page"]+ assert len(errors) == 1+ assert errors[0]["code"] == PageErrorCode.REQUIRED.name+ assert errors[0]["field"] == "attributes"+ assert errors[0]["attributes"] == [file_attribute_id]++def test_page_delete_mutation(staff_api_client, page, permission_manage_pages):query = """mutation DeletePage($id: ID!) {@@ -376,15 +617,10 @@ def test_page_delete_mutation(staff_api_client, page, permission_manage_pages):UPDATE_PAGE_MUTATION = """mutation updatePage(- $id: ID!,- $slug: String,- $is_published: Boolean!,- $attributes: [AttributeValueInput!]+ $id: ID!, $input: PageInput!) {pageUpdate(- id: $id, input: {- slug: $slug, isPublished: $is_published, attributes: $attributes- }+ id: $id, input: $input) {page {id@@ -398,6 +634,11 @@ UPDATE_PAGE_MUTATION = """}values {slug+ name+ file {+ url+ contentType+ }}}}@@ -428,9 +669,11 @@ def test_update_page(staff_api_client, permission_manage_pages, page):variables = {"id": page_id,- "slug": new_slug,- "is_published": True,- "attributes": [{"id": tag_attr_id, "values": [new_value]}],+ "input": {+ "slug": new_slug,+ "isPublished": True,+ "attributes": [{"id": tag_attr_id, "values": [new_value]}],+ },}# when@@ -451,13 +694,13 @@ def test_update_page(staff_api_client, permission_manage_pages, page):for attr in page_type.page_attributes.all():if attr.slug != tag_attr.slug:values = [- {"slug": slug}- for slug in page_attr.filter(assignment__attribute=attr).values_list(- "values__slug", flat=True- )+ {"slug": slug, "file": None, "name": name}+ for slug, name in page_attr.filter(+ assignment__attribute=attr+ ).values_list("values__slug", "values__name")]else:- values = [{"slug": slugify(new_value)}]+ values = [{"slug": slugify(new_value), "file": None, "name": new_value}]attr_data = {"attribute": {"slug": attr.slug},"values": values,@@ -470,6 +713,105 @@ def test_update_page(staff_api_client, permission_manage_pages, page):assert attr_data in expected_attributes+def test_update_page_with_file_attribute_value(+ staff_api_client, permission_manage_pages, page, page_file_attribute+):+ # given+ query = UPDATE_PAGE_MUTATION++ page_type = page.page_type+ page_type.page_attributes.add(page_file_attribute)+ new_value = "test.txt"+ page_file_attribute_id = graphene.Node.to_global_id(+ "Attribute", page_file_attribute.pk+ )++ page_id = graphene.Node.to_global_id("Page", page.id)++ variables = {+ "id": page_id,+ "input": {"attributes": [{"id": page_file_attribute_id, "file": new_value}]},+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_pages]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["pageUpdate"]++ assert not data["pageErrors"]+ assert data["page"]+ updated_attribute = {+ "attribute": {"slug": page_file_attribute.slug},+ "values": [+ {+ "slug": slugify(new_value),+ "name": new_value,+ "file": {+ "url": "http://testserver/media/" + new_value,+ "contentType": None,+ },+ }+ ],+ }+ assert updated_attribute in data["page"]["attributes"]+++def test_update_page_with_file_attribute_new_value_is_not_created(+ staff_api_client, permission_manage_pages, page, page_file_attribute+):+ # given+ query = UPDATE_PAGE_MUTATION++ page_type = page.page_type+ page_type.page_attributes.add(page_file_attribute)+ page_file_attribute_id = graphene.Node.to_global_id(+ "Attribute", page_file_attribute.pk+ )+ existing_value = page_file_attribute.values.first()+ associate_attribute_values_to_instance(page, page_file_attribute, existing_value)++ page_id = graphene.Node.to_global_id("Page", page.id)++ variables = {+ "id": page_id,+ "input": {+ "attributes": [+ {"id": page_file_attribute_id, "file": existing_value.file_url}+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_pages]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["pageUpdate"]++ assert not data["pageErrors"]+ assert data["page"]+ updated_attribute = {+ "attribute": {"slug": page_file_attribute.slug},+ "values": [+ {+ "slug": existing_value.slug,+ "name": existing_value.name,+ "file": {+ "url": existing_value.file_url,+ "contentType": existing_value.content_type,+ },+ }+ ],+ }+ assert updated_attribute in data["page"]["attributes"]++@freeze_time("2020-03-18 12:00:00")def test_public_page_sets_publication_date(staff_api_client, permission_manage_pages, page_type@@ -483,7 +825,7 @@ def test_public_page_sets_publication_date(}page = Page.objects.create(**data)page_id = graphene.Node.to_global_id("Page", page.id)- variables = {"id": page_id, "is_published": True, "slug": page.slug}+ variables = {"id": page_id, "input": {"isPublished": True, "slug": page.slug}}response = staff_api_client.post_graphql(UPDATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages])@@ -503,7 +845,7 @@ def test_update_page_blank_slug_value(assert slug_value != page.slugpage_id = graphene.Node.to_global_id("Page", page.id)- variables = {"id": page_id, "slug": slug_value, "is_published": True}+ variables = {"id": page_id, "input": {"slug": slug_value, "isPublished": True}}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_pages])diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.pyindex acc5425298..eeb665da19 100644--- a/saleor/graphql/product/bulk_mutations/products.py+++ b/saleor/graphql/product/bulk_mutations/products.py@@ -3,6 +3,7 @@ from collections import defaultdictimport graphenefrom django.core.exceptions import ValidationErrorfrom django.db import transaction+from graphene.types import InputObjectTypefrom ....core.permissions import ProductPermissions, ProductTypePermissionsfrom ....order import OrderStatus, models as order_models@@ -10,7 +11,7 @@ from ....product import modelsfrom ....product.error_codes import ProductErrorCodefrom ....product.tasks import update_product_discounted_price_taskfrom ....product.utils import delete_categories-from ....product.utils.variants import generate_name_for_variant+from ....product.utils.variants import generate_and_set_variant_namefrom ....warehouse import models as warehouse_modelsfrom ....warehouse.error_codes import StockErrorCodefrom ...channel import ChannelContext@@ -29,7 +30,6 @@ from ...warehouse.types import Warehousefrom ..mutations.channels import ProductVariantChannelListingAddInputfrom ..mutations.products import (AttributeAssignmentMixin,- AttributeValueInput,ProductVariantCreate,ProductVariantInput,StockInput,@@ -102,9 +102,21 @@ class ProductBulkDelete(ModelBulkDeleteMutation):return response+class BulkAttributeValueInput(InputObjectType):+ id = graphene.ID(description="ID of the selected attribute.")+ values = graphene.List(+ graphene.String,+ required=True,+ description=(+ "The value or slug of an attribute to resolve. "+ "If the passed value is non-existent, it will be created."+ ),+ )++class ProductVariantBulkCreateInput(ProductVariantInput):attributes = graphene.List(- AttributeValueInput,+ BulkAttributeValueInput,required=True,description="List of attributes specific to this variant.",)@@ -290,8 +302,7 @@ class ProductVariantBulkCreate(BaseMutation):attributes = cleaned_input.get("attributes")if attributes:AttributeAssignmentMixin.save(instance, attributes)- instance.name = generate_name_for_variant(instance)- instance.save(update_fields=["name"])+ generate_and_set_variant_name(instance, cleaned_input.get("sku"))@classmethoddef create_variants(cls, info, cleaned_inputs, product, errors):@@ -319,6 +330,20 @@ class ProductVariantBulkCreate(BaseMutation):)sku_list.append(sku)+ @classmethod+ def validate_duplicated_attribute_values(+ cls, attributes_data, used_attribute_values, instance=None+ ):+ attribute_values = defaultdict(list)+ for attr in attributes_data:+ attribute_values[attr.id].extend(attr.values)+ if attribute_values in used_attribute_values:+ raise ValidationError(+ "Duplicated attribute values for product variant.",+ ProductErrorCode.DUPLICATED_INPUT_ITEM,+ )+ used_attribute_values.append(attribute_values)+@classmethoddef clean_variants(cls, info, variants, product, errors):cleaned_inputs = []@@ -326,7 +351,7 @@ class ProductVariantBulkCreate(BaseMutation):used_attribute_values = get_used_variants_attribute_values(product)for index, variant_data in enumerate(variants):try:- ProductVariantCreate.validate_duplicated_attribute_values(+ cls.validate_duplicated_attribute_values(variant_data.attributes, used_attribute_values)except ValidationError as exc:diff --git a/saleor/graphql/product/enums.py b/saleor/graphql/product/enums.pyindex a994a4a43d..a55ea40502 100644--- a/saleor/graphql/product/enums.py+++ b/saleor/graphql/product/enums.py@@ -24,3 +24,9 @@ class ProductTypeConfigurable(graphene.Enum):class ProductTypeEnum(graphene.Enum):DIGITAL = "digital"SHIPPABLE = "shippable"+++class VariantAttributeScope(graphene.Enum):+ ALL = "all"+ VARIANT_SELECTION = "variant_selection"+ NOT_VARIANT_SELECTION = "not_variant_selection"diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.pyindex fd3c179ead..c21162e7c6 100644--- a/saleor/graphql/product/mutations/attributes.py+++ b/saleor/graphql/product/mutations/attributes.py@@ -6,7 +6,7 @@ from django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.db import transactionfrom django.db.models import Q-from ....attribute import AttributeInputType, AttributeType, models as attribute_models+from ....attribute import AttributeType, models as attribute_modelsfrom ....core.permissions import ProductTypePermissionsfrom ....product import modelsfrom ....product.error_codes import ProductErrorCode@@ -118,28 +118,6 @@ class ProductAttributeAssign(BaseMutation):)errors["operations"].append(error)- # check if attributes' input type is assignable to variants- not_assignable_to_variant = attribute_models.Attribute.objects.filter(- Q(pk__in=variant_attrs_pks)- & Q(input_type__in=AttributeInputType.NON_ASSIGNABLE_TO_VARIANTS)- )-- if not_assignable_to_variant:- not_assignable_attr_ids = [- graphene.Node.to_global_id("Attribute", attr.pk)- for attr in not_assignable_to_variant- ]- error = ValidationError(- (- f"Attributes having for input types "- f"{AttributeInputType.NON_ASSIGNABLE_TO_VARIANTS} "- f"cannot be assigned as variant attributes"- ),- code=ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED,- params={"attributes": not_assignable_attr_ids},- )- errors["operations"].append(error)-@classmethoddef check_product_operations_are_assignable(cls, errors, product_attrs_pks):restricted_attributes = attribute_models.Attribute.objects.filter(diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex 7b6d3945ef..73dd1ebbeb 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -1,22 +1,17 @@import datetimefrom collections import defaultdict-from typing import TYPE_CHECKING, Iterable, List, Tuple, Union+from typing import List, Tupleimport graphenefrom django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.db import transaction-from django.db.models import Q, QuerySetfrom django.utils.text import slugifyfrom graphene.types import InputObjectType-from graphql_relay import from_global_id-from ....attribute import AttributeType-from ....attribute.utils import associate_attribute_values_to_instance+from ....attribute import AttributeInputType, AttributeType, models as attribute_modelsfrom ....core.exceptions import PermissionDeniedfrom ....core.permissions import ProductPermissions, ProductTypePermissionsfrom ....order import OrderStatus, models as order_models-from ....page import models as page_models-from ....page.error_codes import PageErrorCodefrom ....product import modelsfrom ....product.error_codes import CollectionErrorCode, ProductErrorCodefrom ....product.tasks import (@@ -30,7 +25,8 @@ from ....product.thumbnails import (create_product_thumbnails,)from ....product.utils import delete_categories, get_products_ids_without_variants-from ....product.utils.variants import generate_name_for_variant+from ....product.utils.variants import generate_and_set_variant_name+from ...attribute.utils import AttributeAssignmentMixin, AttrValuesInputfrom ...channel import ChannelContextfrom ...core.inputs import ReorderInputfrom ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation@@ -58,13 +54,8 @@ from ..utils import (create_stocks,get_used_attribute_values_for_variant,get_used_variants_attribute_values,- validate_attributes_input_for_product_and_page,- validate_attributes_input_for_variant,)-if TYPE_CHECKING:- from ....attribute import models as attribute_models-class CategoryInput(graphene.InputObjectType):description = graphene.String(description="Category description (HTML/text).")@@ -462,12 +453,17 @@ class AttributeValueInput(InputObjectType):id = graphene.ID(description="ID of the selected attribute.")values = graphene.List(graphene.String,- required=True,+ required=False,description=("The value or slug of an attribute to resolve. ""If the passed value is non-existent, it will be created."),)+ file = graphene.String(+ required=False,+ description="URL of the file attribute. Every time, a new value is created.",+ )+ content_type = graphene.String(required=False, description="File content type.")class ProductInput(graphene.InputObjectType):@@ -506,234 +502,7 @@ class ProductCreateInput(ProductInput):)-T_INPUT_MAP = List[Tuple["attribute_models.Attribute", List[str]]]-T_INSTANCE = Union[models.Product, models.ProductVariant, page_models.Page]---class AttributeAssignmentMixin:- """Handles cleaning of the attribute input and creating the proper relations.-- 1. You should first call ``clean_input``, to transform and attempt to resolve- the provided input into actual objects. It will then perform a few- checks to validate the operations supplied by the user are possible and allowed.- 2. Once everything is ready and all your data is saved inside a transaction,- you shall call ``save`` with the cleaned input to build all the required- relations. Once the ``save`` call is done, you are safe from continuing working- or to commit the transaction.-- Note: you shall never call ``save`` outside of a transaction and never before- the targeted instance owns a primary key. Failing to do so, the relations will- be unable to build or might only be partially built.- """-- @classmethod- def _resolve_attribute_nodes(- cls,- qs: QuerySet,- *,- global_ids: List[str],- pks: Iterable[int],- slugs: Iterable[str],- ):- """Retrieve attributes nodes from given global IDs and/or slugs."""- qs = qs.filter(Q(pk__in=pks) | Q(slug__in=slugs))- nodes: List["attribute_models.Attribute"] = list(qs)-- if not nodes:- raise ValidationError(- (- f"Could not resolve to a node: ids={global_ids}"- f" and slugs={list(slugs)}"- ),- code=ProductErrorCode.NOT_FOUND.value,- )-- nodes_pk_list = set()- nodes_slug_list = set()- for node in nodes:- nodes_pk_list.add(node.pk)- nodes_slug_list.add(node.slug)-- for pk, global_id in zip(pks, global_ids):- if pk not in nodes_pk_list:- raise ValidationError(- f"Could not resolve {global_id!r} to Attribute",- code=ProductErrorCode.NOT_FOUND.value,- )-- for slug in slugs:- if slug not in nodes_slug_list:- raise ValidationError(- f"Could not resolve slug {slug!r} to Attribute",- code=ProductErrorCode.NOT_FOUND.value,- )-- return nodes-- @classmethod- def _resolve_attribute_global_id(cls, global_id: str) -> int:- """Resolve an Attribute global ID into an internal ID (int)."""- graphene_type, internal_id = from_global_id(global_id) # type: str, str- if graphene_type != "Attribute":- raise ValidationError(- f"Must receive an Attribute id, got {graphene_type}.",- code=ProductErrorCode.INVALID.value,- )- if not internal_id.isnumeric():- raise ValidationError(- f"An invalid ID value was passed: {global_id}",- code=ProductErrorCode.INVALID.value,- )- return int(internal_id)-- @classmethod- def _pre_save_values(- cls, attribute: "attribute_models.Attribute", values: List[str]- ):- """Lazy-retrieve or create the database objects from the supplied raw values."""- get_or_create = attribute.values.get_or_create- return tuple(- get_or_create(- attribute=attribute,- slug=slugify(value, allow_unicode=True),- defaults={"name": value},- )[0]- for value in values- )-- @classmethod- def _validate_product_attributes_input(- cls, cleaned_input: T_INPUT_MAP, attribute_qs: QuerySet, is_variant: bool- ):- """Check if no invalid operations were supplied.-- :raises ValidationError: when an invalid operation was found.- """- if is_variant:- return cls._check_input_for_variant(cleaned_input, attribute_qs)- else:- return cls._check_input_for_page_and_product(- cleaned_input, attribute_qs, False- )-- @classmethod- def _check_input_for_variant(cls, cleaned_input: T_INPUT_MAP, qs: QuerySet):- """Check the cleaned attribute input for a variant.-- An Attribute queryset is supplied.-- - ensure all attributes are passed- - ensure the values are correct for a variant- """- if len(cleaned_input) != qs.count():- raise ValidationError(- "All attributes must take a value", code=ProductErrorCode.REQUIRED.value- )-- errors = validate_attributes_input_for_variant(cleaned_input)- if errors:- raise ValidationError(errors)-- @classmethod- def _check_input_for_page_and_product(- cls, cleaned_input: T_INPUT_MAP, qs: QuerySet, is_page_attributes: bool- ):- """Check the cleaned attribute input for a product.-- An Attribute queryset is supplied.-- - ensure all required attributes are passed- - ensure the values are correct for a product- """- error_codes_enum = PageErrorCode if is_page_attributes else ProductErrorCode- errors = validate_attributes_input_for_product_and_page(- cleaned_input, qs, error_codes_enum- )-- if errors:- raise ValidationError(errors)-- @classmethod- def clean_input(- cls,- raw_input: dict,- attributes_qs: QuerySet,- is_variant: bool = False,- is_page_attributes: bool = False,- ) -> T_INPUT_MAP:- """Resolve and prepare the input for further checks.-- :param raw_input: The user's attributes input.- :param attributes_qs:- A queryset of attributes, the attribute values must be prefetched.- Prefetch is needed by ``_pre_save_values`` during save.- :param page_attributes: Whether the input is for page type or not.- :param is_variant: Whether the input is for a variant or a product.-- :raises ValidationError: contain the message.- :return: The resolved data- """-- # Mapping to associate the input values back to the resolved attribute nodes- pks = {}- slugs = {}-- # Temporary storage of the passed ID for error reporting- global_ids = []-- for attribute_input in raw_input:- global_id = attribute_input.get("id")- slug = attribute_input.get("slug")- values = attribute_input["values"]-- if global_id:- internal_id = cls._resolve_attribute_global_id(global_id)- global_ids.append(global_id)- pks[internal_id] = values- elif slug:- slugs[slug] = values- else:- raise ValidationError(- "You must whether supply an ID or a slug",- code=ProductErrorCode.REQUIRED.value,- )-- attributes = cls._resolve_attribute_nodes(- attributes_qs, global_ids=global_ids, pks=pks.keys(), slugs=slugs.keys()- )- cleaned_input = []- for attribute in attributes:- key = pks.get(attribute.pk, None)-- # Retrieve the primary key by slug if it- # was not resolved through a global ID but a slug- if key is None:- key = slugs[attribute.slug]-- cleaned_input.append((attribute, key))-- if is_page_attributes:- cls._check_input_for_page_and_product(cleaned_input, attributes_qs, True)- else:- cls._validate_product_attributes_input(- cleaned_input, attributes_qs, is_variant- )- return cleaned_input-- @classmethod- def save(cls, instance: T_INSTANCE, cleaned_input: T_INPUT_MAP):- """Save the cleaned input into the database against the given instance.-- Note: this should always be ran inside a transaction.-- :param instance: the product or variant to associate the attribute against.- :param cleaned_input: the cleaned user input (refer to clean_attributes)- """- for attribute, values in cleaned_input:- attribute_values = cls._pre_save_values(attribute, values)- associate_attribute_values_to_instance(- instance, attribute, *attribute_values- )+T_INPUT_MAP = List[Tuple[attribute_models.Attribute, AttrValuesInput]]class ProductCreate(ModelMutation):@@ -981,11 +750,19 @@ class ProductVariantCreate(ModelMutation):@classmethoddef validate_duplicated_attribute_values(- cls, attributes, used_attribute_values, instance=None+ cls, attributes_data, used_attribute_values, instance=None):attribute_values = defaultdict(list)- for attribute in attributes:- attribute_values[attribute.id].extend(attribute.values)+ for attr, attr_data in attributes_data:+ if attr.input_type == AttributeInputType.FILE:+ values = (+ [slugify(attr_data.file_url.split("/")[-1])]+ if attr_data.file_url+ else []+ )+ else:+ values = attr_data.values+ attribute_values[attr_data.global_id].extend(values)if attribute_values in used_attribute_values:raise ValidationError("Duplicated attribute values for product variant.",@@ -1037,12 +814,11 @@ class ProductVariantCreate(ModelMutation):attributes = cleaned_input.get("attributes")try:if attributes:+ cleaned_attributes = cls.clean_attributes(attributes, product_type)cls.validate_duplicated_attribute_values(- attributes, used_attribute_values, instance- )- cleaned_input["attributes"] = cls.clean_attributes(- attributes, product_type+ cleaned_attributes, used_attribute_values, instance)+ cleaned_input["attributes"] = cleaned_attributeselif not instance.pk and not attributes:# if attributes were not provided on creationraise ValidationError(@@ -1106,8 +882,7 @@ class ProductVariantCreate(ModelMutation):attributes = cleaned_input.get("attributes")if attributes:AttributeAssignmentMixin.save(instance, attributes)- instance.name = generate_name_for_variant(instance)- instance.save(update_fields=["name"])+ generate_and_set_variant_name(instance, cleaned_input.get("sku"))info.context.plugins.product_updated(instance.product)@classmethod@@ -1143,19 +918,29 @@ class ProductVariantUpdate(ProductVariantCreate):@classmethoddef validate_duplicated_attribute_values(- cls, attributes, used_attribute_values, instance=None+ cls, attributes_data, used_attribute_values, instance=None):# Check if the variant is getting updated,# and the assigned attributes do not changeif instance.product_id is not None:assigned_attributes = get_used_attribute_values_for_variant(instance)input_attribute_values = defaultdict(list)- for attribute in attributes:- input_attribute_values[attribute.id].extend(attribute.values)+ for attr, attr_data in attributes_data:+ if attr.input_type == AttributeInputType.FILE:+ values = (+ [slugify(attr_data.file_url.split("/")[-1])]+ if attr_data.file_url+ else []+ )+ else:+ values = attr_data.values+ input_attribute_values[attr_data.global_id].extend(values)if input_attribute_values == assigned_attributes:return# if assigned attributes is getting updated run duplicated attribute validation- super().validate_duplicated_attribute_values(attributes, used_attribute_values)+ super().validate_duplicated_attribute_values(+ attributes_data, used_attribute_values+ )class ProductVariantDelete(ModelDeleteMutation):diff --git a/saleor/graphql/product/tests/test_attributes.py b/saleor/graphql/product/tests/test_attributes.pyindex 4e312335c5..ba839c68ea 100644--- a/saleor/graphql/product/tests/test_attributes.py+++ b/saleor/graphql/product/tests/test_attributes.py@@ -404,7 +404,7 @@ def test_assign_variant_attribute_to_product_type_with_disabled_variants()-def test_assign_variant_attribute_having_unsupported_input_type(+def test_assign_variant_attribute_having_multiselect_input_type(staff_api_client,permission_manage_product_types_and_attributes,product_type,@@ -424,26 +424,19 @@ def test_assign_variant_attribute_having_unsupported_input_type()product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)+ attr_id = graphene.Node.to_global_id("Attribute", attribute.pk)query = PRODUCT_ASSIGN_ATTR_QUERY- operations = [- {"type": "VARIANT", "id": graphene.Node.to_global_id("Attribute", attribute.pk)}- ]+ operations = [{"type": "VARIANT", "id": attr_id}]variables = {"productTypeId": product_type_global_id, "operations": operations}content = get_graphql_content(staff_api_client.post_graphql(query, variables))["data"]["productAttributeAssign"]- assert content["productErrors"][0]["field"] == "operations"- assert (- content["productErrors"][0]["message"]- == "Attributes having for input types ['multiselect'] "- "cannot be assigned as variant attributes"- )- assert (- content["productErrors"][0]["code"]- == ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.name- )+ assert not content["productErrors"]+ assert content["productType"]["id"] == product_type_global_id+ assert len(content["productType"]["variantAttributes"]) == 1+ assert content["productType"]["variantAttributes"][0]["id"] == attr_id@pytest.mark.parametrize(@@ -584,7 +577,7 @@ def test_assign_attribute_to_product_type_multiply_errors_returned(errors = data["productErrors"]assert not data["productType"]- assert len(errors) == 3+ assert len(errors) == 2expected_errors = [{"code": ProductErrorCode.ATTRIBUTE_ALREADY_ASSIGNED.name,@@ -592,12 +585,6 @@ def test_assign_attribute_to_product_type_multiply_errors_returned("message": mock.ANY,"attributes": [color_attr_id],},- {- "code": ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.name,- "field": "operations",- "message": mock.ANY,- "attributes": [unsupported_type_attr_id],- },{"code": ProductErrorCode.INVALID.name,"field": "operations",diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex ed9a1d1d60..2a9dba08d3 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -45,6 +45,7 @@ from ...tests.utils import (get_multipart_request_body,)from ..bulk_mutations.products import ProductVariantStocksUpdate+from ..enums import VariantAttributeScopefrom ..utils import create_stocks@@ -2018,6 +2019,11 @@ CREATE_PRODUCT_MUTATION = """}values {slug+ name+ file {+ url+ contentType+ }}}}@@ -2139,6 +2145,282 @@ def test_create_product_with_rating(assert Product.objects.get().rating == expected_rating+def test_create_product_with_file_attribute(+ staff_api_client,+ product_type,+ category,+ file_attribute,+ color_attribute,+ permission_manage_products,+ settings,+):+ 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"++ values_count = file_attribute.values.count()++ # Add second attribute+ product_type.product_attributes.add(file_attribute)+ file_attr_id = graphene.Node.to_global_id("Attribute", file_attribute.id)+ existing_value = file_attribute.values.first()++ # test creating root product+ variables = {+ "input": {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name,+ "slug": product_slug,+ "attributes": [{"id": file_attr_id, "file": existing_value.file_url}],+ }+ }++ 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+ assert len(data["product"]["attributes"]) == 2+ expected_attributes_data = [+ {"attribute": {"slug": color_attribute.slug}, "values": []},+ {+ "attribute": {"slug": file_attribute.slug},+ "values": [+ {+ "name": existing_value.name,+ "slug": f"{existing_value.slug}-2",+ "file": {"url": existing_value.file_url, "contentType": None},+ }+ ],+ },+ ]+ for attr_data in data["product"]["attributes"]:+ assert attr_data in expected_attributes_data++ file_attribute.refresh_from_db()+ assert file_attribute.values.count() == values_count + 1+++def test_create_product_with_file_attribute_new_attribute_value(+ staff_api_client,+ product_type,+ category,+ file_attribute,+ color_attribute,+ permission_manage_products,+ settings,+):+ 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"++ values_count = file_attribute.values.count()++ # Add second attribute+ product_type.product_attributes.add(file_attribute)+ file_attr_id = graphene.Node.to_global_id("Attribute", file_attribute.id)+ non_existing_value = "new_test.jpg"++ # test creating root product+ variables = {+ "input": {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name,+ "slug": product_slug,+ "attributes": [{"id": file_attr_id, "file": non_existing_value}],+ }+ }++ 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+ assert len(data["product"]["attributes"]) == 2+ expected_attributes_data = [+ {"attribute": {"slug": color_attribute.slug}, "values": []},+ {+ "attribute": {"slug": file_attribute.slug},+ "values": [+ {+ "name": non_existing_value,+ "slug": slugify(non_existing_value, allow_unicode=True),+ "file": {+ "url": "http://testserver/media/" + non_existing_value,+ "contentType": None,+ },+ }+ ],+ },+ ]+ for attr_data in data["product"]["attributes"]:+ assert attr_data in expected_attributes_data++ file_attribute.refresh_from_db()+ assert file_attribute.values.count() == values_count + 1+++def test_create_product_with_file_attribute_not_required_no_file_url_given(+ staff_api_client,+ product_type,+ category,+ file_attribute,+ color_attribute,+ permission_manage_products,+ settings,+):+ 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"++ file_attribute.value_required = False+ file_attribute.save(update_fields=["value_required"])++ # Add second attribute+ product_type.product_attributes.add(file_attribute)+ file_attr_id = graphene.Node.to_global_id("Attribute", file_attribute.id)++ # test creating root product+ variables = {+ "input": {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name,+ "slug": product_slug,+ "attributes": [{"id": file_attr_id, "values": ["test.txt"]}],+ }+ }++ 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+ assert len(data["product"]["attributes"]) == 2+ expected_attributes_data = [+ {"attribute": {"slug": color_attribute.slug}, "values": []},+ {"attribute": {"slug": file_attribute.slug}, "values": []},+ ]+ for attr_data in data["product"]["attributes"]:+ assert attr_data in expected_attributes_data++ file_attribute.refresh_from_db()+++def test_create_product_with_file_attribute_required_no_file_url_given(+ staff_api_client,+ product_type,+ category,+ file_attribute,+ color_attribute,+ permission_manage_products,+ settings,+):+ 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"++ file_attribute.value_required = True+ file_attribute.save(update_fields=["value_required"])++ # Add second attribute+ product_type.product_attributes.add(file_attribute)+ file_attr_id = graphene.Node.to_global_id("Attribute", file_attribute.id)++ # test creating root product+ variables = {+ "input": {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name,+ "slug": product_slug,+ "attributes": [{"id": file_attr_id, "values": ["test.txt"]}],+ }+ }++ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ data = content["data"]["productCreate"]+ errors = data["productErrors"]+ assert not data["product"]+ assert len(errors) == 1+ assert errors[0]["code"] == ProductErrorCode.REQUIRED.name+ assert errors[0]["field"] == "attributes"+ assert errors[0]["attributes"] == [+ graphene.Node.to_global_id("Attribute", file_attribute.pk)+ ]+++def test_create_product_no_values_given(+ staff_api_client, product_type, category, permission_manage_products,+):+ 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"++ # Default attribute defined in product_type fixture+ color_attr = product_type.product_attributes.get(name="Color")+ color_attr_id = graphene.Node.to_global_id("Attribute", color_attr.id)++ # test creating root product+ variables = {+ "input": {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name,+ "slug": product_slug,+ "attributes": [{"id": color_attr_id, "file": "test.jpg"}],+ }+ }++ 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+ assert len(data["product"]["attributes"]) == 1+ assert data["product"]["attributes"][0]["values"] == []++PRODUCT_VARIANT_SET_DEFAULT_MUTATION = """mutation Prod($productId: ID!, $variantId: ID!) {productVariantSetDefault(productId: $productId, variantId: $variantId) {@@ -2589,6 +2871,7 @@ QUERY_CREATE_PRODUCT_WITHOUT_VARIANTS = """idnameslug+ ratingcategory {name}@@ -2725,99 +3008,50 @@ def test_product_create_with_collections_webhook(MUTATION_UPDATE_PRODUCT = """- mutation updateProduct(- $productId: ID!,- $categoryId: ID!,- $name: String!,- $slug: String!,- $descriptionJson: JSONString!,- $chargeTaxes: Boolean!,- $taxCode: String!,- $attributes: [AttributeValueInput!]) {- productUpdate(- id: $productId,- input: {- category: $categoryId,- name: $name,- slug: $slug,- descriptionJson: $descriptionJson,- chargeTaxes: $chargeTaxes,- taxCode: $taxCode,- attributes: $attributes- }) {- product {- category {- name- }- descriptionJson- chargeTaxes- variants {- name- }- taxType {- taxCode- description- }+ mutation updateProduct($productId: ID!, $input: ProductInput!) {+ productUpdate(id: $productId, input: $input) {+ product {+ category {+ name+ }+ rating+ descriptionJson+ chargeTaxes+ variants {+ name+ }+ taxType {+ taxCode+ description+ }+ name+ slug+ productType {+ name+ }+ attributes {+ attribute {+ id+ name+ }+ values {nameslug- productType {- name+ file {+ url+ contentType}- attributes {- attribute {- id- name- }- values {- name- slug- }- }- }- errors {- message- field- }}- }-"""---@freeze_time("2020-03-18 12:00:00")-def test_update_product_rating(- staff_api_client, product, permission_manage_products,-):- query = """- mutation updateProduct($productId: ID!, $input: ProductInput!) {- productUpdate(id: $productId, input: $input) {- product {- rating+ }}productErrors {+ messagefieldcode- message- attributes}}}- """-- product.rating = 5.5- product.save(update_fields=["rating"])- product_id = graphene.Node.to_global_id("Product", product.pk)- expected_rating = 9.57- variables = {"productId": product_id, "input": {"rating": expected_rating}}-- response = staff_api_client.post_graphql(- query, variables, permissions=[permission_manage_products]- )- content = get_graphql_content(response)- data = content["data"]["productUpdate"]- assert data["productErrors"] == []- assert data["product"]["rating"] == expected_rating- product.refresh_from_db()- assert product.rating == expected_rating+"""@patch("saleor.plugins.manager.PluginsManager.product_updated")@@ -2853,13 +3087,15 @@ def test_update_product(variables = {"productId": product_id,- "categoryId": category_id,- "name": product_name,- "slug": product_slug,- "descriptionJson": other_description_json,- "chargeTaxes": product_charge_taxes,- "taxCode": product_tax_rate,- "attributes": [{"id": attribute_id, "values": ["Rainbow"]}],+ "input": {+ "category": category_id,+ "name": product_name,+ "slug": product_slug,+ "descriptionJson": other_description_json,+ "chargeTaxes": product_charge_taxes,+ "taxCode": product_tax_rate,+ "attributes": [{"id": attribute_id, "values": ["Rainbow"]}],+ },}response = staff_api_client.post_graphql(@@ -2867,7 +3103,7 @@ def test_update_product()content = get_graphql_content(response)data = content["data"]["productUpdate"]- assert data["errors"] == []+ assert data["productErrors"] == []assert data["product"]["name"] == product_nameassert data["product"]["slug"] == product_slugassert data["product"]["descriptionJson"] == other_description_json@@ -2887,6 +3123,143 @@ def test_update_product(updated_webhook_mock.assert_called_once_with(product)+@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_update_product_with_file_attribute_value(+ updated_webhook_mock,+ staff_api_client,+ file_attribute,+ non_default_category,+ product,+ product_type,+ permission_manage_products,+ color_attribute,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product_id = graphene.Node.to_global_id("Product", product.pk)++ attribute_id = graphene.Node.to_global_id("Attribute", file_attribute.pk)+ product_type.product_attributes.add(file_attribute)++ new_value = "new_file.json"++ variables = {+ "productId": product_id,+ "input": {"attributes": [{"id": attribute_id, "file": new_value}]},+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ assert data["productErrors"] == []++ attributes = data["product"]["attributes"]++ assert len(attributes) == 2+ expected_file_att_data = {+ "attribute": {"id": attribute_id, "name": file_attribute.name},+ "values": [+ {+ "name": new_value,+ "slug": slugify(new_value),+ "file": {+ "url": "http://testserver/media/" + new_value,+ "contentType": None,+ },+ }+ ],+ }+ assert expected_file_att_data in attributes++ updated_webhook_mock.assert_called_once_with(product)+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_update_product_with_file_attribute_value_new_value_is_not_created(+ updated_webhook_mock,+ staff_api_client,+ file_attribute,+ product,+ product_type,+ permission_manage_products,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ product_id = graphene.Node.to_global_id("Product", product.pk)++ attribute_id = graphene.Node.to_global_id("Attribute", file_attribute.pk)+ product_type.product_attributes.add(file_attribute)+ existing_value = file_attribute.values.first()+ associate_attribute_values_to_instance(product, file_attribute, existing_value)++ variables = {+ "productId": product_id,+ "input": {+ "attributes": [{"id": attribute_id, "file": existing_value.file_url}]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ assert data["productErrors"] == []++ attributes = data["product"]["attributes"]++ assert len(attributes) == 2+ expected_file_att_data = {+ "attribute": {"id": attribute_id, "name": file_attribute.name},+ "values": [+ {+ "name": existing_value.name,+ "slug": existing_value.slug,+ "file": {+ "url": existing_value.file_url,+ "contentType": existing_value.content_type,+ },+ }+ ],+ }+ assert expected_file_att_data in attributes++ updated_webhook_mock.assert_called_once_with(product)+++@freeze_time("2020-03-18 12:00:00")+def test_update_product_rating(+ staff_api_client, product, permission_manage_products,+):+ query = MUTATION_UPDATE_PRODUCT++ product.rating = 5.5+ product.save(update_fields=["rating"])+ product_id = graphene.Node.to_global_id("Product", product.pk)+ expected_rating = 9.57+ variables = {"productId": product_id, "input": {"rating": expected_rating}}++ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ assert data["productErrors"] == []+ assert data["product"]["rating"] == expected_rating+ product.refresh_from_db()+ assert product.rating == expected_rating++UPDATE_PRODUCT_SLUG_MUTATION = """mutation($id: ID!, $slug: String) {productUpdate(@@ -3449,10 +3822,38 @@ def test_product_type(user_api_client, product_type, channel_USD):assert len(content["data"]["productTypes"]["edges"]) == no_product_types+PRODUCT_TYPE_QUERY = """+ query getProductType(+ $id: ID!, $variantSelection: VariantAttributeScope, $channel: String+ ) {+ productType(id: $id) {+ name+ variantAttributes(variantSelection: $variantSelection) {+ slug+ }+ products(first: 20, channel:$channel) {+ totalCount+ edges {+ node {+ name+ }+ }+ }+ taxRate+ taxType {+ taxCode+ description+ }+ }+ }+"""++def test_product_type_query(user_api_client,staff_api_client,product_type,+ file_attribute_with_file_input_type_without_values,product,permission_manage_products,monkeypatch,@@ -3463,32 +3864,78 @@ def test_product_type_query("get_tax_code_from_object_meta",lambda self, x: TaxType(code="123", description="Standard Taxes"),)- query = """- query getProductType($id: ID!, $channel: String) {- productType(id: $id) {- name- products(first: 20, channel:$channel) {- totalCount- edges {- node {- name- }- }- }- taxRate- taxType {- taxCode- description- }- }- }- """++ query = PRODUCT_TYPE_QUERY++ no_products = Product.objects.count()+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(+ is_published=False+ )++ product_type.variant_attributes.add(+ file_attribute_with_file_input_type_without_values+ )+ variant_attributes_count = product_type.variant_attributes.count()++ variables = {+ "id": graphene.Node.to_global_id("ProductType", product_type.id),+ "channel": channel_USD.slug,+ }++ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]+ assert data["productType"]["products"]["totalCount"] == no_products - 1++ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]+ assert data["productType"]["products"]["totalCount"] == no_products+ assert data["productType"]["taxType"]["taxCode"] == "123"+ assert data["productType"]["taxType"]["description"] == "Standard Taxes"+ assert len(data["productType"]["variantAttributes"]) == variant_attributes_count+++ "variant_selection",+ [+ VariantAttributeScope.ALL.name,+ VariantAttributeScope.VARIANT_SELECTION.name,+ VariantAttributeScope.NOT_VARIANT_SELECTION.name,+ ],+)+def test_product_type_query_only_variant_selections_value_set(+ variant_selection,+ user_api_client,+ staff_api_client,+ product_type,+ file_attribute_with_file_input_type_without_values,+ author_page_attribute,+ product,+ permission_manage_products,+ monkeypatch,+ channel_USD,+):+ monkeypatch.setattr(+ PluginsManager,+ "get_tax_code_from_object_meta",+ lambda self, x: TaxType(code="123", description="Standard Taxes"),+ )+ query = PRODUCT_TYPE_QUERY+no_products = Product.objects.count()ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(is_published=False)++ product_type.variant_attributes.add(+ file_attribute_with_file_input_type_without_values, author_page_attribute+ )+variables = {"id": graphene.Node.to_global_id("ProductType", product_type.id),+ "variantSelection": variant_selection,"channel": channel_USD.slug,}@@ -3505,6 +3952,26 @@ def test_product_type_query(assert data["productType"]["taxType"]["taxCode"] == "123"assert data["productType"]["taxType"]["description"] == "Standard Taxes"+ if variant_selection == VariantAttributeScope.VARIANT_SELECTION.name:+ assert (+ len(data["productType"]["variantAttributes"])+ == product_type.variant_attributes.filter(+ input_type=AttributeInputType.DROPDOWN, type=AttributeType.PRODUCT_TYPE+ ).count()+ )+ elif variant_selection == VariantAttributeScope.NOT_VARIANT_SELECTION.name:+ assert (+ len(data["productType"]["variantAttributes"])+ == product_type.variant_attributes.exclude(+ input_type=AttributeInputType.DROPDOWN, type=AttributeType.PRODUCT_TYPE+ ).count()+ )+ else:+ assert (+ len(data["productType"]["variantAttributes"])+ == product_type.variant_attributes.count()+ )+PRODUCT_TYPE_CREATE_MUTATION = """mutation createProductType(diff --git a/saleor/graphql/product/tests/test_utils.py b/saleor/graphql/product/tests/test_utils.pydeleted file mode 100644index 5f6cfd1b7e..0000000000--- a/saleor/graphql/product/tests/test_utils.py+++ /dev/null@@ -1,456 +0,0 @@-import graphene--from ....attribute import AttributeInputType-from ....page.error_codes import PageErrorCode-from ....product.error_codes import ProductErrorCode-from ..utils import (- validate_attributes_input_for_product_and_page,- validate_attributes_input_for_variant,-)---def test_validate_attributes_input_for_product(- weight_attribute, color_attribute, product_type-):- # given- color_attribute.value_required = True- color_attribute.save(update_fields=["value_required"])-- weight_attribute.value_required = True- weight_attribute.save(update_fields=["value_required"])-- input_data = [(weight_attribute, ["a"]), (color_attribute, ["b"])]-- # when- errors = validate_attributes_input_for_product_and_page(- input_data, product_type.product_attributes.all(), ProductErrorCode- )-- # then- assert not errors---def test_validate_attributes_input_for_product_no_values_given(- weight_attribute, color_attribute, product_type-):- # given- color_attribute.value_required = True- color_attribute.save(update_fields=["value_required"])-- weight_attribute.value_required = True- weight_attribute.save(update_fields=["value_required"])-- input_data = [(weight_attribute, []), (color_attribute, [])]-- # when- errors = validate_attributes_input_for_product_and_page(- input_data, product_type.product_attributes.all(), ProductErrorCode- )-- # then- assert len(errors) == 1- error = errors[0]- assert error.code == ProductErrorCode.REQUIRED.value- assert set(error.params["attributes"]) == {- graphene.Node.to_global_id("Attribute", attr.pk)- for attr in [weight_attribute, color_attribute]- }---def test_validate_attributes_input_for_product_too_many_values_given(- weight_attribute, color_attribute, product_type-):- # given- color_attribute.input_type = AttributeInputType.DROPDOWN- color_attribute.value_required = True- color_attribute.save(update_fields=["value_required", "input_type"])-- weight_attribute.value_required = True- weight_attribute.input_type = AttributeInputType.MULTISELECT- weight_attribute.save(update_fields=["value_required", "input_type"])-- input_data = [(weight_attribute, ["abc", "efg"]), (color_attribute, ["a", "b"])]-- # when- errors = validate_attributes_input_for_product_and_page(- input_data, product_type.product_attributes.all(), ProductErrorCode- )-- # then- assert len(errors) == 1- error = errors[0]- assert error.code == ProductErrorCode.INVALID.value- assert error.params["attributes"] == [- graphene.Node.to_global_id("Attribute", color_attribute.pk)- ]---def test_validate_attributes_input_for_product_empty_values_given(- weight_attribute, color_attribute, product_type-):- # given- color_attribute.input_type = AttributeInputType.DROPDOWN- color_attribute.value_required = True- color_attribute.save(update_fields=["value_required", "input_type"])-- weight_attribute.value_required = True- weight_attribute.input_type = AttributeInputType.MULTISELECT- weight_attribute.save(update_fields=["value_required", "input_type"])-- input_data = [(weight_attribute, ["a", None]), (color_attribute, [" "])]-- # when- errors = validate_attributes_input_for_product_and_page(- input_data, product_type.product_attributes.all(), ProductErrorCode- )-- # then- assert len(errors) == 1- error = errors[0]- assert error.code == ProductErrorCode.REQUIRED.value- assert set(error.params["attributes"]) == {- graphene.Node.to_global_id("Attribute", attr.pk)- for attr in [weight_attribute, color_attribute]- }---def test_validate_attributes_input_for_product_lack_of_required_attribute(- weight_attribute, color_attribute, product_type-):- # given- product_attributes = product_type.product_attributes.all()- attr = product_attributes.first()- attr.value_required = True- attr.save(update_fields=["value_required"])-- weight_attribute.value_required = True- weight_attribute.save(update_fields=["value_required"])-- input_data = [(weight_attribute, ["a"])]-- # when- errors = validate_attributes_input_for_product_and_page(- input_data, product_attributes, ProductErrorCode- )-- # then- assert len(errors) == 1- error = errors[0]- assert error.code == ProductErrorCode.REQUIRED.value- assert set(error.params["attributes"]) == {- graphene.Node.to_global_id("Attribute", attr.pk)- }---def test_validate_attributes_input_for_product_multiply_errors(- weight_attribute, color_attribute, product_type-):- # given- color_attribute.input_type = AttributeInputType.DROPDOWN- color_attribute.value_required = True- color_attribute.save(update_fields=["value_required", "input_type"])-- weight_attribute.value_required = True- weight_attribute.input_type = AttributeInputType.MULTISELECT- weight_attribute.save(update_fields=["value_required", "input_type"])-- input_data = [(weight_attribute, [None]), (color_attribute, ["a", "b"])]-- # when- errors = validate_attributes_input_for_product_and_page(- input_data, product_type.product_attributes.all(), ProductErrorCode- )-- # then- assert len(errors) == 2- assert {error.code for error in errors} == {- ProductErrorCode.INVALID.value,- ProductErrorCode.REQUIRED.value,- }- assert {attr for error in errors for attr in error.params["attributes"]} == {- graphene.Node.to_global_id("Attribute", attr.pk)- for attr in [weight_attribute, color_attribute]- }---def test_validate_attributes_input_for_page(- weight_attribute, color_attribute, page_type-):- # given- color_attribute.value_required = True- color_attribute.save(update_fields=["value_required"])-- weight_attribute.value_required = True- weight_attribute.save(update_fields=["value_required"])-- input_data = [(weight_attribute, ["a"]), (color_attribute, ["b"])]-- # when- errors = validate_attributes_input_for_product_and_page(- input_data, page_type.page_attributes.all(), PageErrorCode- )-- # then- assert not errors---def test_validate_attributes_input_for_page_no_values_given(- weight_attribute, color_attribute, page_type-):- # given- color_attribute.value_required = True- color_attribute.save(update_fields=["value_required"])-- weight_attribute.value_required = True- weight_attribute.save(update_fields=["value_required"])-- input_data = [(weight_attribute, []), (color_attribute, [])]-- # when- errors = validate_attributes_input_for_product_and_page(- input_data, page_type.page_attributes.all(), PageErrorCode- )-- # then- assert len(errors) == 1- error = errors[0]- assert error.code == PageErrorCode.REQUIRED.value- assert set(error.params["attributes"]) == {- graphene.Node.to_global_id("Attribute", attr.pk)- for attr in [weight_attribute, color_attribute]- }---def test_validate_attributes_input_for_page_too_many_values_given(- weight_attribute, color_attribute, page_type-):- # given- color_attribute.input_type = AttributeInputType.DROPDOWN- color_attribute.value_required = True- color_attribute.save(update_fields=["value_required", "input_type"])-- weight_attribute.value_required = True- weight_attribute.input_type = AttributeInputType.MULTISELECT- weight_attribute.save(update_fields=["value_required", "input_type"])-- input_data = [(weight_attribute, ["abc", "efg"]), (color_attribute, ["a", "b"])]-- # when- errors = validate_attributes_input_for_product_and_page(- input_data, page_type.page_attributes.all(), PageErrorCode- )-- # then- assert len(errors) == 1- error = errors[0]- assert error.code == PageErrorCode.INVALID.value- assert error.params["attributes"] == [- graphene.Node.to_global_id("Attribute", color_attribute.pk)- ]---def test_validate_attributes_input_for_page_empty_values_given(- weight_attribute, color_attribute, page_type-):- # given- color_attribute.input_type = AttributeInputType.DROPDOWN- color_attribute.value_required = True- color_attribute.save(update_fields=["value_required", "input_type"])-- weight_attribute.value_required = True- weight_attribute.input_type = AttributeInputType.MULTISELECT- weight_attribute.save(update_fields=["value_required", "input_type"])-- input_data = [(weight_attribute, ["a", None]), (color_attribute, [" "])]-- # when- errors = validate_attributes_input_for_product_and_page(- input_data, page_type.page_attributes.all(), PageErrorCode- )-- # then- assert len(errors) == 1- error = errors[0]- assert error.code == PageErrorCode.REQUIRED.value- assert set(error.params["attributes"]) == {- graphene.Node.to_global_id("Attribute", attr.pk)- for attr in [weight_attribute, color_attribute]- }---def test_validate_attributes_input_for_page_lack_of_required_attribute(- weight_attribute, color_attribute, page_type-):- # given- page_attributes = page_type.page_attributes.all()- attr = page_attributes.first()- attr.value_required = True- attr.save(update_fields=["value_required"])-- weight_attribute.value_required = True- weight_attribute.save(update_fields=["value_required"])-- input_data = [(weight_attribute, ["a"])]-- # when- errors = validate_attributes_input_for_product_and_page(- input_data, page_attributes, PageErrorCode- )-- # then- assert len(errors) == 1- error = errors[0]- assert error.code == PageErrorCode.REQUIRED.value- assert set(error.params["attributes"]) == {- graphene.Node.to_global_id("Attribute", attr.pk)- }---def test_validate_attributes_input_for_page_multiply_errors(- weight_attribute, color_attribute, page_type-):- # given- color_attribute.input_type = AttributeInputType.DROPDOWN- color_attribute.value_required = True- color_attribute.save(update_fields=["value_required", "input_type"])-- weight_attribute.value_required = True- weight_attribute.input_type = AttributeInputType.MULTISELECT- weight_attribute.save(update_fields=["value_required", "input_type"])-- input_data = [(weight_attribute, [None]), (color_attribute, ["a", "b"])]-- # when- errors = validate_attributes_input_for_product_and_page(- input_data, page_type.page_attributes.all(), PageErrorCode- )-- # then- assert len(errors) == 2- assert {error.code for error in errors} == {- PageErrorCode.INVALID.value,- PageErrorCode.REQUIRED.value,- }- assert {attr for error in errors for attr in error.params["attributes"]} == {- graphene.Node.to_global_id("Attribute", attr.pk)- for attr in [weight_attribute, color_attribute]- }---def test_validate_attributes_input_for_variant(weight_attribute, color_attribute):- # given- color_attribute.value_required = True- color_attribute.save(update_fields=["value_required"])-- weight_attribute.value_required = True- weight_attribute.save(update_fields=["value_required"])-- input_data = [(weight_attribute, ["a"]), (color_attribute, ["b"])]-- # when- errors = validate_attributes_input_for_variant(input_data)-- # then- assert not errors---def test_validate_attributes_input_for_variant_no_values_given(- weight_attribute, color_attribute-):- # given- color_attribute.value_required = True- color_attribute.save(update_fields=["value_required"])-- weight_attribute.value_required = True- weight_attribute.save(update_fields=["value_required"])-- input_data = [(weight_attribute, []), (color_attribute, [])]-- # when- errors = validate_attributes_input_for_variant(input_data)-- # then- assert len(errors) == 1- error = errors[0]- assert error.code == ProductErrorCode.REQUIRED.value- assert set(error.params["attributes"]) == {- graphene.Node.to_global_id("Attribute", attr.pk)- for attr in [weight_attribute, color_attribute]- }---def test_validate_attributes_input_for_variant_too_many_values_given(- weight_attribute, color_attribute-):- # given- color_attribute.value_required = True- color_attribute.save(update_fields=["value_required"])-- weight_attribute.value_required = True- weight_attribute.save(update_fields=["value_required"])-- input_data = [(weight_attribute, ["abc", "efg"]), (color_attribute, ["a", "b"])]-- # when- errors = validate_attributes_input_for_variant(input_data)-- # then- assert len(errors) == 1- error = errors[0]- assert error.code == ProductErrorCode.INVALID.value- assert set(error.params["attributes"]) == {- graphene.Node.to_global_id("Attribute", attr.pk)- for attr in [weight_attribute, color_attribute]- }---def test_validate_attributes_input_for_variant_empty_values_given(- weight_attribute, color_attribute-):- # given- color_attribute.value_required = True- color_attribute.save(update_fields=["value_required", "input_type"])-- weight_attribute.value_required = True- weight_attribute.save(update_fields=["value_required", "input_type"])-- input_data = [(weight_attribute, [None]), (color_attribute, [" "])]-- # when- errors = validate_attributes_input_for_variant(input_data)-- # then- assert len(errors) == 1- error = errors[0]- assert error.code == ProductErrorCode.REQUIRED.value- assert set(error.params["attributes"]) == {- graphene.Node.to_global_id("Attribute", attr.pk)- for attr in [weight_attribute, color_attribute]- }---def test_validate_attributes_input_for_variant_multiply_errors(- weight_attribute, color_attribute-):- # given- color_attribute.value_required = True- color_attribute.save(update_fields=["value_required", "input_type"])-- weight_attribute.value_required = True- weight_attribute.save(update_fields=["value_required", "input_type"])-- input_data = [(weight_attribute, [None]), (color_attribute, ["a", "b"])]-- # when- errors = validate_attributes_input_for_variant(input_data)-- # then- assert len(errors) == 2- assert {error.code for error in errors} == {- ProductErrorCode.INVALID.value,- ProductErrorCode.REQUIRED.value,- }- assert {attr for error in errors for attr in error.params["attributes"]} == {- graphene.Node.to_global_id("Attribute", attr.pk)- for attr in [weight_attribute, color_attribute]- }diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.pyindex 1689b7141f..cbbe98f253 100644--- a/saleor/graphql/product/tests/test_variant.py+++ b/saleor/graphql/product/tests/test_variant.py@@ -3,9 +3,11 @@ from uuid import uuid4import grapheneimport pytest+from django.utils.text import slugifyfrom measurement.measures import Weightfrom prices import Money, TaxedMoney+from ....attribute import AttributeInputTypefrom ....attribute.utils import associate_attribute_values_to_instancefrom ....core.weight import WeightUnitsfrom ....order import OrderStatus@@ -270,7 +272,12 @@ CREATE_VARIANT_MUTATION = """slug}values {+ nameslug+ file {+ url+ contentType+ }}}costPrice {@@ -346,6 +353,192 @@ def test_create_variant(updated_webhook_mock.assert_called_once_with(product)+@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_create_variant_with_file_attribute(+ updated_webhook_mock,+ staff_api_client,+ product,+ product_type,+ file_attribute,+ permission_manage_products,+ warehouse,+):+ query = CREATE_VARIANT_MUTATION+ product_id = graphene.Node.to_global_id("Product", product.pk)+ sku = "1"+ weight = 10.22++ product_type.variant_attributes.clear()+ product_type.variant_attributes.add(file_attribute)+ file_attr_id = graphene.Node.to_global_id("Attribute", file_attribute.id)+ existing_value = file_attribute.values.first()++ values_count = file_attribute.values.count()++ stocks = [+ {+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),+ "quantity": 20,+ }+ ]++ variables = {+ "productId": product_id,+ "sku": sku,+ "stocks": stocks,+ "weight": weight,+ "attributes": [{"id": file_attr_id, "file": existing_value.file_url}],+ "trackInventory": True,+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)["data"]["productVariantCreate"]+ assert not content["productErrors"]+ data = content["productVariant"]+ assert data["name"] == sku+ assert data["sku"] == sku+ assert data["attributes"][0]["attribute"]["slug"] == file_attribute.slug+ assert data["attributes"][0]["values"][0]["slug"] == f"{existing_value.slug}-2"+ assert data["attributes"][0]["values"][0]["name"] == existing_value.name+ assert data["weight"]["unit"] == WeightUnitsEnum.KG.name+ assert data["weight"]["value"] == weight+ assert len(data["stocks"]) == 1+ assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]+ assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug++ file_attribute.refresh_from_db()+ assert file_attribute.values.count() == values_count + 1++ updated_webhook_mock.assert_called_once_with(product)+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_create_variant_with_file_attribute_new_value(+ updated_webhook_mock,+ staff_api_client,+ product,+ product_type,+ file_attribute,+ permission_manage_products,+ warehouse,+):+ 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++ product_type.variant_attributes.clear()+ product_type.variant_attributes.add(file_attribute)+ file_attr_id = graphene.Node.to_global_id("Attribute", file_attribute.id)+ new_value = "new_value.txt"++ values_count = file_attribute.values.count()++ 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": file_attr_id, "file": new_value}],+ "trackInventory": True,+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)["data"]["productVariantCreate"]+ assert not content["productErrors"]+ data = content["productVariant"]+ assert data["name"] == sku+ assert data["sku"] == sku+ assert data["attributes"][0]["attribute"]["slug"] == file_attribute.slug+ assert data["attributes"][0]["values"][0]["slug"] == slugify(new_value)+ assert data["weight"]["unit"] == WeightUnitsEnum.KG.name+ assert data["weight"]["value"] == weight+ assert len(data["stocks"]) == 1+ assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]+ assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug++ file_attribute.refresh_from_db()+ assert file_attribute.values.count() == values_count + 1++ updated_webhook_mock.assert_called_once_with(product)+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_create_variant_with_file_attribute_no_file_url_given(+ updated_webhook_mock,+ staff_api_client,+ product,+ product_type,+ file_attribute,+ permission_manage_products,+ warehouse,+):+ 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++ product_type.variant_attributes.clear()+ product_type.variant_attributes.add(file_attribute)+ file_attr_id = graphene.Node.to_global_id("Attribute", file_attribute.id)++ values_count = file_attribute.values.count()++ 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": file_attr_id}],+ "trackInventory": True,+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)["data"]["productVariantCreate"]+ errors = content["productErrors"]+ data = content["productVariant"]+ assert not errors+ assert data["name"] == sku+ assert data["sku"] == sku+ assert data["attributes"][0]["attribute"]["slug"] == file_attribute.slug+ assert len(data["attributes"][0]["values"]) == 0+ assert data["weight"]["unit"] == WeightUnitsEnum.KG.name+ assert data["weight"]["value"] == weight+ assert len(data["stocks"]) == 1+ assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]+ assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug++ file_attribute.refresh_from_db()+ assert file_attribute.values.count() == values_count++ updated_webhook_mock.assert_called_once_with(product)++def test_create_product_variant_with_negative_weight(staff_api_client, product, product_type, permission_manage_products):@@ -726,6 +919,22 @@ QUERY_UPDATE_VARIANT_ATTRIBUTES = """sku: $sku,attributes: $attributes}) {+ productVariant {+ sku+ attributes {+ attribute {+ slug+ }+ values {+ slug+ name+ file {+ url+ contentType+ }+ }+ }+ }errors {fieldmessage@@ -770,7 +979,7 @@ def test_update_product_variant_not_all_attributes(assert len(content["data"]["productVariantUpdate"]["errors"]) == 1assert content["data"]["productVariantUpdate"]["errors"][0] == {"field": "attributes",- "message": "All attributes must take a value",+ "message": "All variant selection attributes must take a value.",}assert not product.variants.filter(sku=sku).exists()@@ -911,11 +1120,155 @@ def test_update_product_variant_with_duplicated_attribute(}+def test_update_product_variant_with_current_file_attribute(+ staff_api_client,+ product_with_variant_with_file_attribute,+ file_attribute,+ permission_manage_products,+):+ product = product_with_variant_with_file_attribute+ variant = product.variants.first()+ sku = str(uuid4())[:12]+ assert not variant.sku == sku+ assert set(variant.attributes.first().values.values_list("slug", flat=True)) == {+ "test_filetxt"+ }+ second_value = file_attribute.values.last()++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ file_attribute_id = graphene.Node.to_global_id("Attribute", file_attribute.pk)++ variables = {+ "id": variant_id,+ "sku": sku,+ "price": 15,+ "attributes": [{"id": file_attribute_id, "file": second_value.file_url}],+ }++ response = staff_api_client.post_graphql(+ QUERY_UPDATE_VARIANT_ATTRIBUTES,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)++ data = content["data"]["productVariantUpdate"]+ assert not data["errors"]+ variant_data = data["productVariant"]+ assert variant_data+ assert variant_data["sku"] == sku+ assert len(variant_data["attributes"]) == 1+ assert variant_data["attributes"][0]["attribute"]["slug"] == file_attribute.slug+ assert len(variant_data["attributes"][0]["values"]) == 1+ assert (+ variant_data["attributes"][0]["values"][0]["slug"]+ == f"{slugify(second_value)}-2"+ )+++def test_update_product_variant_with_duplicated_file_attribute(+ staff_api_client,+ product_with_variant_with_file_attribute,+ file_attribute,+ permission_manage_products,+):+ product = product_with_variant_with_file_attribute+ variant = product.variants.first()+ variant2 = product.variants.first()++ variant2.pk = None+ variant2.sku = str(uuid4())[:12]+ variant2.save()+ file_attr_value = file_attribute.values.last()+ associate_attribute_values_to_instance(variant2, file_attribute, file_attr_value)++ sku = str(uuid4())[:12]+ assert not variant.sku == sku++ assert set(variant.attributes.first().values.values_list("slug", flat=True)) == {+ "test_filetxt"+ }+ assert set(variant2.attributes.first().values.values_list("slug", flat=True)) == {+ "test_filejpeg"+ }++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ file_attribute_id = graphene.Node.to_global_id("Attribute", file_attribute.pk)++ variables = {+ "id": variant_id,+ "price": 15,+ "attributes": [{"id": file_attribute_id, "file": file_attr_value.file_url}],+ "sku": sku,+ }++ response = staff_api_client.post_graphql(+ QUERY_UPDATE_VARIANT_ATTRIBUTES,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)++ data = content["data"]["productVariantUpdate"]+ assert data["productErrors"][0] == {+ "field": "attributes",+ "code": ProductErrorCode.DUPLICATED_INPUT_ITEM.name,+ }+++def test_update_product_variant_with_file_attribute_new_value_is_not_created(+ staff_api_client,+ product_with_variant_with_file_attribute,+ file_attribute,+ permission_manage_products,+):+ product = product_with_variant_with_file_attribute+ variant = product.variants.first()+ sku = str(uuid4())[:12]+ assert not variant.sku == sku++ existing_value = file_attribute.values.first()+ assert variant.attributes.filter(+ assignment__attribute=file_attribute, values=existing_value+ ).exists()++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ file_attribute_id = graphene.Node.to_global_id("Attribute", file_attribute.pk)++ variables = {+ "id": variant_id,+ "sku": sku,+ "price": 15,+ "attributes": [{"id": file_attribute_id, "file": existing_value.file_url}],+ }++ response = staff_api_client.post_graphql(+ QUERY_UPDATE_VARIANT_ATTRIBUTES,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)++ data = content["data"]["productVariantUpdate"]+ assert not data["errors"]+ variant_data = data["productVariant"]+ assert variant_data+ assert variant_data["sku"] == sku+ assert len(variant_data["attributes"]) == 1+ assert variant_data["attributes"][0]["attribute"]["slug"] == file_attribute.slug+ assert len(variant_data["attributes"][0]["values"]) == 1+ value_data = variant_data["attributes"][0]["values"][0]+ assert value_data["slug"] == existing_value.slug+ assert value_data["name"] == existing_value.name+ assert value_data["file"]["url"] == existing_value.file_url+ assert value_data["file"]["contentType"] == existing_value.content_type++@pytest.mark.parametrize("values, message",(([], "Attribute expects a value but none were given"),- (["one", "two"], "A variant attribute cannot take more than one value"),+ (["one", "two"], "Attribute must take only one value"),([" "], "Attribute values cannot be blank"),([None], "Attribute values cannot be blank"),),@@ -1407,6 +1760,7 @@ PRODUCT_VARIANT_BULK_CREATE_MUTATION = """}productVariants{id+ nameskustocks {warehouse {@@ -1461,6 +1815,50 @@ def test_product_variant_bulk_create_by_attribute_id(data = content["data"]["productVariantBulkCreate"]assert not data["bulkProductErrors"]assert data["count"] == 1+ assert data["productVariants"][0]["name"] == attribute_value.name+ assert product_variant_count + 1 == ProductVariant.objects.count()+ assert attribute_value_count == size_attribute.values.count()+ product_variant = ProductVariant.objects.get(sku=sku)+ product.refresh_from_db()+ assert product.default_variant == product_variant+++def test_product_variant_bulk_create_only_not_variant_selection_attributes(+ staff_api_client, product, size_attribute, permission_manage_products+):+ """Ensure that sku is set as variant name when only variant selection attributes+ are assigned.+ """+ product_variant_count = ProductVariant.objects.count()+ attribute_value_count = size_attribute.values.count()++ size_attribute.input_type = AttributeInputType.MULTISELECT+ size_attribute.save(update_fields=["input_type"])++ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribut_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)++ attribute_value = size_attribute.values.last()+ sku = str(uuid4())[:12]+ variants = [+ {+ "sku": sku,+ "weight": 2.5,+ "trackInventory": True,+ "attributes": [{"id": attribut_id, "values": [attribute_value.name]}],+ }+ ]++ variables = {"productId": product_id, "variants": variants}+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantBulkCreate"]+ assert not data["bulkProductErrors"]+ assert data["count"] == 1+ assert data["productVariants"][0]["name"] == skuassert product_variant_count + 1 == ProductVariant.objects.count()assert attribute_value_count == size_attribute.values.count()product_variant = ProductVariant.objects.get(sku=sku)@@ -1519,6 +1917,50 @@ def test_product_variant_bulk_create_with_new_attribute_value(assert attribute_value_count + 1 == size_attribute.values.count()+def test_product_variant_bulk_create_variant_selection_and_other_attributes(+ staff_api_client,+ product,+ size_attribute,+ file_attribute,+ permission_manage_products,+):+ """Ensure that only values for variant selection attributes are required."""+ product_type = product.product_type+ product_type.variant_attributes.add(file_attribute)++ product_variant_count = ProductVariant.objects.count()+ attribute_value_count = size_attribute.values.count()++ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)++ attribute_value = size_attribute.values.last()+ sku = str(uuid4())[:12]+ variants = [+ {+ "sku": sku,+ "weight": 2.5,+ "trackInventory": True,+ "attributes": [{"id": attribute_id, "values": [attribute_value.name]}],+ }+ ]++ variables = {"productId": product_id, "variants": variants}+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantBulkCreate"]+ assert not data["bulkProductErrors"]+ assert data["count"] == 1+ assert product_variant_count + 1 == ProductVariant.objects.count()+ assert attribute_value_count == size_attribute.values.count()+ product_variant = ProductVariant.objects.get(sku=sku)+ product.refresh_from_db()+ assert product.default_variant == product_variant++def test_product_variant_bulk_create_stocks_input(staff_api_client, product, permission_manage_products, warehouses, size_attribute):diff --git a/saleor/graphql/product/tests/test_variant_query.py b/saleor/graphql/product/tests/test_variant_query.pyindex 09fe935329..6d33b9927e 100644--- a/saleor/graphql/product/tests/test_variant_query.py+++ b/saleor/graphql/product/tests/test_variant_query.py@@ -1,11 +1,21 @@import graphene+import pytest+from ....attribute.utils import _associate_attribute_to_instancefrom ...tests.utils import assert_graphql_error_with_message, get_graphql_content+from ..enums import VariantAttributeScopeVARIANT_QUERY = """-query variant($id: ID, $sku: String, $channel: String){- productVariant(id: $id, sku: $sku, channel: $channel){+query variant(+ $id: ID, $sku: String, $variantSelection: VariantAttributeScope, $channel: String+){+ productVariant(id:$id, sku:$sku, channel: $channel){sku+ attributes(variantSelection: $variantSelection) {+ attribute {+ slug+ }+ }}}"""@@ -339,3 +349,58 @@ def test_get_variant_by_sku_as_anonymous_user(api_client, variant, channel_USD):content = get_graphql_content(response)data = content["data"]["productVariant"]assert data["sku"] == variant.sku+++ "variant_selection",+ [+ VariantAttributeScope.ALL.name,+ VariantAttributeScope.VARIANT_SELECTION.name,+ VariantAttributeScope.NOT_VARIANT_SELECTION.name,+ ],+)+def test_get_variant_by_id_with_variant_selection_filter(+ variant_selection,+ staff_api_client,+ permission_manage_products,+ variant,+ size_attribute,+ file_attribute_with_file_input_type_without_values,+ product_type,+):+ # given+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ variables = {"id": variant_id, "variantSelection": variant_selection}++ product_type.variant_attributes.add(+ file_attribute_with_file_input_type_without_values+ )++ _associate_attribute_to_instance(+ variant, file_attribute_with_file_input_type_without_values.pk+ )+ _associate_attribute_to_instance(variant, size_attribute.pk)++ # when+ response = staff_api_client.post_graphql(+ VARIANT_QUERY,+ variables,+ permissions=[permission_manage_products],+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productVariant"]+ assert data["sku"] == variant.sku+ if variant_selection == VariantAttributeScope.NOT_VARIANT_SELECTION.name:+ assert len(data["attributes"]) == 1+ assert (+ data["attributes"][0]["attribute"]["slug"]+ == file_attribute_with_file_input_type_without_values.slug+ )+ elif variant_selection == VariantAttributeScope.VARIANT_SELECTION.name:+ assert len(data["attributes"]) == 1+ assert data["attributes"][0]["attribute"]["slug"] == size_attribute.slug+ else:+ len(data["attributes"]) == 2diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex e448cbf613..06bd9da9a4 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -1,4 +1,5 @@from dataclasses import asdict+from typing import Optionalimport graphenefrom django.conf import settings@@ -19,6 +20,7 @@ from ....product.utils.availability import (get_product_availability,get_variant_availability,)+from ....product.utils.variants import get_variant_selection_attributesfrom ....warehouse.availability import (get_available_quantity,get_quantity_allocated,@@ -80,6 +82,7 @@ from ..dataloaders import (VariantChannelListingByVariantIdLoader,VariantsChannelListingByProductIdAndChanneSlugLoader,)+from ..enums import VariantAttributeScopefrom ..filters import ProductFilterInputfrom ..sorters import ProductOrderfrom .channels import (@@ -189,6 +192,9 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):graphene.NonNull(SelectedAttribute),required=True,description="List of attributes assigned to this variant.",+ variant_selection=graphene.Argument(+ VariantAttributeScope, description="Define scope of returned attributes.",+ ),)cost_price = graphene.Field(Money, description="Cost price of the variant.")margin = graphene.Int(description="Gross margin percentage value.")@@ -282,9 +288,35 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):).load((root.node.id, info.context.country))@staticmethod- def resolve_attributes(root: ChannelContext[models.ProductVariant], info):- return SelectedAttributesByProductVariantIdLoader(info.context).load(- root.node.id+ def resolve_attributes(+ root: ChannelContext[models.ProductVariant],+ info,+ variant_selection: Optional[str] = None,+ ):+ def apply_variant_selection_filter(selected_attributes):+ if not variant_selection or variant_selection == VariantAttributeScope.ALL:+ return selected_attributes+ attributes = [+ selected_att["attribute"] for selected_att in selected_attributes+ ]+ variant_selection_attrs = get_variant_selection_attributes(attributes)++ if variant_selection == VariantAttributeScope.VARIANT_SELECTION:+ return [+ selected_attribute+ for selected_attribute in selected_attributes+ if selected_attribute["attribute"] in variant_selection_attrs+ ]+ return [+ selected_attribute+ for selected_attribute in selected_attributes+ if selected_attribute["attribute"] not in variant_selection_attrs+ ]++ return (+ SelectedAttributesByProductVariantIdLoader(info.context)+ .load(root.node.id)+ .then(apply_variant_selection_filter))@staticmethod@@ -772,7 +804,11 @@ class ProductType(CountableDjangoObjectType):TaxType, description="A type of tax. Assigned by enabled tax gateway")variant_attributes = graphene.List(- Attribute, description="Variant attributes of that product type."+ Attribute,+ description="Variant attributes of that product type.",+ variant_selection=graphene.Argument(+ VariantAttributeScope, description="Define scope of returned attributes.",+ ),)product_attributes = graphene.List(Attribute, description="Product attributes of that product type."@@ -816,8 +852,22 @@ class ProductType(CountableDjangoObjectType):return ProductAttributesByProductTypeIdLoader(info.context).load(root.pk)@staticmethod- def resolve_variant_attributes(root: models.ProductType, info):- return VariantAttributesByProductTypeIdLoader(info.context).load(root.pk)+ def resolve_variant_attributes(+ root: models.ProductType, info, variant_selection: Optional[str] = None,+ ):+ def apply_variant_selection_filter(attributes):+ if not variant_selection or variant_selection == VariantAttributeScope.ALL:+ return attributes+ variant_selection_attrs = get_variant_selection_attributes(attributes)+ if variant_selection == VariantAttributeScope.VARIANT_SELECTION:+ return variant_selection_attrs+ return [attr for attr in attributes if attr not in variant_selection_attrs]++ return (+ VariantAttributesByProductTypeIdLoader(info.context)+ .load(root.pk)+ .then(apply_variant_selection_filter)+ )@staticmethoddef resolve_products(root: models.ProductType, info, channel=None, **_kwargs):diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.pyindex e2f2f70fbc..dadf5f67ee 100644--- a/saleor/graphql/product/utils.py+++ b/saleor/graphql/product/utils.py@@ -1,144 +1,18 @@from collections import defaultdict-from typing import TYPE_CHECKING, Dict, List, Tuple+from typing import TYPE_CHECKING, Dict, Listimport graphenefrom django.core.exceptions import ValidationErrorfrom django.db import transaction-from django.db.models import Qfrom django.db.utils import IntegrityError-from ...attribute import AttributeInputType-from ...product.error_codes import ProductErrorCodefrom ...warehouse.models import Stockif TYPE_CHECKING:from django.db.models import QuerySet- from ...attribute.models import Attributefrom ...product.models import ProductVariant-def validate_attributes_input_for_product_and_page(- input_data: List[Tuple["Attribute", List[str]]],- attribute_qs: "QuerySet",- error_code_enum,-):- """Validate attribute input.-- - ensure all required attributes are passed- - ensure the values are correct for a products or a page- """-- error_no_value_given = ValidationError(- "Attribute expects a value but none were given",- code=error_code_enum.REQUIRED.value,- )- error_dropdown_get_more_than_one_value = ValidationError(- "Attribute attribute must take only one value",- code=error_code_enum.INVALID.value,- )- error_blank_value = ValidationError(- "Attribute values cannot be blank", code=error_code_enum.REQUIRED.value,- )-- attribute_errors: Dict[ValidationError, List[str]] = defaultdict(list)- for attribute, values in input_data:- attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)- if not values:- if attribute.value_required:- attribute_errors[error_no_value_given].append(attribute_id)- continue-- if attribute.input_type != AttributeInputType.MULTISELECT and len(values) != 1:- attribute_errors[error_dropdown_get_more_than_one_value].append(- attribute_id- )- continue-- for value in values:- if value is None or not value.strip():- attribute_errors[error_blank_value].append(attribute_id)- continue-- errors = prepare_error_list_from_error_attribute_mapping(attribute_errors)- errors = validate_required_attributes(- input_data, attribute_qs, errors, error_code_enum- )-- return errors---def validate_required_attributes(- input_data: List[Tuple["Attribute", List[str]]],- attribute_qs: "QuerySet",- errors: List[ValidationError],- error_code_enum,-):- """Ensure all required attributes are supplied."""-- supplied_attribute_pk = [attribute.pk for attribute, _ in input_data]-- missing_required_attributes = attribute_qs.filter(- Q(value_required=True) & ~Q(pk__in=supplied_attribute_pk)- )-- if missing_required_attributes:- ids = [- graphene.Node.to_global_id("Attribute", attr.pk)- for attr in missing_required_attributes- ]- error = ValidationError(- "All attributes flagged as having a value required must be supplied.",- code=error_code_enum.REQUIRED.value,- params={"attributes": ids},- )- errors.append(error)-- return errors---def validate_attributes_input_for_variant(- input_data: List[Tuple["Attribute", List[str]]]-):- error_no_value_given = ValidationError(- "Attribute expects a value but none were given",- code=ProductErrorCode.REQUIRED.value,- )- error_more_than_one_value_given = ValidationError(- "A variant attribute cannot take more than one value",- code=ProductErrorCode.INVALID.value,- )- error_blank_value = ValidationError(- "Attribute values cannot be blank", code=ProductErrorCode.REQUIRED.value,- )-- attribute_errors: Dict[ValidationError, List[str]] = defaultdict(list)- for attribute, values in input_data:- attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)- if not values:- attribute_errors[error_no_value_given].append(attribute_id)- continue-- if len(values) != 1:- attribute_errors[error_more_than_one_value_given].append(attribute_id)- continue-- if values[0] is None or not values[0].strip():- attribute_errors[error_blank_value].append(attribute_id)-- return prepare_error_list_from_error_attribute_mapping(attribute_errors)---def prepare_error_list_from_error_attribute_mapping(- attribute_errors: Dict[ValidationError, List[str]]-):- errors = []- for error, attributes in attribute_errors.items():- error.params = {"attributes": attributes}- errors.append(error)-- return errors--def get_used_attribute_values_for_variant(variant):"""Create a dict of attributes values for variant.@@ -152,8 +26,8 @@ def get_used_attribute_values_for_variant(variant):for assigned_variant_attribute in variant.attributes.all():attribute = assigned_variant_attribute.attributeattribute_id = graphene.Node.to_global_id("Attribute", attribute.id)- for variant in assigned_variant_attribute.values.all():- attribute_values[attribute_id].append(variant.slug)+ for attr_value in assigned_variant_attribute.values.all():+ attribute_values[attribute_id].append(attr_value.slug)return attribute_valuesdiff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 9047b0c1bb..0939b68bf5 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -489,6 +489,7 @@ input AttributeInput {enum AttributeInputTypeEnum {DROPDOWNMULTISELECT+ FILE}type AttributeReorderValues {@@ -565,6 +566,7 @@ type AttributeValue implements Node {type: AttributeValueType @deprecated(reason: "Use the `inputType` field to determine the type of attribute's value. This field will be removed after 2020-07-31.")translation(languageCode: LanguageCodeEnum!): AttributeValueTranslationinputType: AttributeInputTypeEnum+ file: File}type AttributeValueBulkDelete {@@ -593,7 +595,9 @@ type AttributeValueDelete {input AttributeValueInput {id: ID- values: [String]!+ values: [String]+ file: String+ contentType: String}type AttributeValueTranslatableContent implements Node {@@ -658,6 +662,11 @@ enum AuthorizationKeyType {GOOGLE_OAUTH2}+input BulkAttributeValueInput {+ id: ID+ values: [String]!+}+type BulkProductError {field: Stringmessage: String@@ -1961,6 +1970,11 @@ enum ExportScope {FILTER}+type File {+ url: String!+ contentType: String+}+enum FileTypesEnum {CSVXLSX@@ -1968,7 +1982,7 @@ enum FileTypesEnum {type FileUpload {errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")- uploadedFile: UploadedFile+ uploadedFile: FileuploadErrors: [UploadError!]!}@@ -4087,7 +4101,7 @@ type ProductType implements Node & ObjectWithMetadata {products(channel: String, before: String, after: String, first: Int, last: Int): ProductCountableConnection @deprecated(reason: "Use the top-level `products` query with the `productTypes` filter.")taxRate: TaxRateTypetaxType: TaxType- variantAttributes: [Attribute]+ variantAttributes(variantSelection: VariantAttributeScope): [Attribute]productAttributes: [Attribute]availableAttributes(filter: AttributeFilterInput, before: String, after: String, first: Int, last: Int): AttributeCountableConnection}@@ -4194,7 +4208,7 @@ type ProductVariant implements Node & ObjectWithMetadata {channelListings: [ProductVariantChannelListing!]pricing: VariantPricingInfoisAvailable: Boolean @deprecated(reason: "Use the stock field instead. This field will be removed after 2020-07-31.")- attributes: [SelectedAttribute!]!+ attributes(variantSelection: VariantAttributeScope): [SelectedAttribute!]!costPrice: Moneymargin: IntquantityOrdered: Int@@ -4214,7 +4228,7 @@ type ProductVariantBulkCreate {}input ProductVariantBulkCreateInput {- attributes: [AttributeValueInput]!+ attributes: [BulkAttributeValueInput]!sku: String!trackInventory: Booleanweight: WeightScalar@@ -5268,11 +5282,6 @@ enum UploadErrorCode {GRAPHQL_ERROR}-type UploadedFile {- url: String!- contentType: String!-}-type User implements Node & ObjectWithMetadata {id: ID!lastLogin: DateTime@@ -5365,6 +5374,12 @@ type VAT {reducedRates: [ReducedRate]!}+enum VariantAttributeScope {+ ALL+ VARIANT_SELECTION+ NOT_VARIANT_SELECTION+}+type VariantImageAssign {errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")productVariant: ProductVariantdiff --git a/saleor/product/tasks.py b/saleor/product/tasks.pyindex 8f8ce41d02..42adc450cd 100644--- a/saleor/product/tasks.py+++ b/saleor/product/tasks.py@@ -10,7 +10,7 @@ from .utils.variant_prices import (update_products_discounted_prices_of_catalogues,update_products_discounted_prices_of_discount,)-from .utils.variants import generate_name_for_variant+from .utils.variants import generate_and_set_variant_namedef _update_variants_names(instance: ProductType, saved_attributes: Iterable):@@ -31,8 +31,7 @@ def _update_variants_names(instance: ProductType, saved_attributes: Iterable):"attributes__values__translations").all()for variant in variants_to_be_updated:- variant.name = generate_name_for_variant(variant)- variant.save(update_fields=["name"])+ generate_and_set_variant_name(variant, variant.sku)@app.taskdiff --git a/saleor/product/tests/test_generate_and_set_variant_name.py b/saleor/product/tests/test_generate_and_set_variant_name.pynew file mode 100644index 0000000000..ccb2c8d66d--- /dev/null+++ b/saleor/product/tests/test_generate_and_set_variant_name.py@@ -0,0 +1,196 @@+from decimal import Decimal+from unittest.mock import MagicMock, Mock++import pytest++from ...attribute import AttributeInputType+from ...attribute.models import AttributeValue+from ...attribute.utils import associate_attribute_values_to_instance+from ...product.models import ProductVariantChannelListing+from ..models import Product, ProductType, ProductVariant+from ..tasks import _update_variants_names+from ..utils.variants import generate_and_set_variant_name+++def variant_with_no_attributes(category, channel_USD):+ """Create a variant having no attributes, the same for the parent product."""+ product_type = ProductType.objects.create(+ name="Test product type", has_variants=True, is_shipping_required=True+ )+ product = Product.objects.create(+ name="Test product", product_type=product_type, category=category,+ )+ variant = ProductVariant.objects.create(product=product, sku="123")+ ProductVariantChannelListing.objects.create(+ variant=variant,+ channel=channel_USD,+ cost_price_amount=Decimal(1),+ price_amount=Decimal(10),+ currency=channel_USD.currency_code,+ )+ return variant+++def test_generate_and_set_variant_name_different_attributes(+ variant_with_no_attributes, color_attribute_without_values, size_attribute+):+ """Test the name generation from a given variant containing multiple attributes and+ different input types (dropdown and multiselect).+ """++ variant = variant_with_no_attributes+ color_attribute = color_attribute_without_values++ # Assign the attributes to the product type+ variant.product.product_type.variant_attributes.set(+ (color_attribute, size_attribute)+ )++ # Set the color attribute to a multi-value attribute+ color_attribute.input_type = AttributeInputType.MULTISELECT+ color_attribute.save(update_fields=["input_type"])++ # Create colors+ colors = AttributeValue.objects.bulk_create(+ [+ AttributeValue(attribute=color_attribute, name="Yellow", slug="yellow"),+ AttributeValue(attribute=color_attribute, name="Blue", slug="blue"),+ AttributeValue(attribute=color_attribute, name="Red", slug="red"),+ ]+ )++ # Retrieve the size attribute value "Big"+ size = size_attribute.values.get(slug="big")++ # Associate the colors and size to variant attributes+ associate_attribute_values_to_instance(variant, color_attribute, *tuple(colors))+ associate_attribute_values_to_instance(variant, size_attribute, size)++ # Generate the variant name from the attributes+ generate_and_set_variant_name(variant, variant.sku)+ variant.refresh_from_db()+ assert variant.name == "Big"+++def test_generate_and_set_variant_name_only_variant_selection_attributes(+ variant_with_no_attributes, color_attribute_without_values, size_attribute+):+ """Test the name generation for a given variant containing multiple attributes+ with input types allowed in variant selection.+ """++ variant = variant_with_no_attributes+ color_attribute = color_attribute_without_values++ # Assign the attributes to the product type+ variant.product.product_type.variant_attributes.set(+ (color_attribute, size_attribute)+ )++ # Create values+ colors = AttributeValue.objects.bulk_create(+ [+ AttributeValue(attribute=color_attribute, name="Yellow", slug="yellow"),+ AttributeValue(attribute=color_attribute, name="Blue", slug="blue"),+ AttributeValue(attribute=color_attribute, name="Red", slug="red"),+ ]+ )++ # Retrieve the size attribute value "Big"+ size = size_attribute.values.get(slug="big")++ # Associate the colors and size to variant attributes+ associate_attribute_values_to_instance(variant, color_attribute, *tuple(colors))+ associate_attribute_values_to_instance(variant, size_attribute, size)++ # Generate the variant name from the attributes+ generate_and_set_variant_name(variant, variant.sku)+ variant.refresh_from_db()+ assert variant.name == "Yellow, Blue, Red / Big"+++def test_generate_and_set_variant_name_only_not_variant_selection_attributes(+ variant_with_no_attributes, color_attribute_without_values, file_attribute+):+ """Test the name generation for a given variant containing multiple attributes+ with input types not allowed in variant selection.+ """++ variant = variant_with_no_attributes+ color_attribute = color_attribute_without_values++ # Assign the attributes to the product type+ variant.product.product_type.variant_attributes.set(+ (color_attribute, file_attribute)+ )++ # Set the color attribute to a multi-value attribute+ color_attribute.input_type = AttributeInputType.MULTISELECT+ color_attribute.save(update_fields=["input_type"])++ # Create values+ values = AttributeValue.objects.bulk_create(+ [+ AttributeValue(attribute=color_attribute, name="Yellow", slug="yellow"),+ AttributeValue(attribute=color_attribute, name="Blue", slug="blue"),+ AttributeValue(+ attribute=file_attribute,+ name="test_file_3.txt",+ slug="test_file3txt",+ file_url="http://mirumee.com/test_media/test_file3.txt",+ content_type="text/plain",+ ),+ ]+ )++ # Associate the colors and size to variant attributes+ associate_attribute_values_to_instance(variant, color_attribute, *values[:2])+ associate_attribute_values_to_instance(variant, file_attribute, values[-1])++ # Generate the variant name from the attributes+ generate_and_set_variant_name(variant, variant.sku)+ variant.refresh_from_db()+ assert variant.name == variant.sku+++def test_generate_name_from_values_empty(variant_with_no_attributes):+ """Ensure generate a variant name from a variant without any attributes assigned+ returns an empty string."""+ variant = variant_with_no_attributes+ generate_and_set_variant_name(variant, variant.sku)+ variant.refresh_from_db()+ assert variant.name == variant.sku+++def test_product_type_update_changes_variant_name(product):+ new_name = "test_name"+ product_variant = product.variants.first()+ assert not product_variant.name == new_name+ attribute = product.product_type.variant_attributes.first()+ attribute_value = attribute.values.first()+ attribute_value.name = new_name+ attribute_value.save()+ _update_variants_names(product.product_type, [attribute])+ product_variant.refresh_from_db()+ assert product_variant.name == new_name+++def test_only_not_variant_selection_attr_left_variant_name_change_to_sku(product):+ new_name = "test_name"+ product_variant = product.variants.first()+ assert not product_variant.name == new_name+ attribute = product.product_type.variant_attributes.first()+ attribute.input_type = AttributeInputType.MULTISELECT+ attribute.save(update_fields=["input_type"])+ _update_variants_names(product.product_type, [attribute])+ product_variant.refresh_from_db()+ assert product_variant.name == product_variant.sku+++def test_update_variants_changed_does_nothing_with_no_attributes():+ product_type = MagicMock(spec=ProductType)+ product_type.variant_attributes.all = Mock(return_value=[])+ saved_attributes = []+ # FIXME: This method no longer returns any value+ assert _update_variants_names(product_type, saved_attributes) is Nonediff --git a/saleor/product/tests/test_generate_name_for_variant.py b/saleor/product/tests/test_generate_name_for_variant.pydeleted file mode 100644index 5fa9a774cc..0000000000--- a/saleor/product/tests/test_generate_name_for_variant.py+++ /dev/null@@ -1,100 +0,0 @@-from decimal import Decimal-from unittest.mock import MagicMock, Mock--import pytest--from ...attribute import AttributeInputType-from ...attribute.models import AttributeValue-from ...attribute.utils import associate_attribute_values_to_instance-from ...product.models import ProductVariantChannelListing-from ..models import Product, ProductType, ProductVariant-from ..tasks import _update_variants_names-from ..utils.variants import generate_name_for_variant---def variant_with_no_attributes(category, channel_USD):- """Create a variant having no attributes, the same for the parent product."""- product_type = ProductType.objects.create(- name="Test product type", has_variants=True, is_shipping_required=True- )- product = Product.objects.create(- name="Test product", product_type=product_type, category=category,- )- variant = ProductVariant.objects.create(product=product, sku="123")- ProductVariantChannelListing.objects.create(- variant=variant,- channel=channel_USD,- cost_price_amount=Decimal(1),- price_amount=Decimal(10),- currency=channel_USD.currency_code,- )- return variant---def test_generate_name_for_variant(- variant_with_no_attributes, color_attribute_without_values, size_attribute-):- """Test the name generation from a given variant containing multiple attributes and- different input types (dropdown and multiselect).- """-- variant = variant_with_no_attributes- color_attribute = color_attribute_without_values-- # Assign the attributes to the product type- variant.product.product_type.variant_attributes.set(- (color_attribute, size_attribute)- )-- # Set the color attribute to a multi-value attribute- color_attribute.input_type = AttributeInputType.MULTISELECT- color_attribute.save(update_fields=["input_type"])-- # Create colors- colors = AttributeValue.objects.bulk_create(- [- AttributeValue(attribute=color_attribute, name="Yellow", slug="yellow"),- AttributeValue(attribute=color_attribute, name="Blue", slug="blue"),- AttributeValue(attribute=color_attribute, name="Red", slug="red"),- ]- )-- # Retrieve the size attribute value "Big"- size = size_attribute.values.get(slug="big")-- # Associate the colors and size to variant attributes- associate_attribute_values_to_instance(variant, color_attribute, *tuple(colors))- associate_attribute_values_to_instance(variant, size_attribute, size)-- # Generate the variant name from the attributes- name = generate_name_for_variant(variant)- assert name == "Yellow, Blue, Red / Big"---def test_generate_name_from_values_empty(variant_with_no_attributes):- """Ensure generate a variant name from a variant without any attributes assigned- returns an empty string."""- name = generate_name_for_variant(variant_with_no_attributes)- assert name == ""---def test_product_type_update_changes_variant_name(product):- new_name = "test_name"- product_variant = product.variants.first()- assert not product_variant.name == new_name- attribute = product.product_type.variant_attributes.first()- attribute_value = attribute.values.first()- attribute_value.name = new_name- attribute_value.save()- _update_variants_names(product.product_type, [attribute])- product_variant.refresh_from_db()- assert product_variant.name == new_name---def test_update_variants_changed_does_nothing_with_no_attributes():- product_type = MagicMock(spec=ProductType)- product_type.variant_attributes.all = Mock(return_value=[])- saved_attributes = []- # FIXME: This method no longer returns any value- assert _update_variants_names(product_type, saved_attributes) is Nonediff --git a/saleor/product/tests/test_get_variant_selection_attributes.py b/saleor/product/tests/test_get_variant_selection_attributes.pynew file mode 100644index 0000000000..9951287593--- /dev/null+++ b/saleor/product/tests/test_get_variant_selection_attributes.py@@ -0,0 +1,21 @@+from ...attribute import AttributeInputType+from ..utils.variants import get_variant_selection_attributes+++def test_get_variant_selection_attributes(+ product_type_attribute_list, file_attribute_with_file_input_type_without_values+):+ # given+ multiselect_attr = product_type_attribute_list[0]+ multiselect_attr.input_type = AttributeInputType.MULTISELECT+ multiselect_attr.save(update_fields=["input_type"])++ attrs = product_type_attribute_list + [+ file_attribute_with_file_input_type_without_values+ ]++ # when+ result = get_variant_selection_attributes(attrs)++ # then+ assert result == product_type_attribute_list[1:]diff --git a/saleor/product/utils/variants.py b/saleor/product/utils/variants.pyindex 7852b986bf..91ae539582 100644--- a/saleor/product/utils/variants.py+++ b/saleor/product/utils/variants.py@@ -1,17 +1,45 @@from typing import TYPE_CHECKING+from ...attribute import AttributeInputType, AttributeType+if TYPE_CHECKING:from ...attribute.models import AssignedVariantAttributefrom ..models import ProductVariant-def generate_name_for_variant(variant: "ProductVariant") -> str:+def generate_and_set_variant_name(variant: "ProductVariant", sku: str):"""Generate ProductVariant's name based on its attributes."""attributes_display = []- for attribute_rel in variant.attributes.all(): # type: AssignedVariantAttribute- values_qs = attribute_rel.values.all() # FIXME: this should be sorted+ variant_selection_input_types = AttributeInputType.ALLOWED_IN_VARIANT_SELECTION+ variant_selection_attributes = variant.attributes.filter(+ assignment__attribute__input_type__in=variant_selection_input_types,+ assignment__attribute__type=AttributeType.PRODUCT_TYPE,+ )+ for (+ attribute_rel+ ) in variant_selection_attributes.iterator(): # type: AssignedVariantAttribute+ values_qs = attribute_rel.values.order_by()translated_values = [str(value.translated) for value in values_qs]attributes_display.append(", ".join(translated_values))- return " / ".join(attributes_display)+ name = " / ".join(attributes_display)+ if not name:+ name = sku++ variant.name = name+ variant.save(update_fields=["name"])+++def get_variant_selection_attributes(attributes):+ """Return attributes that can be used in variant selection.++ Attribute must be product attribute and attribute input type must be+ in ALLOWED_IN_VARIANT_SELECTION list.+ """+ return [+ attribute+ for attribute in attributes+ if attribute.input_type in AttributeInputType.ALLOWED_IN_VARIANT_SELECTION+ and attribute.type == AttributeType.PRODUCT_TYPE+ ]diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 23af243290..5999acafa4 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -723,7 +723,12 @@ def shipping_method_channel_PLN(shipping_zone, channel_PLN):@pytest.fixturedef color_attribute(db): # pylint: disable=W0613attribute = Attribute.objects.create(- slug="color", name="Color", type=AttributeType.PRODUCT_TYPE+ slug="color",+ name="Color",+ type=AttributeType.PRODUCT_TYPE,+ filterable_in_storefront=True,+ filterable_in_dashboard=True,+ available_in_grid=True,)AttributeValue.objects.create(attribute=attribute, name="Red", slug="red")AttributeValue.objects.create(attribute=attribute, name="Blue", slug="blue")@@ -733,7 +738,12 @@ def color_attribute(db): # pylint: disable=W0613@pytest.fixturedef color_attribute_without_values(db): # pylint: disable=W0613return Attribute.objects.create(- slug="color", name="Color", type=AttributeType.PRODUCT_TYPE+ slug="color",+ name="Color",+ type=AttributeType.PRODUCT_TYPE,+ filterable_in_storefront=True,+ filterable_in_dashboard=True,+ available_in_grid=True,)@@ -748,7 +758,12 @@ def pink_attribute_value(color_attribute): # pylint: disable=W0613@pytest.fixturedef size_attribute(db): # pylint: disable=W0613attribute = Attribute.objects.create(- slug="size", name="Size", type=AttributeType.PRODUCT_TYPE+ slug="size",+ name="Size",+ type=AttributeType.PRODUCT_TYPE,+ filterable_in_storefront=True,+ filterable_in_dashboard=True,+ available_in_grid=True,)AttributeValue.objects.create(attribute=attribute, name="Small", slug="small")AttributeValue.objects.create(attribute=attribute, name="Big", slug="big")@@ -758,7 +773,12 @@ def size_attribute(db): # pylint: disable=W0613@pytest.fixturedef weight_attribute(db):attribute = Attribute.objects.create(- slug="material", name="Material", type=AttributeType.PRODUCT_TYPE+ slug="material",+ name="Material",+ type=AttributeType.PRODUCT_TYPE,+ filterable_in_storefront=True,+ filterable_in_dashboard=True,+ available_in_grid=True,)AttributeValue.objects.create(attribute=attribute, name="Cotton", slug="cotton")AttributeValue.objects.create(@@ -767,10 +787,50 @@ def weight_attribute(db):return attribute+def file_attribute(db):+ attribute = Attribute.objects.create(+ slug="image",+ name="Image",+ type=AttributeType.PRODUCT_TYPE,+ input_type=AttributeInputType.FILE,+ )+ AttributeValue.objects.create(+ attribute=attribute,+ name="test_file.txt",+ slug="test_filetxt",+ file_url="http://mirumee.com/test_media/test_file.txt",+ content_type="text/plain",+ )+ AttributeValue.objects.create(+ attribute=attribute,+ name="test_file.jpeg",+ slug="test_filejpeg",+ file_url="http://mirumee.com/test_media/test_file.jpeg",+ content_type="image/jpeg",+ )+ return attribute+++def file_attribute_with_file_input_type_without_values(db):+ return Attribute.objects.create(+ slug="image",+ name="Image",+ type=AttributeType.PRODUCT_TYPE,+ input_type=AttributeInputType.FILE,+ )++@pytest.fixturedef size_page_attribute(db):attribute = Attribute.objects.create(- slug="page-size", name="Page size", type=AttributeType.PAGE_TYPE+ slug="page-size",+ name="Page size",+ type=AttributeType.PAGE_TYPE,+ filterable_in_storefront=True,+ filterable_in_dashboard=True,+ available_in_grid=True,)AttributeValue.objects.create(attribute=attribute, name="10", slug="10")AttributeValue.objects.create(attribute=attribute, name="15", slug="15")@@ -780,7 +840,12 @@ def size_page_attribute(db):@pytest.fixturedef tag_page_attribute(db):attribute = Attribute.objects.create(- slug="tag", name="tag", type=AttributeType.PAGE_TYPE+ slug="tag",+ name="tag",+ type=AttributeType.PAGE_TYPE,+ filterable_in_storefront=True,+ filterable_in_dashboard=True,+ available_in_grid=True,)AttributeValue.objects.create(attribute=attribute, name="About", slug="about")AttributeValue.objects.create(attribute=attribute, name="Help", slug="help")@@ -801,6 +866,31 @@ def author_page_attribute(db):return attribute+def page_file_attribute(db):+ attribute = Attribute.objects.create(+ slug="image",+ name="Image",+ type=AttributeType.PAGE_TYPE,+ input_type=AttributeInputType.FILE,+ )+ AttributeValue.objects.create(+ attribute=attribute,+ name="test_file.txt",+ slug="test_filetxt",+ file_url="http://mirumee.com/test_media/test_file.txt",+ content_type="text/plain",+ )+ AttributeValue.objects.create(+ attribute=attribute,+ name="test_file.jpeg",+ slug="test_filejpeg",+ file_url="http://mirumee.com/test_media/test_file.jpeg",+ content_type="image/jpeg",+ )+ return attribute++@pytest.fixturedef product_type_attribute_list() -> List[Attribute]:return list(@@ -1144,6 +1234,49 @@ def product_with_variant_with_two_attributes(return product+def product_with_variant_with_file_attribute(+ color_attribute, file_attribute, category, warehouse, channel_USD+):+ product_type = ProductType.objects.create(+ name="Type with variant and file attribute",+ slug="type-with-file-attribute",+ has_variants=True,+ is_shipping_required=True,+ )+ product_type.variant_attributes.add(file_attribute)++ product = Product.objects.create(+ name="Test product with variant and file attribute",+ slug="test-product-with-variant-and-file-attribute",+ product_type=product_type,+ category=category,+ )+ ProductChannelListing.objects.create(+ product=product,+ channel=channel_USD,+ is_published=True,+ currency=channel_USD.currency_code,+ visible_in_listings=True,+ available_for_purchase=datetime.date(1999, 1, 1),+ )++ variant = ProductVariant.objects.create(product=product, sku="prodVarTest",)+ ProductVariantChannelListing.objects.create(+ variant=variant,+ channel=channel_USD,+ price_amount=Decimal(10),+ cost_price_amount=Decimal(1),+ currency=channel_USD.currency_code,+ )++ associate_attribute_values_to_instance(+ variant, file_attribute, file_attribute.values.first()+ )++ return product++@pytest.fixturedef product_with_multiple_values_attributes(product, product_type, category) -> Product: