Skip to content

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

Staff users can now flag attributes as to be hidden in the storefront (#4338)

NyanKiyoshi26609748e744
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 66ab4844e5..60d7a07964 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ All notable, unreleased changes to this project will be documented in this file.
- 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
- Implemented a `input_type` field into the attribute models and refactored the product attributes to be able to store more than one value per attribute per product. - #4255 by @NyanKiyoshi.
+- Staff users can now flag attributes as to be hidden in the storefront. - #4338 by @NyanKiyoshi
## [Unreleased]
diff --git a/saleor/graphql/product/descriptions.py b/saleor/graphql/product/descriptions.py
index 4dd4c1c61c..dc21a3da6d 100644
--- a/saleor/graphql/product/descriptions.py
+++ b/saleor/graphql/product/descriptions.py
@@ -4,6 +4,9 @@ class AttributeDescriptions:
SLUG = "Internal representation of an attribute name."
VALUES = "List of attribute's values."
IS_VARIANT_ONLY = "Whether the attribute is for variants only"
+ VISIBLE_IN_STOREFRONT = (
+ "Whether the attribute should be visible or not in storefront"
+ )
class AttributeValueDescriptions:
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.py
index 46610e2dd4..d5b6fbcfd4 100644
--- a/saleor/graphql/product/mutations/attributes.py
+++ b/saleor/graphql/product/mutations/attributes.py
@@ -35,6 +35,9 @@ class AttributeCreateInput(graphene.InputObjectType):
is_variant_only = graphene.Boolean(
required=False, description=AttributeDescriptions.IS_VARIANT_ONLY
)
+ visible_in_storefront = graphene.Boolean(
+ description=AttributeDescriptions.VISIBLE_IN_STOREFRONT
+ )
class AttributeUpdateInput(graphene.InputObjectType):
@@ -53,6 +56,9 @@ class AttributeUpdateInput(graphene.InputObjectType):
is_variant_only = graphene.Boolean(
required=False, description=AttributeDescriptions.IS_VARIANT_ONLY
)
+ visible_in_storefront = graphene.Boolean(
+ description=AttributeDescriptions.VISIBLE_IN_STOREFRONT
+ )
class AttributeAssignInput(graphene.InputObjectType):
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index 240b67b40e..fec1b83e3f 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -30,7 +30,7 @@ def _filter_attributes_by_product_types(attribute_qs, product_qs):
def resolve_attributes(info, category_id=None, collection_id=None, query=None):
- qs = models.Attribute.objects.all()
+ qs = models.Attribute.objects.get_visible_to_user(info.context.user)
qs = filter_by_query_param(qs, query, ATTRIBUTES_SEARCH_FIELDS)
if category_id:
diff --git a/saleor/graphql/product/types/attributes.py b/saleor/graphql/product/types/attributes.py
index f792bee470..f839a460a0 100644
--- a/saleor/graphql/product/types/attributes.py
+++ b/saleor/graphql/product/types/attributes.py
@@ -96,7 +96,12 @@ class Attribute(CountableDjangoObjectType, MetadataObjectType):
description = """
Custom attribute of a product. Attributes can be
assigned to products and variants at the product type level."""
- only_fields = ["id", "product_types", "product_variant_types"]
+ only_fields = [
+ "id",
+ "product_types",
+ "product_variant_types",
+ "visible_in_storefront",
+ ]
interfaces = [relay.Node]
model = models.Attribute
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 1d7a537a27..f2bd35efcf 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -1,3 +1,5 @@
+from typing import Dict
+
import graphene
import graphene_django_optimizer as gql_optimizer
from django.db.models import Prefetch
@@ -79,7 +81,7 @@ def resolve_attribute_list(attributes_json, attributes_qs):
`attributes_qs` is the queryset of attribute objects. If it's prefetch
beforehand along with the values, it saves database queries.
"""
- attributes_map = {}
+ attributes_map = {} # type: Dict[int, models.Attribute]
values_map = {}
for attr in attributes_qs:
attributes_map[attr.pk] = attr
@@ -274,9 +276,11 @@ class ProductVariant(CountableDjangoObjectType, MetadataObjectType):
@gql_optimizer.resolver_hints(
prefetch_related="product__product_type__variant_attributes__values"
)
- def resolve_attributes(root: models.ProductVariant, *_args):
- attributes_qs = root.product.product_type.variant_attributes.all()
- return resolve_attribute_list(root.attributes, attributes_qs)
+ def resolve_attributes(root: models.ProductVariant, info):
+ attr_qs = root.product.product_type.variant_attributes.get_visible_to_user(
+ info.context.user
+ )
+ return resolve_attribute_list(root.attributes, attr_qs)
@staticmethod
@permission_required("product.manage_products")
@@ -556,8 +560,10 @@ class Product(CountableDjangoObjectType, MetadataObjectType):
@gql_optimizer.resolver_hints(
prefetch_related="product_type__product_attributes__values"
)
- def resolve_attributes(root: models.Product, *_args):
- attributes_qs = root.product_type.product_attributes.all()
+ def resolve_attributes(root: models.Product, info):
+ attributes_qs = root.product_type.product_attributes.get_visible_to_user(
+ info.context.user
+ )
return resolve_attribute_list(root.attributes, attributes_qs)
@staticmethod
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 0db55953e8..5344eae5b1 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -145,8 +145,10 @@ type Attribute implements Node {
id: ID!
productTypes(before: String, after: String, first: Int, last: Int): ProductTypeCountableConnection
productVariantTypes(before: String, after: String, first: Int, last: Int): ProductTypeCountableConnection
+ visibleInStorefront: Boolean!
privateMeta: [MetaStore]!
meta: [MetaStore]!
+ inputType: AttributeInputTypeEnum
name: String
slug: String
values: [AttributeValue]
@@ -195,10 +197,12 @@ type AttributeCreate {
}
input AttributeCreateInput {
+ inputType: AttributeInputTypeEnum
name: String!
slug: String
values: [AttributeValueCreateInput]
isVariantOnly: Boolean
+ visibleInStorefront: Boolean
}
type AttributeDelete {
@@ -211,6 +215,11 @@ input AttributeInput {
value: String!
}
+enum AttributeInputTypeEnum {
+ DROPDOWN
+ MULTISELECT
+}
+
scalar AttributeScalar
type AttributeTranslate {
@@ -245,6 +254,7 @@ input AttributeUpdateInput {
removeValues: [ID]
addValues: [AttributeValueCreateInput]
isVariantOnly: Boolean
+ visibleInStorefront: Boolean
}
type AttributeUpdateMeta {
@@ -265,6 +275,7 @@ type AttributeValue implements Node {
type: AttributeValueType
value: String
translation(languageCode: LanguageCodeEnum!): AttributeValueTranslation
+ inputType: AttributeInputTypeEnum
}
type AttributeValueBulkDelete {
@@ -291,7 +302,7 @@ type AttributeValueDelete {
input AttributeValueInput {
slug: String!
- value: String!
+ values: [String]!
}
type AttributeValueTranslate {
diff --git a/saleor/product/migrations/0096_migrate_attrs_to_m2m.py b/saleor/product/migrations/0096_migrate_attrs_to_m2m.py
index fba518eedc..8d42b6451e 100644
--- a/saleor/product/migrations/0096_migrate_attrs_to_m2m.py
+++ b/saleor/product/migrations/0096_migrate_attrs_to_m2m.py
@@ -150,4 +150,10 @@ class Migration(migrations.Migration):
# Remove the migrated foreign keys
migrations.RemoveField(model_name="attribute", name="product_variant_type_old"),
migrations.RemoveField(model_name="attribute", name="product_type_old"),
+ # whether the attribute is visible in storefront
+ migrations.AddField(
+ model_name="attribute",
+ name="visible_in_storefront",
+ field=models.BooleanField(default=True),
+ ),
]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 1361984f12..01ab022a71 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -484,6 +484,18 @@ class AttributeQuerySet(models.QuerySet):
| Q(attributevariant__product_type_id=product_type_pk)
)
+ @staticmethod
+ def user_has_access_to_all(user):
+ return user.is_active and user.has_perm("product.manage_products")
+
+ def get_public_attributes(self):
+ return self.filter(visible_in_storefront=True)
+
+ def get_visible_to_user(self, user):
+ if self.user_has_access_to_all(user):
+ return self.all()
+ return self.get_public_attributes()
+
class Attribute(ModelWithMetadata):
slug = models.SlugField(max_length=50, unique=True)
@@ -510,6 +522,7 @@ class Attribute(ModelWithMetadata):
through_fields=["attribute", "product_type"],
)
+ visible_in_storefront = models.BooleanField(default=True)
is_variant_only = models.BooleanField(default=False)
objects = AttributeQuerySet.as_manager()
diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.py
index 72b3635946..065324cd25 100644
--- a/tests/api/test_attributes.py
+++ b/tests/api/test_attributes.py
@@ -5,6 +5,7 @@ from django.template.defaultfilters import slugify
from saleor.graphql.product.enums import AttributeTypeEnum, AttributeValueType
from saleor.graphql.product.types.attributes import resolve_attribute_value_type
+from saleor.graphql.product.types.products import resolve_attribute_list
from saleor.graphql.product.utils import attributes_to_json
from saleor.product import AttributeInputType
from saleor.product.models import Attribute, AttributeValue, Category, ProductType
@@ -74,9 +75,7 @@ def test_get_single_attribute_by_pk(user_api_client, color_attribute_without_val
assert content["data"]["attribute"]["slug"] == color_attribute_without_values.slug
-def test_attributes_query(user_api_client, product):
- attributes = Attribute.objects.prefetch_related("values")
- query = """
+QUERY_ATTRIBUTES = """
query {
attributes(first: 20) {
edges {
@@ -93,13 +92,169 @@ def test_attributes_query(user_api_client, product):
}
}
}
- """
+"""
+
+
+def test_attributes_query(user_api_client, product):
+ attributes = Attribute.objects
+ query = QUERY_ATTRIBUTES
response = user_api_client.post_graphql(query)
content = get_graphql_content(response)
attributes_data = content["data"]["attributes"]["edges"]
+ assert attributes_data
assert len(attributes_data) == attributes.count()
+def test_attributes_query_hidden_attribute(user_api_client, product, color_attribute):
+ query = QUERY_ATTRIBUTES
+
+ # hide the attribute
+ color_attribute.visible_in_storefront = False
+ color_attribute.save(update_fields=["visible_in_storefront"])
+
+ attribute_count = Attribute.objects.get_visible_to_user(
+ user_api_client.user
+ ).count()
+ assert attribute_count == 1
+
+ response = user_api_client.post_graphql(query)
+ content = get_graphql_content(response)
+ attributes_data = content["data"]["attributes"]["edges"]
+ assert len(attributes_data) == attribute_count
+
+
+def test_attributes_query_hidden_attribute_as_staff_user(
+ staff_api_client, product, color_attribute, permission_manage_products
+):
+ query = QUERY_ATTRIBUTES
+
+ # hide the attribute
+ color_attribute.visible_in_storefront = False
+ color_attribute.save(update_fields=["visible_in_storefront"])
+
+ attribute_count = Attribute.objects.all().count()
+
+ # The user doesn't have the permission yet to manage products,
+ # the user shouldn't be able to see the hidden attributes
+ assert Attribute.objects.get_visible_to_user(staff_api_client.user).count() == 1
+
+ # The user should now be able to see the attributes
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ response = staff_api_client.post_graphql(query)
+ content = get_graphql_content(response)
+ attributes_data = content["data"]["attributes"]["edges"]
+ assert len(attributes_data) == attribute_count
+
+
+QUERY_PRODUCT_ATTRIBUTES = """
+ {
+ products(first: 1) {
+ edges {
+ node {
+ attributes {
+ value {
+ name
+ }
+ attribute {
+ name
+ }
+ }
+ }
+ }
+ }
+ }
+"""
+
+
+def test_resolve_product_attributes_with_hidden(
+ user_api_client, product, color_attribute
+):
+ query = QUERY_PRODUCT_ATTRIBUTES
+
+ # Hide one attribute from the storefront
+ color_attribute.visible_in_storefront = False
+ color_attribute.save(update_fields=["visible_in_storefront"])
+
+ gql_attrs = get_graphql_content(user_api_client.post_graphql(query))["data"][
+ "products"
+ ]["edges"][0]["node"]["attributes"]
+ assert len(gql_attrs) == len(product.attributes) - 1
+
+
+def test_resolve_product_attributes_with_hidden_as_staff_user(
+ staff_api_client, product, color_attribute, permission_manage_products
+):
+ query = QUERY_PRODUCT_ATTRIBUTES
+
+ # Hide one attribute from the storefront
+ color_attribute.visible_in_storefront = False
+ color_attribute.save(update_fields=["visible_in_storefront"])
+
+ # Add proper permissions
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ gql_attrs = get_graphql_content(staff_api_client.post_graphql(query))["data"][
+ "products"
+ ]["edges"][0]["node"]["attributes"]
+ assert len(gql_attrs) == len(product.attributes)
+
+
+QUERY_VARIANT_ATTRIBUTES = """
+ {
+ products(first: 1) {
+ edges {
+ node {
+ variants {
+ attributes {
+ value {
+ name
+ }
+ attribute {
+ name
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+"""
+
+
+def test_resolve_variant_attributes_with_hidden(
+ user_api_client, product, size_attribute
+):
+ query = QUERY_VARIANT_ATTRIBUTES
+
+ # Hide one attribute from the storefront
+ size_attribute.visible_in_storefront = False
+ size_attribute.save(update_fields=["visible_in_storefront"])
+
+ gql_attrs = get_graphql_content(user_api_client.post_graphql(query))["data"][
+ "products"
+ ]["edges"][0]["node"]["variants"][0]["attributes"]
+ assert len(gql_attrs) == len(product.variants.first().attributes) - 1
+
+
+def test_resolve_variant_attributes_with_hidden_as_staff_user(
+ staff_api_client, product, size_attribute, permission_manage_products
+):
+ query = QUERY_VARIANT_ATTRIBUTES
+
+ # Hide one attribute from the storefront
+ size_attribute.visible_in_storefront = False
+ size_attribute.save(update_fields=["visible_in_storefront"])
+
+ # Add proper permissions
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ gql_attrs = get_graphql_content(staff_api_client.post_graphql(query))["data"][
+ "products"
+ ]["edges"][0]["node"]["variants"][0]["attributes"]
+ assert len(gql_attrs) == len(product.variants.first().attributes)
+
+
def test_attributes_in_category_query(user_api_client, product):
category = Category.objects.first()
query = """
@@ -684,6 +839,22 @@ def test_resolve_attribute_value_type(raw_value, expected_type):
assert resolve_attribute_value_type(raw_value) == expected_type
+def test_resolve_attribute_list(color_attribute):
+ value = color_attribute.values.first()
+ attributes_json = {str(color_attribute.pk): [str(value.pk)]}
+ res = resolve_attribute_list(attributes_json, Attribute.objects.all())
+ assert len(res) == 1
+ assert res[0].attribute.name == color_attribute.name
+ assert res[0].value.name == value.name
+
+ # test passing invalid json should resolve to empty list
+ attr_pk = str(Attribute.objects.order_by("pk").last().pk + 1)
+ val_pk = str(AttributeValue.objects.order_by("pk").last().pk + 1)
+ attributes_json = {attr_pk: [val_pk]}
+ res = resolve_attribute_list(attributes_json, Attribute.objects.all())
+ assert res == []
+
+
ASSIGN_ATTR_QUERY = """
mutation assign($productTypeId: ID!, $operations: [AttributeAssignInput]!) {
attributeAssign(productTypeId: $productTypeId, operations: $operations) {
@@ -801,10 +972,7 @@ def test_assign_variant_attribute_having_unsupported_input_type(
query = ASSIGN_ATTR_QUERY
operations = [
- {
- "attributeType": "VARIANT",
- "attributeId": graphene.Node.to_global_id("Attribute", attribute.pk),
- }
+ {"type": "VARIANT", "id": graphene.Node.to_global_id("Attribute", attribute.pk)}
]
variables = {"productTypeId": product_type_global_id, "operations": operations}
diff --git a/tests/api/test_product.py b/tests/api/test_product.py
index 9f7f518089..9c3c3d87c8 100644
--- a/tests/api/test_product.py
+++ b/tests/api/test_product.py
@@ -15,7 +15,6 @@ from saleor.core.taxes import TaxType
from saleor.extensions.manager import ExtensionsManager
from saleor.graphql.core.enums import ReportingPeriod
from saleor.graphql.product.enums import StockAvailability
-from saleor.graphql.product.types.products import resolve_attribute_list
from saleor.product import AttributeInputType
from saleor.product.models import (
Attribute,
@@ -68,22 +67,6 @@ def query_collections_with_filter():
return query
-def test_resolve_attribute_list(color_attribute):
- value = color_attribute.values.first()
- attributes_json = {str(color_attribute.pk): [str(value.pk)]}
- res = resolve_attribute_list(attributes_json, Attribute.objects.all())
- assert len(res) == 1
- assert res[0].attribute.name == color_attribute.name
- assert res[0].value.name == value.name
-
- # test passing invalid json should resolve to empty list
- attr_pk = str(Attribute.objects.order_by("pk").last().pk + 1)
- val_pk = str(AttributeValue.objects.order_by("pk").last().pk + 1)
- attributes_json = {attr_pk: [val_pk]}
- res = resolve_attribute_list(attributes_json, Attribute.objects.all())
- assert res == []
-
-
def test_fetch_all_products(user_api_client, product):
query = """
query {