Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Staff users can now flag attributes as to be hidden in the storefront (#4338)
NyanKiyoshi26609748e744
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 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.pyindex 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.pyindex 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.pyindex 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.pyindex 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 beassigned 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.Attributediff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex 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 grapheneimport graphene_django_optimizer as gql_optimizerfrom 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 prefetchbeforehand 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)@staticmethoddiff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 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): ProductTypeCountableConnectionproductVariantTypes(before: String, after: String, first: Int, last: Int): ProductTypeCountableConnection+ visibleInStorefront: Boolean!privateMeta: [MetaStore]!meta: [MetaStore]!+ inputType: AttributeInputTypeEnumname: Stringslug: Stringvalues: [AttributeValue]@@ -195,10 +197,12 @@ type AttributeCreate {}input AttributeCreateInput {+ inputType: AttributeInputTypeEnumname: String!slug: Stringvalues: [AttributeValueCreateInput]isVariantOnly: Boolean+ visibleInStorefront: Boolean}type AttributeDelete {@@ -211,6 +215,11 @@ input AttributeInput {value: String!}+enum AttributeInputTypeEnum {+ DROPDOWN+ MULTISELECT+}+scalar AttributeScalartype 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: AttributeValueTypevalue: Stringtranslation(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.pyindex 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 keysmigrations.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.pyindex 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.pyindex 72b3635946..065324cd25 100644--- a/tests/api/test_attributes.py+++ b/tests/api/test_attributes.py@@ -5,6 +5,7 @@ from django.template.defaultfilters import slugifyfrom saleor.graphql.product.enums import AttributeTypeEnum, AttributeValueTypefrom saleor.graphql.product.types.attributes import resolve_attribute_value_type+from saleor.graphql.product.types.products import resolve_attribute_listfrom saleor.graphql.product.utils import attributes_to_jsonfrom saleor.product import AttributeInputTypefrom 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_valassert 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_ATTRIBUTESresponse = user_api_client.post_graphql(query)content = get_graphql_content(response)attributes_data = content["data"]["attributes"]["edges"]+ assert attributes_dataassert 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_QUERYoperations = [- {- "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.pyindex 9f7f518089..9c3c3d87c8 100644--- a/tests/api/test_product.py+++ b/tests/api/test_product.py@@ -15,7 +15,6 @@ from saleor.core.taxes import TaxTypefrom saleor.extensions.manager import ExtensionsManagerfrom saleor.graphql.core.enums import ReportingPeriodfrom saleor.graphql.product.enums import StockAvailability-from saleor.graphql.product.types.products import resolve_attribute_listfrom saleor.product import AttributeInputTypefrom 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 {