Skip to content

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

Add assign mutations

NyanKiyoshic71d52f37379
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.py
index 3f389c005e..3834c81be7 100644
--- a/saleor/dashboard/product/forms.py
+++ b/saleor/dashboard/product/forms.py
@@ -1,7 +1,7 @@
import bleach
from django import forms
from django.conf import settings
-from django.db.models import Count, Q
+from django.db.models import Count
from django.forms.models import ModelChoiceIterator
from django.forms.widgets import CheckboxSelectMultiple
from django.utils.encoding import smart_text
@@ -110,25 +110,12 @@ class ProductTypeForm(forms.ModelForm):
self.fields["tax_rate"].choices = [
(tax.code, tax.description) for tax in manager.get_tax_rate_type_choices()
]
- unassigned_attrs_q = Q(
- product_types__isnull=True, product_variant_types__isnull=True
- )
+ variant_attrs_qs = product_attrs_qs = Attribute.objects.all()
if self.instance.pk:
- product_attrs_qs = Attribute.objects.filter(
- Q(attributeproduct__product_type_id=self.instance.pk)
- | unassigned_attrs_q
- )
- variant_attrs_qs = Attribute.objects.filter(
- Q(attributevariant__product_type_id=self.instance.pk)
- | unassigned_attrs_q
- )
product_attrs_initial = self.instance.product_attributes.all()
variant_attrs_initial = self.instance.variant_attributes.all()
else:
- unassigned_attrs = Attribute.objects.filter(unassigned_attrs_q)
- product_attrs_qs = unassigned_attrs
- variant_attrs_qs = unassigned_attrs
product_attrs_initial = []
variant_attrs_initial = []
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.py
index 6d659de928..1f789258c4 100644
--- a/saleor/graphql/product/mutations/attributes.py
+++ b/saleor/graphql/product/mutations/attributes.py
@@ -1,14 +1,21 @@
+from typing import List
+
import graphene
from django.core.exceptions import ValidationError
+from django.db.models import Q
from django.template.defaultfilters import slugify
from ....product import models
from ...core.mutations import (
+ BaseMutation,
ClearMetaBaseMutation,
ModelDeleteMutation,
ModelMutation,
UpdateMetaBaseMutation,
)
+from ...core.utils import from_global_id_strict_type
+from ...product.enums import AttributeTypeEnum
+from ...product.types import ProductType
from ..descriptions import AttributeDescriptions, AttributeValueDescriptions
from ..types import Attribute
@@ -41,6 +48,15 @@ class AttributeUpdateInput(graphene.InputObjectType):
)
+class AttributeAssignInput(graphene.InputObjectType):
+ attribute_id = graphene.ID(
+ required=True, description="The ID of the attribute to assign"
+ )
+ attribute_type = AttributeTypeEnum(
+ required=True, description="The attribute type to be assigned as."
+ )
+
+
class AttributeMixin:
@classmethod
def check_values_are_unique(cls, values_input, attribute):
@@ -207,6 +223,130 @@ class AttributeUpdate(AttributeMixin, ModelMutation):
return AttributeUpdate(attribute=instance)
+class BaseAttributeAssignmentMutation(BaseMutation):
+ 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(
+ AttributeAssignInput,
+ required=True,
+ description="The operations to perform.",
+ )
+
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def check_permissions(cls, user):
+ return user.has_perm("product.manage_products")
+
+ @classmethod
+ def get_operations(cls, info, operations: List[AttributeAssignInput]):
+ """Resolves all passed global ids into integer PKs of the Attribute type."""
+ product_attrs_pks = []
+ variant_attrs_pks = []
+
+ for operation in operations:
+ pk = from_global_id_strict_type(
+ info, operation.attribute_id, only_type=Attribute, field="operations"
+ )
+ if operation.attribute_type == AttributeTypeEnum.PRODUCT:
+ product_attrs_pks.append(pk)
+ else:
+ variant_attrs_pks.append(pk)
+
+ return product_attrs_pks, variant_attrs_pks
+
+
+class AttributeAssign(BaseAttributeAssignmentMutation):
+ class Meta:
+ description = "Assign attributes to a given product type."
+
+ @classmethod
+ def clean_operations(cls, product_type, product_attrs_pks, variant_attrs_pks):
+ """Ensures the requested attributes are not already assigned
+ to that product type."""
+ qs = (
+ models.Attribute.get_assigned_attributes(product_type.pk)
+ .values_list("name", "slug")
+ .filter(Q(pk__in=product_attrs_pks) | Q(pk__in=variant_attrs_pks))
+ )
+
+ invalid_attributes = list(qs)
+ if invalid_attributes:
+ msg = ", ".join([f"{name} ({slug})" for name, slug in invalid_attributes])
+ raise ValidationError(
+ {
+ "operations": (
+ f"{msg} have already been assigned to this product type."
+ )
+ }
+ )
+
+ @classmethod
+ def save_field_values(cls, product_type, field, pks):
+ """Add in bulk the PKs to assign to a given product type."""
+ getattr(product_type, field).add(*pks)
+
+ @classmethod
+ def perform_mutation(
+ cls, _root, info, product_type_id: str, operations: List[AttributeAssignInput]
+ ):
+ # Retrieve the requested product type
+ product_type = graphene.Node.get_node_from_global_id(
+ info, product_type_id, only_type=ProductType
+ ) # type: models.ProductType
+
+ # Resolve all the passed IDs to ints
+ product_attrs_pks, variant_attrs_pks = cls.get_operations(info, operations)
+
+ if variant_attrs_pks and not product_type.has_variants:
+ raise ValidationError(
+ {"operations": "Variants are disabled in this product type."}
+ )
+
+ # Ensure the attribute are assignable
+ cls.clean_operations(product_type, product_attrs_pks, variant_attrs_pks)
+
+ # Commit
+ cls.save_field_values(product_type, "product_attributes", product_attrs_pks)
+ cls.save_field_values(product_type, "variant_attributes", variant_attrs_pks)
+
+ return cls(product_type=product_type)
+
+
+class AttributeUnAssign(BaseAttributeAssignmentMutation):
+ class Meta:
+ description = "Un-assign attributes from a given product type."
+
+ @classmethod
+ def save_field_values(cls, product_type, field, pks):
+ """Add in bulk the PKs to assign to a given product type."""
+ getattr(product_type, field).remove(*pks)
+
+ @classmethod
+ def perform_mutation(
+ cls, _root, info, product_type_id: str, operations: List[AttributeAssignInput]
+ ):
+ # Retrieve the requested product type
+ product_type = graphene.Node.get_node_from_global_id(
+ info, product_type_id, only_type=ProductType
+ ) # type: models.ProductType
+
+ # Resolve all the passed IDs to ints
+ product_attrs_pks, variant_attrs_pks = cls.get_operations(info, operations)
+
+ # Commit
+ cls.save_field_values(product_type, "product_attributes", product_attrs_pks)
+ cls.save_field_values(product_type, "variant_attributes", variant_attrs_pks)
+
+ return cls(product_type=product_type)
+
+
class AttributeDelete(ModelDeleteMutation):
class Arguments:
id = graphene.ID(required=True, description="ID of an attribute to delete.")
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index 80a5982b7e..490c4934c4 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -27,10 +27,12 @@ from .bulk_mutations.products import (
from .enums import StockAvailability
from .filters import CollectionFilter, ProductFilter, ProductTypeFilter
from .mutations.attributes import (
+ AttributeAssign,
AttributeClearMeta,
AttributeClearPrivateMeta,
AttributeCreate,
AttributeDelete,
+ AttributeUnAssign,
AttributeUpdate,
AttributeUpdateMeta,
AttributeUpdatePrivateMeta,
@@ -293,6 +295,8 @@ class ProductMutations(graphene.ObjectType):
attribute_create = AttributeCreate.Field()
attribute_delete = AttributeDelete.Field()
attribute_bulk_delete = AttributeBulkDelete.Field()
+ attribute_assign = AttributeAssign.Field()
+ attribute_un_assign = AttributeUnAssign.Field()
attribute_update = AttributeUpdate.Field()
attribute_translate = AttributeTranslate.Field()
attribute_update_metadata = AttributeUpdateMeta.Field()
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 351d932b36..251d8f84c7 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -153,6 +153,16 @@ type Attribute implements Node {
translation(languageCode: LanguageCodeEnum!): AttributeTranslation
}
+type AttributeAssign {
+ errors: [Error!]
+ productType: ProductType
+}
+
+input AttributeAssignInput {
+ attributeId: ID!
+ attributeType: AttributeTypeEnum!
+}
+
type AttributeBulkDelete {
errors: [Error!]
count: Int!
@@ -213,6 +223,16 @@ type AttributeTranslation implements Node {
language: LanguageDisplay!
}
+enum AttributeTypeEnum {
+ PRODUCT
+ VARIANT
+}
+
+type AttributeUnAssign {
+ errors: [Error!]
+ productType: ProductType
+}
+
type AttributeUpdate {
errors: [Error!]
attribute: Attribute
@@ -1688,6 +1708,8 @@ type Mutations {
attributeCreate(input: AttributeCreateInput!): AttributeCreate
attributeDelete(id: ID!): AttributeDelete
attributeBulkDelete(ids: [ID]!): AttributeBulkDelete
+ attributeAssign(operations: [AttributeAssignInput]!, productTypeId: ID!): AttributeAssign
+ attributeUnAssign(operations: [AttributeAssignInput]!, productTypeId: ID!): AttributeUnAssign
attributeUpdate(id: ID!, input: AttributeUpdateInput!): AttributeUpdate
attributeTranslate(id: ID!, input: NameTranslationInput!, languageCode: LanguageCodeEnum!): AttributeTranslate
attributeUpdateMetadata(id: ID!, input: MetaInput!): AttributeUpdateMeta
diff --git a/saleor/product/models.py b/saleor/product/models.py
index be98ba1089..59ad4765ce 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -6,7 +6,7 @@ from django.conf import settings
from django.contrib.postgres.fields import HStoreField, JSONField
from django.core.validators import MinValueValidator
from django.db import models
-from django.db.models import F
+from django.db.models import F, Q
from django.urls import reverse
from django.utils.encoding import smart_text
from django.utils.html import strip_tags
@@ -469,6 +469,20 @@ class Attribute(ModelWithMetadata):
def __str__(self):
return self.name
+ @classmethod
+ def get_unassigned_attributes(cls, product_type_pk: int):
+ return cls.objects.exclude(
+ attributeproduct__product_type_id=product_type_pk,
+ attributevariant__product_type_id=product_type_pk,
+ )
+
+ @classmethod
+ def get_assigned_attributes(cls, product_type_pk: int):
+ return cls.objects.filter(
+ Q(attributeproduct__product_type_id=product_type_pk)
+ | Q(attributevariant__product_type_id=product_type_pk)
+ )
+
def get_formfield_name(self):
return slugify("attribute-%s-%s" % (self.slug, self.pk), allow_unicode=True)
diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.py
index 7f5d0364bb..8b111dad82 100644
--- a/tests/api/test_attributes.py
+++ b/tests/api/test_attributes.py
@@ -3,10 +3,10 @@ import pytest
from django.db.models import Q
from django.template.defaultfilters import slugify
-from saleor.graphql.product.enums import AttributeValueType
+from saleor.graphql.product.enums import AttributeTypeEnum, AttributeValueType
from saleor.graphql.product.types.attributes import resolve_attribute_value_type
from saleor.graphql.product.utils import attributes_to_hstore
-from saleor.product.models import Attribute, AttributeValue, Category
+from saleor.product.models import Attribute, AttributeValue, Category, ProductType
from tests.api.utils import get_graphql_content
@@ -681,3 +681,260 @@ def test_delete_attribute_value(
)
def test_resolve_attribute_value_type(raw_value, expected_type):
assert resolve_attribute_value_type(raw_value) == expected_type
+
+
+ASSIGN_ATTR_QUERY = """
+ mutation assign($productTypeId: ID!, $operations: [AttributeAssignInput]!) {
+ attributeAssign(productTypeId: $productTypeId, operations: $operations) {
+ errors {
+ field
+ message
+ }
+ productType {
+ id
+ productAttributes {
+ id
+ }
+ variantAttributes {
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def test_assign_attributes_to_product_type(
+ staff_api_client, permission_manage_products, attribute_list
+):
+ product_type = ProductType.objects.create(name="Default Type", has_variants=True)
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+
+ query = ASSIGN_ATTR_QUERY
+ operations = []
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
+
+ product_attributes = attribute_list[:2]
+ variant_attributes = attribute_list[2:]
+
+ for attr in product_attributes:
+ operations.append(
+ {
+ "attributeType": "PRODUCT",
+ "attributeId": graphene.Node.to_global_id("Attribute", attr.pk),
+ }
+ )
+
+ for attr in variant_attributes:
+ operations.append(
+ {
+ "attributeType": "VARIANT",
+ "attributeId": graphene.Node.to_global_id("Attribute", attr.pk),
+ }
+ )
+
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ )["data"]["attributeAssign"]
+ assert not content["errors"], "Should have succeeded"
+
+ assert content["productType"]["id"] == product_type_global_id
+ assert len(content["productType"]["productAttributes"]) == len(product_attributes)
+ assert len(content["productType"]["variantAttributes"]) == len(variant_attributes)
+
+ for attr, gql_attr in zip(
+ product_attributes, content["productType"]["productAttributes"]
+ ):
+ assert gql_attr["id"] == graphene.Node.to_global_id("Attribute", attr.pk)
+
+ for attr, gql_attr in zip(
+ variant_attributes, content["productType"]["variantAttributes"]
+ ):
+ assert gql_attr["id"] == graphene.Node.to_global_id("Attribute", attr.pk)
+
+
+def test_assign_variant_attribute_to_product_type_with_disabled_variants(
+ staff_api_client,
+ permission_manage_products,
+ product_type_without_variant,
+ color_attribute_without_values,
+):
+ """The assignAttribute mutation should raise an error when trying
+ to add an attribute as a variant attribute when
+ the product type doesn't support variants"""
+
+ product_type = product_type_without_variant
+ attribute = color_attribute_without_values
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+
+ query = ASSIGN_ATTR_QUERY
+ operations = [
+ {
+ "attributeType": "VARIANT",
+ "attributeId": graphene.Node.to_global_id("Attribute", attribute.pk),
+ }
+ ]
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
+
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
+ "data"
+ ]["attributeAssign"]
+ assert content["errors"] == [
+ {
+ "field": "operations",
+ "message": "Variants are disabled in this product type.",
+ }
+ ]
+
+
+ "product_type_attribute_type, gql_attribute_type",
+ (
+ (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.VARIANT),
+ (AttributeTypeEnum.VARIANT, AttributeTypeEnum.PRODUCT),
+ (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.PRODUCT),
+ (AttributeTypeEnum.VARIANT, AttributeTypeEnum.VARIANT),
+ ),
+)
+def test_assign_attribute_to_product_type_having_already_that_attribute(
+ staff_api_client,
+ permission_manage_products,
+ color_attribute_without_values,
+ product_type_attribute_type,
+ gql_attribute_type,
+):
+ """The assignAttribute mutation should raise an error when trying
+ to add an attribute already contained in the product type."""
+
+ product_type = ProductType.objects.create(name="Type")
+ attribute = color_attribute_without_values
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+
+ if product_type_attribute_type == AttributeTypeEnum.PRODUCT:
+ product_type.product_attributes.add(attribute)
+ elif product_type_attribute_type == AttributeTypeEnum.VARIANT:
+ product_type.variant_attributes.add(attribute)
+ else:
+ raise ValueError(f"Unknown: {product_type}")
+
+ query = ASSIGN_ATTR_QUERY
+ operations = [
+ {
+ "attributeType": gql_attribute_type.value,
+ "attributeId": graphene.Node.to_global_id("Attribute", attribute.pk),
+ }
+ ]
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
+
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
+ "data"
+ ]["attributeAssign"]
+ assert content["errors"] == [
+ {
+ "field": "operations",
+ "message": "Color (color) have already been assigned to this product type.",
+ }
+ ]
+
+
+UNASSIGN_ATTR_QUERY = """
+ mutation unAssignAttribute(
+ $productTypeId: ID!, $operations: [AttributeAssignInput]!
+ ) {
+ attributeUnAssign(productTypeId: $productTypeId, operations: $operations) {
+ errors {
+ field
+ message
+ }
+ productType {
+ id
+ variantAttributes {
+ id
+ }
+ productAttributes {
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def test_unassign_attributes_from_product_type(
+ staff_api_client, permission_manage_products, attribute_list
+):
+ product_type = ProductType.objects.create(name="Type")
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+
+ variant_attribute, *product_attributes = attribute_list
+ product_type.product_attributes.add(*product_attributes)
+ product_type.variant_attributes.add(variant_attribute)
+
+ remaining_attribute_global_id = graphene.Node.to_global_id(
+ "Attribute", product_attributes[1].pk
+ )
+
+ query = UNASSIGN_ATTR_QUERY
+ operations = [
+ {
+ "attributeType": "PRODUCT",
+ "attributeId": graphene.Node.to_global_id(
+ "Attribute", product_attributes[0].pk
+ ),
+ }
+ ]
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
+
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ )["data"]["attributeUnAssign"]
+ assert not content["errors"]
+
+ assert content["productType"]["id"] == product_type_global_id
+ assert len(content["productType"]["productAttributes"]) == 1
+ assert len(content["productType"]["variantAttributes"]) == 1
+
+ assert (
+ content["productType"]["productAttributes"][0]["id"]
+ == remaining_attribute_global_id
+ )
+
+
+def test_unassign_attributes_not_in_product_type(
+ staff_api_client, permission_manage_products, color_attribute_without_values
+):
+ """The unAssignAttribute mutation should not raise any error when trying
+ to remove an attribute that is not/no longer in the product type."""
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ product_type = ProductType.objects.create(name="Type")
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+
+ query = UNASSIGN_ATTR_QUERY
+ operations = [
+ {
+ "attributeType": "VARIANT",
+ "attributeId": graphene.Node.to_global_id(
+ "Attribute", color_attribute_without_values.pk
+ ),
+ }
+ ]
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
+
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
+ "data"
+ ]["attributeUnAssign"]
+ assert not content["errors"]
+
+ assert content["productType"]["id"] == product_type_global_id
+ assert len(content["productType"]["productAttributes"]) == 0
+ assert len(content["productType"]["variantAttributes"]) == 0
diff --git a/tests/api/test_bulk_delete.py b/tests/api/test_bulk_delete.py
index 93452760c2..5a3f1c9bbd 100644
--- a/tests/api/test_bulk_delete.py
+++ b/tests/api/test_bulk_delete.py
@@ -35,14 +35,6 @@ MUTATION_DELETE_ORDER_LINES = """
"""
-def attribute_list():
- attribute_1 = Attribute.objects.create(slug="size", name="Size")
- attribute_2 = Attribute.objects.create(slug="weight", name="Weight")
- attribute_3 = Attribute.objects.create(slug="thickness", name="Thickness")
- return attribute_1, attribute_2, attribute_3
-
-
@pytest.fixture
def attribute_value_list(color_attribute):
value_1 = AttributeValue.objects.create(
diff --git a/tests/conftest.py b/tests/conftest.py
index 4f75b748f7..90fc8fe0a9 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -344,6 +344,19 @@ def size_attribute(db): # pylint: disable=W0613
return attribute
+def attribute_list():
+ return list(
+ Attribute.objects.bulk_create(
+ [
+ Attribute(slug="size", name="Size"),
+ Attribute(slug="weight", name="Weight"),
+ Attribute(slug="thickness", name="Thickness"),
+ ]
+ )
+ )
+
+
@pytest.fixture
def image():
img_data = BytesIO()