Skip to content

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

[SALEOR-3090] Boolean attributes (#7454)

Piotr Grundas1ce0d8cb848b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f03f675b5f..298fd6b0d6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -115,6 +115,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Order events performance - #7424 by tomaszszymanski129
- Add hash to uploading images #7453 by @IKarbowiak
- Add file format validation for uploaded images - #7447 by @IKarbowiak
+- Add boolean attributes - #7454 by @piotrgrundas
- Fix attaching params for address form errors - #7485 by @IKarbowiak
### Breaking
diff --git a/saleor/attribute/__init__.py b/saleor/attribute/__init__.py
index 484b9cccd6..35f99d668f 100644
--- a/saleor/attribute/__init__.py
+++ b/saleor/attribute/__init__.py
@@ -10,6 +10,7 @@ class AttributeInputType:
REFERENCE = "reference"
NUMERIC = "numeric"
RICH_TEXT = "rich-text"
+ BOOLEAN = "boolean"
CHOICES = [
(DROPDOWN, "Dropdown"),
@@ -18,9 +19,11 @@ class AttributeInputType:
(REFERENCE, "Reference"),
(NUMERIC, "Numeric"),
(RICH_TEXT, "Rich Text"),
+ (BOOLEAN, "Boolean"),
]
+
# list of the input types that can be used in variant selection
- ALLOWED_IN_VARIANT_SELECTION = [DROPDOWN]
+ ALLOWED_IN_VARIANT_SELECTION = [DROPDOWN, BOOLEAN]
TYPES_WITH_CHOICES = [
DROPDOWN,
@@ -42,20 +45,24 @@ ATTRIBUTE_PROPERTIES_CONFIGURATION = {
AttributeInputType.DROPDOWN,
AttributeInputType.MULTISELECT,
AttributeInputType.NUMERIC,
+ AttributeInputType.BOOLEAN,
],
"filterable_in_dashboard": [
AttributeInputType.DROPDOWN,
AttributeInputType.MULTISELECT,
AttributeInputType.NUMERIC,
+ AttributeInputType.BOOLEAN,
],
"available_in_grid": [
AttributeInputType.DROPDOWN,
AttributeInputType.MULTISELECT,
AttributeInputType.NUMERIC,
+ AttributeInputType.BOOLEAN,
],
"storefront_search_position": [
AttributeInputType.DROPDOWN,
AttributeInputType.MULTISELECT,
+ AttributeInputType.BOOLEAN,
],
}
diff --git a/saleor/attribute/migrations/0013_auto_20210609_2245.py b/saleor/attribute/migrations/0013_auto_20210609_2245.py
new file mode 100644
index 0000000000..032006fc54
--- /dev/null
+++ b/saleor/attribute/migrations/0013_auto_20210609_2245.py
@@ -0,0 +1,35 @@
+# Generated by Django 3.1.8 on 2021-06-09 22:45
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("attribute", "0012_merge_20210608_1034"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="attributevalue",
+ name="boolean",
+ field=models.BooleanField(blank=True, null=True),
+ ),
+ migrations.AlterField(
+ model_name="attribute",
+ name="input_type",
+ field=models.CharField(
+ choices=[
+ ("dropdown", "Dropdown"),
+ ("multiselect", "Multi Select"),
+ ("file", "File"),
+ ("reference", "Reference"),
+ ("numeric", "Numeric"),
+ ("rich-text", "Rich Text"),
+ ("boolean", "Boolean"),
+ ],
+ default="dropdown",
+ max_length=50,
+ ),
+ ),
+ ]
diff --git a/saleor/attribute/models/base.py b/saleor/attribute/models/base.py
index c81b6d9045..a822877edc 100644
--- a/saleor/attribute/models/base.py
+++ b/saleor/attribute/models/base.py
@@ -200,6 +200,7 @@ class AttributeValue(SortableModel):
Attribute, related_name="values", on_delete=models.CASCADE
)
rich_text = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ boolean = models.BooleanField(blank=True, null=True)
translated = TranslationProxy()
diff --git a/saleor/csv/tests/export/products_data/test_get_products_data.py b/saleor/csv/tests/export/products_data/test_get_products_data.py
index 44b366199a..907ae65356 100644
--- a/saleor/csv/tests/export/products_data/test_get_products_data.py
+++ b/saleor/csv/tests/export/products_data/test_get_products_data.py
@@ -240,6 +240,7 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(
product_with_variant_with_two_attributes,
rich_text_attribute,
color_attribute,
+ boolean_attribute,
variant_with_many_stocks,
):
# given
@@ -250,6 +251,7 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(
product_type_product_reference_attribute,
numeric_attribute,
rich_text_attribute,
+ boolean_attribute,
)
product.product_type.product_attributes.add(
file_attribute,
@@ -257,6 +259,17 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(
product_type_product_reference_attribute,
numeric_attribute,
rich_text_attribute,
+ boolean_attribute,
+ )
+
+ # add boolean attribute
+ associate_attribute_values_to_instance(
+ variant_with_many_stocks,
+ boolean_attribute,
+ boolean_attribute.values.first(),
+ )
+ associate_attribute_values_to_instance(
+ product, boolean_attribute, boolean_attribute.values.first()
)
# add rich text attribute
diff --git a/saleor/csv/tests/export/products_data/test_handle_relations_data.py b/saleor/csv/tests/export/products_data/test_handle_relations_data.py
index ce80bbc3ac..5ff6db7868 100644
--- a/saleor/csv/tests/export/products_data/test_handle_relations_data.py
+++ b/saleor/csv/tests/export/products_data/test_handle_relations_data.py
@@ -799,6 +799,7 @@ def test_add_attribute_info_to_data(product):
entity_type=None,
unit=None,
rich_text=None,
+ boolean=None,
)
input_data = {pk: {}}
@@ -827,6 +828,7 @@ def test_add_attribute_info_to_data_update_attribute_data(product):
entity_type=None,
unit=None,
rich_text=None,
+ boolean=None,
)
input_data = {pk: {expected_header: {"value1"}}}
@@ -850,6 +852,7 @@ def test_add_attribute_info_to_data_no_slug(product):
entity_type=None,
unit=None,
rich_text=None,
+ boolean=None,
)
input_data = {pk: {}}
@@ -874,6 +877,7 @@ def test_add_attribute_info_when_no_value(product):
entity_type=None,
rich_text=None,
unit=None,
+ boolean=None,
)
input_data = {pk: {}}
@@ -900,6 +904,7 @@ def test_add_file_attribute_info_to_data(product):
entity_type=None,
unit=None,
rich_text=None,
+ boolean=None,
)
input_data = {pk: {}}
@@ -925,6 +930,7 @@ def test_add_rich_text_attribute_info_to_data(product):
entity_type=None,
unit=None,
rich_text=dummy_editorjs("Dummy"),
+ boolean=None,
)
input_data = {pk: {}}
@@ -938,6 +944,32 @@ def test_add_rich_text_attribute_info_to_data(product):
assert result[pk][expected_header] == {"Dummy"}
+def test_add_boolean_attribute_info_to_data(product):
+ # given
+ pk = product.pk
+ slug = "xx_false"
+ attribute_data = AttributeData(
+ slug=slug,
+ value=None,
+ file_url=None,
+ input_type="boolean",
+ entity_type=None,
+ unit=None,
+ rich_text=None,
+ boolean=False,
+ )
+ input_data = {pk: {}}
+
+ # when
+ result = add_attribute_info_to_data(
+ product.pk, attribute_data, "product attribute", input_data
+ )
+
+ # then
+ expected_header = f"{slug} (product attribute)"
+ assert result[pk][expected_header] == {"False"}
+
+
def test_add_reference_attribute_info_to_data(product, page):
# given
pk = product.pk
@@ -951,6 +983,7 @@ def test_add_reference_attribute_info_to_data(product, page):
entity_type="Page",
unit=None,
rich_text="None",
+ boolean=None,
)
input_data = {pk: {}}
@@ -980,6 +1013,7 @@ def test_add_reference_info_to_data_update_attribute_data(product, page):
entity_type="Page",
unit=None,
rich_text=None,
+ boolean=None,
)
input_data = {pk: {expected_header: values}}
@@ -1005,6 +1039,7 @@ def test_add_numeric_attribute_info_to_data(product, numeric_attribute):
entity_type=None,
unit=numeric_attribute.unit,
rich_text=None,
+ boolean=None,
)
input_data = {pk: {}}
@@ -1030,6 +1065,7 @@ def test_add_numeric_attribute_info_to_data_no_unit(product, numeric_attribute):
entity_type=None,
unit=None,
rich_text=None,
+ boolean=None,
)
input_data = {pk: {}}
@@ -1056,6 +1092,7 @@ def test_add_attribute_info_to_data_no_file_url_for_file_attribute(product):
entity_type=None,
rich_text=None,
unit=None,
+ boolean=None,
)
input_data = {pk: {}}
@@ -1073,15 +1110,41 @@ def test_add_attribute_info_to_data_no_rich_text_for_rich_text_attribute(product
# given
pk = product.pk
slug = "test_attribute_slug"
- value = "test value"
attribute_data = AttributeData(
slug=slug,
- value=value,
+ value=None,
file_url=None,
input_type="rich-text",
entity_type=None,
rich_text=None,
unit=None,
+ boolean=None,
+ )
+ input_data = {pk: {}}
+
+ # when
+ result = add_attribute_info_to_data(
+ product.pk, attribute_data, "product attribute", input_data
+ )
+
+ # then
+ expected_header = f"{slug} (product attribute)"
+ assert result[pk][expected_header] == {""}
+
+
+def test_add_attribute_info_to_data_no_boolean_for_boolean_attribute(product):
+ # given
+ pk = product.pk
+ slug = "xxx_None"
+ attribute_data = AttributeData(
+ slug=slug,
+ value=None,
+ file_url=None,
+ input_type="boolean",
+ entity_type=None,
+ rich_text=None,
+ unit=None,
+ boolean=None,
)
input_data = {pk: {}}
@@ -1107,6 +1170,7 @@ def test_add_attribute_info_to_data_no_value_for_reference_attribute(product):
entity_type=None,
rich_text=None,
unit=None,
+ boolean=None,
)
input_data = {pk: {}}
diff --git a/saleor/csv/tests/export/products_data/utils.py b/saleor/csv/tests/export/products_data/utils.py
index db4d5eb277..6fe0827a6b 100644
--- a/saleor/csv/tests/export/products_data/utils.py
+++ b/saleor/csv/tests/export/products_data/utils.py
@@ -44,6 +44,8 @@ def get_attribute_value(assigned_attribute):
value += f" {attribute.unit}"
elif attribute.input_type == AttributeInputType.RICH_TEXT:
value = clean_editor_js(value_instance.rich_text, to_string=True)
+ elif attribute.input_type == AttributeInputType.BOOLEAN:
+ value = str(value_instance.boolean)
else:
value = value_instance.slug
return value
diff --git a/saleor/csv/utils/__init__.py b/saleor/csv/utils/__init__.py
index 0f157a750b..e06f39ada6 100644
--- a/saleor/csv/utils/__init__.py
+++ b/saleor/csv/utils/__init__.py
@@ -24,6 +24,7 @@ class ProductExportFields:
"value": "attributes__values__slug",
"file_url": "attributes__values__file_url",
"rich_text": "attributes__values__rich_text",
+ "boolean": "attributes__values__boolean",
"slug": "attributes__assignment__attribute__slug",
"input_type": "attributes__assignment__attribute__input_type",
"entity_type": "attributes__assignment__attribute__entity_type",
@@ -51,6 +52,7 @@ class ProductExportFields:
"value": "variants__attributes__values__slug",
"file_url": "variants__attributes__values__file_url",
"rich_text": "variants__attributes__values__rich_text",
+ "boolean": "variants__attributes__values__boolean",
"slug": "variants__attributes__assignment__attribute__slug",
"input_type": "variants__attributes__assignment__attribute__input_type",
"entity_type": "variants__attributes__assignment__attribute__entity_type",
diff --git a/saleor/csv/utils/products_data.py b/saleor/csv/utils/products_data.py
index 138a5e3551..7703281c6f 100644
--- a/saleor/csv/utils/products_data.py
+++ b/saleor/csv/utils/products_data.py
@@ -293,7 +293,16 @@ def add_image_uris_to_data(
AttributeData = namedtuple(
"AttributeData",
- ["slug", "file_url", "value", "input_type", "entity_type", "unit", "rich_text"],
+ [
+ "slug",
+ "file_url",
+ "value",
+ "input_type",
+ "entity_type",
+ "unit",
+ "rich_text",
+ "boolean",
+ ],
)
@@ -314,6 +323,7 @@ def handle_attribute_data(
entity_type=data.pop(attribute_fields["entity_type"], None),
unit=data.pop(attribute_fields["unit"], None),
rich_text=data.pop(attribute_fields["rich_text"], None),
+ boolean=data.pop(attribute_fields["boolean"], None),
)
if attribute_ids and attribute_pk in attribute_ids:
@@ -405,6 +415,11 @@ def add_attribute_info_to_data(
value += f" {attribute_data.unit}"
elif input_type == AttributeInputType.RICH_TEXT:
value = clean_editor_js(attribute_data.rich_text, to_string=True)
+ elif (
+ input_type == AttributeInputType.BOOLEAN
+ and attribute_data.boolean is not None
+ ):
+ value = str(attribute_data.boolean)
else:
value = attribute_data.value if attribute_data.value else ""
if header in result_data[pk]:
diff --git a/saleor/graphql/attribute/descriptions.py b/saleor/graphql/attribute/descriptions.py
index 9070e9c132..3b727e9afc 100644
--- a/saleor/graphql/attribute/descriptions.py
+++ b/saleor/graphql/attribute/descriptions.py
@@ -5,6 +5,7 @@ class AttributeDescriptions:
SLUG = "Internal representation of an attribute name."
TYPE = "The attribute type."
UNIT = "The unit of attribute values."
+ BOOLEAN = "The boolean value of the attribute."
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."
@@ -30,3 +31,4 @@ class AttributeValueDescriptions:
VALUES_RANGE = "The range that the returned values should be in."
VALUE = "Represents the value of the attribute value."
RICH_TEXT = "Represents the text (JSON) of the attribute value."
+ BOOLEAN = "Represents the boolean value of the attribute value."
diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.py
index 433c3201e4..e836962cc6 100644
--- a/saleor/graphql/attribute/types.py
+++ b/saleor/graphql/attribute/types.py
@@ -41,6 +41,9 @@ class AttributeValue(CountableDjangoObjectType):
rich_text = graphene.JSONString(
description=AttributeValueDescriptions.RICH_TEXT, required=False
)
+ boolean = graphene.Boolean(
+ description=AttributeValueDescriptions.BOOLEAN, required=False
+ )
class Meta:
description = "Represents a value of an attribute."
@@ -205,6 +208,9 @@ class AttributeInput(graphene.InputObjectType):
required=False,
description=AttributeValueDescriptions.VALUES_RANGE,
)
+ boolean = graphene.Boolean(
+ required=False, description=AttributeDescriptions.BOOLEAN
+ )
class AttributeValueInput(graphene.InputObjectType):
@@ -230,3 +236,6 @@ class AttributeValueInput(graphene.InputObjectType):
rich_text = graphene.JSONString(
required=False, description="Text content in JSON format."
)
+ boolean = graphene.Boolean(
+ required=False, description=AttributeValueDescriptions.BOOLEAN
+ )
diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.py
index 6d94bea1b6..240eb0be5b 100644
--- a/saleor/graphql/attribute/utils.py
+++ b/saleor/graphql/attribute/utils.py
@@ -38,6 +38,7 @@ class AttrValuesInput:
file_url: Optional[str] = None
content_type: Optional[str] = None
rich_text: Optional[dict] = None
+ boolean: Optional[bool] = None
T_INSTANCE = Union[
@@ -172,11 +173,29 @@ class AttributeAssignmentMixin:
defaults = {
"rich_text": attr_values.rich_text,
"name": truncatechars(
- clean_editor_js(attr_values.rich_text, to_string=True), 50
+ clean_editor_js(attr_values.rich_text, to_string=True), 200
),
}
return cls._update_or_create_value(instance, attribute, defaults)
+ @classmethod
+ def _pre_save_boolean_values(
+ cls,
+ instance: T_INSTANCE,
+ attribute: attribute_models.Attribute,
+ attr_values: AttrValuesInput,
+ ):
+ get_or_create = attribute.values.get_or_create
+ value, _ = get_or_create(
+ attribute=attribute,
+ slug=slugify(f"{attribute.id}_{attr_values.boolean}", allow_unicode=True),
+ defaults={
+ "name": f"{attribute.name}: {'Yes' if attr_values.boolean else 'No'}",
+ "boolean": attr_values.boolean,
+ },
+ )
+ return (value,)
+
@classmethod
def _update_or_create_value(
cls,
@@ -345,6 +364,7 @@ class AttributeAssignmentMixin:
content_type=attribute_input.get("content_type"),
references=attribute_input.get("references", []),
rich_text=attribute_input.get("rich_text"),
+ boolean=attribute_input.get("boolean"),
)
if global_id:
@@ -439,6 +459,7 @@ class AttributeAssignmentMixin:
AttributeInputType.REFERENCE: cls._pre_save_reference_values,
AttributeInputType.RICH_TEXT: cls._pre_save_rich_text_values,
AttributeInputType.NUMERIC: cls._pre_save_numeric_values,
+ AttributeInputType.BOOLEAN: cls._pre_save_boolean_values,
}
clean_assignment = []
for attribute, attr_values in cleaned_input:
@@ -544,6 +565,8 @@ def validate_attributes_input(
validate_reference_attributes_input(*attrs)
elif attribute.input_type == AttributeInputType.RICH_TEXT:
validate_rich_text_attributes_input(*attrs)
+ elif attribute.input_type == AttributeInputType.BOOLEAN:
+ validate_boolean_input(*attrs)
# validation for other input types
else:
validate_standard_attributes_input(*attrs)
@@ -593,6 +616,19 @@ def validate_reference_attributes_input(
)
+def validate_boolean_input(
+ attribute: "Attribute",
+ attr_values: "AttrValuesInput",
+ attribute_errors: T_ERROR_DICT,
+ variant_validation: bool,
+):
+ attribute_id = attr_values.global_id
+ value = attr_values.boolean
+
+ if attribute.value_required and value is None:
+ attribute_errors[AttributeInputErrors.ERROR_BLANK_VALUE].append(attribute_id)
+
+
def validate_rich_text_attributes_input(
attribute: "Attribute",
attr_values: "AttrValuesInput",
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index 21292fd721..687c855cf4 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -110,6 +110,28 @@ def _clean_product_attributes_range_filter_input(filter_value, queries):
queries[attr_pk] += attr_val_pks
+def _clean_product_attributes_boolean_filter_input(
+ filter_value, queries: T_PRODUCT_FILTER_QUERIES
+):
+ attribute_slugs = [slug for slug, _ in filter_value]
+ attributes = Attribute.objects.filter(
+ input_type=AttributeInputType.BOOLEAN, slug__in=attribute_slugs
+ ).prefetch_related("values")
+ values_map = {
+ attr.slug: {
+ "pk": attr.pk,
+ "values": {val.boolean: val.pk for val in attr.values.all()},
+ }
+ for attr in attributes
+ }
+
+ for attr_slug, val in filter_value:
+ attr_pk = values_map[attr_slug]["pk"]
+ value_pk = values_map[attr_slug]["values"].get(val)
+ if value_pk:
+ queries[attr_pk] = [value_pk]
+
+
def filter_products_by_attributes_values(qs, queries: T_PRODUCT_FILTER_QUERIES):
filters = []
for values in queries.values():
@@ -145,13 +167,19 @@ def filter_products_by_attributes_values(qs, queries: T_PRODUCT_FILTER_QUERIES):
return qs.filter(*filters)
-def filter_products_by_attributes(qs, filter_values, filter_range_values):
+def filter_products_by_attributes(
+ qs, filter_values, filter_range_values, filter_boolean_values
+):
queries: Dict[int, List[Optional[int]]] = defaultdict(list)
try:
if filter_values:
_clean_product_attributes_filter_input(filter_values, queries)
if filter_range_values:
_clean_product_attributes_range_filter_input(filter_range_values, queries)
+ if filter_boolean_values:
+ _clean_product_attributes_boolean_filter_input(
+ filter_boolean_values, queries
+ )
except ValueError:
return Product.objects.none()
return filter_products_by_attributes_values(qs, queries)
@@ -242,13 +270,19 @@ def _filter_attributes(qs, _, value):
if value:
value_list = []
value_range_list = []
+ boolean_list = []
+
for v in value:
slug = v["slug"]
if "values" in v:
value_list.append((slug, v["values"]))
elif "values_range" in v:
value_range_list.append((slug, v["values_range"]))
- qs = filter_products_by_attributes(qs, value_list, value_range_list)
+ elif "boolean" in v:
+ boolean_list.append((slug, v["boolean"]))
+ qs = filter_products_by_attributes(
+ qs, value_list, value_range_list, boolean_list
+ )
return qs
diff --git a/saleor/graphql/product/tests/benchmark/test_product.py b/saleor/graphql/product/tests/benchmark/test_product.py
index 8e803f4219..88fe0b9ff3 100644
--- a/saleor/graphql/product/tests/benchmark/test_product.py
+++ b/saleor/graphql/product/tests/benchmark/test_product.py
@@ -630,3 +630,43 @@ def test_filter_products_by_numeric_attributes(
},
}
get_graphql_content(api_client.post_graphql(query, variables))
+
+
[email protected]_queries(autouse=False)
+def test_filter_products_by_boolean_attributes(
+ api_client, product_list, boolean_attribute, channel_USD, count_queries
+):
+ query = """
+ query ($channel: String, $filter: ProductFilterInput){
+ products(
+ channel: $channel,
+ filter: $filter,
+ first: 20,
+ ) {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ }
+ """
+
+ product = product_list[0]
+ product.product_type.product_attributes.add(boolean_attribute)
+ associate_attribute_values_to_instance(
+ product, boolean_attribute, *boolean_attribute.values.all()
+ )
+ variables = {
+ "channel": channel_USD.slug,
+ "filter": {
+ "attributes": [
+ {
+ "slug": boolean_attribute.slug,
+ "boolean": True,
+ }
+ ]
+ },
+ }
+ get_graphql_content(api_client.post_graphql(query, variables))
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 41632e068d..5241f9c76e 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -1719,7 +1719,7 @@ def test_products_query_with_filter_attributes(
@pytest.mark.parametrize(
- "gte, lte, expected_products",
+ "gte, lte, expected_products_index",
[
(None, 8, [1]),
(0, 8, [1]),
@@ -1734,7 +1734,7 @@ def test_products_query_with_filter_attributes(
def test_products_query_with_filter_numeric_attributes(
gte,
lte,
- expected_products,
+ expected_products_index,
query_products_with_filter,
staff_api_client,
product,
@@ -1792,12 +1792,79 @@ def test_products_query_with_filter_numeric_attributes(
content = get_graphql_content(response)
products = content["data"]["products"]["edges"]
- assert len(products) == len(expected_products)
+ assert len(products) == len(expected_products_index)
assert set(product["node"]["id"] for product in products) == {
- products_ids[index] for index in expected_products
+ products_ids[index] for index in expected_products_index
}
assert set(product["node"]["name"] for product in products) == {
- products_instances[index].name for index in expected_products
+ products_instances[index].name for index in expected_products_index
+ }
+
+
+ "filter_value, expected_products_index",
+ [
+ (False, [0, 1]),
+ (True, [0]),
+ ],
+)
+def test_products_query_with_filter_boolean_attributes(
+ filter_value,
+ expected_products_index,
+ query_products_with_filter,
+ staff_api_client,
+ product,
+ category,
+ boolean_attribute,
+ permission_manage_products,
+):
+ product.product_type.product_attributes.add(boolean_attribute)
+
+ associate_attribute_values_to_instance(
+ product, boolean_attribute, boolean_attribute.values.get(boolean=filter_value)
+ )
+
+ product_type = ProductType.objects.create(
+ name="Custom Type",
+ slug="custom-type",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ boolean_attribute.product_types.add(product_type)
+
+ second_product = Product.objects.create(
+ name="Second product",
+ slug="second-product",
+ product_type=product_type,
+ category=category,
+ )
+ associate_attribute_values_to_instance(
+ second_product, boolean_attribute, boolean_attribute.values.get(boolean=False)
+ )
+
+ second_product.refresh_from_db()
+ products_instances = [product, second_product]
+ products_ids = [
+ graphene.Node.to_global_id("Product", p.pk) for p in products_instances
+ ]
+
+ variables = {
+ "filter": {
+ "attributes": [{"slug": boolean_attribute.slug, "boolean": filter_value}]
+ }
+ }
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(query_products_with_filter, variables)
+ content = get_graphql_content(response)
+ products = content["data"]["products"]["edges"]
+
+ assert len(products) == len(expected_products_index)
+ assert set(product["node"]["id"] for product in products) == {
+ products_ids[index] for index in expected_products_index
+ }
+ assert set(product["node"]["name"] for product in products) == {
+ products_instances[index].name for index in expected_products_index
}
@@ -3022,6 +3089,7 @@ CREATE_PRODUCT_MUTATION = """
name
reference
richText
+ boolean
file {
url
contentType
@@ -3231,18 +3299,79 @@ def test_create_product_with_rich_text_attribute(
"values": [
{
"slug": f"{product_id}_{rich_text_attribute.id}",
- "name": "test producttest producttest producttest productt…",
+ "name": (
+ "test producttest producttest producttest producttest product"
+ ),
"reference": None,
"richText": rich_text,
"file": None,
+ "boolean": None,
}
],
},
]
+
for attr_data in data["product"]["attributes"]:
assert attr_data in expected_attributes_data
+def test_create_product_with_boolean_attribute(
+ staff_api_client,
+ product_type,
+ category,
+ boolean_attribute,
+ permission_manage_products,
+ product,
+):
+ query = CREATE_PRODUCT_MUTATION
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+ product_name = "test name"
+
+ # Add second attribute
+ product_type.product_attributes.add(boolean_attribute)
+ boolean_attribute_id = graphene.Node.to_global_id("Attribute", boolean_attribute.id)
+
+ # test creating root product
+ variables = {
+ "input": {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "attributes": [
+ {
+ "id": boolean_attribute_id,
+ "boolean": False,
+ }
+ ],
+ }
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productCreate"]
+ assert data["errors"] == []
+ assert data["product"]["name"] == product_name
+
+ expected_attributes_data = {
+ "attribute": {"slug": "boolean"},
+ "values": [
+ {
+ "slug": f"{boolean_attribute.id}_false",
+ "name": "Boolean: No",
+ "reference": None,
+ "richText": None,
+ "boolean": False,
+ "file": None,
+ }
+ ],
+ }
+ assert expected_attributes_data in data["product"]["attributes"]
+
+
SEARCH_PRODUCTS_QUERY = """
query Products(
$filters: ProductFilterInput, $sortBy: ProductOrder, $channel: String
@@ -3492,6 +3621,7 @@ def test_create_product_with_file_attribute(
},
"reference": None,
"richText": None,
+ "boolean": None,
}
],
},
@@ -3560,6 +3690,7 @@ def test_create_product_with_page_reference_attribute(
"name": page.title,
"file": None,
"richText": None,
+ "boolean": None,
"reference": reference,
}
],
@@ -3629,6 +3760,7 @@ def test_create_product_with_product_reference_attribute(
"name": product.name,
"file": None,
"richText": None,
+ "boolean": None,
"reference": reference,
}
],
@@ -3698,6 +3830,7 @@ def test_create_product_with_product_reference_attribute_values_saved_in_order(
"name": product.name,
"file": None,
"richText": None,
+ "boolean": None,
"reference": reference,
}
for product, reference in zip(reference_instances, reference_ids)
@@ -3770,6 +3903,7 @@ def test_create_product_with_file_attribute_new_attribute_value(
"slug": slugify(non_existing_value, allow_unicode=True),
"reference": None,
"richText": None,
+ "boolean": None,
"file": {
"url": "http://testserver/media/" + non_existing_value,
"contentType": None,
@@ -4808,6 +4942,7 @@ MUTATION_UPDATE_PRODUCT = """
id
name
slug
+ boolean
reference
file {
url
@@ -4980,6 +5115,59 @@ def test_update_product_without_description_clear_description_plaintext(
assert product.description_plaintext == ""
+@patch("saleor.plugins.manager.PluginsManager.product_updated")
+def test_update_product_with_boolean_attribute_value(
+ updated_webhook_mock,
+ staff_api_client,
+ product,
+ product_type,
+ boolean_attribute,
+ permission_manage_products,
+):
+ # given
+ query = MUTATION_UPDATE_PRODUCT
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ attribute_id = graphene.Node.to_global_id("Attribute", boolean_attribute.pk)
+ product_type.product_attributes.add(boolean_attribute)
+
+ new_value = False
+
+ variables = {
+ "productId": product_id,
+ "input": {"attributes": [{"id": attribute_id, "boolean": new_value}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productUpdate"]
+ assert data["errors"] == []
+
+ attributes = data["product"]["attributes"]
+ assert len(attributes) == 2
+ expected_att_data = {
+ "attribute": {"id": attribute_id, "name": boolean_attribute.name},
+ "values": [
+ {
+ "id": ANY,
+ "name": "Boolean: No",
+ "boolean": new_value,
+ "slug": f"{boolean_attribute.id}_false",
+ "reference": None,
+ "file": None,
+ }
+ ],
+ }
+ assert expected_att_data in attributes
+
+ updated_webhook_mock.assert_called_once_with(product)
+
+
@patch("saleor.plugins.manager.PluginsManager.product_updated")
def test_update_product_with_file_attribute_value(
updated_webhook_mock,
@@ -5029,6 +5217,7 @@ def test_update_product_with_file_attribute_value(
"url": "http://testserver/media/" + new_value,
"contentType": None,
},
+ "boolean": None,
}
],
}
@@ -5090,6 +5279,7 @@ def test_update_product_with_file_attribute_value_new_value_is_not_created(
"url": f"http://testserver/media/{existing_value.file_url}",
"contentType": existing_value.content_type,
},
+ "boolean": None,
}
],
}
@@ -5147,6 +5337,7 @@ def test_update_product_with_numeric_attribute_value(
),
"reference": None,
"file": None,
+ "boolean": None,
}
],
}
@@ -5208,6 +5399,7 @@ def test_update_product_with_numeric_attribute_value_new_value_is_not_created(
"slug": slug_value,
"reference": None,
"file": None,
+ "boolean": None,
}
],
}
@@ -5342,6 +5534,7 @@ def test_update_product_with_page_reference_attribute_value(
"slug": f"{product.id}_{page.id}",
"file": None,
"reference": reference,
+ "boolean": None,
}
],
}
@@ -5415,6 +5608,7 @@ def test_update_product_with_page_reference_attribute_existing_value(
"slug": f"{product.id}_{page.id}",
"file": None,
"reference": reference,
+ "boolean": None,
}
],
}
@@ -5526,6 +5720,7 @@ def test_update_product_with_product_reference_attribute_value(
"slug": f"{product.id}_{product_ref.id}",
"file": None,
"reference": reference,
+ "boolean": None,
}
],
}
@@ -5600,6 +5795,7 @@ def test_update_product_with_product_reference_attribute_existing_value(
"slug": f"{product.id}_{product_ref.id}",
"file": None,
"reference": reference,
+ "boolean": None,
}
],
}
@@ -6704,6 +6900,7 @@ PRODUCT_TYPE_CREATE_MUTATION = """
node {
name
richText
+ boolean
}
}
@@ -6822,8 +7019,8 @@ def test_create_product_type_with_rich_text_attribute(
"name": "Color",
"choices": {
"edges": [
- {"node": {"name": "Red", "richText": None}},
- {"node": {"name": "Blue", "richText": None}},
+ {"node": {"name": "Red", "richText": None, "boolean": None}},
+ {"node": {"name": "Blue", "richText": None, "boolean": None}},
]
},
},
@@ -6836,6 +7033,41 @@ def test_create_product_type_with_rich_text_attribute(
assert attribute in expected_attributes
+def test_create_product_type_with_boolean_attribute(
+ staff_api_client,
+ product_type,
+ permission_manage_product_types_and_attributes,
+ boolean_attribute,
+):
+ query = PRODUCT_TYPE_CREATE_MUTATION
+ product_type_name = "test type"
+ slug = "test-type"
+
+ product_type.product_attributes.add(boolean_attribute)
+ product_attributes_ids = [
+ graphene.Node.to_global_id("Attribute", attr.id)
+ for attr in product_type.product_attributes.all()
+ ]
+
+ variables = {
+ "name": product_type_name,
+ "slug": slug,
+ "productAttributes": product_attributes_ids,
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productTypeCreate"]["productType"]
+ errors = content["data"]["productTypeCreate"]["errors"]
+
+ assert not errors
+ assert data["name"] == product_type_name
+ assert data["slug"] == slug
+ assert {"choices": {"edges": []}, "name": "Boolean"} in data["productAttributes"]
+
+
@pytest.mark.parametrize(
"input_slug, expected_slug",
(
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index e6896569d2..ac0cd5a0a1 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -361,6 +361,7 @@ CREATE_VARIANT_MUTATION = """
slug
reference
richText
+ boolean
file {
url
contentType
@@ -502,6 +503,69 @@ def test_create_variant_with_file_attribute(
created_webhook_mock.assert_called_once_with(product.variants.last())
+@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
+def test_create_variant_with_boolean_attribute(
+ created_webhook_mock,
+ permission_manage_products,
+ product,
+ product_type,
+ staff_api_client,
+ boolean_attribute,
+ size_attribute,
+ warehouse,
+):
+ product_type.variant_attributes.add(boolean_attribute)
+ query = CREATE_VARIANT_MUTATION
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ boolean_attr_id = graphene.Node.to_global_id("Attribute", boolean_attribute.id)
+ size_attr_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
+
+ variables = {
+ "productId": product_id,
+ "sku": "1",
+ "stocks": [
+ {
+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
+ "quantity": 20,
+ }
+ ],
+ "costPrice": 3.22,
+ "price": 1.32,
+ "weight": 10.22,
+ "attributes": [
+ {"id": boolean_attr_id, "boolean": True},
+ {"id": size_attr_id, "values": ["XXXL"]},
+ ],
+ "trackInventory": True,
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)["data"]["productVariantCreate"]
+ flush_post_commit_hooks()
+ data = content["productVariant"]
+
+ assert not content["errors"]
+ assert data["name"] == "Boolean: Yes / XXXL"
+ expected_attribute_data = {
+ "attribute": {"slug": "boolean"},
+ "values": [
+ {
+ "name": "Boolean: Yes",
+ "slug": f"{boolean_attribute.id}_true",
+ "reference": None,
+ "richText": None,
+ "boolean": True,
+ "file": None,
+ }
+ ],
+ }
+
+ assert expected_attribute_data in data["attributes"]
+ created_webhook_mock.assert_called_once_with(product.variants.last())
+
+
@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
def test_create_variant_with_file_attribute_new_value(
created_webhook_mock,
@@ -694,6 +758,7 @@ def test_create_variant_with_page_reference_attribute(
"richText": None,
"reference": page_ref_1,
"name": page_list[0].title,
+ "boolean": None,
},
{
"slug": f"{variant_pk}_{page_list[1].pk}",
@@ -701,6 +766,7 @@ def test_create_variant_with_page_reference_attribute(
"richText": None,
"reference": page_ref_2,
"name": page_list[1].title,
+ "boolean": None,
},
]
for value in expected_values:
@@ -844,6 +910,7 @@ def test_create_variant_with_product_reference_attribute(
"richText": None,
"reference": product_ref_1,
"name": product_list[0].name,
+ "boolean": None,
},
{
"slug": f"{variant_pk}_{product_list[1].pk}",
@@ -851,6 +918,7 @@ def test_create_variant_with_product_reference_attribute(
"richText": None,
"reference": product_ref_2,
"name": product_list[1].name,
+ "boolean": None,
},
]
for value in expected_values:
@@ -1495,6 +1563,7 @@ QUERY_UPDATE_VARIANT_ATTRIBUTES = """
}
reference
richText
+ boolean
}
}
}
@@ -1587,6 +1656,56 @@ def test_update_product_variant_with_current_attribute(
assert variant.attributes.last().values.first().slug == "small"
+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
+def test_update_variant_with_boolean_attribute(
+ product_variant_updated,
+ permission_manage_products,
+ product,
+ product_type,
+ staff_api_client,
+ boolean_attribute,
+ warehouse,
+ size_attribute,
+):
+ product_type.variant_attributes.add(boolean_attribute)
+ query = QUERY_UPDATE_VARIANT_ATTRIBUTES
+ variant = product.variants.first()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ sku = "123"
+ attr_id = graphene.Node.to_global_id("Attribute", boolean_attribute.id)
+ size_attr_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
+
+ new_value = False
+ values_count = boolean_attribute.values.count()
+ variables = {
+ "id": variant_id,
+ "sku": sku,
+ "attributes": [
+ {"id": size_attr_id, "values": ["XXXL"]},
+ {"id": attr_id, "boolean": new_value},
+ ],
+ }
+
+ associate_attribute_values_to_instance(
+ variant, boolean_attribute, boolean_attribute.values.first()
+ )
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)["data"]["productVariantUpdate"]
+ variant.refresh_from_db()
+ data = content["productVariant"]
+
+ assert not content["errors"]
+ assert data["sku"] == sku
+ assert data["attributes"][-1]["attribute"]["slug"] == boolean_attribute.slug
+ assert data["attributes"][-1]["values"][0]["name"] == "Boolean: No"
+ assert data["attributes"][-1]["values"][0]["boolean"] is new_value
+ assert boolean_attribute.values.count() == values_count
+ product_variant_updated.assert_called_once_with(product.variants.last())
+
+
@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
def test_update_variant_with_rich_text_attribute(
product_variant_updated,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index f058b5bc28..acebe5f54c 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -519,6 +519,7 @@ input AttributeInput {
slug: String!
values: [String]
valuesRange: IntRangeInput
+ boolean: Boolean
}
enum AttributeInputTypeEnum {
@@ -528,6 +529,7 @@ enum AttributeInputTypeEnum {
REFERENCE
NUMERIC
RICH_TEXT
+ BOOLEAN
}
type AttributeReorderValues {
@@ -608,6 +610,7 @@ type AttributeValue implements Node {
reference: ID
file: File
richText: JSONString
+ boolean: Boolean
}
type AttributeValueBulkDelete {
@@ -658,6 +661,7 @@ input AttributeValueInput {
contentType: String
references: [ID!]
richText: JSONString
+ boolean: Boolean
}
type AttributeValueTranslatableContent implements Node {
diff --git a/saleor/static/populatedb_data.json b/saleor/static/populatedb_data.json
index 424c6f2bda..de904df06e 100644
--- a/saleor/static/populatedb_data.json
+++ b/saleor/static/populatedb_data.json
@@ -4181,8 +4181,8 @@
"fields": {
"private_metadata": {},
"metadata": {},
- "sku": "lake-tunes-mp3",
- "name": "MP3",
+ "sku": "lake-tunes-cd",
+ "name": "CD / Signed: Yes",
"product": 120,
"track_inventory": true,
"weight": null,
@@ -4223,8 +4223,8 @@
"fields": {
"private_metadata": {},
"metadata": {},
- "sku": "lagoon-chants-mp3",
- "name": "MP3",
+ "sku": "lagoon-chants-vinyl",
+ "name": "Signed: No / Vinyl",
"product": 123,
"track_inventory": true,
"weight": null,
@@ -8388,7 +8388,7 @@
"variant": 317,
"assignment": 8,
"values": [
- 85
+ 84
]
}
},
@@ -8421,7 +8421,7 @@
"variant": 320,
"assignment": 8,
"values": [
- 85
+ 63
]
}
},
@@ -8479,6 +8479,28 @@
99
]
}
+ },
+ {
+ "model": "attribute.assignedvariantattribute",
+ "pk": 131,
+ "fields": {
+ "variant": 317,
+ "assignment": 11,
+ "values": [
+ 101
+ ]
+ }
+ },
+ {
+ "model": "attribute.assignedvariantattribute",
+ "pk": 132,
+ "fields": {
+ "variant": 320,
+ "assignment": 11,
+ "values": [
+ 102
+ ]
+ }
},
{
"model": "attribute.assignedpageattribute",
@@ -8654,6 +8676,15 @@
"attribute": 33,
"product_type": 12
}
+ },
+ {
+ "model": "attribute.attributevariant",
+ "pk": 11,
+ "fields": {
+ "sort_order": null,
+ "attribute": 34,
+ "product_type": 15
+ }
},
{
"model": "attribute.attributepage",
@@ -9049,6 +9080,27 @@
"available_in_grid": true
}
},
+ {
+ "model": "attribute.attribute",
+ "pk": 34,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "slug": "signed",
+ "name": "Signed",
+ "type": "product-type",
+ "input_type": "boolean",
+ "entity_type": null,
+ "unit": null,
+ "value_required": false,
+ "is_variant_only": false,
+ "visible_in_storefront": true,
+ "filterable_in_storefront": true,
+ "filterable_in_dashboard": true,
+ "storefront_search_position": 0,
+ "available_in_grid": true
+ }
+ },
{
"model": "attribute.attributevalue",
"pk": 1,
@@ -9755,6 +9807,34 @@
"content_type": null,
"attribute": 32
}
+ },
+ {
+ "model": "attribute.attributevalue",
+ "pk": 101,
+ "fields": {
+ "sort_order": 1,
+ "name": "Signed: Yes",
+ "value": "",
+ "slug": "34_true",
+ "file_url": null,
+ "content_type": null,
+ "boolean": true,
+ "attribute": 34
+ }
+ },
+ {
+ "model": "attribute.attributevalue",
+ "pk": 102,
+ "fields": {
+ "sort_order": 1,
+ "name": "Signed: No",
+ "value": "",
+ "slug": "34_false",
+ "file_url": null,
+ "content_type": null,
+ "boolean": false,
+ "attribute": 34
+ }
},
{
"model": "product.productimage",
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 236c2d6ef5..5d3320d094 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -811,6 +811,32 @@ def attribute_choices_for_sorting(db):
return attribute
+def boolean_attribute(db):
+ attribute = Attribute.objects.create(
+ slug="boolean",
+ name="Boolean",
+ type=AttributeType.PRODUCT_TYPE,
+ input_type=AttributeInputType.BOOLEAN,
+ filterable_in_storefront=True,
+ filterable_in_dashboard=True,
+ available_in_grid=True,
+ )
+ AttributeValue.objects.create(
+ attribute=attribute,
+ name=f"{attribute.name}: Yes",
+ slug=f"{attribute.id}_true",
+ boolean=True,
+ )
+ AttributeValue.objects.create(
+ attribute=attribute,
+ name=f"{attribute.name}: No",
+ slug=f"{attribute.id}_false",
+ boolean=False,
+ )
+ return attribute
+
+
@pytest.fixture
def rich_text_attribute(db):
attribute = Attribute.objects.create(