Skip to content

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

Implement field for fetching unassigned attributes from product types

NyanKiyoshi733d7d1c205c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fa74b4858e..1a1fb30759 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,9 @@ All notable, unreleased changes to this project will be documented in this file.
- They now accept an optional `slug` input parameter for setting the internal representation of the attribute instead of always generating it. This allows users to have multiple attributes with the same name but that are different things or set of values. - #4260 by @NyanKiyoshi
- The `Attribute` model:
- They now always unique, instead of being unique only into a given product type. - #4260 by @NyanKiyoshi
+- Attributes can now be associated to multiple product types. - #4266 by @NyanKiyoshi
+- The `Attribute` model's `product_type` field was renamed to `product_types` (M2M related manager). - #4266 by @NyanKiyoshi
+- Added `attributeAssign(...)` and `attributeUnassign(...)` mutations in the GraphQL API. - #4266 by @NyanKiyoshi
## [Unreleased]
diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.py
index 49eeabc1b7..11f59c3502 100644
--- a/saleor/dashboard/product/views.py
+++ b/saleor/dashboard/product/views.py
@@ -153,6 +153,9 @@ def product_create(request, type_pk):
@permission_required("product.manage_products")
def product_edit(request, pk):
product = get_object_or_404(Product.objects.prefetch_related("variants"), pk=pk)
+ for k, v in product.attributes.items():
+ product.attributes[k] = [v]
+ product.save()
form = forms.ProductForm(request.POST or None, instance=product)
edit_variant = not product.product_type.has_variants
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.py
index 1f789258c4..4edf83c606 100644
--- a/saleor/graphql/product/mutations/attributes.py
+++ b/saleor/graphql/product/mutations/attributes.py
@@ -271,7 +271,7 @@ class AttributeAssign(BaseAttributeAssignmentMutation):
"""Ensures the requested attributes are not already assigned
to that product type."""
qs = (
- models.Attribute.get_assigned_attributes(product_type.pk)
+ models.Attribute.objects.get_assigned_attributes(product_type.pk)
.values_list("name", "slug")
.filter(Q(pk__in=product_attrs_pks) | Q(pk__in=variant_attrs_pks))
)
@@ -319,7 +319,7 @@ class AttributeAssign(BaseAttributeAssignmentMutation):
return cls(product_type=product_type)
-class AttributeUnAssign(BaseAttributeAssignmentMutation):
+class AttributeUnassign(BaseAttributeAssignmentMutation):
class Meta:
description = "Un-assign attributes from a given product type."
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index 490c4934c4..7a5c6b56d0 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -32,7 +32,7 @@ from .mutations.attributes import (
AttributeClearPrivateMeta,
AttributeCreate,
AttributeDelete,
- AttributeUnAssign,
+ AttributeUnassign,
AttributeUpdate,
AttributeUpdateMeta,
AttributeUpdatePrivateMeta,
@@ -296,7 +296,7 @@ class ProductMutations(graphene.ObjectType):
attribute_delete = AttributeDelete.Field()
attribute_bulk_delete = AttributeBulkDelete.Field()
attribute_assign = AttributeAssign.Field()
- attribute_un_assign = AttributeUnAssign.Field()
+ attribute_unassign = AttributeUnassign.Field()
attribute_update = AttributeUpdate.Field()
attribute_translate = AttributeTranslate.Field()
attribute_update_metadata = AttributeUpdateMeta.Field()
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 944ac07cd5..2f77c57374 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -631,6 +631,12 @@ class ProductType(CountableDjangoObjectType, MetadataObjectType):
product_attributes = graphene.List(
Attribute, description="Product attributes of that product type."
)
+ available_attributes = gql_optimizer.field(
+ PrefetchingConnectionField(
+ Attribute,
+ description="List of attributes that are available for assignment.",
+ )
+ )
class Meta:
description = """Represents a type of product. It defines what
@@ -677,6 +683,12 @@ class ProductType(CountableDjangoObjectType, MetadataObjectType):
qs = root.products.visible_to_user(info.context.user)
return gql_optimizer.query(qs, info)
+ @staticmethod
+ @permission_required("product.manage_products")
+ def resolve_available_attributes(root: models.ProductType, info, **_kwargs):
+ qs = models.Attribute.objects.get_unassigned_attributes(root.pk)
+ return gql_optimizer.query(qs, info)
+
@staticmethod
@permission_required("account.manage_products")
def resolve_private_meta(root, _info):
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 251d8f84c7..0508c74a16 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -228,7 +228,7 @@ enum AttributeTypeEnum {
VARIANT
}
-type AttributeUnAssign {
+type AttributeUnassign {
errors: [Error!]
productType: ProductType
}
@@ -1709,7 +1709,7 @@ type Mutations {
attributeDelete(id: ID!): AttributeDelete
attributeBulkDelete(ids: [ID]!): AttributeBulkDelete
attributeAssign(operations: [AttributeAssignInput]!, productTypeId: ID!): AttributeAssign
- attributeUnAssign(operations: [AttributeAssignInput]!, productTypeId: ID!): AttributeUnAssign
+ 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
@@ -2584,6 +2584,7 @@ type ProductType implements Node {
taxType: TaxType
variantAttributes: [Attribute]
productAttributes: [Attribute]
+ availableAttributes(before: String, after: String, first: Int, last: Int): AttributeCountableConnection
}
type ProductTypeBulkDelete {
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 59ad4765ce..8b219b852e 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -443,6 +443,20 @@ class AttributeVariant(models.Model):
)
+class AttributeQuerySet(models.QuerySet):
+ def get_unassigned_attributes(self, product_type_pk: int):
+ return self.exclude(
+ Q(attributeproduct__product_type_id=product_type_pk)
+ | Q(attributevariant__product_type_id=product_type_pk)
+ )
+
+ def get_assigned_attributes(self, product_type_pk: int):
+ return self.filter(
+ Q(attributeproduct__product_type_id=product_type_pk)
+ | Q(attributevariant__product_type_id=product_type_pk)
+ )
+
+
class Attribute(ModelWithMetadata):
slug = models.SlugField(max_length=50, unique=True)
name = models.CharField(max_length=50)
@@ -461,6 +475,7 @@ class Attribute(ModelWithMetadata):
through_fields=["attribute", "product_type"],
)
+ objects = AttributeQuerySet.as_manager()
translated = TranslationProxy()
class Meta:
@@ -469,20 +484,6 @@ 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 8b111dad82..d031358260 100644
--- a/tests/api/test_attributes.py
+++ b/tests/api/test_attributes.py
@@ -847,7 +847,7 @@ UNASSIGN_ATTR_QUERY = """
mutation unAssignAttribute(
$productTypeId: ID!, $operations: [AttributeAssignInput]!
) {
- attributeUnAssign(productTypeId: $productTypeId, operations: $operations) {
+ attributeUnassign(productTypeId: $productTypeId, operations: $operations) {
errors {
field
message
@@ -895,7 +895,7 @@ def test_unassign_attributes_from_product_type(
staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
)
- )["data"]["attributeUnAssign"]
+ )["data"]["attributeUnassign"]
assert not content["errors"]
assert content["productType"]["id"] == product_type_global_id
@@ -932,7 +932,7 @@ def test_unassign_attributes_not_in_product_type(
content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
"data"
- ]["attributeUnAssign"]
+ ]["attributeUnassign"]
assert not content["errors"]
assert content["productType"]["id"] == product_type_global_id
diff --git a/tests/api/test_product.py b/tests/api/test_product.py
index 30d8282286..2278a4b454 100644
--- a/tests/api/test_product.py
+++ b/tests/api/test_product.py
@@ -2301,3 +2301,75 @@ def test_product_base_price_permission(
assert "basePrice" in content["data"]["product"]
assert content["data"]["product"]["basePrice"]["amount"] == product.price.amount
+
+
+def test_product_type_get_unassigned_attributes(
+ staff_api_client, permission_manage_products
+):
+ query = """
+ query($productTypeId:ID!) {
+ productType(id: $productTypeId) {
+ availableAttributes(first: 10) {
+ edges {
+ node {
+ id
+ slug
+ }
+ }
+ }
+ }
+ }
+ """
+
+ target_product_type, ignored_product_type = ProductType.objects.bulk_create(
+ [ProductType(name="Type 1"), ProductType(name="Type 2")]
+ )
+
+ unassigned_attributes = list(
+ Attribute.objects.bulk_create(
+ [
+ Attribute(slug="size", name="Size"),
+ Attribute(slug="weight", name="Weight"),
+ Attribute(slug="thickness", name="Thickness"),
+ ]
+ )
+ )
+
+ assigned_attributes = list(
+ Attribute.objects.bulk_create(
+ [Attribute(slug="color", name="Color"), Attribute(slug="type", name="Type")]
+ )
+ )
+
+ # Ensure that assigning them to another product type
+ # doesn't return an invalid response
+ ignored_product_type.product_attributes.add(*unassigned_attributes)
+
+ # Assign the other attributes to the target product type
+ target_product_type.product_attributes.add(*assigned_attributes)
+
+ gql_unassigned_attributes = get_graphql_content(
+ staff_api_client.post_graphql(
+ query,
+ {
+ "productTypeId": graphene.Node.to_global_id(
+ "ProductType", target_product_type.pk
+ )
+ },
+ permissions=[permission_manage_products],
+ )
+ )["data"]["productType"]["availableAttributes"]["edges"]
+
+ assert len(gql_unassigned_attributes) == len(
+ unassigned_attributes
+ ), gql_unassigned_attributes
+
+ received_ids = sorted((attr["node"]["id"] for attr in gql_unassigned_attributes))
+ expected_ids = sorted(
+ (
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in unassigned_attributes
+ )
+ )
+
+ assert received_ids == expected_ids