Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Variant selection attributes (#8235)

Paweł Kucharskid7a6efe01ede
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 108f562e7e..53fdcbff44 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Introduce sales webhooks - #8157 @kuchichan
- Batch loads in queries for Apollo Federation - #8273 by @rafalp
- Reserve stocks for checkouts - #7589 by @rafalp
+- Add `variant_selection` to `ProductAttributeAssign` operations - #8235 by @kuchichan
# 3.0.0 [Unreleased]
diff --git a/saleor/attribute/__init__.py b/saleor/attribute/__init__.py
index e8818a3761..5505455c2a 100644
--- a/saleor/attribute/__init__.py
+++ b/saleor/attribute/__init__.py
@@ -29,7 +29,7 @@ class AttributeInputType:
]
# list of the input types that can be used in variant selection
- ALLOWED_IN_VARIANT_SELECTION = [DROPDOWN, BOOLEAN, SWATCH]
+ ALLOWED_IN_VARIANT_SELECTION = [DROPDOWN, BOOLEAN, SWATCH, NUMERIC]
TYPES_WITH_CHOICES = [
DROPDOWN,
diff --git a/saleor/attribute/migrations/0018_attributevariant_variant_selection.py b/saleor/attribute/migrations/0018_attributevariant_variant_selection.py
new file mode 100644
index 0000000000..3a9f3bfffe
--- /dev/null
+++ b/saleor/attribute/migrations/0018_attributevariant_variant_selection.py
@@ -0,0 +1,34 @@
+# Generated by Django 3.2.7 on 2021-09-29 09:20
+
+from django.db import migrations, models
+
+
+def update_variant_selection(apps, schema_editor):
+ # Copied in order to avoid imports
+ # (does not contain NUMERIC by purpose - backward compatibility)
+
+ ALLOWED_IN_VARIANT_SELECTION = ["dropdown", "boolean", "swatch"]
+ AttributeVariant = apps.get_model("attribute", "AttributeVariant")
+ attribute_variants = AttributeVariant.objects.select_related("attribute").filter(
+ attribute__input_type__in=ALLOWED_IN_VARIANT_SELECTION
+ )
+
+ attribute_variants.update(variant_selection=True)
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("attribute", "0017_auto_20210811_0701"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="attributevariant",
+ name="variant_selection",
+ field=models.BooleanField(default=False),
+ ),
+ migrations.RunPython(
+ update_variant_selection, reverse_code=migrations.RunPython.noop
+ ),
+ ]
diff --git a/saleor/attribute/models/product_variant.py b/saleor/attribute/models/product_variant.py
index ed48e5a83a..6d9abfbf03 100644
--- a/saleor/attribute/models/product_variant.py
+++ b/saleor/attribute/models/product_variant.py
@@ -59,6 +59,7 @@ class AttributeVariant(SortableModel):
through_fields=("assignment", "variant"),
related_name="attributesrelated",
)
+ variant_selection = models.BooleanField(default=False)
objects = models.Manager.from_queryset(AssociatedAttributeQuerySet)()
diff --git a/saleor/graphql/attribute/tests/test_utils.py b/saleor/graphql/attribute/tests/test_utils.py
index 4e33677963..1e18fbd285 100644
--- a/saleor/graphql/attribute/tests/test_utils.py
+++ b/saleor/graphql/attribute/tests/test_utils.py
@@ -239,7 +239,7 @@ def test_validate_attributes_input_for_product_lack_of_required_attribute(
input_data,
product_attributes,
is_page_attributes=False,
- variant_validation=False,
+ variant_validation=None,
)
# then
@@ -534,7 +534,7 @@ def test_validate_attributes_input_for_page_lack_of_required_attribute(
# when
errors = validate_attributes_input(
- input_data, page_attributes, is_page_attributes=True, variant_validation=False
+ input_data, page_attributes, is_page_attributes=True, variant_validation=None
)
# then
@@ -705,6 +705,10 @@ def test_validate_not_required_variant_selection_attributes_input_no_values_give
weight_attribute.input_type = AttributeInputType.MULTISELECT
weight_attribute.save(update_fields=["value_required", "input_type"])
+ # To be verified.
+ product_type.variant_attributes.add(weight_attribute)
+ product_type.variant_attributes.add(color_attribute)
+
input_data = [
(
weight_attribute,
@@ -729,10 +733,14 @@ def test_validate_not_required_variant_selection_attributes_input_no_values_give
]
attributes = product_type.variant_attributes.all()
-
# when
errors = validate_attributes_input(
- input_data, attributes, is_page_attributes=False, variant_validation=True
+ input_data,
+ attributes,
+ is_page_attributes=False,
+ variant_validation=attributes.values(
+ "id", "attributevariant__variant_selection"
+ ),
)
# then
@@ -776,7 +784,12 @@ def test_validate_attributes_input_too_many_values_given(
# when
errors = validate_attributes_input(
- input_data, attributes, is_page_attributes=False, variant_validation=True
+ input_data,
+ attributes,
+ is_page_attributes=False,
+ variant_validation=attributes.values(
+ "id", "attributevariant__variant_selection"
+ ),
)
# then
@@ -929,7 +942,7 @@ def test_validate_attributes_with_file_input_type_for_product(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
- variant_validation=False,
+ variant_validation=None,
)
# then
@@ -974,7 +987,7 @@ def test_validate_attributes_with_file_input_type_for_product_no_file_given(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
- variant_validation=False,
+ variant_validation=None,
)
# then
@@ -1024,7 +1037,7 @@ def test_validate_not_required_attrs_with_file_input_type_for_product_no_file_gi
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
- variant_validation=False,
+ variant_validation=None,
)
# then
@@ -1069,7 +1082,7 @@ def test_validate_attributes_with_file_input_type_for_product_empty_file_value(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
- variant_validation=False,
+ variant_validation=None,
)
# then
@@ -1104,7 +1117,7 @@ def test_validate_numeric_attributes_input_for_product(numeric_attribute, produc
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
- variant_validation=False,
+ variant_validation=None,
)
# then
@@ -1137,7 +1150,7 @@ def test_validate_numeric_attributes_input_for_product_not_numeric_value_given(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
- variant_validation=False,
+ variant_validation=None,
)
# then
@@ -1174,7 +1187,7 @@ def test_validate_numeric_attributes_input_for_product_blank_value(
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
- variant_validation=False,
+ variant_validation=None,
)
# then
@@ -1211,7 +1224,7 @@ def test_validate_numeric_attributes_input_for_product_more_than_one_value_given
input_data,
product_type.product_attributes.all(),
is_page_attributes=False,
- variant_validation=False,
+ variant_validation=None,
)
# then
diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.py
index 843862f13f..a0c54119f2 100644
--- a/saleor/graphql/attribute/types.py
+++ b/saleor/graphql/attribute/types.py
@@ -8,6 +8,7 @@ from ...core.permissions import PagePermissions, ProductPermissions
from ...core.tracing import traced_resolver
from ...graphql.utils import get_user_or_app_from_context
from ..core.connection import CountableDjangoObjectType
+from ..core.descriptions import ADDED_IN_31
from ..core.enums import MeasurementUnitsEnum
from ..core.fields import FilterInputConnectionField
from ..core.types import File
@@ -204,6 +205,27 @@ class Attribute(CountableDjangoObjectType):
return root.input_type in AttributeInputType.TYPES_WITH_CHOICES
+class AssignedVariantAttribute(graphene.ObjectType):
+ attribute = graphene.Field(
+ Attribute, description="Attribute assigned to variant.", required=True
+ )
+ variant_selection = graphene.Boolean(
+ required=True,
+ description=(
+ "Determines, whether assigned attribute is "
+ "allowed for variant selection. Supported variant types for "
+ "variant selection are: "
+ f"{AttributeInputType.ALLOWED_IN_VARIANT_SELECTION}"
+ ),
+ )
+
+ class Meta:
+ description = (
+ f"{ADDED_IN_31} Represents assigned attribute to variant with "
+ "variant selection attached."
+ )
+
+
class SelectedAttribute(graphene.ObjectType):
attribute = graphene.Field(
Attribute,
diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.py
index aea87b698a..1b051d1029 100644
--- a/saleor/graphql/attribute/utils.py
+++ b/saleor/graphql/attribute/utils.py
@@ -331,7 +331,7 @@ class AttributeAssignmentMixin:
:raises ValidationError: when an invalid operation was found.
"""
- variant_validation = False
+ variant_validation_pairs = None
if is_variant:
qs = get_variant_selection_attributes(attribute_qs)
if len(cleaned_input) < qs.count():
@@ -339,13 +339,15 @@ class AttributeAssignmentMixin:
"All variant selection attributes must take a value.",
code=ProductErrorCode.REQUIRED.value,
)
- variant_validation = True
+ variant_validation_pairs = attribute_qs.values(
+ "id", "attributevariant__variant_selection"
+ )
errors = validate_attributes_input(
cleaned_input,
attribute_qs,
is_page_attributes=is_page_attributes,
- variant_validation=variant_validation,
+ variant_validation=variant_validation_pairs,
)
if errors:
@@ -512,10 +514,9 @@ class AttributeAssignmentMixin:
).delete()
-def get_variant_selection_attributes(qs: "QuerySet"):
+def get_variant_selection_attributes(qs: "QuerySet") -> "QuerySet":
return qs.filter(
- input_type__in=AttributeInputType.ALLOWED_IN_VARIANT_SELECTION,
- type=AttributeType.PRODUCT_TYPE,
+ type=AttributeType.PRODUCT_TYPE, attributevariant__variant_selection=True
)
@@ -572,7 +573,7 @@ def validate_attributes_input(
attribute_qs: "QuerySet",
*,
is_page_attributes: bool,
- variant_validation: bool,
+ variant_validation: Optional["QuerySet"] = None,
):
"""Validate attribute input.
@@ -609,7 +610,7 @@ def validate_attributes_input(
errors = prepare_error_list_from_error_attribute_mapping(
attribute_errors, error_code_enum
)
- if not variant_validation:
+ if variant_validation is None:
errors = validate_required_attributes(
input_data, attribute_qs, errors, error_code_enum
)
@@ -621,7 +622,7 @@ def validate_file_attributes_input(
attribute: "Attribute",
attr_values: "AttrValuesInput",
attribute_errors: T_ERROR_DICT,
- variant_validation: bool,
+ variant_validation: Optional["QuerySet"] = None,
):
attribute_id = attr_values.global_id
value = attr_values.file_url
@@ -640,7 +641,7 @@ def validate_reference_attributes_input(
attribute: "Attribute",
attr_values: "AttrValuesInput",
attribute_errors: T_ERROR_DICT,
- variant_validation: bool,
+ variant_validation: Optional["QuerySet"],
):
attribute_id = attr_values.global_id
references = attr_values.references
@@ -655,7 +656,7 @@ def validate_boolean_input(
attribute: "Attribute",
attr_values: "AttrValuesInput",
attribute_errors: T_ERROR_DICT,
- variant_validation: bool,
+ variant_validation: Optional["QuerySet"],
):
attribute_id = attr_values.global_id
value = attr_values.boolean
@@ -668,7 +669,7 @@ def validate_rich_text_attributes_input(
attribute: "Attribute",
attr_values: "AttrValuesInput",
attribute_errors: T_ERROR_DICT,
- variant_validation: bool,
+ variant_validation: Optional["QuerySet"],
):
attribute_id = attr_values.global_id
text = clean_editor_js(attr_values.rich_text or {}, to_string=True)
@@ -681,7 +682,7 @@ def validate_standard_attributes_input(
attribute: "Attribute",
attr_values: "AttrValuesInput",
attribute_errors: T_ERROR_DICT,
- variant_validation: bool,
+ variant_validation: Optional["QuerySet"],
):
attribute_id = attr_values.global_id
@@ -710,7 +711,7 @@ def validate_date_time_input(
attribute: "Attribute",
attr_values: "AttrValuesInput",
attribute_errors: T_ERROR_DICT,
- variant_validation: bool,
+ variant_validation: Optional["QuerySet"],
):
is_blank_date = (
attribute.input_type == AttributeInputType.DATE and not attr_values.date
@@ -750,16 +751,17 @@ def validate_values(
].append(attribute_id)
-def is_value_required(attribute: attribute_models.Attribute, variant_validation: bool):
+def is_value_required(
+ attribute: attribute_models.Attribute, variant_validation: Optional["QuerySet"]
+):
return attribute.value_required or (
- variant_validation and is_variant_selection_attribute(attribute)
+ variant_validation is not None
+ and variant_validation.get(id=attribute.id)[
+ "attributevariant__variant_selection"
+ ]
)
-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",
diff --git a/saleor/graphql/product/dataloaders/attributes.py b/saleor/graphql/product/dataloaders/attributes.py
index 9085b48c05..bb54e3c771 100644
--- a/saleor/graphql/product/dataloaders/attributes.py
+++ b/saleor/graphql/product/dataloaders/attributes.py
@@ -21,10 +21,13 @@ class BaseProductAttributesByProductTypeIdLoader(DataLoader):
"""Loads product attributes by product type ID."""
model_name = None
+ extra_fields = None
def batch_load(self, keys):
if not self.model_name:
raise ValueError("Provide a model_name for this dataloader.")
+ if not self.extra_fields:
+ self.extra_fields = []
requestor = get_user_or_app_from_context(self.context)
if requestor.is_active and requestor.has_perm(
@@ -33,27 +36,32 @@ class BaseProductAttributesByProductTypeIdLoader(DataLoader):
qs = self.model_name.objects.all()
else:
qs = self.model_name.objects.filter(attribute__visible_in_storefront=True)
+
product_type_attribute_pairs = qs.filter(product_type_id__in=keys).values_list(
- "product_type_id", "attribute_id"
+ "product_type_id", "attribute_id", *self.extra_fields
)
product_type_to_attributes_map = defaultdict(list)
- for product_type_id, attr_id in product_type_attribute_pairs:
- product_type_to_attributes_map[product_type_id].append(attr_id)
+ for product_type_id, attr_id, *extra_fields in product_type_attribute_pairs:
+ product_type_to_attributes_map[product_type_id].append(
+ (attr_id, *extra_fields)
+ )
def map_attributes(attributes):
attributes_map = {attr.id: attr for attr in attributes}
return [
[
- attributes_map[attr_id]
- for attr_id in product_type_to_attributes_map[product_type_id]
+ (attributes_map[attr_id], *extra_fields)
+ for attr_id, *extra_fields in product_type_to_attributes_map[
+ product_type_id
+ ]
]
for product_type_id in keys
]
return (
AttributesByAttributeId(self.context)
- .load_many(set(attr_id for _, attr_id in product_type_attribute_pairs))
+ .load_many(set(attr_id for _, attr_id, *_ in product_type_attribute_pairs))
.then(map_attributes)
)
@@ -74,6 +82,7 @@ class VariantAttributesByProductTypeIdLoader(
context_key = "variant_attributes_by_producttype"
model_name = AttributeVariant
+ extra_fields = ["variant_selection"]
class AttributeProductsByProductTypeIdLoader(DataLoader):
@@ -319,6 +328,7 @@ class SelectedAttributesByProductVariantIdLoader(DataLoader):
attribute_ids = list(
{ap.attribute_id for aps in attribute_products for ap in aps}
)
+
attribute_products = dict(zip(product_type_ids, attribute_products))
def with_attributes(attributes):
@@ -345,12 +355,19 @@ class SelectedAttributesByProductVariantIdLoader(DataLoader):
attribute = id_to_attribute[
assigned_producttype_attribute.attribute_id
]
+ variant_selection = (
+ assigned_producttype_attribute.variant_selection
+ )
if variant_assignment:
values = attribute_values[variant_assignment.id]
else:
values = []
selected_attributes_map[key].append(
- {"values": values, "attribute": attribute}
+ {
+ "values": values,
+ "attribute": attribute,
+ "variant_selection": variant_selection,
+ }
)
return [selected_attributes_map[key] for key in keys]
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.py
index a18f03f868..1ce7c3b1ea 100644
--- a/saleor/graphql/product/mutations/attributes.py
+++ b/saleor/graphql/product/mutations/attributes.py
@@ -1,11 +1,11 @@
-from collections import defaultdict
+from collections import Counter, defaultdict
from typing import List
import graphene
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db.models import Q
-from ....attribute import AttributeType
+from ....attribute import AttributeInputType, AttributeType
from ....attribute import models as attribute_models
from ....core.permissions import ProductPermissions, ProductTypePermissions
from ....core.tracing import traced_atomic_transaction
@@ -17,6 +17,7 @@ from ...attribute.mutations import (
)
from ...attribute.types import Attribute
from ...channel import ChannelContext
+from ...core.descriptions import ADDED_IN_31
from ...core.inputs import ReorderInput
from ...core.mutations import BaseMutation
from ...core.types.common import ProductError
@@ -30,9 +31,60 @@ class ProductAttributeAssignInput(graphene.InputObjectType):
type = ProductAttributeType(
required=True, description="The attribute type to be assigned as."
)
+ variant_selection = graphene.Boolean(
+ required=False,
+ description=(
+ f"{ADDED_IN_31} Whether attribute is allowed in variant selection. "
+ f"Allowed types are: {AttributeInputType.ALLOWED_IN_VARIANT_SELECTION}."
+ ),
+ )
+
+
+class ProductAttributeAssignmentUpdateInput(graphene.InputObjectType):
+ id = graphene.ID(required=True, description="The ID of the attribute to assign.")
+ variant_selection = graphene.Boolean(
+ required=True,
+ description=(
+ f"{ADDED_IN_31} Whether attribute is allowed in variant selection. "
+ f"Allowed types are: {AttributeInputType.ALLOWED_IN_VARIANT_SELECTION}."
+ ),
+ )
+
+
+class VariantAssignmentValidationMixin:
+ @classmethod
+ def check_allowed_types(cls, errors, variant_attrs_data):
+ variant_attrs_pks = [
+ pk for pk, variant_selection, *_ in variant_attrs_data if variant_selection
+ ]
+ qs = (
+ attribute_models.Attribute.objects.filter(
+ pk__in=variant_attrs_pks,
+ )
+ .exclude(input_type__in=AttributeInputType.ALLOWED_IN_VARIANT_SELECTION)
+ .values_list("pk", "name", "input_type")
+ )
+
+ invalid_attributes = list(qs)
+
+ if invalid_attributes:
+ invalid_attr_ids = [
+ graphene.Node.to_global_id("Attribute", pk)
+ for pk, _, __ in invalid_attributes
+ ]
+ error = ValidationError(
+ (
+ f"Some of the attributes types are not supported for "
+ "variant selection. Supported types are: "
+ f"{AttributeInputType.ALLOWED_IN_VARIANT_SELECTION}."
+ ),
+ code=ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED,
+ params={"attributes": invalid_attr_ids},
+ )
+ errors["operations"].append(error)
-class ProductAttributeAssign(BaseMutation):
+class ProductAttributeAssign(BaseMutation, VariantAssignmentValidationMixin):
product_type = graphene.Field(ProductType, description="The updated product type.")
class Arguments:
@@ -62,16 +114,21 @@ class ProductAttributeAssign(BaseMutation):
"""Resolve all passed global ids into integer PKs of the Attribute type."""
product_attrs_pks = []
variant_attrs_pks = []
-
for operation in operations:
pk = cls.get_global_id_or_error(
operation.id, only_type=Attribute, field="operations"
)
+
+ variant_selection = (
+ operation.variant_selection
+ if operation.variant_selection is not None
+ else False
+ )
+
if operation.type == ProductAttributeType.PRODUCT:
- product_attrs_pks.append(pk)
+ product_attrs_pks.append((pk, variant_selection, operation.type))
else:
- variant_attrs_pks.append(pk)
-
+ variant_attrs_pks.append((pk, variant_selection, operation.type))
return product_attrs_pks, variant_attrs_pks
@classmethod
@@ -122,6 +179,22 @@ class ProductAttributeAssign(BaseMutation):
)
errors["operations"].append(error)
+ @classmethod
+ def check_type_and_variant_coherence(cls, errors, product_attrs_data):
+ for attr_pk, variant_selection, type_ in product_attrs_data:
+ if variant_selection:
+ msg = (
+ f"Attribute with pk: '{attr_pk}' with different type "
+ f"than 'VARIANT' (found: '{type_}') cannot be assigned with "
+ "variant_selection: true."
+ )
+ error = ValidationError(
+ msg,
+ code=ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED,
+ params={"attributes": attr_pk},
+ )
+ errors["operations"].append(error)
+
@classmethod
def check_product_operations_are_assignable(cls, errors, product_attrs_pks):
restricted_attributes = attribute_models.Attribute.objects.filter(
@@ -141,9 +214,11 @@ class ProductAttributeAssign(BaseMutation):
errors["operations"].append(error)
@classmethod
- def clean_operations(cls, product_type, product_attrs_pks, variant_attrs_pks):
+ def clean_operations(cls, product_type, product_attrs_data, variant_attrs_data):
"""Ensure the attributes are not already assigned to the product type."""
errors = defaultdict(list)
+ product_attrs_pks = [pk for pk, _, __ in product_attrs_data]
+ variant_attrs_pks = [pk for pk, _, __ in variant_attrs_data]
attrs_pk = product_attrs_pks + variant_attrs_pks
attributes = attribute_models.Attribute.objects.filter(
@@ -163,6 +238,8 @@ class ProductAttributeAssign(BaseMutation):
cls.check_attributes_types(errors, product_attrs_pks, variant_attrs_pks)
cls.check_product_operations_are_assignable(errors, product_attrs_pks)
+ cls.check_type_and_variant_coherence(errors, product_attrs_data)
+ cls.check_allowed_types(errors, variant_attrs_data)
cls.check_operations_not_assigned_already(
errors, product_type, product_attrs_pks, variant_attrs_pks
)
@@ -174,8 +251,20 @@ class ProductAttributeAssign(BaseMutation):
def save_field_values(cls, product_type, model_name, pks):
"""Add in bulk the PKs to assign to a given product type."""
model = getattr(attribute_models, model_name)
- for pk in pks:
- model.objects.create(product_type=product_type, attribute_id=pk)
+
+ if model_name == "AttributeVariant":
+ for pk, variant_selection, _ in pks:
+ model.objects.create(
+ product_type=product_type,
+ attribute_id=pk,
+ variant_selection=variant_selection,
+ )
+ else:
+ for pk, variant_selection, _ in pks:
+ model.objects.create(
+ product_type=product_type,
+ attribute_id=pk,
+ )
@classmethod
@traced_atomic_transaction()
@@ -188,7 +277,8 @@ class ProductAttributeAssign(BaseMutation):
)
# Resolve all the passed IDs to ints
- product_attrs_pks, variant_attrs_pks = cls.get_operations(info, operations)
+ product_attrs_data, variant_attrs_data = cls.get_operations(info, operations)
+ variant_attrs_pks = [pk for pk, _, __ in variant_attrs_data]
if variant_attrs_pks and not product_type.has_variants:
raise ValidationError(
@@ -201,11 +291,11 @@ class ProductAttributeAssign(BaseMutation):
)
# Ensure the attribute are assignable
- cls.clean_operations(product_type, product_attrs_pks, variant_attrs_pks)
+ cls.clean_operations(product_type, product_attrs_data, variant_attrs_data)
# Commit
- cls.save_field_values(product_type, "AttributeProduct", product_attrs_pks)
- cls.save_field_values(product_type, "AttributeVariant", variant_attrs_pks)
+ cls.save_field_values(product_type, "AttributeProduct", product_attrs_data)
+ cls.save_field_values(product_type, "AttributeVariant", variant_attrs_data)
return cls(product_type=product_type)
@@ -266,6 +356,204 @@ class ProductAttributeUnassign(BaseMutation):
return cls(product_type=product_type)
+class ProductAttributeAssignmentUpdate(BaseMutation, VariantAssignmentValidationMixin):
+ product_type = graphene.Field(ProductType, description="The updated product type.")
+
+ class Arguments:
+ product_type_id = graphene.ID(
+ required=True,
+ description="ID of the product type to assign the attributes into.",
+ )
+ operations = graphene.List(
+ ProductAttributeAssignmentUpdateInput,
+ required=True,
+ description="The operations to perform.",
+ )
+
+ class Meta:
+ description = (
+ f"{ADDED_IN_31} Update attributes assigned to product "
+ "variant for given product type."
+ )
+
+ error_type_class = ProductError
+ error_type_field = "product_errors"
+
+ @classmethod
+ def check_permissions(cls, context):
+ return context.user.has_perm(
+ ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES
+ )
+
+ @classmethod
+ def get_operations(
+ cls, info, operations: List[ProductAttributeAssignmentUpdateInput]
+ ):
+ variant_attrs_pks = []
+ for operation in operations:
+ pk = cls.get_global_id_or_error(
+ operation.id, only_type=Attribute, field="operations"
+ )
+ variant_attrs_pks.append((pk, operation.variant_selection))
+
+ return variant_attrs_pks
+
+ @classmethod
+ def check_attribute_assigment_exsistence(
+ cls, errors, product_type, variant_attrs_pks
+ ):
+ """Ensure the attributes are assigned to VariantAttributes."""
+
+ assigned_attributes = (
+ attribute_models.Attribute.objects.get_assigned_product_type_attributes(
+ product_type.pk
+ )
+ .values_list("pk", flat=True)
+ .distinct()
+ .filter(pk__in=variant_attrs_pks)
+ )
+
+ if len(variant_attrs_pks) != len(assigned_attributes):
+ invalid_attrs = set(variant_attrs_pks) - set(
+ str(pk) for pk in assigned_attributes
+ )
+ invalid_attrs = [
+ graphene.Node.to_global_id("Attribute", pk) for pk in invalid_attrs
+ ]
+ error = ValidationError(
+ "Attribute is not assigned to product type.",
+ code=ProductErrorCode.NOT_FOUND,
+ params={
+ "attributes": invalid_attrs,
+ },
+ )
+ errors["operations"].append(error)
+
+ @classmethod
+ def check_attribute_assigment_to_product_variant(
+ cls, errors, variant_attrs_pks, product_type
+ ):
+ assigned_attributes = attribute_models.AttributeVariant.objects.filter(
+ product_type_id=product_type.pk, attribute_id__in=variant_attrs_pks
+ ).values_list("attribute_id", flat=True)
+
+ if len(variant_attrs_pks) != len(assigned_attributes):
+ invalid_attrs = set(variant_attrs_pks) - set(
+ str(pk) for pk in assigned_attributes
+ )
+ invalid_attrs = [
+ graphene.Node.to_global_id("Attribute", pk) for pk in invalid_attrs
+ ]
+ error = ValidationError(
+ "Attribute is not assigned to product variant.",
+ code=ProductErrorCode.NOT_FOUND,
+ params={
+ "attributes": invalid_attrs,
+ },
+ )
+ errors["operations"].append(error)
+
+ @classmethod
+ def check_for_duplicates(cls, errors, variant_attrs_pks):
+ counter = Counter(variant_attrs_pks)
+ invalid_ids = []
+ for element, count in counter.items():
+ if count > 1:
+ invalid_ids.append(graphene.Node.to_global_id("Attribute", element))
+
+ if invalid_ids:
+ error = ValidationError(
+ "Attribute ids should be unique within operations.",
+ code=ProductErrorCode.INVALID,
+ params={"attributes": invalid_ids},
+ )
+ errors["operations"].append(error)
+
+ @classmethod
+ def clean_operations(cls, product_type, variant_attrs_data):
+ errors = defaultdict(list)
+ variant_attrs_pks = [pk for pk, _, in variant_attrs_data]
+
+ cls.check_for_duplicates(errors, variant_attrs_pks)
+ if errors:
+ raise ValidationError(errors)
+
+ attributes = attribute_models.Attribute.objects.filter(
+ id__in=variant_attrs_pks
+ ).values_list("pk", flat=True)
+ if len(variant_attrs_pks) != len(attributes):
+ invalid_attrs = set(variant_attrs_pks) - set(str(pk) for pk in attributes)
+ invalid_attrs = [
+ graphene.Node.to_global_id("Attribute", pk) for pk in invalid_attrs
+ ]
+ error = ValidationError(
+ "Attribute doesn't exist.",
+ code=ProductErrorCode.NOT_FOUND,
+ params={"attributes": list(invalid_attrs)},
+ )
+ errors["operations"].append(error)
+
+ cls.check_attribute_assigment_exsistence(
+ errors, product_type, variant_attrs_pks
+ )
+ cls.check_attribute_assigment_to_product_variant(
+ errors, variant_attrs_pks, product_type
+ )
+ cls.check_allowed_types(errors, variant_attrs_data)
+
+ if errors:
+ raise ValidationError(errors)
+
+ @classmethod
+ def update_field_values(cls, product_type, variant_attrs_data):
+ ids_with_variant_selection_true = [
+ id_ for id_, variant_selection in variant_attrs_data if variant_selection
+ ]
+ ids_with_variant_selection_false = [
+ id_
+ for id_, variant_selection in variant_attrs_data
+ if not variant_selection
+ ]
+ attribute_models.AttributeVariant.objects.filter(
+ product_type_id=product_type.pk,
+ attribute_id__in=ids_with_variant_selection_true,
+ ).update(variant_selection=True)
+
+ attribute_models.AttributeVariant.objects.filter(
+ product_type_id=product_type.pk,
+ attribute_id__in=ids_with_variant_selection_false,
+ ).update(variant_selection=False)
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, root, info, **data):
+ product_type_id: str = data["product_type_id"]
+ operations: List[ProductAttributeAssignmentUpdateInput] = data["operations"]
+ # Retrieve the requested product type
+
+ product_type: models.ProductType = graphene.Node.get_node_from_global_id(
+ info, product_type_id, only_type=ProductType
+ )
+
+ # Resolve all passed IDs to ints
+ variant_attrs_data = cls.get_operations(info, operations)
+ variant_attrs_pks = [pk for pk, _ in variant_attrs_data]
+
+ if variant_attrs_pks and not product_type.has_variants:
+ raise ValidationError(
+ {
+ "operations": ValidationError(
+ "Variants are disabled in this product type.",
+ code=ProductErrorCode.ATTRIBUTE_VARIANTS_DISABLED.value,
+ )
+ }
+ )
+
+ cls.clean_operations(product_type, variant_attrs_data)
+ cls.update_field_values(product_type, variant_attrs_data)
+ return cls(product_type=product_type)
+
+
class ProductTypeReorderAttributes(BaseReorderAttributesMutation):
product_type = graphene.Field(
ProductType, description="Product type from which attributes are reordered."
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index 00fe991dae..1476f1994e 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -43,6 +43,7 @@ from .filters import (
)
from .mutations.attributes import (
ProductAttributeAssign,
+ ProductAttributeAssignmentUpdate,
ProductAttributeUnassign,
ProductReorderAttributeValues,
ProductTypeReorderAttributes,
@@ -396,6 +397,7 @@ class ProductQueries(graphene.ObjectType):
class ProductMutations(graphene.ObjectType):
product_attribute_assign = ProductAttributeAssign.Field()
+ product_attribute_assignment_update = ProductAttributeAssignmentUpdate.Field()
product_attribute_unassign = ProductAttributeUnassign.Field()
category_create = CategoryCreate.Field()
diff --git a/saleor/graphql/product/tests/test_attributes.py b/saleor/graphql/product/tests/test_attributes.py
index c21d2088ee..1d41057a04 100644
--- a/saleor/graphql/product/tests/test_attributes.py
+++ b/saleor/graphql/product/tests/test_attributes.py
@@ -417,10 +417,6 @@ def test_assign_variant_attribute_having_multiselect_input_type(
product_type,
size_attribute,
):
- """The assignAttribute mutation should raise an error when trying
- to use an attribute as a variant attribute when
- the attribute's input type doesn't support variants"""
-
attribute = size_attribute
attribute.input_type = AttributeInputType.MULTISELECT
attribute.save(update_fields=["input_type"])
@@ -446,6 +442,85 @@ def test_assign_variant_attribute_having_multiselect_input_type(
assert content["productType"]["variantAttributes"][0]["id"] == attr_id
+def test_assign_variant_attribute_having_multiselect_input_type_with_variant_selection(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ product_type,
+ size_attribute,
+):
+ """The assignAttribute mutation should raise an error when trying
+ to use an attribute as a variant attribute when
+ the attribute's input type doesn't support variants"""
+
+ attribute = size_attribute
+ attribute.input_type = AttributeInputType.MULTISELECT
+ attribute.save(update_fields=["input_type"])
+ product_type.variant_attributes.clear()
+
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
+ )
+
+ 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": attr_id, "variantSelection": True}]
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
+
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
+ "data"
+ ]["productAttributeAssign"]
+
+ assert content["errors"][0]["field"] == "operations"
+ assert content["errors"][0]["message"] == (
+ "Some of the attributes types are not supported for variant selection. "
+ f"Supported types are: {AttributeInputType.ALLOWED_IN_VARIANT_SELECTION}."
+ )
+ assert (
+ content["errors"][0]["code"]
+ == ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.name
+ )
+ assert len(content["errors"]) == 1
+
+
+def test_assign_product_attribute_having_variant_selection(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ product_type,
+ size_attribute,
+):
+ attribute = size_attribute
+ attribute.input_type = AttributeInputType.MULTISELECT
+ attribute.save(update_fields=["input_type"])
+ product_type.variant_attributes.clear()
+
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
+ )
+
+ 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": "PRODUCT", "id": attr_id, "variantSelection": True}]
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
+
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
+ "data"
+ ]["productAttributeAssign"]
+
+ assert content["errors"][0]["field"] == "operations"
+ assert (
+ f"Attribute with pk: '{attribute.pk}' with different type than "
+ f"'VARIANT' (found: 'PRODUCT') cannot be assigned with variant_selection: true."
+ ) == content["errors"][0]["message"]
+ assert (
+ content["errors"][0]["code"]
+ == ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.name
+ )
+
+
@pytest.mark.parametrize(
"product_type_attribute_type, gql_attribute_type",
(
@@ -502,6 +577,280 @@ def test_assign_attribute_to_product_type_having_already_that_attribute(
)
+PRODUCT_ASSIGN_ATTR_UPDATE_QUERY = """
+ mutation assign(
+ $productTypeId: ID!, $operations: [ProductAttributeAssignmentUpdateInput]!
+ ) {
+ productAttributeAssignmentUpdate(
+ productTypeId: $productTypeId, operations: $operations
+ ) {
+ errors {
+ field
+ code
+ message
+ attributes
+ }
+ productType {
+ id
+ productAttributes {
+ id
+ }
+ variantAttributes {
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def test_assignment_attribute_update_not_assigned_attribute_should_raise_an_errors(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ color_attribute_without_values,
+):
+ """The productAttributeAssignmentUpdate mutation should raise an error when trying
+ to modify unassigned variant attribute."""
+
+ product_type = ProductType.objects.create(name="Type", kind=ProductTypeKind.NORMAL)
+ attribute = color_attribute_without_values
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
+ )
+
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+
+ query = PRODUCT_ASSIGN_ATTR_UPDATE_QUERY
+ operations = [
+ {
+ "id": graphene.Node.to_global_id("Attribute", attribute.pk),
+ "variantSelection": True,
+ }
+ ]
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
+
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
+ "data"
+ ]["productAttributeAssignmentUpdate"]
+
+ expected_errors = [
+ {
+ "field": "operations",
+ "message": "Attribute is not assigned to product type.",
+ "code": ProductErrorCode.NOT_FOUND.name,
+ "attributes": [graphene.Node.to_global_id("Attribute", attribute.pk)],
+ },
+ {
+ "field": "operations",
+ "message": "Attribute is not assigned to product variant.",
+ "code": ProductErrorCode.NOT_FOUND.name,
+ "attributes": [graphene.Node.to_global_id("Attribute", attribute.pk)],
+ },
+ ]
+ assert len(content["errors"]) == 2
+
+ for error in content["errors"]:
+ assert error in expected_errors
+
+
+def test_assignment_attribute_update_assigned_to_product_should_raise_an_error(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ color_attribute_without_values,
+):
+ """The productAttributeAssignmentUpdate mutation should raise an error when trying
+ to modify assigned to product attribute."""
+
+ product_type = ProductType.objects.create(name="Type", kind=ProductTypeKind.NORMAL)
+ attribute = color_attribute_without_values
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
+ )
+
+ product_type.product_attributes.add(attribute)
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+
+ query = PRODUCT_ASSIGN_ATTR_UPDATE_QUERY
+ operations = [
+ {
+ "id": graphene.Node.to_global_id("Attribute", attribute.pk),
+ "variantSelection": True,
+ }
+ ]
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
+
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
+ "data"
+ ]["productAttributeAssignmentUpdate"]
+
+ expected_errors = [
+ {
+ "field": "operations",
+ "message": "Attribute is not assigned to product variant.",
+ "code": ProductErrorCode.NOT_FOUND.name,
+ "attributes": [graphene.Node.to_global_id("Attribute", attribute.pk)],
+ },
+ ]
+ assert len(content["errors"]) == 1
+
+ for error in content["errors"]:
+ assert error in expected_errors
+
+
+def test_assignment_attrib_update_assigned_with_duplicates_type_should_raise_an_error(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ color_attribute_without_values,
+):
+ """The productAttributeAssignmentUpdate mutation should raise an error when
+ to modify operations with duplicated attribute ids."""
+
+ product_type = ProductType.objects.create(name="Type", kind=ProductTypeKind.NORMAL)
+ attribute = color_attribute_without_values
+
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
+ )
+
+ product_type.variant_attributes.add(attribute)
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+
+ query = PRODUCT_ASSIGN_ATTR_UPDATE_QUERY
+ id_ = graphene.Node.to_global_id("Attribute", attribute.pk)
+ operations = [
+ {
+ "id": id_,
+ "variantSelection": True,
+ },
+ {
+ "id": id_,
+ "variantSelection": False,
+ },
+ ]
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
+
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
+ "data"
+ ]["productAttributeAssignmentUpdate"]
+
+ expected_error_msg = "Attribute ids should be unique within operations."
+
+ expected_errors = [
+ {
+ "field": "operations",
+ "message": expected_error_msg,
+ "code": ProductErrorCode.INVALID.name,
+ "attributes": [id_],
+ },
+ ]
+ assert len(content["errors"]) == 1
+
+ for error in content["errors"]:
+ assert error in expected_errors
+
+
+def test_assignment_attribute_update_assigned_unsupported_type_should_raise_an_error(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ color_attribute_without_values,
+):
+ """The productAttributeAssignmentUpdate mutation should raise an error when trying
+ to modify unsupported variant attribute."""
+
+ product_type = ProductType.objects.create(name="Type", kind=ProductTypeKind.NORMAL)
+ attribute = color_attribute_without_values
+ attribute.input_type = AttributeInputType.MULTISELECT
+ attribute.save(update_fields=["input_type"])
+
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
+ )
+
+ product_type.variant_attributes.add(attribute)
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+
+ query = PRODUCT_ASSIGN_ATTR_UPDATE_QUERY
+ operations = [
+ {
+ "id": graphene.Node.to_global_id("Attribute", attribute.pk),
+ "variantSelection": True,
+ }
+ ]
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
+
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
+ "data"
+ ]["productAttributeAssignmentUpdate"]
+
+ expected_error_msg = (
+ f"Some of the attributes types are not supported for "
+ "variant selection. Supported types are: "
+ f"{AttributeInputType.ALLOWED_IN_VARIANT_SELECTION}."
+ )
+
+ expected_errors = [
+ {
+ "field": "operations",
+ "message": expected_error_msg,
+ "code": ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.name,
+ "attributes": [graphene.Node.to_global_id("Attribute", attribute.pk)],
+ },
+ ]
+ assert len(content["errors"]) == 1
+
+ for error in content["errors"]:
+ assert error in expected_errors
+
+
+def test_assignment_attribute_update_assigned_should_modify_variant_selection(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ size_attribute,
+ color_attribute_without_values,
+):
+ """The productAttributeAssignmentUpdate mutation should modify
+ variant selection when validation successful."""
+
+ product_type = ProductType.objects.create(name="Type", kind=ProductTypeKind.NORMAL)
+ attribute_1 = color_attribute_without_values
+ attribute_2 = size_attribute
+
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
+ )
+
+ product_type.variant_attributes.add(
+ attribute_1, through_defaults={"variant_selection": False}
+ )
+ product_type.variant_attributes.add(
+ attribute_2, through_defaults={"variant_selection": True}
+ )
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+
+ query = PRODUCT_ASSIGN_ATTR_UPDATE_QUERY
+ operations = [
+ {
+ "id": graphene.Node.to_global_id("Attribute", attribute_1.pk),
+ "variantSelection": True,
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", attribute_2.pk),
+ "variantSelection": False,
+ },
+ ]
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
+
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
+ "data"
+ ]["productAttributeAssignmentUpdate"]
+
+ assert len(content["errors"]) == 0
+ assert AttributeVariant.objects.get(attribute_id=attribute_1.pk).variant_selection
+ assert not AttributeVariant.objects.get(
+ attribute_id=attribute_2.pk
+ ).variant_selection
+
+
def test_assign_page_attribute_to_product_type(
staff_api_client,
permission_manage_product_types_and_attributes,
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 447497b034..5b52b9e9c2 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -7617,6 +7617,123 @@ def test_product_type_query_only_variant_selections_value_set(
)
+PRODUCT_TYPE_QUERY_ASSIGNED_VARIANT_ATTRIBUTES = """
+ query getProductType(
+ $id: ID!, $variantSelection: VariantAttributeScope, $channel: String
+ ) {
+ productType(id: $id) {
+ name
+ assignedVariantAttributes(variantSelection: $variantSelection) {
+ attribute {
+ slug
+ }
+ variantSelection
+ }
+ products(first: 20, channel:$channel) {
+ totalCount
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ taxType {
+ taxCode
+ description
+ }
+ }
+ }
+"""
+
+
+ "variant_selection",
+ [
+ VariantAttributeScope.ALL.name,
+ VariantAttributeScope.VARIANT_SELECTION.name,
+ VariantAttributeScope.NOT_VARIANT_SELECTION.name,
+ ],
+)
+def test_product_type_query_only_assigned_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_type_page_reference_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_ASSIGNED_VARIANT_ATTRIBUTES
+
+ 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,
+ product_type_page_reference_attribute,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductType", product_type.id),
+ "variantSelection": variant_selection,
+ "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"
+
+ if variant_selection == VariantAttributeScope.VARIANT_SELECTION.name:
+ assert (
+ len(data["productType"]["assignedVariantAttributes"])
+ == product_type.variant_attributes.filter(
+ input_type=AttributeInputType.DROPDOWN, type=AttributeType.PRODUCT_TYPE
+ ).count()
+ )
+ assert all(
+ assign["variantSelection"]
+ for assign in data["productType"]["assignedVariantAttributes"]
+ )
+ elif variant_selection == VariantAttributeScope.NOT_VARIANT_SELECTION.name:
+ assert (
+ len(data["productType"]["assignedVariantAttributes"])
+ == product_type.variant_attributes.exclude(
+ input_type=AttributeInputType.DROPDOWN, type=AttributeType.PRODUCT_TYPE
+ ).count()
+ )
+ assert not any(
+ assign["variantSelection"]
+ for assign in data["productType"]["assignedVariantAttributes"]
+ )
+
+ else:
+ assert (
+ len(data["productType"]["assignedVariantAttributes"])
+ == product_type.variant_attributes.count()
+ )
+
+
PRODUCT_TYPE_CREATE_MUTATION = """
mutation createProductType(
$name: String,
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index 66de793d20..573fb45084 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -730,7 +730,9 @@ def test_create_variant_with_boolean_attribute(
size_attribute,
warehouse,
):
- product_type.variant_attributes.add(boolean_attribute)
+ product_type.variant_attributes.add(
+ boolean_attribute, through_defaults={"variant_selection": True}
+ )
query = CREATE_VARIANT_MUTATION
product_id = graphene.Node.to_global_id("Product", product.pk)
boolean_attr_id = graphene.Node.to_global_id("Attribute", boolean_attribute.id)
@@ -1384,7 +1386,9 @@ def test_create_product_variant_not_all_attributes(
"Attribute", product_type.variant_attributes.first().pk
)
variant_value = "test-value"
- product_type.variant_attributes.add(color_attribute)
+ product_type.variant_attributes.add(
+ color_attribute, through_defaults={"variant_selection": True}
+ )
variables = {
"productId": product_id,
@@ -2142,7 +2146,9 @@ def test_update_product_variant_not_all_attributes(
"Attribute", product_type.variant_attributes.first().id
)
variant_value = "test-value"
- product_type.variant_attributes.add(color_attribute)
+ product_type.variant_attributes.add(
+ color_attribute, through_defaults={"variant_selection": True}
+ )
variables = {
"id": variant_id,
@@ -2522,6 +2528,9 @@ def test_update_product_variant_clear_attributes(
attribute = variant_attr.assignment.attribute
attribute.input_type = AttributeInputType.MULTISELECT
attribute.value_required = False
+ attribute_variant = attribute.attributevariant.get()
+ attribute_variant.variant_selection = False
+ attribute_variant.save(update_fields=["variant_selection"])
attribute.save(update_fields=["value_required", "input_type"])
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
@@ -3951,7 +3960,9 @@ def test_product_variant_bulk_create_with_swatch_attribute(
staff_api_client, product, swatch_attribute, permission_manage_products
):
product_variant_count = ProductVariant.objects.count()
- product.product_type.variant_attributes.set([swatch_attribute])
+ product.product_type.variant_attributes.set(
+ [swatch_attribute], through_defaults={"variant_selection": True}
+ )
attribute_value_count = swatch_attribute.values.count()
product_id = graphene.Node.to_global_id("Product", product.pk)
attribute_id = graphene.Node.to_global_id("Attribute", swatch_attribute.pk)
@@ -4003,6 +4014,10 @@ def test_product_variant_bulk_create_only_not_variant_selection_attributes(
attribute_value_count = size_attribute.values.count()
size_attribute.input_type = AttributeInputType.MULTISELECT
+ variant_attribute = size_attribute.attributevariant.get()
+ variant_attribute.variant_selection = False
+ variant_attribute.save(update_fields=["variant_selection"])
+
size_attribute.save(update_fields=["input_type"])
product_id = graphene.Node.to_global_id("Product", product.pk)
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 0abeb23065..1725a80f67 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -30,7 +30,7 @@ from ...account import types as account_types
from ...account.enums import CountryCodeEnum
from ...attribute.filters import AttributeFilterInput
from ...attribute.resolvers import resolve_attributes
-from ...attribute.types import Attribute, SelectedAttribute
+from ...attribute.types import AssignedVariantAttribute, Attribute, SelectedAttribute
from ...channel import ChannelContext, ChannelQsContext
from ...channel.dataloaders import ChannelBySlugLoader
from ...channel.types import ChannelContextType, ChannelContextTypeWithMetadata
@@ -394,9 +394,12 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
if not variant_selection or variant_selection == VariantAttributeScope.ALL:
return selected_attributes
attributes = [
- selected_att["attribute"] for selected_att in selected_attributes
+ (selected_att["attribute"], selected_att["variant_selection"])
+ for selected_att in selected_attributes
+ ]
+ variant_selection_attrs = [
+ attr for attr, _ in get_variant_selection_attributes(attributes)
]
- variant_selection_attrs = get_variant_selection_attributes(attributes)
if variant_selection == VariantAttributeScope.VARIANT_SELECTION:
return [
@@ -1126,6 +1129,20 @@ class ProductType(CountableDjangoObjectType):
VariantAttributeScope,
description="Define scope of returned attributes.",
),
+ deprecation_reason=(
+ f"{DEPRECATED_IN_3X_FIELD} Use `assignedVariantAttributes` instead."
+ ),
+ )
+ assigned_variant_attributes = graphene.List(
+ AssignedVariantAttribute,
+ description=(
+ f"{ADDED_IN_31} Variant attributes of that product "
+ "type with attached variant selection."
+ ),
+ variant_selection=graphene.Argument(
+ VariantAttributeScope,
+ description="Define scope of returned attributes.",
+ ),
)
product_attributes = graphene.List(
Attribute, description="Product attributes of that product type."
@@ -1159,7 +1176,14 @@ class ProductType(CountableDjangoObjectType):
@staticmethod
def resolve_product_attributes(root: models.ProductType, info):
- return ProductAttributesByProductTypeIdLoader(info.context).load(root.pk)
+ def unpack_attributes(attributes):
+ return [attr for attr, *_ in attributes]
+
+ return (
+ ProductAttributesByProductTypeIdLoader(info.context)
+ .load(root.pk)
+ .then(unpack_attributes)
+ )
@staticmethod
@traced_resolver
@@ -1170,11 +1194,46 @@ class ProductType(CountableDjangoObjectType):
):
def apply_variant_selection_filter(attributes):
if not variant_selection or variant_selection == VariantAttributeScope.ALL:
- return attributes
+ return [attr for attr, *_ in attributes]
+ variant_selection_attrs = get_variant_selection_attributes(attributes)
+ if variant_selection == VariantAttributeScope.VARIANT_SELECTION:
+ return [attr for attr, *_ in variant_selection_attrs]
+ return [
+ attr
+ for attr, variant_selection in attributes
+ if (attr, variant_selection) not in variant_selection_attrs
+ ]
+
+ return (
+ VariantAttributesByProductTypeIdLoader(info.context)
+ .load(root.pk)
+ .then(apply_variant_selection_filter)
+ )
+
+ @staticmethod
+ @traced_resolver
+ def resolve_assigned_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 [
+ {"attribute": attr, "variant_selection": variant_selection}
+ for attr, variant_selection in 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 [
+ {"attribute": attr, "variant_selection": variant_selection}
+ for attr, variant_selection in variant_selection_attrs
+ ]
+ return [
+ {"attribute": attr, "variant_selection": variant_selection}
+ for attr, variant_selection in attributes
+ if (attr, variant_selection) not in variant_selection_attrs
+ ]
return (
VariantAttributesByProductTypeIdLoader(info.context)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index e9b75ed170..c569511cb2 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -457,6 +457,11 @@ type AssignNavigation {
errors: [MenuError!]!
}
+type AssignedVariantAttribute {
+ attribute: Attribute!
+ variantSelection: Boolean!
+}
+
type Attribute implements Node & ObjectWithMetadata {
id: ID!
productTypes(before: String, after: String, first: Int, last: Int): ProductTypeCountableConnection!
@@ -3749,6 +3754,7 @@ type Mutation {
shippingZoneBulkDelete(ids: [ID]!): ShippingZoneBulkDelete
shippingZoneUpdate(id: ID!, input: ShippingZoneUpdateInput!): ShippingZoneUpdate
productAttributeAssign(operations: [ProductAttributeAssignInput]!, productTypeId: ID!): ProductAttributeAssign
+ productAttributeAssignmentUpdate(operations: [ProductAttributeAssignmentUpdateInput]!, productTypeId: ID!): ProductAttributeAssignmentUpdate
productAttributeUnassign(attributeIds: [ID]!, productTypeId: ID!): ProductAttributeUnassign
categoryCreate(input: CategoryInput!, parent: ID): CategoryCreate
categoryDelete(id: ID!): CategoryDelete
@@ -5201,6 +5207,18 @@ type ProductAttributeAssign {
input ProductAttributeAssignInput {
id: ID!
type: ProductAttributeType!
+ variantSelection: Boolean
+}
+
+type ProductAttributeAssignmentUpdate {
+ productType: ProductType
+ productErrors: [ProductError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
+ errors: [ProductError!]!
+}
+
+input ProductAttributeAssignmentUpdateInput {
+ id: ID!
+ variantSelection: Boolean!
}
enum ProductAttributeType {
@@ -5528,7 +5546,8 @@ type ProductType implements Node & ObjectWithMetadata {
kind: ProductTypeKindEnum!
products(channel: String, before: String, after: String, first: Int, last: Int): ProductCountableConnection @deprecated(reason: "This field will be removed in Saleor 4.0. Use the top-level `products` query with the `productTypes` filter.")
taxType: TaxType
- variantAttributes(variantSelection: VariantAttributeScope): [Attribute]
+ variantAttributes(variantSelection: VariantAttributeScope): [Attribute] @deprecated(reason: "This field will be removed in Saleor 4.0. Use `assignedVariantAttributes` instead.")
+ assignedVariantAttributes(variantSelection: VariantAttributeScope): [AssignedVariantAttribute]
productAttributes: [Attribute]
availableAttributes(filter: AttributeFilterInput, before: String, after: String, first: Int, last: Int): AttributeCountableConnection
}
diff --git a/saleor/product/tests/test_generate_and_set_variant_name.py b/saleor/product/tests/test_generate_and_set_variant_name.py
index 2f187b157f..4a0a15c30b 100644
--- a/saleor/product/tests/test_generate_and_set_variant_name.py
+++ b/saleor/product/tests/test_generate_and_set_variant_name.py
@@ -49,9 +49,10 @@ def test_generate_and_set_variant_name_different_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)
+ variant.product.product_type.variant_attributes.add(
+ size_attribute, through_defaults={"variant_selection": True}
)
+ variant.product.product_type.variant_attributes.add(color_attribute)
# Set the color attribute to a multi-value attribute
color_attribute.input_type = AttributeInputType.MULTISELECT
@@ -91,7 +92,7 @@ def test_generate_and_set_variant_name_only_variant_selection_attributes(
# Assign the attributes to the product type
variant.product.product_type.variant_attributes.set(
- (color_attribute, size_attribute)
+ (color_attribute, size_attribute), through_defaults={"variant_selection": True}
)
# Create values
@@ -195,6 +196,10 @@ def test_only_not_variant_selection_attr_left_variant_name_change_to_sku(product
product_variant = product.variants.first()
assert not product_variant.name == new_name
attribute = product.product_type.variant_attributes.first()
+ variant_attribute = attribute.attributevariant.get()
+ variant_attribute.variant_selection = False
+ variant_attribute.save(update_fields=["variant_selection"])
+
attribute.input_type = AttributeInputType.MULTISELECT
attribute.save(update_fields=["input_type"])
_update_variants_names(product.product_type, [attribute])
@@ -218,6 +223,10 @@ def test_only_not_variant_selection_attr_left_variant_name_change_to_global_id(p
product_variant.save()
attribute = product.product_type.variant_attributes.first()
attribute.input_type = AttributeInputType.MULTISELECT
+ variant_attribute = attribute.attributevariant.get()
+ variant_attribute.variant_selection = False
+ variant_attribute.save(update_fields=["variant_selection"])
+
attribute.save(update_fields=["input_type"])
_update_variants_names(product.product_type, [attribute])
product_variant.refresh_from_db()
diff --git a/saleor/product/tests/test_get_variant_selection_attributes.py b/saleor/product/tests/test_get_variant_selection_attributes.py
index aea0265b6a..6787aeb341 100644
--- a/saleor/product/tests/test_get_variant_selection_attributes.py
+++ b/saleor/product/tests/test_get_variant_selection_attributes.py
@@ -23,8 +23,11 @@ def test_get_variant_selection_attributes(
product_type_product_reference_attribute,
]
+ # for now, instead of skipping test
+ attrs = zip(attrs, (False, True, True, False, True, False, False, False))
+
# when
- result = get_variant_selection_attributes(attrs)
+ result = [attr for attr, *_ in 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.py
index 7d00491740..36cc1b11d2 100644
--- a/saleor/product/utils/variants.py
+++ b/saleor/product/utils/variants.py
@@ -1,9 +1,9 @@
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING, List, Optional, Sequence, Tuple
-from ...attribute import AttributeInputType, AttributeType
+from ...attribute import AttributeType
if TYPE_CHECKING:
- from ...attribute.models import AssignedVariantAttribute
+ from ...attribute.models import AssignedVariantAttribute, Attribute
from ..models import ProductVariant
@@ -11,9 +11,8 @@ def generate_and_set_variant_name(variant: "ProductVariant", sku: Optional[str])
"""Generate ProductVariant's name based on its attributes."""
attributes_display = []
- 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__variant_selection=True,
assignment__attribute__type=AttributeType.PRODUCT_TYPE,
)
for (
@@ -31,15 +30,16 @@ def generate_and_set_variant_name(variant: "ProductVariant", sku: Optional[str])
variant.save(update_fields=["name"])
-def get_variant_selection_attributes(attributes):
+def get_variant_selection_attributes(
+ attributes: Sequence[Tuple["Attribute", bool]]
+) -> List[Tuple["Attribute", bool]]:
"""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
+ (attribute, variant_selection)
+ for attribute, variant_selection in attributes
+ if variant_selection and attribute.type == AttributeType.PRODUCT_TYPE
]
diff --git a/saleor/static/populatedb_data.json b/saleor/static/populatedb_data.json
index 64332622ff..2a23919422 100644
--- a/saleor/static/populatedb_data.json
+++ b/saleor/static/populatedb_data.json
@@ -8685,7 +8685,8 @@
"fields": {
"sort_order": null,
"attribute": 13,
- "product_type": 14
+ "product_type": 14,
+ "variant_selection": false
}
},
{
@@ -8694,7 +8695,8 @@
"fields": {
"sort_order": null,
"attribute": 15,
- "product_type": 9
+ "product_type": 9,
+ "variant_selection": false
}
},
{
@@ -8703,7 +8705,8 @@
"fields": {
"sort_order": null,
"attribute": 18,
- "product_type": 7
+ "product_type": 7,
+ "variant_selection": false
}
},
{
@@ -8712,7 +8715,8 @@
"fields": {
"sort_order": null,
"attribute": 19,
- "product_type": 8
+ "product_type": 8,
+ "variant_selection": true
}
},
{
@@ -8721,7 +8725,8 @@
"fields": {
"sort_order": null,
"attribute": 22,
- "product_type": 12
+ "product_type": 12,
+ "variant_selection": true
}
},
{
@@ -8730,7 +8735,8 @@
"fields": {
"sort_order": null,
"attribute": 24,
- "product_type": 13
+ "product_type": 13,
+ "variant_selection": true
}
},
{
@@ -8739,7 +8745,8 @@
"fields": {
"sort_order": 0,
"attribute": 19,
- "product_type": 15
+ "product_type": 15,
+ "variant_selection": false
}
},
{
@@ -8748,7 +8755,8 @@
"fields": {
"sort_order": null,
"attribute": 32,
- "product_type": 12
+ "product_type": 12,
+ "variant_selection": false
}
},
{
@@ -8757,7 +8765,8 @@
"fields": {
"sort_order": null,
"attribute": 33,
- "product_type": 12
+ "product_type": 12,
+ "variant_selection": false
}
},
{
@@ -8766,7 +8775,8 @@
"fields": {
"sort_order": null,
"attribute": 34,
- "product_type": 15
+ "product_type": 15,
+ "variant_selection": true
}
},
{
@@ -8775,7 +8785,8 @@
"fields": {
"sort_order": null,
"attribute": 35,
- "product_type": 15
+ "product_type": 15,
+ "variant_selection": false
}
},
{
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 4460a7d01c..d8b1bac8b9 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -1536,7 +1536,9 @@ def product_type(color_attribute, size_attribute):
is_shipping_required=True,
)
product_type.product_attributes.add(color_attribute)
- product_type.variant_attributes.add(size_attribute)
+ product_type.variant_attributes.add(
+ size_attribute, through_defaults={"variant_selection": True}
+ )
return product_type