Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Attributes can now be flagged as required
NyanKiyoshied554d06b0fb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ddd6814647..68886f8343 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ All notable, unreleased changes to this project will be documented in this file.- 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- Added flags to attributes: whether they are filterable or not in dashboard and/or storefront. - #4341 by @NyanKiyoshi.+- Attributes can now be flagged as required. - #4340 by @NyanKiyoshi.## [Unreleased]diff --git a/saleor/graphql/product/descriptions.py b/saleor/graphql/product/descriptions.pyindex 79e8ad3305..c4d2764594 100644--- a/saleor/graphql/product/descriptions.py+++ b/saleor/graphql/product/descriptions.py@@ -3,6 +3,7 @@ class AttributeDescriptions:NAME = "Name of an attribute displayed in the interface."SLUG = "Internal representation of an attribute name."VALUES = "List of attribute's values."+ VALUE_REQUIRED = "Whether the attribute requires values to be passed or not"IS_VARIANT_ONLY = "Whether the attribute is for variants only"VISIBLE_IN_STOREFRONT = ("Whether the attribute should be visible or not in storefront"diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.pyindex 8afeecbec0..44f6a7834f 100644--- a/saleor/graphql/product/mutations/attributes.py+++ b/saleor/graphql/product/mutations/attributes.py@@ -32,6 +32,7 @@ class AttributeCreateInput(graphene.InputObjectType):values = graphene.List(AttributeValueCreateInput, description=AttributeDescriptions.VALUES)+ value_required = graphene.Boolean(description=AttributeDescriptions.VALUE_REQUIRED)is_variant_only = graphene.Boolean(required=False, description=AttributeDescriptions.IS_VARIANT_ONLY)@@ -59,6 +60,7 @@ class AttributeUpdateInput(graphene.InputObjectType):name="addValues",description="New values to be created for this attribute.",)+ value_required = graphene.Boolean(description=AttributeDescriptions.VALUE_REQUIRED)is_variant_only = graphene.Boolean(required=False, description=AttributeDescriptions.IS_VARIANT_ONLY)diff --git a/saleor/graphql/product/types/attributes.py b/saleor/graphql/product/types/attributes.pyindex 7e6f4191bf..9cbf22e5d8 100644--- a/saleor/graphql/product/types/attributes.py+++ b/saleor/graphql/product/types/attributes.py@@ -79,6 +79,11 @@ class Attribute(CountableDjangoObjectType, MetadataObjectType):model_field="values",)+ value_required = gql_optimizer.field(+ graphene.Boolean(description=AttributeDescriptions.VALUE_REQUIRED),+ model_field="value_required",+ )+visible_in_storefront = gql_optimizer.field(graphene.Boolean(description=AttributeDescriptions.VISIBLE_IN_STOREFRONT),model_field="visible_in_storefront",@@ -127,6 +132,11 @@ class Attribute(CountableDjangoObjectType, MetadataObjectType):def resolve_meta(root, _info):return resolve_meta(root, _info)+ @staticmethod+ @permission_required("product.manage_products")+ def resolve_value_required(root: models.Attribute, *_args):+ return root.value_required+@staticmethod@permission_required("product.manage_products")def resolve_visible_in_storefront(root: models.Attribute, *_args):diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.pyindex 0b394aca64..3cbb9d4b54 100644--- a/saleor/graphql/product/utils.py+++ b/saleor/graphql/product/utils.py@@ -7,6 +7,11 @@ from ...product import AttributeInputType, modelsdef validate_attribute_input(instance: models.Attribute, values: List[str]):+ if not values:+ if not instance.value_required:+ return+ raise ValueError(f"{instance.slug} expects a value but none were given")+if instance.input_type != AttributeInputType.MULTISELECT and len(values) != 1:raise ValueError(f"A {instance.input_type} attribute must take only one value")@@ -20,6 +25,7 @@ def attributes_to_json(attribute_value_input: List[dict], attributes_queryset):"""attributes_map = {attr.slug: attr for attr in attributes_queryset}attributes_json = defaultdict(list)+ passed_slugs = set()values_map = {}for attr in attributes_queryset:@@ -28,16 +34,14 @@ def attributes_to_json(attribute_value_input: List[dict], attributes_queryset):for attribute_input in attribute_value_input:attr_slug = attribute_input.get("slug")+ passed_slugs.add(attr_slug)if attr_slug not in attributes_map:raise ValueError("Attribute %r doesn't belong to given product type." % (attr_slug,))- values = attribute_input.get("values")- if not values:- continue-attribute = attributes_map[attr_slug] # type: models.Attribute+ values = attribute_input.get("values")validate_attribute_input(attribute, values)for value in values:@@ -51,4 +55,9 @@ def attributes_to_json(attribute_value_input: List[dict], attributes_queryset):attributes_json[str(attribute.pk)].append(str(value_id))+ # Check that all required attributes were passed+ for missing_slug in attributes_map.keys() ^ passed_slugs:+ attribute = attributes_map[missing_slug] # type: models.Attribute+ validate_attribute_input(attribute, [])+return attributes_jsondiff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex a7f3a60c92..0021573a40 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -151,6 +151,7 @@ type Attribute implements Node {name: Stringslug: Stringvalues: [AttributeValue]+ valueRequired: BooleanvisibleInStorefront: BooleanfilterableInStorefront: BooleanfilterableInDashboard: Boolean@@ -203,6 +204,7 @@ input AttributeCreateInput {name: String!slug: Stringvalues: [AttributeValueCreateInput]+ valueRequired: BooleanisVariantOnly: BooleanvisibleInStorefront: BooleanfilterableInStorefront: Boolean@@ -257,6 +259,7 @@ input AttributeUpdateInput {slug: StringremoveValues: [ID]addValues: [AttributeValueCreateInput]+ valueRequired: BooleanisVariantOnly: BooleanvisibleInStorefront: BooleanfilterableInStorefront: Booleandiff --git a/saleor/product/migrations/0096_migrate_attrs_to_m2m.py b/saleor/product/migrations/0096_migrate_attrs_to_m2m.pyindex c79081ff26..0d6ffafd5a 100644--- a/saleor/product/migrations/0096_migrate_attrs_to_m2m.py+++ b/saleor/product/migrations/0096_migrate_attrs_to_m2m.py@@ -166,4 +166,9 @@ class Migration(migrations.Migration):name="filterable_in_storefront",field=models.BooleanField(default=True),),+ migrations.AddField(+ model_name="attribute",+ name="value_required",+ field=models.BooleanField(default=False),+ ),]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex f5c430c2d5..f551370cc7 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -522,8 +522,9 @@ class Attribute(ModelWithMetadata):through_fields=["attribute", "product_type"],)- visible_in_storefront = models.BooleanField(default=True)+ value_required = models.BooleanField(default=False)is_variant_only = models.BooleanField(default=False)+ visible_in_storefront = models.BooleanField(default=True)filterable_in_storefront = models.BooleanField(default=True)filterable_in_dashboard = models.BooleanField(default=True)diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.pyindex b2ffd5ed2c..9c5f73c6af 100644--- a/tests/api/test_attributes.py+++ b/tests/api/test_attributes.py@@ -37,6 +37,29 @@ def test_attributes_to_json(product, color_attribute):attributes_to_json(input_data, attrs_qs)[email protected]("input", ([{"slug": "color", "values": []}], []))+def test_attributes_to_json_missing_required_value(product, color_attribute, input):+ # A value is required+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required"])++ # test transforming slugs of existing attributes to IDs+ attrs_qs = product.product_type.product_attributes.all()++ with pytest.raises(ValueError) as exc:+ attributes_to_json(input, attrs_qs)+ assert exc.value.args == ("color expects a value but none were given",)+++def test_attributes_to_json_without_values(product, color_attribute):+ # test transforming slugs of existing attributes to IDs+ input_data = [{"slug": color_attribute.slug, "values": []}]+ attrs_qs = product.product_type.product_attributes.all()++ # The attribute should be ignored and raise no error as the value is not required+ assert not attributes_to_json(input_data, attrs_qs)++def test_attributes_to_json_duplicated_slug(product, color_attribute, size_attribute):# It's possible to have a value with the same slug but for a different attribute.# Ensure that `attributes_to_json` works in that case.@@ -1170,6 +1193,7 @@ def test_retrieve_product_attributes_input_type(("filterable_in_storefront", True),("filterable_in_dashboard", True),("visible_in_storefront", True),+ ("value_required", False),),)def test_retrieving_the_restricted_attributes_restricted(