Skip to content

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

Switch to rich text

Piotr Grundas3b2976bcff44
diff --git a/saleor/attribute/__init__.py b/saleor/attribute/__init__.py
index 484e4a6e6a..f2d6665fda 100644
--- a/saleor/attribute/__init__.py
+++ b/saleor/attribute/__init__.py
@@ -5,14 +5,14 @@ class AttributeInputType:
MULTISELECT = "multiselect"
FILE = "file"
REFERENCE = "reference"
- TEXT = "text"
+ RICH_TEXT = "rich-text"
CHOICES = [
(DROPDOWN, "Dropdown"),
(MULTISELECT, "Multi Select"),
(FILE, "File"),
(REFERENCE, "Reference"),
- (TEXT, "Text"),
+ (RICH_TEXT, "Rich Text"),
]
# list of the input types that can be used in variant selection
ALLOWED_IN_VARIANT_SELECTION = [DROPDOWN]
diff --git a/saleor/attribute/migrations/0008_auto_20210325_1311.py b/saleor/attribute/migrations/0008_auto_20210406_1628.py
similarity index 57%
rename from saleor/attribute/migrations/0008_auto_20210325_1311.py
rename to saleor/attribute/migrations/0008_auto_20210406_1628.py
index 818b0ada9b..0c32b86a7a 100644
--- a/saleor/attribute/migrations/0008_auto_20210325_1311.py
+++ b/saleor/attribute/migrations/0008_auto_20210406_1628.py
@@ -1,7 +1,10 @@
-# Generated by Django 3.1.7 on 2021-03-25 13:11
+# Generated by Django 3.1.7 on 2021-04-06 16:28
from django.db import migrations, models
+import saleor.core.db.fields
+import saleor.core.utils.editorjs
+
class Migration(migrations.Migration):
@@ -10,6 +13,15 @@ class Migration(migrations.Migration):
]
operations = [
+ migrations.AddField(
+ model_name="attributevalue",
+ name="rich_text",
+ field=saleor.core.db.fields.SanitizedJSONField(
+ blank=True,
+ null=True,
+ sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ ),
+ ),
migrations.AlterField(
model_name="attribute",
name="input_type",
@@ -19,7 +31,7 @@ class Migration(migrations.Migration):
("multiselect", "Multi Select"),
("file", "File"),
("reference", "Reference"),
- ("text", "Text"),
+ ("rich-text", "Rich Text"),
],
default="dropdown",
max_length=50,
diff --git a/saleor/attribute/models/base.py b/saleor/attribute/models/base.py
index 92c6792469..4c8dddb5db 100644
--- a/saleor/attribute/models/base.py
+++ b/saleor/attribute/models/base.py
@@ -4,7 +4,9 @@ from django.db import models
from django.db.models import F, Q
from ...account.utils import requestor_is_staff_member_or_app
+from ...core.db.fields import SanitizedJSONField
from ...core.models import ModelWithMetadata, SortableModel
+from ...core.utils.editorjs import clean_editor_js
from ...core.utils.translations import TranslationProxy
from ...page.models import PageType
from ...product.models import ProductType
@@ -189,6 +191,7 @@ class AttributeValue(SortableModel):
attribute = models.ForeignKey(
Attribute, related_name="values", on_delete=models.CASCADE
)
+ rich_text = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
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 b37b8b424c..6290335362 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
@@ -236,7 +236,7 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(
product_type_product_reference_attribute,
product_with_image,
product_with_variant_with_two_attributes,
- text_attribute,
+ rich_text_attribute,
variant_with_many_stocks,
):
# given
@@ -245,13 +245,13 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(
file_attribute,
product_type_page_reference_attribute,
product_type_product_reference_attribute,
- text_attribute,
+ rich_text_attribute,
)
product.product_type.product_attributes.add(
file_attribute,
product_type_page_reference_attribute,
product_type_product_reference_attribute,
- text_attribute,
+ rich_text_attribute,
)
# add file attribute
@@ -262,12 +262,14 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(
product, file_attribute, file_attribute.values.first()
)
- # add text attribute
+ # add rich text attribute
associate_attribute_values_to_instance(
- variant_with_many_stocks, text_attribute, text_attribute.values.first()
+ variant_with_many_stocks,
+ rich_text_attribute,
+ rich_text_attribute.values.first(),
)
associate_attribute_values_to_instance(
- product, text_attribute, text_attribute.values.first()
+ product, rich_text_attribute, rich_text_attribute.values.first()
)
# add page reference 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 70a446722c..367fdeb823 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
@@ -3,6 +3,7 @@ from unittest.mock import patch
from .....attribute.models import Attribute, AttributeValue
from .....attribute.utils import associate_attribute_values_to_instance
from .....product.models import Product, ProductMedia, ProductVariant, VariantMedia
+from .....tests.utils import dummy_editorjs
from .....warehouse.models import Warehouse
from ....utils import ProductExportFields
from ....utils.products_data import (
@@ -768,7 +769,12 @@ def test_add_attribute_info_to_data(product):
slug = "test_attribute_slug"
value = "test value"
attribute_data = AttributeData(
- slug=slug, value=value, file_url=None, input_type="dropdown", entity_type=None
+ slug=slug,
+ value=value,
+ file_url=None,
+ input_type="dropdown",
+ entity_type=None,
+ rich_text=None,
)
input_data = {pk: {}}
@@ -790,7 +796,12 @@ def test_add_attribute_info_to_data_update_attribute_data(product):
expected_header = f"{slug} (variant attribute)"
attribute_data = AttributeData(
- slug=slug, value=value, file_url=None, input_type="dropdown", entity_type=None
+ slug=slug,
+ value=value,
+ file_url=None,
+ input_type="dropdown",
+ entity_type=None,
+ rich_text=None,
)
input_data = {pk: {expected_header: {"value1"}}}
@@ -807,7 +818,12 @@ def test_add_attribute_info_to_data_no_slug(product):
# given
pk = product.pk
attribute_data = AttributeData(
- slug=None, value=None, file_url=None, input_type="dropdown", entity_type=None
+ slug=None,
+ value=None,
+ file_url=None,
+ input_type="dropdown",
+ entity_type=None,
+ rich_text=None,
)
input_data = {pk: {}}
@@ -826,7 +842,12 @@ def test_add_file_attribute_info_to_data(product):
slug = "testtxt"
test_url = "test.txt"
attribute_data = AttributeData(
- slug=slug, value=None, file_url=test_url, input_type="file", entity_type=None
+ slug=slug,
+ value=None,
+ file_url=test_url,
+ input_type="file",
+ entity_type=None,
+ rich_text=None,
)
input_data = {pk: {}}
@@ -840,6 +861,30 @@ def test_add_file_attribute_info_to_data(product):
assert result[pk][expected_header] == {"http://mirumee.com/media/" + test_url}
+def test_add_text_attribute_info_to_data(product):
+ # given
+ pk = product.pk
+ slug = "testtxt"
+ attribute_data = AttributeData(
+ slug=slug,
+ value=None,
+ file_url=None,
+ input_type="rich-text",
+ entity_type=None,
+ rich_text=dummy_editorjs("Dummy"),
+ )
+ 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] == {"Dummy"}
+
+
def test_add_reference_attribute_info_to_data(product, page):
# given
pk = product.pk
@@ -851,6 +896,7 @@ def test_add_reference_attribute_info_to_data(product, page):
file_url=None,
input_type="reference",
entity_type="Page",
+ rich_text="None",
)
input_data = {pk: {}}
@@ -878,6 +924,7 @@ def test_add_reference_info_to_data_update_attribute_data(product, page):
file_url=None,
input_type="reference",
entity_type="Page",
+ rich_text=None,
)
input_data = {pk: {expected_header: values}}
diff --git a/saleor/csv/tests/export/products_data/utils.py b/saleor/csv/tests/export/products_data/utils.py
index 2dcb1bfbf9..7b65e5c6cb 100644
--- a/saleor/csv/tests/export/products_data/utils.py
+++ b/saleor/csv/tests/export/products_data/utils.py
@@ -1,4 +1,5 @@
from .....attribute import AttributeInputType
+from .....core.utils.editorjs import clean_editor_js
def add_product_attribute_data_to_expected_data(data, product, attribute_ids, pk=None):
@@ -35,6 +36,8 @@ def get_attribute_value(assigned_attribute):
elif attribute.input_type == AttributeInputType.REFERENCE:
ref_id = value_instance.slug.split("_")[1]
value = f"{attribute.entity_type}_{ref_id}"
+ elif attribute.input_type == AttributeInputType.RICH_TEXT:
+ value = clean_editor_js(value_instance.rich_text, to_string=True)
else:
value = value_instance.slug
return value
diff --git a/saleor/csv/utils/__init__.py b/saleor/csv/utils/__init__.py
index 40cf7db83f..b8be169129 100644
--- a/saleor/csv/utils/__init__.py
+++ b/saleor/csv/utils/__init__.py
@@ -23,6 +23,7 @@ class ProductExportFields:
PRODUCT_ATTRIBUTE_FIELDS = {
"value": "attributes__values__slug",
"file_url": "attributes__values__file_url",
+ "rich_text": "attributes__values__rich_text",
"slug": "attributes__assignment__attribute__slug",
"input_type": "attributes__assignment__attribute__input_type",
"entity_type": "attributes__assignment__attribute__entity_type",
@@ -48,6 +49,7 @@ class ProductExportFields:
VARIANT_ATTRIBUTE_FIELDS = {
"value": "variants__attributes__values__slug",
"file_url": "variants__attributes__values__file_url",
+ "rich_text": "variants__attributes__values__rich_text",
"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 19cffba54a..422d361eae 100644
--- a/saleor/csv/utils/products_data.py
+++ b/saleor/csv/utils/products_data.py
@@ -10,6 +10,7 @@ from django.db.models.functions import Cast, Concat
from ...attribute import AttributeInputType
from ...core.utils import build_absolute_uri
+from ...core.utils.editorjs import clean_editor_js
from . import ProductExportFields
if TYPE_CHECKING:
@@ -131,7 +132,6 @@ def prepare_products_relations_data(
channel_pk_lookup = channel_fields.pop("channel_pk")
channel_slug_lookup = channel_fields.pop("slug")
-
for data in relations_data.iterator():
pk = data.get("pk")
collection = data.get("collections__slug")
@@ -290,7 +290,8 @@ def add_image_uris_to_data(
AttributeData = namedtuple(
- "AttributeData", ["slug", "file_url", "value", "input_type", "entity_type"]
+ "AttributeData",
+ ["slug", "file_url", "value", "input_type", "entity_type", "rich_text"],
)
@@ -309,6 +310,7 @@ def handle_attribute_data(
file_url=data.pop(attribute_fields["file_url"], None),
value=data.pop(attribute_fields["value"], None),
entity_type=data.pop(attribute_fields["entity_type"], None),
+ rich_text=data.pop(attribute_fields["rich_text"], None),
)
if attribute_ids and attribute_pk in attribute_ids:
@@ -391,6 +393,8 @@ def add_attribute_info_to_data(
elif input_type == AttributeInputType.REFERENCE:
reference_id = attribute_data.value.split("_")[1]
value = f"{attribute_data.entity_type}_{reference_id}"
+ elif input_type == AttributeInputType.RICH_TEXT:
+ value = clean_editor_js(attribute_data.rich_text, to_string=True)
else:
value = attribute_data.value
if header in result_data[pk]:
diff --git a/saleor/graphql/attribute/descriptions.py b/saleor/graphql/attribute/descriptions.py
index 81d7848096..6d0d79443e 100644
--- a/saleor/graphql/attribute/descriptions.py
+++ b/saleor/graphql/attribute/descriptions.py
@@ -27,3 +27,4 @@ class AttributeValueDescriptions:
TYPE = "Type of value (used only when `value` field is set)."
FILE = "Represents file URL and content type (if attribute value is a file)."
VALUE = "Represents the value of the attribute value."
+ RICH_TEXT = "Represents the text (JSON) of the attribute value."
diff --git a/saleor/graphql/attribute/mutations.py b/saleor/graphql/attribute/mutations.py
index 68841045df..06a54952a8 100644
--- a/saleor/graphql/attribute/mutations.py
+++ b/saleor/graphql/attribute/mutations.py
@@ -190,6 +190,7 @@ class BaseReorderAttributeValuesMutation(BaseMutation):
class AttributeValueCreateInput(graphene.InputObjectType):
name = graphene.String(required=True, description=AttributeValueDescriptions.NAME)
value = graphene.String(description=AttributeValueDescriptions.VALUE)
+ rich_text = graphene.JSONString(description=AttributeValueDescriptions.RICH_TEXT)
class AttributeCreateInput(graphene.InputObjectType):
diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.py
index ee84114b34..5b81c2a880 100644
--- a/saleor/graphql/attribute/types.py
+++ b/saleor/graphql/attribute/types.py
@@ -32,6 +32,9 @@ class AttributeValue(CountableDjangoObjectType):
file = graphene.Field(
File, description=AttributeValueDescriptions.FILE, required=False
)
+ rich_text = graphene.JSONString(
+ description=AttributeValueDescriptions.RICH_TEXT, required=False
+ )
class Meta:
description = "Represents a value of an attribute."
diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.py
index bced2f44e3..123de77cfd 100644
--- a/saleor/graphql/attribute/utils.py
+++ b/saleor/graphql/attribute/utils.py
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple, Union
import graphene
from django.core.exceptions import ValidationError
from django.db.models import Q
+from django.template.defaultfilters import truncatechars
from django.utils.text import slugify
from graphql.error import GraphQLError
from graphql_relay import from_global_id
@@ -13,6 +14,7 @@ from ...attribute import AttributeEntityType, AttributeInputType, AttributeType
from ...attribute import models as attribute_models
from ...attribute.utils import associate_attribute_values_to_instance
from ...core.utils import generate_unique_slug
+from ...core.utils.editorjs import clean_editor_js
from ...page import models as page_models
from ...page.error_codes import PageErrorCode
from ...product import models as product_models
@@ -32,6 +34,7 @@ class AttrValuesInput:
references: Union[List[str], List[page_models.Page]]
file_url: Optional[str] = None
content_type: Optional[str] = None
+ rich_text: Optional[dict] = None
T_INSTANCE = Union[
@@ -257,7 +260,7 @@ class AttributeAssignmentMixin:
raise ValidationError(errors)
@classmethod
- def _pre_save_text_values(
+ def _pre_save_rich_text_values(
cls,
instance: T_INSTANCE,
attribute: attribute_models.Attribute,
@@ -265,18 +268,18 @@ class AttributeAssignmentMixin:
):
"""Lazy-retrieve or create the database object from the supplied raw value."""
value_model = attribute.values.model
- text = attr_values.values[0] if attr_values.values else ""
- # don't create new value when assignment already exists
- value = cls._get_assigned_attribute_value_if_exists(
- instance, attribute, "name", text
- )
+ slug = slugify(f"{instance.id}_{attribute.id}", allow_unicode=True)
+ value = value_model.objects.update_or_create(
+ attribute=attribute,
+ slug=slug,
+ defaults={
+ "rich_text": attr_values.rich_text,
+ "name": truncatechars(
+ clean_editor_js(attr_values.rich_text, to_string=True), 50
+ ),
+ },
+ )[0]
- if value is None:
- value = value_model.objects.create(
- attribute=attribute,
- name=text,
- slug=slugify(text, allow_unicode=True),
- )
return (value,)
@classmethod
@@ -317,6 +320,7 @@ class AttributeAssignmentMixin:
file_url=attribute_input.get("file"),
content_type=attribute_input.get("content_type"),
references=attribute_input.get("references", []),
+ rich_text=attribute_input.get("rich_text"),
)
if global_id:
@@ -406,8 +410,8 @@ class AttributeAssignmentMixin:
attribute_values = cls._pre_save_reference_values(
instance, attribute, attr_values
)
- elif attribute.input_type == AttributeInputType.TEXT:
- attribute_values = cls._pre_save_text_values(
+ elif attribute.input_type == AttributeInputType.RICH_TEXT:
+ attribute_values = cls._pre_save_rich_text_values(
instance, attribute, attr_values
)
else:
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index fbe196f748..a2edcaef4f 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -469,6 +469,9 @@ class AttributeValueInput(InputObjectType):
description="List of entity IDs that will be used as references.",
required=False,
)
+ rich_text = graphene.JSONString(
+ required=False, description="Text content in JSON format."
+ )
class ProductInput(graphene.InputObjectType):
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 9d90214ebf..2a614f935f 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -2383,6 +2383,7 @@ CREATE_PRODUCT_MUTATION = """
slug
name
reference
+ richText
file {
url
contentType
@@ -2538,7 +2539,7 @@ def test_create_product_with_text_attribute(
staff_api_client,
product_type,
category,
- text_attribute,
+ rich_text_attribute,
color_attribute,
permission_manage_products,
product,
@@ -2551,8 +2552,11 @@ def test_create_product_with_text_attribute(
product_slug = "product-test-slug"
# Add second attribute
- product_type.product_attributes.add(text_attribute)
- text_attribute_id = graphene.Node.to_global_id("Attribute", text_attribute.id)
+ product_type.product_attributes.add(rich_text_attribute)
+ rich_text_attribute_id = graphene.Node.to_global_id(
+ "Attribute", rich_text_attribute.id
+ )
+ rich_text = json.dumps(dummy_editorjs("test product" * 5))
# test creating root product
variables = {
@@ -2561,7 +2565,12 @@ def test_create_product_with_text_attribute(
"category": category_id,
"name": product_name,
"slug": product_slug,
- "attributes": [{"id": text_attribute_id, "values": ["Cool text"]}],
+ "attributes": [
+ {
+ "id": rich_text_attribute_id,
+ "richText": rich_text,
+ }
+ ],
}
}
@@ -2576,19 +2585,21 @@ def test_create_product_with_text_attribute(
assert data["product"]["productType"]["name"] == product_type.name
assert data["product"]["category"]["name"] == category.name
_, product_id = graphene.Node.from_global_id(data["product"]["id"])
+
expected_attributes_data = [
+ {"attribute": {"slug": "color"}, "values": []},
{
"attribute": {"slug": "text"},
"values": [
{
- "slug": "cool-text",
- "name": "Cool text",
+ "slug": f"{product_id}_{rich_text_attribute.id}",
+ "name": "test producttest producttest producttest productt…",
"reference": None,
+ "richText": rich_text,
"file": None,
}
],
},
- {"attribute": {"slug": color_attribute.slug}, "values": []},
]
for attr_data in data["product"]["attributes"]:
assert attr_data in expected_attributes_data
@@ -2835,6 +2846,7 @@ def test_create_product_with_file_attribute(
"slug": f"{existing_value.slug}-2",
"file": {"url": existing_value.file_url, "contentType": None},
"reference": None,
+ "richText": None,
}
],
},
@@ -2902,6 +2914,7 @@ def test_create_product_with_page_reference_attribute(
"slug": f"{product_id}_{page.id}",
"name": page.title,
"file": None,
+ "richText": None,
"reference": reference,
}
],
@@ -2970,6 +2983,7 @@ def test_create_product_with_product_reference_attribute(
"slug": f"{product_id}_{product.id}",
"name": product.name,
"file": None,
+ "richText": None,
"reference": reference,
}
],
@@ -3038,6 +3052,7 @@ def test_create_product_with_product_reference_attribute_values_saved_in_order(
"slug": f"{product_id}_{product.id}",
"name": product.name,
"file": None,
+ "richText": None,
"reference": reference,
}
for product, reference in zip(reference_instances, reference_ids)
@@ -3109,6 +3124,7 @@ def test_create_product_with_file_attribute_new_attribute_value(
"name": non_existing_value,
"slug": slugify(non_existing_value, allow_unicode=True),
"reference": None,
+ "richText": None,
"file": {
"url": "http://testserver/media/" + non_existing_value,
"contentType": None,
@@ -5541,6 +5557,7 @@ PRODUCT_TYPE_CREATE_MUTATION = """
name
values {
name
+ richText
}
}
}
@@ -5623,14 +5640,13 @@ def test_create_product_type_with_text_attribute(
staff_api_client,
product_type,
permission_manage_product_types_and_attributes,
- text_attribute,
+ rich_text_attribute,
):
query = PRODUCT_TYPE_CREATE_MUTATION
product_type_name = "test type"
slug = "test-type"
- product_type.product_attributes.add(text_attribute)
-
+ product_type.product_attributes.add(rich_text_attribute)
product_attributes_ids = [
graphene.Node.to_global_id("Attribute", attr.id)
for attr in product_type.product_attributes.all()
@@ -5653,8 +5669,24 @@ def test_create_product_type_with_text_attribute(
assert data["name"] == product_type_name
assert data["slug"] == slug
expected_attributes = [
- {"name": "Color", "values": [{"name": "Red"}, {"name": "Blue"}]},
- {"name": "Text", "values": [{"name": "Some cool text"}]},
+ {
+ "name": "Color",
+ "values": [
+ {"name": "Red", "richText": None},
+ {"name": "Blue", "richText": None},
+ ],
+ },
+ {
+ "name": "Text",
+ "values": [
+ {
+ "name": "Rich text attribute content.",
+ "richText": json.dumps(
+ rich_text_attribute.values.first().rich_text
+ ),
+ }
+ ],
+ },
]
for attribute in data["productAttributes"]:
assert attribute in expected_attributes
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index 332292732a..9827819fe2 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -1,3 +1,4 @@
+import json
from unittest.mock import ANY, patch
from uuid import uuid4
@@ -15,7 +16,7 @@ from ....order import OrderStatus
from ....order.models import OrderLine
from ....product.error_codes import ProductErrorCode
from ....product.models import Product, ProductChannelListing, ProductVariant
-from ....tests.utils import flush_post_commit_hooks
+from ....tests.utils import dummy_editorjs, flush_post_commit_hooks
from ....warehouse.error_codes import StockErrorCode
from ....warehouse.models import Stock, Warehouse
from ...core.enums import WeightUnitsEnum
@@ -293,6 +294,7 @@ CREATE_VARIANT_MUTATION = """
name
slug
reference
+ richText
file {
url
contentType
@@ -628,12 +630,14 @@ def test_create_variant_with_page_reference_attribute(
{
"slug": f"{variant_pk}_{page_list[0].pk}",
"file": None,
+ "richText": None,
"reference": page_ref_1,
"name": page_list[0].title,
},
{
"slug": f"{variant_pk}_{page_list[1].pk}",
"file": None,
+ "richText": None,
"reference": page_ref_2,
"name": page_list[1].title,
},
@@ -770,12 +774,14 @@ def test_create_variant_with_product_reference_attribute(
{
"slug": f"{variant_pk}_{product_list[0].pk}",
"file": None,
+ "richText": None,
"reference": product_ref_1,
"name": product_list[0].name,
},
{
"slug": f"{variant_pk}_{product_list[1].pk}",
"file": None,
+ "richText": None,
"reference": product_ref_2,
"name": product_list[1].name,
},
@@ -1057,18 +1063,18 @@ def test_create_variant_with_text_attribute(
product,
product_type,
staff_api_client,
- text_attribute,
+ rich_text_attribute,
warehouse,
):
- product_type.variant_attributes.add(text_attribute)
+ product_type.variant_attributes.add(rich_text_attribute)
query = CREATE_VARIANT_MUTATION
product_id = graphene.Node.to_global_id("Product", product.pk)
sku = "1"
price = 1.32
cost_price = 3.22
weight = 10.22
- attr_id = graphene.Node.to_global_id("Attribute", text_attribute.id)
- text = "Sample text"
+ attr_id = graphene.Node.to_global_id("Attribute", rich_text_attribute.id)
+ rich_text = json.dumps(dummy_editorjs("Sample text"))
stocks = [
{
"warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
@@ -1083,7 +1089,7 @@ def test_create_variant_with_text_attribute(
"price": price,
"weight": weight,
"attributes": [
- {"id": attr_id, "values": text},
+ {"id": attr_id, "richText": rich_text},
],
"trackInventory": True,
}
@@ -1098,8 +1104,7 @@ def test_create_variant_with_text_attribute(
assert not content["productErrors"]
assert data["name"] == sku
assert data["sku"] == sku
- assert data["attributes"][-1]["attribute"]["slug"] == text_attribute.slug
- assert data["attributes"][-1]["values"][0]["name"] == text
+ assert data["attributes"][-1]["values"][0]["richText"] == rich_text
created_webhook_mock.assert_called_once_with(product.variants.last())
@@ -1108,7 +1113,7 @@ def test_create_variant_with_text_attribute_length_exceeded(
product,
product_type,
staff_api_client,
- text_attribute,
+ rich_text_attribute,
warehouse,
):
query = CREATE_VARIANT_MUTATION
@@ -1118,8 +1123,8 @@ def test_create_variant_with_text_attribute_length_exceeded(
cost_price = 3.22
weight = 10.22
- product_type.variant_attributes.add(text_attribute)
- attr_id = graphene.Node.to_global_id("Attribute", text_attribute.id)
+ product_type.variant_attributes.add(rich_text_attribute)
+ attr_id = graphene.Node.to_global_id("Attribute", rich_text_attribute.id)
stocks = [
{
@@ -1360,6 +1365,7 @@ QUERY_UPDATE_VARIANT_ATTRIBUTES = """
contentType
}
reference
+ richText
}
}
}
@@ -1461,27 +1467,30 @@ def test_update_variant_with_text_attribute(
product,
product_type,
staff_api_client,
- text_attribute,
+ rich_text_attribute,
warehouse,
):
- product_type.variant_attributes.add(text_attribute)
+ product_type.variant_attributes.add(rich_text_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", text_attribute.id)
- text = text_attribute.values.first().name
+ attr_id = graphene.Node.to_global_id("Attribute", rich_text_attribute.id)
+ rich_text_attribute_value = rich_text_attribute.values.first()
+ rich_text = json.dumps(rich_text_attribute_value.rich_text)
variables = {
"id": variant_id,
"sku": sku,
"attributes": [
- {"id": attr_id, "values": text},
+ {"id": attr_id, "richText": rich_text},
],
}
+ rich_text_attribute_value.slug = f"{variant.id}_{rich_text_attribute.id}"
+ rich_text_attribute_value.save()
+ values_count = rich_text_attribute.values.count()
associate_attribute_values_to_instance(
- variant, text_attribute, text_attribute.values.first()
+ variant, rich_text_attribute, rich_text_attribute.values.first()
)
- values_count = text_attribute.values.count()
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
@@ -1492,9 +1501,9 @@ def test_update_variant_with_text_attribute(
assert not content["productErrors"]
assert data["sku"] == sku
- assert data["attributes"][-1]["attribute"]["slug"] == text_attribute.slug
- assert data["attributes"][-1]["values"][0]["name"] == text
- assert text_attribute.values.count() == values_count
+ assert data["attributes"][-1]["attribute"]["slug"] == rich_text_attribute.slug
+ assert data["attributes"][-1]["values"][0]["richText"] == rich_text
+ assert rich_text_attribute.values.count() == values_count
product_variant_updated.assert_called_once_with(product.variants.last())
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index c3f6b5eca5..1ff5f7cc71 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -499,7 +499,7 @@ enum AttributeInputTypeEnum {
MULTISELECT
FILE
REFERENCE
- TEXT
+ RICH_TEXT
}
type AttributeReorderValues {
@@ -578,6 +578,7 @@ type AttributeValue implements Node {
inputType: AttributeInputTypeEnum
reference: ID
file: File
+ richText: JSONString
}
type AttributeValueBulkDelete {
@@ -596,6 +597,7 @@ type AttributeValueCreate {
input AttributeValueCreateInput {
name: String!
value: String
+ richText: JSONString
}
type AttributeValueDelete {
@@ -611,6 +613,7 @@ input AttributeValueInput {
file: String
contentType: String
references: [ID!]
+ richText: JSONString
}
type AttributeValueTranslatableContent implements Node {
diff --git a/saleor/settings.py b/saleor/settings.py
index 2299bf50c3..94ad4d4009 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -263,6 +263,7 @@ INSTALLED_APPS = [
"django_countries",
"django_filters",
"phonenumber_field",
+ "django_extensions",
]
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 9a02389455..16232e08ea 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -18,6 +18,7 @@ from django.core.files import File
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import connection
from django.forms import ModelForm
+from django.template.defaultfilters import truncatechars
from django.test.utils import CaptureQueriesContext as BaseCaptureQueriesContext
from django.utils import timezone
from django_countries import countries
@@ -39,6 +40,7 @@ from ..checkout.models import Checkout
from ..checkout.utils import add_variant_to_checkout
from ..core import JobStatus
from ..core.payments import PaymentInterface
+from ..core.utils.editorjs import clean_editor_js
from ..csv.events import ExportEvents
from ..csv.models import ExportEvent, ExportFile
from ..discount import DiscountInfo, DiscountValueType, VoucherType
@@ -774,18 +776,22 @@ def color_attribute(db):
@pytest.fixture
-def text_attribute(db):
+def rich_text_attribute(db):
attribute = Attribute.objects.create(
slug="text",
name="Text",
type=AttributeType.PRODUCT_TYPE,
- input_type=AttributeInputType.TEXT,
- filterable_in_storefront=True,
- filterable_in_dashboard=True,
- available_in_grid=True,
+ input_type=AttributeInputType.RICH_TEXT,
+ filterable_in_storefront=False,
+ filterable_in_dashboard=False,
+ available_in_grid=False,
)
+ text = "Rich text attribute content."
AttributeValue.objects.create(
- attribute=attribute, name="Some cool text", slug="come-cool-text"
+ attribute=attribute,
+ name=truncatechars(clean_editor_js(dummy_editorjs(text), to_string=True), 50),
+ slug=f"instance_{attribute.id}",
+ rich_text=dummy_editorjs(text),
)
return attribute
@@ -1148,7 +1154,6 @@ def product_type(color_attribute, size_attribute):
has_variants=True,
is_shipping_required=True,
)
-
product_type.product_attributes.add(color_attribute)
product_type.variant_attributes.add(size_attribute)
return product_type