Skip to content

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

New attribute type: plain text (#9907)

Iga Karbowiakdc0ce6ba34ab
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 26d6807cf4..93f213cb32 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ All notable, unreleased changes to this project will be documented in this file.
### Other changes
- Fix inaccurate tax calculations - #9799 by @IKarbowiak
+- Introduce plain text attribute - #9907 by @IKarbowiak
#### Saleor Apps
- Add webhooks `PAGE_TYPE_CREATED`, `PAGE_TYPE_UPDATED` and `PAGE_TYPE_DELETED` - #9859 by @SzymJ
diff --git a/saleor/attribute/__init__.py b/saleor/attribute/__init__.py
index c4485e6a60..556b6d9ed7 100644
--- a/saleor/attribute/__init__.py
+++ b/saleor/attribute/__init__.py
@@ -7,6 +7,7 @@ class AttributeInputType:
REFERENCE = "reference"
NUMERIC = "numeric"
RICH_TEXT = "rich-text"
+ PLAIN_TEXT = "plain-text"
SWATCH = "swatch"
BOOLEAN = "boolean"
DATE = "date"
@@ -19,6 +20,7 @@ class AttributeInputType:
(REFERENCE, "Reference"),
(NUMERIC, "Numeric"),
(RICH_TEXT, "Rich Text"),
+ (PLAIN_TEXT, "Plain Text"),
(SWATCH, "Swatch"),
(BOOLEAN, "Boolean"),
(DATE, "Date"),
@@ -35,11 +37,20 @@ class AttributeInputType:
]
# list of the input types that are unique per instances
- TYPES_WITH_UNIQUE_VALUES = [FILE, REFERENCE, RICH_TEXT, NUMERIC, DATE, DATE_TIME]
+ TYPES_WITH_UNIQUE_VALUES = [
+ FILE,
+ REFERENCE,
+ RICH_TEXT,
+ PLAIN_TEXT,
+ NUMERIC,
+ DATE,
+ DATE_TIME,
+ ]
# list of the translatable attributes, excluding attributes with choices.
TRANSLATABLE_ATTRIBUTES = [
RICH_TEXT,
+ PLAIN_TEXT,
]
diff --git a/saleor/attribute/migrations/0022_plain_text_attribute.py b/saleor/attribute/migrations/0022_plain_text_attribute.py
new file mode 100644
index 0000000000..6fafb3f354
--- /dev/null
+++ b/saleor/attribute/migrations/0022_plain_text_attribute.py
@@ -0,0 +1,44 @@
+# Generated by Django 3.2.13 on 2022-05-24 11:39
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("attribute", "0021_auto_20220406_1713"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="attributevalue",
+ name="plain_text",
+ field=models.TextField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="attributevaluetranslation",
+ name="plain_text",
+ field=models.TextField(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"),
+ ("plain-text", "Plain Text"),
+ ("swatch", "Swatch"),
+ ("boolean", "Boolean"),
+ ("date", "Date"),
+ ("date-time", "Date Time"),
+ ],
+ default="dropdown",
+ max_length=50,
+ ),
+ ),
+ ]
diff --git a/saleor/attribute/models/base.py b/saleor/attribute/models/base.py
index ca88089840..1480cfb599 100644
--- a/saleor/attribute/models/base.py
+++ b/saleor/attribute/models/base.py
@@ -216,6 +216,10 @@ class AttributeValue(SortableModel):
Attribute, related_name="values", on_delete=models.CASCADE
)
rich_text = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ plain_text = models.TextField(
+ blank=True,
+ null=True,
+ )
boolean = models.BooleanField(blank=True, null=True)
date_time = models.DateTimeField(blank=True, null=True)
@@ -262,6 +266,10 @@ class AttributeValueTranslation(Translation):
)
name = models.CharField(max_length=100)
rich_text = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ plain_text = models.TextField(
+ blank=True,
+ null=True,
+ )
class Meta:
unique_together = (("language_code", "attribute_value"),)
diff --git a/saleor/graphql/attribute/descriptions.py b/saleor/graphql/attribute/descriptions.py
index b2d477aa79..e313204b35 100644
--- a/saleor/graphql/attribute/descriptions.py
+++ b/saleor/graphql/attribute/descriptions.py
@@ -46,6 +46,9 @@ class AttributeValueDescriptions:
"Represents the text of the attribute value, includes formatting."
+ RICH_CONTENT
)
+ PLAIN_TEXT = (
+ "Represents the text of the attribute value, plain text without formating."
+ )
BOOLEAN = "Represents the boolean value of the attribute value."
DATE = "Represents the date value of the attribute value."
DATE_TIME = "Represents the date/time value of the attribute value."
diff --git a/saleor/graphql/attribute/mutations.py b/saleor/graphql/attribute/mutations.py
index 250a7951ce..14edf3a654 100644
--- a/saleor/graphql/attribute/mutations.py
+++ b/saleor/graphql/attribute/mutations.py
@@ -192,6 +192,7 @@ class BaseReorderAttributeValuesMutation(BaseMutation):
class AttributeValueInput(graphene.InputObjectType):
value = graphene.String(description=AttributeValueDescriptions.VALUE)
rich_text = JSONString(description=AttributeValueDescriptions.RICH_TEXT)
+ plain_text = graphene.String(description=AttributeValueDescriptions.PLAIN_TEXT)
file_url = graphene.String(
required=False,
description="URL of the file attribute. Every time, a new value is created.",
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py
index bc66f038bf..a5f937f799 100644
--- a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py
@@ -621,6 +621,53 @@ def test_create_attribute_with_reference_input_type_entity_type_not_given(
assert errors[0]["code"] == AttributeErrorCode.REQUIRED.name
+def test_create_attribute_with_plain_text_input_type(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+):
+ # given
+ query = CREATE_ATTRIBUTE_MUTATION
+
+ attribute_name = "Example name"
+ variables = {
+ "input": {
+ "name": attribute_name,
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ "inputType": AttributeInputTypeEnum.PLAIN_TEXT.name,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["attributeCreate"]["errors"]
+ data = content["data"]["attributeCreate"]
+
+ # Check if the attribute was correctly created
+ assert data["attribute"]["name"] == attribute_name
+ assert data["attribute"]["slug"] == slugify(
+ attribute_name
+ ), "The default slug should be the slugified name"
+ assert (
+ data["attribute"]["productTypes"]["edges"] == []
+ ), "The attribute should not have been assigned to a product type"
+
+ # Check if the attribute values were correctly created
+ assert len(data["attribute"]["choices"]["edges"]) == 0
+ assert data["attribute"]["type"] == AttributeTypeEnum.PRODUCT_TYPE.name
+ assert data["attribute"]["inputType"] == AttributeInputTypeEnum.PLAIN_TEXT.name
+
+
def test_create_page_attribute_and_attribute_values(
staff_api_client,
permission_manage_page_types_and_attributes,
diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.py
index 664f92f9bb..57bff72ae4 100644
--- a/saleor/graphql/attribute/types.py
+++ b/saleor/graphql/attribute/types.py
@@ -54,6 +54,9 @@ class AttributeValue(ModelObjectType):
rich_text = JSONString(
description=AttributeValueDescriptions.RICH_TEXT, required=False
)
+ plain_text = graphene.String(
+ description=AttributeValueDescriptions.PLAIN_TEXT, required=False
+ )
boolean = graphene.Boolean(
description=AttributeValueDescriptions.BOOLEAN, required=False
)
@@ -387,6 +390,7 @@ class AttributeValueInput(graphene.InputObjectType):
required=False,
)
rich_text = JSONString(required=False, description="Text content in JSON format.")
+ plain_text = graphene.String(required=False, description="Plain text content.")
boolean = graphene.Boolean(
required=False, description=AttributeValueDescriptions.BOOLEAN
)
diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.py
index 9337b3c594..965b84cad9 100644
--- a/saleor/graphql/attribute/utils.py
+++ b/saleor/graphql/attribute/utils.py
@@ -40,6 +40,7 @@ class AttrValuesInput:
file_url: Optional[str] = None
content_type: Optional[str] = None
rich_text: Optional[dict] = None
+ plain_text: Optional[str] = None
boolean: Optional[bool] = None
date: Optional[str] = None
date_time: Optional[str] = None
@@ -139,193 +140,6 @@ class AttributeAssignmentMixin:
)
return int(internal_id)
- @classmethod
- def _pre_save_values(
- cls, attribute: attribute_models.Attribute, attr_values: AttrValuesInput
- ):
- """Lazy-retrieve or create the database objects from the supplied raw values."""
- get_or_create = attribute.values.get_or_create
-
- if not attr_values.values:
- return tuple()
-
- return tuple(
- get_or_create(
- attribute=attribute,
- slug=slugify(value, allow_unicode=True),
- defaults={"name": value},
- )[0]
- for value in attr_values.values
- )
-
- @classmethod
- def _pre_save_numeric_values(
- cls,
- instance: T_INSTANCE,
- attribute: attribute_models.Attribute,
- attr_values: AttrValuesInput,
- ):
- if not attr_values.values:
- return tuple()
- defaults = {
- "name": attr_values.values[0],
- }
- return cls._update_or_create_value(instance, attribute, defaults)
-
- @classmethod
- def _pre_save_rich_text_values(
- cls,
- instance: T_INSTANCE,
- attribute: attribute_models.Attribute,
- attr_values: AttrValuesInput,
- ):
- if not attr_values.rich_text:
- return tuple()
- defaults = {
- "rich_text": attr_values.rich_text,
- "name": truncatechars(
- 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,
- ):
- if attr_values.boolean is None:
- return tuple()
- get_or_create = attribute.values.get_or_create
- boolean = bool(attr_values.boolean)
- value, _ = get_or_create(
- attribute=attribute,
- slug=slugify(f"{attribute.id}_{boolean}", allow_unicode=True),
- defaults={
- "name": f"{attribute.name}: {'Yes' if boolean else 'No'}",
- "boolean": boolean,
- },
- )
- return (value,)
-
- @classmethod
- def _pre_save_date_time_values(
- cls,
- instance: T_INSTANCE,
- attribute: attribute_models.Attribute,
- attr_values: AttrValuesInput,
- ):
- is_date_attr = attribute.input_type == AttributeInputType.DATE
- value = attr_values.date if is_date_attr else attr_values.date_time
-
- if value is None:
- return tuple()
-
- tz = timezone.get_current_timezone()
- date_time = (
- datetime(
- value.year, value.month, value.day, 0, 0, tzinfo=tz # type: ignore
- )
- if is_date_attr
- else value
- )
- defaults = {"name": value, "date_time": date_time}
- return (
- cls._update_or_create_value(instance, attribute, defaults) if value else ()
- )
-
- @classmethod
- def _update_or_create_value(
- cls,
- instance: T_INSTANCE,
- attribute: attribute_models.Attribute,
- value_defaults: dict,
- ):
- update_or_create = attribute.values.update_or_create
- slug = slugify(f"{instance.id}_{attribute.id}", allow_unicode=True)
- value, _created = update_or_create(
- attribute=attribute,
- slug=slug,
- defaults=value_defaults,
- )
- return (value,)
-
- @classmethod
- def _pre_save_reference_values(
- cls,
- instance,
- attribute: attribute_models.Attribute,
- attr_values: AttrValuesInput,
- ):
- """Lazy-retrieve or create the database objects from the supplied raw values.
-
- Slug value is generated based on instance and reference entity id.
- """
- if not attr_values.references:
- return tuple()
-
- field_name = cls.REFERENCE_VALUE_NAME_MAPPING[
- attribute.entity_type # type: ignore
- ]
- get_or_create = attribute.values.get_or_create
-
- reference_list = []
- for ref in attr_values.references:
- reference_page = None
- reference_product = None
-
- if attribute.entity_type == AttributeEntityType.PAGE:
- reference_page = ref
- else:
- reference_product = ref
-
- reference_list.append(
- get_or_create(
- attribute=attribute,
- reference_product=reference_product,
- reference_page=reference_page,
- slug=slugify(
- f"{instance.id}_{ref.id}", # type: ignore
- allow_unicode=True,
- ),
- defaults={"name": getattr(ref, field_name)},
- )[0]
- )
- return tuple(reference_list)
-
- @classmethod
- def _pre_save_file_value(
- cls,
- instance: T_INSTANCE,
- attribute: attribute_models.Attribute,
- attr_value: AttrValuesInput,
- ):
- """Create database file attribute value object from the supplied value.
-
- For every URL new value must be created as file attribute can be removed
- separately from every instance.
- """
- file_url = attr_value.file_url
- if not file_url:
- return tuple()
- name = file_url.split("/")[-1]
- # don't create new value when assignment already exists
- value = cls._get_assigned_attribute_value_if_exists(
- instance, attribute, "file_url", attr_value.file_url
- )
- if value is None:
- value = attribute_models.AttributeValue(
- attribute=attribute,
- file_url=file_url,
- name=name,
- content_type=attr_value.content_type,
- )
- value.slug = generate_unique_slug(value, name) # type: ignore
- value.save()
- return (value,)
-
@classmethod
def _get_assigned_attribute_value_if_exists(
cls,
@@ -382,6 +196,7 @@ class AttributeAssignmentMixin:
content_type=attribute_input.get("content_type"),
references=attribute_input.get("references", []),
rich_text=attribute_input.get("rich_text"),
+ plain_text=attribute_input.get("plain_text"),
boolean=attribute_input.get("boolean"),
date=attribute_input.get("date"),
date_time=attribute_input.get("date_time"),
@@ -509,6 +324,7 @@ class AttributeAssignmentMixin:
AttributeInputType.FILE: cls._pre_save_file_value,
AttributeInputType.REFERENCE: cls._pre_save_reference_values,
AttributeInputType.RICH_TEXT: cls._pre_save_rich_text_values,
+ AttributeInputType.PLAIN_TEXT: cls._pre_save_plain_text_values,
AttributeInputType.NUMERIC: cls._pre_save_numeric_values,
AttributeInputType.BOOLEAN: cls._pre_save_boolean_values,
AttributeInputType.DATE: cls._pre_save_date_time_values,
@@ -534,6 +350,208 @@ class AttributeAssignmentMixin:
assignment__attribute_id__in=clean_assignment
).delete()
+ @classmethod
+ def _pre_save_values(
+ cls, attribute: attribute_models.Attribute, attr_values: AttrValuesInput
+ ):
+ """Lazy-retrieve or create the database objects from the supplied raw values."""
+ get_or_create = attribute.values.get_or_create
+
+ if not attr_values.values:
+ return tuple()
+
+ return tuple(
+ get_or_create(
+ attribute=attribute,
+ slug=slugify(value, allow_unicode=True),
+ defaults={"name": value},
+ )[0]
+ for value in attr_values.values
+ )
+
+ @classmethod
+ def _pre_save_numeric_values(
+ cls,
+ instance: T_INSTANCE,
+ attribute: attribute_models.Attribute,
+ attr_values: AttrValuesInput,
+ ):
+ if not attr_values.values:
+ return tuple()
+ defaults = {
+ "name": attr_values.values[0],
+ }
+ return cls._update_or_create_value(instance, attribute, defaults)
+
+ @classmethod
+ def _pre_save_rich_text_values(
+ cls,
+ instance: T_INSTANCE,
+ attribute: attribute_models.Attribute,
+ attr_values: AttrValuesInput,
+ ):
+ if not attr_values.rich_text:
+ return tuple()
+ defaults = {
+ "rich_text": attr_values.rich_text,
+ "name": truncatechars(
+ clean_editor_js(attr_values.rich_text, to_string=True), 200
+ ),
+ }
+ return cls._update_or_create_value(instance, attribute, defaults)
+
+ @classmethod
+ def _pre_save_plain_text_values(
+ cls,
+ instance: T_INSTANCE,
+ attribute: attribute_models.Attribute,
+ attr_values: AttrValuesInput,
+ ):
+ if not attr_values.plain_text:
+ return tuple()
+ defaults = {
+ "plain_text": attr_values.plain_text,
+ "name": truncatechars(attr_values.plain_text, 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,
+ ):
+ if attr_values.boolean is None:
+ return tuple()
+ get_or_create = attribute.values.get_or_create
+ boolean = bool(attr_values.boolean)
+ value, _ = get_or_create(
+ attribute=attribute,
+ slug=slugify(f"{attribute.id}_{boolean}", allow_unicode=True),
+ defaults={
+ "name": f"{attribute.name}: {'Yes' if boolean else 'No'}",
+ "boolean": boolean,
+ },
+ )
+ return (value,)
+
+ @classmethod
+ def _pre_save_date_time_values(
+ cls,
+ instance: T_INSTANCE,
+ attribute: attribute_models.Attribute,
+ attr_values: AttrValuesInput,
+ ):
+ is_date_attr = attribute.input_type == AttributeInputType.DATE
+ value = attr_values.date if is_date_attr else attr_values.date_time
+
+ if value is None:
+ return tuple()
+
+ tz = timezone.get_current_timezone()
+ date_time = (
+ datetime(
+ value.year, value.month, value.day, 0, 0, tzinfo=tz # type: ignore
+ )
+ if is_date_attr
+ else value
+ )
+ defaults = {"name": value, "date_time": date_time}
+ return (
+ cls._update_or_create_value(instance, attribute, defaults) if value else ()
+ )
+
+ @classmethod
+ def _update_or_create_value(
+ cls,
+ instance: T_INSTANCE,
+ attribute: attribute_models.Attribute,
+ value_defaults: dict,
+ ):
+ update_or_create = attribute.values.update_or_create
+ slug = slugify(f"{instance.id}_{attribute.id}", allow_unicode=True)
+ value, _created = update_or_create(
+ attribute=attribute,
+ slug=slug,
+ defaults=value_defaults,
+ )
+ return (value,)
+
+ @classmethod
+ def _pre_save_reference_values(
+ cls,
+ instance,
+ attribute: attribute_models.Attribute,
+ attr_values: AttrValuesInput,
+ ):
+ """Lazy-retrieve or create the database objects from the supplied raw values.
+
+ Slug value is generated based on instance and reference entity id.
+ """
+ if not attr_values.references:
+ return tuple()
+
+ field_name = cls.REFERENCE_VALUE_NAME_MAPPING[
+ attribute.entity_type # type: ignore
+ ]
+ get_or_create = attribute.values.get_or_create
+
+ reference_list = []
+ for ref in attr_values.references:
+ reference_page = None
+ reference_product = None
+
+ if attribute.entity_type == AttributeEntityType.PAGE:
+ reference_page = ref
+ else:
+ reference_product = ref
+
+ reference_list.append(
+ get_or_create(
+ attribute=attribute,
+ reference_product=reference_product,
+ reference_page=reference_page,
+ slug=slugify(
+ f"{instance.id}_{ref.id}", # type: ignore
+ allow_unicode=True,
+ ),
+ defaults={"name": getattr(ref, field_name)},
+ )[0]
+ )
+ return tuple(reference_list)
+
+ @classmethod
+ def _pre_save_file_value(
+ cls,
+ instance: T_INSTANCE,
+ attribute: attribute_models.Attribute,
+ attr_value: AttrValuesInput,
+ ):
+ """Create database file attribute value object from the supplied value.
+
+ For every URL new value must be created as file attribute can be removed
+ separately from every instance.
+ """
+ file_url = attr_value.file_url
+ if not file_url:
+ return tuple()
+ name = file_url.split("/")[-1]
+ # don't create new value when assignment already exists
+ value = cls._get_assigned_attribute_value_if_exists(
+ instance, attribute, "file_url", attr_value.file_url
+ )
+ if value is None:
+ value = attribute_models.AttributeValue(
+ attribute=attribute,
+ file_url=file_url,
+ name=name,
+ content_type=attr_value.content_type,
+ )
+ value.slug = generate_unique_slug(value, name) # type: ignore
+ value.save()
+ return (value,)
+
def get_variant_selection_attributes(qs: "QuerySet") -> "QuerySet":
return qs.filter(
@@ -756,8 +774,6 @@ def validate_values(
attribute_errors[AttributeInputErrors.ERROR_BLANK_VALUE].append(
attribute_id
)
- elif not is_numeric and len(value) > name_field.max_length:
- attribute_errors[AttributeInputErrors.ERROR_MAX_LENGTH].append(attribute_id)
elif is_numeric:
try:
float(value)
@@ -765,6 +781,8 @@ def validate_values(
attribute_errors[
AttributeInputErrors.ERROR_NUMERIC_VALUE_REQUIRED
].append(attribute_id)
+ elif len(value) > name_field.max_length:
+ attribute_errors[AttributeInputErrors.ERROR_MAX_LENGTH].append(attribute_id)
def validate_required_attributes(
diff --git a/saleor/graphql/page/tests/mutations/test_page_create.py b/saleor/graphql/page/tests/mutations/test_page_create.py
index 9efce11fc9..bbe04d4263 100644
--- a/saleor/graphql/page/tests/mutations/test_page_create.py
+++ b/saleor/graphql/page/tests/mutations/test_page_create.py
@@ -39,6 +39,7 @@ CREATE_PAGE_MUTATION = """
reference
date
dateTime
+ plainText
file {
url
contentType
@@ -412,6 +413,7 @@ def test_create_page_with_file_attribute(
"contentType": None,
},
"reference": None,
+ "plainText": None,
"date": None,
"dateTime": None,
}
@@ -489,6 +491,7 @@ def test_create_page_with_file_attribute_new_attribute_value(
"url": "http://testserver/media/" + new_value,
"contentType": new_value_content_type,
},
+ "plainText": None,
"date": None,
"dateTime": None,
}
@@ -658,6 +661,7 @@ def test_create_page_with_page_reference_attribute(
"file": None,
"name": page.title,
"reference": reference,
+ "plainText": None,
"date": None,
"dateTime": None,
}
@@ -717,6 +721,7 @@ def test_create_page_with_date_attribute(
{
"file": None,
"reference": None,
+ "plainText": None,
"dateTime": None,
"date": str(date_value),
"name": str(date_value),
@@ -776,6 +781,7 @@ def test_create_page_with_date_time_attribute(
{
"file": None,
"reference": None,
+ "plainText": None,
"dateTime": date_time_value.isoformat(),
"date": None,
"name": str(date_time_value),
@@ -787,6 +793,66 @@ def test_create_page_with_date_time_attribute(
assert expected_attributes_data in data["page"]["attributes"]
+def test_create_page_with_plain_text_attribute(
+ staff_api_client,
+ permission_manage_pages,
+ page_type,
+ plain_text_attribute_page_type,
+ page,
+):
+ # given
+ page_type.page_attributes.add(plain_text_attribute_page_type)
+
+ page_title = "test title"
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
+ plain_text_attribute_id = graphene.Node.to_global_id(
+ "Attribute", plain_text_attribute_page_type.id
+ )
+ text = "test plain text attribute content"
+
+ variables = {
+ "input": {
+ "title": page_title,
+ "pageType": page_type_id,
+ "attributes": [
+ {"id": plain_text_attribute_id, "plainText": text},
+ ],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageCreate"]
+ errors = data["errors"]
+
+ assert not errors
+ assert data["page"]["title"] == page_title
+ assert data["page"]["pageType"]["id"] == page_type_id
+ page_id = data["page"]["id"]
+ _, new_page_pk = graphene.Node.from_global_id(page_id)
+ expected_attributes_data = {
+ "attribute": {"slug": plain_text_attribute_page_type.slug},
+ "values": [
+ {
+ "file": None,
+ "reference": None,
+ "dateTime": None,
+ "date": None,
+ "name": text,
+ "plainText": text,
+ "slug": f"{new_page_pk}_{plain_text_attribute_page_type.id}",
+ }
+ ],
+ }
+
+ assert expected_attributes_data in data["page"]["attributes"]
+
+
def test_create_page_with_page_reference_attribute_not_required_no_references_given(
staff_api_client,
permission_manage_pages,
@@ -955,6 +1021,7 @@ def test_create_page_with_product_reference_attribute(
"file": None,
"name": product.name,
"reference": reference,
+ "plainText": None,
"dateTime": None,
"date": None,
}
diff --git a/saleor/graphql/page/tests/mutations/test_page_update.py b/saleor/graphql/page/tests/mutations/test_page_update.py
index 43ae64d1be..80ae0f8c80 100644
--- a/saleor/graphql/page/tests/mutations/test_page_update.py
+++ b/saleor/graphql/page/tests/mutations/test_page_update.py
@@ -43,6 +43,7 @@ UPDATE_PAGE_MUTATION = """
url
contentType
}
+ plainText
}
}
}
@@ -98,7 +99,13 @@ def test_update_page(staff_api_client, permission_manage_pages, page):
for attr in page_type.page_attributes.all():
if attr.slug != tag_attr.slug:
values = [
- {"slug": slug, "file": None, "name": name, "reference": None}
+ {
+ "slug": slug,
+ "file": None,
+ "name": name,
+ "reference": None,
+ "plainText": None,
+ }
for slug, name in page_attr.filter(
assignment__attribute=attr
).values_list("values__slug", "values__name")
@@ -109,6 +116,7 @@ def test_update_page(staff_api_client, permission_manage_pages, page):
"slug": slugify(new_value),
"file": None,
"name": new_value,
+ "plainText": None,
"reference": None,
}
]
@@ -215,7 +223,13 @@ def test_update_page_only_title(staff_api_client, permission_manage_pages, page)
page_attr = page.attributes.all()
for attr in page_type.page_attributes.all():
values = [
- {"slug": slug, "file": None, "name": name, "reference": None}
+ {
+ "slug": slug,
+ "file": None,
+ "name": name,
+ "reference": None,
+ "plainText": None,
+ }
for slug, name in page_attr.filter(assignment__attribute=attr).values_list(
"values__slug", "values__name"
)
@@ -269,6 +283,7 @@ def test_update_page_with_file_attribute_value(
{
"slug": slugify(new_value),
"name": new_value,
+ "plainText": None,
"reference": None,
"file": {
"url": "http://testserver/media/" + new_value,
@@ -322,6 +337,7 @@ def test_update_page_with_file_attribute_new_value_is_not_created(
{
"slug": existing_value.slug,
"name": existing_value.name,
+ "plainText": None,
"reference": None,
"file": {
"url": f"http://testserver/media/{existing_value.file_url}",
@@ -413,6 +429,7 @@ def test_update_page_with_page_reference_attribute_new_value(
"slug": f"{page.pk}_{ref_page.pk}",
"name": page.title,
"file": None,
+ "plainText": None,
"reference": reference,
}
],
@@ -478,6 +495,7 @@ def test_update_page_with_page_reference_attribute_existing_value(
"slug": attr_value.slug,
"file": None,
"name": page.title,
+ "plainText": None,
"reference": reference,
}
],
@@ -488,6 +506,168 @@ def test_update_page_with_page_reference_attribute_existing_value(
assert page_type_page_reference_attribute.values.count() == values_count
+def test_update_page_with_plain_text_attribute_new_value(
+ staff_api_client,
+ permission_manage_pages,
+ page_list,
+ plain_text_attribute_page_type,
+):
+ # given
+ query = UPDATE_PAGE_MUTATION
+
+ page = page_list[0]
+ page_type = page.page_type
+ page_type.page_attributes.add(plain_text_attribute_page_type)
+
+ values_count = plain_text_attribute_page_type.values.count()
+ attribute_id = graphene.Node.to_global_id(
+ "Attribute", plain_text_attribute_page_type.pk
+ )
+ text = "test plain text attribute content"
+
+ page_id = graphene.Node.to_global_id("Page", page.id)
+
+ variables = {
+ "id": page_id,
+ "input": {"attributes": [{"id": attribute_id, "plainText": text}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_pages]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageUpdate"]
+
+ assert not data["errors"]
+ assert data["page"]
+ updated_attribute = {
+ "attribute": {"slug": plain_text_attribute_page_type.slug},
+ "values": [
+ {
+ "slug": f"{page.pk}_{plain_text_attribute_page_type.pk}",
+ "name": text,
+ "file": None,
+ "reference": None,
+ "plainText": text,
+ }
+ ],
+ }
+ assert updated_attribute in data["page"]["attributes"]
+
+ plain_text_attribute_page_type.refresh_from_db()
+ assert plain_text_attribute_page_type.values.count() == values_count + 1
+
+
+def test_update_page_with_plain_text_attribute_existing_value(
+ staff_api_client,
+ permission_manage_pages,
+ page_list,
+ plain_text_attribute_page_type,
+):
+ # given
+ query = UPDATE_PAGE_MUTATION
+
+ page = page_list[0]
+ page_type = page.page_type
+ page_type.page_attributes.add(plain_text_attribute_page_type)
+
+ values_count = plain_text_attribute_page_type.values.count()
+ attribute_id = graphene.Node.to_global_id(
+ "Attribute", plain_text_attribute_page_type.pk
+ )
+ attribute_value = plain_text_attribute_page_type.values.first()
+ attribute_value.slug = f"{page.pk}_{plain_text_attribute_page_type.pk}"
+ attribute_value.save(update_fields=["slug"])
+
+ text = attribute_value.plain_text
+
+ page_id = graphene.Node.to_global_id("Page", page.id)
+
+ variables = {
+ "id": page_id,
+ "input": {"attributes": [{"id": attribute_id, "plainText": text}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_pages]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageUpdate"]
+
+ assert not data["errors"]
+ assert data["page"]
+ updated_attribute = {
+ "attribute": {"slug": plain_text_attribute_page_type.slug},
+ "values": [
+ {
+ "slug": attribute_value.slug,
+ "name": text,
+ "file": None,
+ "reference": None,
+ "plainText": text,
+ }
+ ],
+ }
+ assert updated_attribute in data["page"]["attributes"]
+
+ plain_text_attribute_page_type.refresh_from_db()
+ assert plain_text_attribute_page_type.values.count() == values_count
+
+
[email protected]("value", ["", " ", None])
+def test_update_page_with_required_plain_text_attribute_empty_value(
+ value,
+ staff_api_client,
+ permission_manage_pages,
+ page_list,
+ plain_text_attribute_page_type,
+):
+ # given
+ query = UPDATE_PAGE_MUTATION
+
+ page = page_list[0]
+ page_type = page.page_type
+ page_type.page_attributes.add(plain_text_attribute_page_type)
+
+ attribute_id = graphene.Node.to_global_id(
+ "Attribute", plain_text_attribute_page_type.pk
+ )
+ attribute_value = plain_text_attribute_page_type.values.first()
+ attribute_value.slug = f"{page.pk}_{plain_text_attribute_page_type.pk}"
+ attribute_value.save(update_fields=["slug"])
+
+ plain_text_attribute_page_type.value_required = True
+ plain_text_attribute_page_type.save(update_fields=["value_required"])
+
+ page_id = graphene.Node.to_global_id("Page", page.id)
+
+ variables = {
+ "id": page_id,
+ "input": {"attributes": [{"id": attribute_id, "plainText": value}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_pages]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageUpdate"]
+ errors = data["errors"]
+
+ assert not data["page"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PageErrorCode.REQUIRED.name
+ assert errors[0]["field"] == "attributes"
+
+
def test_update_page_with_product_reference_attribute_new_value(
staff_api_client,
permission_manage_pages,
@@ -532,6 +712,7 @@ def test_update_page_with_product_reference_attribute_new_value(
"slug": f"{page.pk}_{product.pk}",
"name": product.name,
"file": None,
+ "plainText": None,
"reference": reference,
}
],
@@ -597,6 +778,7 @@ def test_update_page_with_product_reference_attribute_existing_value(
"file": None,
"name": page.title,
"reference": reference,
+ "plainText": None,
}
],
}
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 3df5f4195e..a6195b8be8 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -3064,6 +3064,54 @@ def test_products_query_with_filter_search_by_rich_text_attribute(
assert products[0]["node"]["name"] == product_with_rich_text_attr.name
[email protected]("search_value", ["plain", "test plain", "PLAIN text"])
+def test_products_query_with_filter_search_by_plain_text_attribute(
+ search_value,
+ query_products_with_filter,
+ staff_api_client,
+ product_list,
+ permission_manage_products,
+ channel_USD,
+ plain_text_attribute,
+):
+ # given
+ product_with_plain_text_attr = product_list[1]
+
+ product_type = product_with_plain_text_attr.product_type
+ product_type.product_attributes.add(plain_text_attribute)
+
+ plain_text_value = plain_text_attribute.values.first()
+ plain_text_value.plain_text = "Test plain text."
+ plain_text_value.save(update_fields=["plain_text"])
+
+ associate_attribute_values_to_instance(
+ product_with_plain_text_attr, plain_text_attribute, plain_text_value
+ )
+
+ product_with_plain_text_attr.refresh_from_db()
+
+ product_with_plain_text_attr.search_vector = prepare_product_search_vector_value(
+ product_with_plain_text_attr
+ )
+ product_with_plain_text_attr.save(update_fields=["search_vector"])
+
+ variables = {"filter": {"search": search_value}, "channel": channel_USD.slug}
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ # then
+ response = staff_api_client.post_graphql(query_products_with_filter, variables)
+ content = get_graphql_content(response)
+ products = content["data"]["products"]["edges"]
+
+ assert len(products) == 1
+ assert products[0]["node"]["id"] == graphene.Node.to_global_id(
+ "Product", product_with_plain_text_attr.id
+ )
+ assert products[0]["node"]["name"] == product_with_plain_text_attr.name
+
+
@pytest.mark.parametrize("search_value", ["13456", "13456 cm"])
def test_products_query_with_filter_search_by_numeric_attribute_value(
search_value,
@@ -4261,6 +4309,7 @@ CREATE_PRODUCT_MUTATION = """
name
reference
richText
+ plainText
boolean
dateTime
date
@@ -4477,6 +4526,7 @@ def test_create_product_with_rich_text_attribute(
),
"reference": None,
"richText": rich_text,
+ "plainText": None,
"file": None,
"boolean": None,
"date": None,
@@ -4537,6 +4587,135 @@ def test_create_product_no_value_for_rich_text_attribute(
assert expected_attributes_data in data["product"]["attributes"]
+def test_create_product_with_plain_text_attribute(
+ staff_api_client,
+ product_type,
+ category,
+ plain_text_attribute,
+ color_attribute,
+ permission_manage_products,
+):
+ # given
+ 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"
+ product_slug = "product-test-slug"
+
+ # Add second attribute
+ product_type.product_attributes.add(plain_text_attribute)
+ plain_text_attribute_id = graphene.Node.to_global_id(
+ "Attribute", plain_text_attribute.id
+ )
+ text_value = "test product" * 5
+
+ # test creating root product
+ variables = {
+ "input": {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "slug": product_slug,
+ "attributes": [
+ {
+ "id": plain_text_attribute_id,
+ "plainText": text_value,
+ }
+ ],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productCreate"]
+ assert data["errors"] == []
+ assert data["product"]["name"] == product_name
+ assert data["product"]["slug"] == product_slug
+ 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": plain_text_attribute.slug},
+ "values": [
+ {
+ "slug": f"{product_id}_{plain_text_attribute.id}",
+ "name": text_value,
+ "reference": None,
+ "richText": None,
+ "plainText": text_value,
+ "file": None,
+ "boolean": None,
+ "date": None,
+ "dateTime": None,
+ }
+ ],
+ },
+ ]
+
+ for attr_data in data["product"]["attributes"]:
+ assert attr_data in expected_attributes_data
+
+
+def test_create_product_no_value_for_plain_text_attribute(
+ staff_api_client,
+ product_type,
+ plain_text_attribute,
+ permission_manage_products,
+):
+ # given
+ """Ensure mutation not fail when as attributes input only plain text attribute id
+ is provided."""
+ query = CREATE_PRODUCT_MUTATION
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ product_name = "test name"
+
+ # Add second attribute
+ product_type.product_attributes.add(plain_text_attribute)
+ plain_text_attribute_id = graphene.Node.to_global_id(
+ "Attribute", plain_text_attribute.id
+ )
+
+ # test creating root product
+ variables = {
+ "input": {
+ "productType": product_type_id,
+ "name": product_name,
+ "attributes": [
+ {
+ "id": plain_text_attribute_id,
+ }
+ ],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productCreate"]
+ assert data["errors"] == []
+ assert data["product"]["name"] == product_name
+ assert data["product"]["productType"]["name"] == product_type.name
+ expected_attributes_data = {
+ "attribute": {"slug": plain_text_attribute.slug},
+ "values": [],
+ }
+ assert expected_attributes_data in data["product"]["attributes"]
+
+
@freeze_time(datetime(2020, 5, 5, 5, 5, 5, tzinfo=pytz.utc))
def test_create_product_with_date_time_attribute(
staff_api_client,
@@ -4589,6 +4768,7 @@ def test_create_product_with_date_time_attribute(
"name": str(value),
"reference": None,
"richText": None,
+ "plainText": None,
"boolean": None,
"file": None,
"date": None,
@@ -4650,6 +4830,7 @@ def test_create_product_with_date_attribute(
"name": str(value),
"reference": None,
"richText": None,
+ "plainText": None,
"boolean": None,
"file": None,
"date": str(value),
@@ -4755,6 +4936,7 @@ def test_create_product_with_boolean_attribute(
"name": "Boolean: No",
"reference": None,
"richText": None,
+ "plainText": None,
"boolean": False,
"date": None,
"dateTime": None,
@@ -5079,6 +5261,7 @@ def test_create_product_with_file_attribute(
},
"reference": None,
"richText": None,
+ "plainText": None,
"boolean": None,
"date": None,
"dateTime": None,
@@ -5150,6 +5333,7 @@ def test_create_product_with_page_reference_attribute(
"name": page.title,
"file": None,
"richText": None,
+ "plainText": None,
"boolean": None,
"date": None,
"dateTime": None,
@@ -5222,6 +5406,7 @@ def test_create_product_with_product_reference_attribute(
"name": product.name,
"file": None,
"richText": None,
+ "plainText": None,
"boolean": None,
"date": None,
"dateTime": None,
@@ -5294,6 +5479,7 @@ def test_create_product_with_product_reference_attribute_values_saved_in_order(
"name": product.name,
"file": None,
"richText": None,
+ "plainText": None,
"boolean": None,
"date": None,
"dateTime": None,
@@ -5420,6 +5606,7 @@ def test_create_product_with_file_attribute_new_attribute_value(
"slug": slugify(non_existing_value, allow_unicode=True),
"reference": None,
"richText": None,
+ "plainText": None,
"boolean": None,
"date": None,
"dateTime": None,
@@ -8978,6 +9165,7 @@ PRODUCT_TYPE_CREATE_MUTATION = """
node {
name
richText
+ plainText
boolean
date
dateTime
@@ -9189,6 +9377,7 @@ def test_create_product_type_with_rich_text_attribute(
"node": {
"name": "Red",
"richText": None,
+ "plainText": None,
"boolean": None,
"date": None,
"dateTime": None,
@@ -9198,6 +9387,7 @@ def test_create_product_type_with_rich_text_attribute(
"node": {
"name": "Blue",
"richText": None,
+ "plainText": None,
"boolean": None,
"date": None,
"dateTime": None,
@@ -9215,6 +9405,46 @@ def test_create_product_type_with_rich_text_attribute(
assert attribute in expected_attributes
+def test_create_product_type_with_plain_text_attribute(
+ staff_api_client,
+ product_type,
+ permission_manage_product_types_and_attributes,
+ plain_text_attribute,
+):
+ query = PRODUCT_TYPE_CREATE_MUTATION
+ product_type_name = "test type"
+ slug = "test-type"
+
+ product_type.product_attributes.add(plain_text_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,
+ "kind": ProductTypeKindEnum.NORMAL.name,
+ "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
+ expected_plain_text_attribute = {
+ "name": plain_text_attribute.name,
+ "choices": {"edges": []},
+ }
+ assert expected_plain_text_attribute in data["productAttributes"]
+
+
def test_create_product_type_with_date_attribute(
staff_api_client,
product_type,
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index 86d9140eda..91c0366b7d 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -520,6 +520,7 @@ CREATE_VARIANT_MUTATION = """
slug
reference
richText
+ plainText
boolean
date
dateTime
@@ -829,6 +830,7 @@ def test_create_variant_with_boolean_attribute(
"slug": f"{boolean_attribute.id}_true",
"reference": None,
"richText": None,
+ "plainText": None,
"boolean": True,
"file": None,
"dateTime": None,
@@ -1031,6 +1033,7 @@ def test_create_variant_with_page_reference_attribute(
"slug": f"{variant_pk}_{page_list[0].pk}",
"file": None,
"richText": None,
+ "plainText": None,
"reference": page_ref_1,
"name": page_list[0].title,
"boolean": None,
@@ -1041,6 +1044,7 @@ def test_create_variant_with_page_reference_attribute(
"slug": f"{variant_pk}_{page_list[1].pk}",
"file": None,
"richText": None,
+ "plainText": None,
"reference": page_ref_2,
"name": page_list[1].title,
"boolean": None,
@@ -1187,6 +1191,7 @@ def test_create_variant_with_product_reference_attribute(
"slug": f"{variant_pk}_{product_list[0].pk}",
"file": None,
"richText": None,
+ "plainText": None,
"reference": product_ref_1,
"name": product_list[0].name,
"boolean": None,
@@ -1197,6 +1202,7 @@ def test_create_variant_with_product_reference_attribute(
"slug": f"{variant_pk}_{product_list[1].pk}",
"file": None,
"richText": None,
+ "plainText": None,
"reference": product_ref_2,
"name": product_list[1].name,
"boolean": None,
@@ -1654,6 +1660,62 @@ def test_create_variant_with_rich_text_attribute(
created_webhook_mock.assert_called_once_with(product.variants.last())
+@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
+def test_create_variant_with_plain_text_attribute(
+ created_webhook_mock,
+ permission_manage_products,
+ product,
+ product_type,
+ staff_api_client,
+ plain_text_attribute,
+ warehouse,
+):
+ # given
+ product_type.variant_attributes.add(plain_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", plain_text_attribute.id)
+ text = "Sample text"
+ stocks = [
+ {
+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
+ "quantity": 20,
+ }
+ ]
+ variables = {
+ "productId": product_id,
+ "sku": sku,
+ "stocks": stocks,
+ "costPrice": cost_price,
+ "price": price,
+ "weight": weight,
+ "attributes": [
+ {"id": attr_id, "plainText": text},
+ ],
+ "trackInventory": True,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)["data"]["productVariantCreate"]
+ flush_post_commit_hooks()
+ data = content["productVariant"]
+
+ assert not content["errors"]
+ assert data["name"] == sku
+ assert data["sku"] == sku
+ assert data["attributes"][-1]["values"][0]["plainText"] == text
+ created_webhook_mock.assert_called_once_with(product.variants.last())
+
+
@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
@freeze_time(datetime(2020, 5, 5, 5, 5, 5, tzinfo=pytz.utc))
def test_create_variant_with_date_attribute(
@@ -1701,6 +1763,7 @@ def test_create_variant_with_date_attribute(
"file": None,
"reference": None,
"richText": None,
+ "plainText": None,
"dateTime": None,
"date": str(date_value),
"name": str(date_value),
@@ -1764,6 +1827,7 @@ def test_create_variant_with_date_time_attribute(
"file": None,
"reference": None,
"richText": None,
+ "plainText": None,
"dateTime": date_time_value.isoformat(),
"date": None,
"name": str(date_time_value),
@@ -2225,6 +2289,7 @@ QUERY_UPDATE_VARIANT_ATTRIBUTES = """
}
reference
richText
+ plainText
boolean
date
dateTime
@@ -2410,6 +2475,110 @@ def test_update_variant_with_rich_text_attribute(
product_variant_updated.assert_called_once_with(product.variants.last())
+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
+def test_update_variant_with_plain_text_attribute(
+ product_variant_updated,
+ permission_manage_products,
+ product,
+ product_type,
+ staff_api_client,
+ plain_text_attribute,
+ warehouse,
+):
+ # given
+ product_type.variant_attributes.add(plain_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", plain_text_attribute.id)
+ plain_text_attribute_value = plain_text_attribute.values.first()
+ text = plain_text_attribute_value.plain_text
+ variables = {
+ "id": variant_id,
+ "sku": sku,
+ "attributes": [
+ {"id": attr_id, "plainText": text},
+ ],
+ }
+ plain_text_attribute_value.slug = f"{variant.id}_{plain_text_attribute.id}"
+ plain_text_attribute_value.save()
+ values_count = plain_text_attribute.values.count()
+ associate_attribute_values_to_instance(
+ variant, plain_text_attribute, plain_text_attribute.values.first()
+ )
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ 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"] == plain_text_attribute.slug
+ assert data["attributes"][-1]["values"][0]["plainText"] == text
+ assert plain_text_attribute.values.count() == values_count
+ product_variant_updated.assert_called_once_with(product.variants.last())
+
+
[email protected]("value", ["", " ", None])
+def test_update_variant_with_required_plain_text_attribute_no_value(
+ value,
+ permission_manage_products,
+ product,
+ product_type,
+ staff_api_client,
+ plain_text_attribute,
+):
+ # given
+ product_type.variant_attributes.add(plain_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", plain_text_attribute.id)
+
+ plain_text_attribute_value = plain_text_attribute.values.first()
+ plain_text_attribute_value.slug = f"{variant.id}_{plain_text_attribute.id}"
+ plain_text_attribute_value.save()
+
+ associate_attribute_values_to_instance(
+ variant, plain_text_attribute, plain_text_attribute.values.first()
+ )
+
+ plain_text_attribute.value_required = True
+ plain_text_attribute.save(update_fields=["value_required"])
+
+ variables = {
+ "id": variant_id,
+ "sku": sku,
+ "attributes": [
+ {"id": attr_id, "plainText": value},
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)["data"]["productVariantUpdate"]
+ variant.refresh_from_db()
+ data = content["productVariant"]
+ errors = content["errors"]
+
+ assert not data
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.REQUIRED.name
+ assert errors[0]["field"] == "attributes"
+
+
@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
def test_update_variant_with_date_attribute(
product_variant_updated,
@@ -2454,6 +2623,7 @@ def test_update_variant_with_date_attribute(
"file": None,
"reference": None,
"richText": None,
+ "plainText": None,
"dateTime": None,
"date": str(date_value),
"name": str(date_value),
@@ -2515,6 +2685,7 @@ def test_update_variant_with_date_time_attribute(
"file": None,
"reference": None,
"richText": None,
+ "plainText": None,
"dateTime": date_time_value.isoformat(),
"date": None,
"name": str(date_time_value),
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index a0c14f8c0d..e10c1d9796 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -4103,6 +4103,7 @@ enum AttributeInputTypeEnum {
REFERENCE
NUMERIC
RICH_TEXT
+ PLAIN_TEXT
SWATCH
BOOLEAN
DATE
@@ -4209,6 +4210,11 @@ type AttributeValue implements Node {
"""
richText: JSONString
+ """
+ Represents the text of the attribute value, plain text without formating.
+ """
+ plainText: String
+
"""Represents the boolean value of the attribute value."""
boolean: Boolean
@@ -4232,6 +4238,9 @@ type AttributeValueTranslation implements Node {
Rich text format. For reference see https://editorjs.io/
"""
richText: JSONString
+
+ """Attribute plain text value."""
+ plainText: String
}
type File {
@@ -5807,6 +5816,9 @@ type AttributeValueTranslatableContent implements Node {
"""
richText: JSONString
+ """Attribute plain text value."""
+ plainText: String
+
"""Returns translated attribute value fields for the given language code."""
translation(
"""A language code to return the translation for attribute value."""
@@ -15277,6 +15289,9 @@ input AttributeValueInput {
"""Text content in JSON format."""
richText: JSONString
+ """Plain text content."""
+ plainText: String
+
"""Represents the boolean value of the attribute value."""
boolean: Boolean
@@ -19406,6 +19421,11 @@ input AttributeValueCreateInput {
"""
richText: JSONString
+ """
+ Represents the text of the attribute value, plain text without formating.
+ """
+ plainText: String
+
"""URL of the file attribute. Every time, a new value is created."""
fileUrl: String
@@ -19491,6 +19511,11 @@ input AttributeValueUpdateInput {
"""
richText: JSONString
+ """
+ Represents the text of the attribute value, plain text without formating.
+ """
+ plainText: String
+
"""URL of the file attribute. Every time, a new value is created."""
fileUrl: String
@@ -19595,6 +19620,9 @@ input AttributeValueTranslationInput {
Rich text format. For reference see https://editorjs.io/
"""
richText: JSONString
+
+ """Translated text."""
+ plainText: String
}
"""
diff --git a/saleor/graphql/translations/mutations.py b/saleor/graphql/translations/mutations.py
index 89acc5907d..8fe4c108b0 100644
--- a/saleor/graphql/translations/mutations.py
+++ b/saleor/graphql/translations/mutations.py
@@ -137,6 +137,7 @@ class NameTranslationInput(graphene.InputObjectType):
class AttributeValueTranslationInput(NameTranslationInput):
rich_text = JSONString(description="Translated text." + RICH_CONTENT)
+ plain_text = graphene.String(description="Translated text.")
class SeoTranslationInput(graphene.InputObjectType):
diff --git a/saleor/graphql/translations/tests/test_translations.py b/saleor/graphql/translations/tests/test_translations.py
index f6481be500..a579c59ed4 100644
--- a/saleor/graphql/translations/tests/test_translations.py
+++ b/saleor/graphql/translations/tests/test_translations.py
@@ -7,6 +7,7 @@ from django.contrib.auth.models import Permission
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
+from ....attribute.utils import associate_attribute_values_to_instance
from ....tests.utils import dummy_editorjs
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.payloads import generate_translation_payload
@@ -3115,21 +3116,7 @@ def test_product_and_attribute_translation(user_api_client, product, channel_USD
assert attribute_translation_data["language"]["code"] == "PL"
-def test_product_attribute_value_rich_text_translation(
- staff_api_client,
- product_with_rich_text_attribute,
- permission_manage_translations,
-):
- rich_text = dummy_editorjs("Test_dummy_data")
- assigned_attribute = product_with_rich_text_attribute[0].attributes.first()
- attribute_value = assigned_attribute.attribute.values.first()
- attribute_value.translations.create(language_code="pl", rich_text=rich_text)
-
- product_id = graphene.Node.to_global_id(
- "Product", product_with_rich_text_attribute[0].id
- )
-
- query = """
+PRODUCT_ATTRIBUTE_VALUES_TRANSLATION_QUERY = """
query translation(
$kind: TranslatableKinds!
$id: ID!
@@ -3141,24 +3128,47 @@ def test_product_attribute_value_rich_text_translation(
attributeValues {
name
richText
+ plainText
translation(languageCode: $languageCode) {
name
richText
+ plainText
}
}
}
}
}
"""
+
+
+def test_product_attribute_value_rich_text_translation(
+ staff_api_client,
+ product_with_rich_text_attribute,
+ permission_manage_translations,
+):
+ # given
+ rich_text = dummy_editorjs("Test_dummy_data")
+ assigned_attribute = product_with_rich_text_attribute[0].attributes.first()
+ attribute_value = assigned_attribute.attribute.values.first()
+ attribute_value.translations.create(language_code="pl", rich_text=rich_text)
+
+ product_id = graphene.Node.to_global_id(
+ "Product", product_with_rich_text_attribute[0].id
+ )
+
+ query = PRODUCT_ATTRIBUTE_VALUES_TRANSLATION_QUERY
variables = {
"id": product_id,
"kind": TranslatableKinds.PRODUCT.name,
"languageCode": LanguageCodeEnum.PL.name,
}
+ # when
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_translations]
)
+
+ # then
data = get_graphql_content(response)["data"]
attribute_value_response = data["translation"]["attributeValues"][0]
@@ -3167,12 +3177,79 @@ def test_product_attribute_value_rich_text_translation(
assert attribute_value_response["translation"]["richText"] == json.dumps(rich_text)
+def test_product_attribute_value_plain_text_translation(
+ staff_api_client,
+ plain_text_attribute,
+ product,
+ permission_manage_translations,
+):
+ # given
+ product_type = product.product_type
+ product_type.product_attributes.set([plain_text_attribute])
+
+ product_attr_value = plain_text_attribute.values.first()
+ associate_attribute_values_to_instance(
+ product, plain_text_attribute, product_attr_value
+ )
+
+ text = "Test plain text translation"
+ product_attr_value.translations.create(language_code="pl", plain_text=text)
+
+ product_id = graphene.Node.to_global_id("Product", product.id)
+
+ query = PRODUCT_ATTRIBUTE_VALUES_TRANSLATION_QUERY
+ variables = {
+ "id": product_id,
+ "kind": TranslatableKinds.PRODUCT.name,
+ "languageCode": LanguageCodeEnum.PL.name,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_translations]
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]
+
+ attribute_value_response = data["translation"]["attributeValues"][0]
+ assert attribute_value_response["name"] == product_attr_value.name
+ assert attribute_value_response["plainText"] == product_attr_value.plain_text
+ assert attribute_value_response["translation"]["plainText"] == text
+
+
+PRODUCT_VARIANT_ATTRIBUTE_VALUES_TRANSLATION_QUERY = """
+ query translation(
+ $kind: TranslatableKinds!
+ $id: ID!
+ $languageCode: LanguageCodeEnum!
+ ) {
+ translation(kind: $kind, id: $id) {
+ ... on ProductVariantTranslatableContent {
+ name
+ attributeValues {
+ name
+ richText
+ plainText
+ translation(languageCode: $languageCode) {
+ name
+ richText
+ plainText
+ }
+ }
+ }
+ }
+ }
+"""
+
+
def test_product_variant_attribute_value_rich_text_translation(
staff_api_client,
product_with_rich_text_attribute,
permission_manage_translations,
product_type_with_rich_text_attribute,
):
+ # given
rich_text = dummy_editorjs("Test_dummy_data")
variant_attr = product_type_with_rich_text_attribute.variant_attributes.first()
attribute_value = variant_attr.values.first()
@@ -3182,36 +3259,19 @@ def test_product_variant_attribute_value_rich_text_translation(
"ProductVariant", product_with_rich_text_attribute[1].id
)
- query = """
- query translation(
- $kind: TranslatableKinds!
- $id: ID!
- $languageCode: LanguageCodeEnum!
- ) {
- translation(kind: $kind, id: $id) {
- ... on ProductVariantTranslatableContent {
- name
- attributeValues {
- name
- richText
- translation(languageCode: $languageCode) {
- name
- richText
- }
- }
- }
- }
- }
- """
+ query = PRODUCT_VARIANT_ATTRIBUTE_VALUES_TRANSLATION_QUERY
variables = {
"id": variant_id,
"kind": TranslatableKinds.VARIANT.name,
"languageCode": LanguageCodeEnum.PL.name,
}
+ # when
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_translations]
)
+
+ # then
data = get_graphql_content(response)["data"]
translations_response = data["translation"]["attributeValues"][0]
@@ -3220,6 +3280,71 @@ def test_product_variant_attribute_value_rich_text_translation(
assert translations_response["translation"]["richText"] == json.dumps(rich_text)
+def test_product_variant_attribute_value_plain_text_translation(
+ staff_api_client,
+ variant,
+ plain_text_attribute,
+ permission_manage_translations,
+):
+ # given
+ product_type = variant.product.product_type
+ product_type.variant_attributes.set([plain_text_attribute])
+
+ attribute_value = plain_text_attribute.values.first()
+ associate_attribute_values_to_instance(
+ variant, plain_text_attribute, attribute_value
+ )
+
+ text = "Test plain text translation"
+ attribute_value.translations.create(language_code="pl", plain_text=text)
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ query = PRODUCT_VARIANT_ATTRIBUTE_VALUES_TRANSLATION_QUERY
+ variables = {
+ "id": variant_id,
+ "kind": TranslatableKinds.VARIANT.name,
+ "languageCode": LanguageCodeEnum.PL.name,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_translations]
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]
+
+ translations_response = data["translation"]["attributeValues"][0]
+ assert translations_response["name"] == attribute_value.name
+ assert translations_response["plainText"] == attribute_value.plain_text
+ assert translations_response["translation"]["plainText"] == text
+
+
+PAGE_ATTRIBUTE_VALUES_TRANSLATION_QUERY = """
+ query translation(
+ $kind: TranslatableKinds!
+ $id: ID!
+ $languageCode: LanguageCodeEnum!
+ ) {
+ translation(kind: $kind, id: $id) {
+ ... on PageTranslatableContent {
+ attributeValues {
+ name
+ richText
+ plainText
+ translation(languageCode: $languageCode) {
+ name
+ richText
+ plainText
+ }
+ }
+ }
+ }
+ }
+"""
+
+
def test_page_attribute_value_rich_text_translation(
staff_api_client,
page_with_rich_text_attribute,
@@ -3234,27 +3359,7 @@ def test_page_attribute_value_rich_text_translation(
page_id = graphene.Node.to_global_id("Page", page_with_rich_text_attribute.id)
- query = """
- query translation(
- $kind: TranslatableKinds!
- $id: ID!
- $languageCode: LanguageCodeEnum!
- ) {
- translation(kind: $kind, id: $id) {
- ... on PageTranslatableContent {
- attributeValues {
- name
- richText
- translation(languageCode: $languageCode) {
- name
- richText
- }
- }
- }
- }
- }
-
- """
+ query = PAGE_ATTRIBUTE_VALUES_TRANSLATION_QUERY
variables = {
"id": page_id,
@@ -3270,3 +3375,46 @@ def test_page_attribute_value_rich_text_translation(
assert attribute_value_response["name"] == attribute_value.name
assert attribute_value_response["richText"] == json.dumps(attribute_value.rich_text)
assert attribute_value_response["translation"]["richText"] == json.dumps(rich_text)
+
+
+def test_page_attribute_value_plain_text_translation(
+ staff_api_client,
+ plain_text_attribute_page_type,
+ page,
+ permission_manage_translations,
+ permission_manage_pages,
+):
+ # given
+ page_type = page.page_type
+ page_type.page_attributes.set([plain_text_attribute_page_type])
+ attribute_value = plain_text_attribute_page_type.values.first()
+
+ associate_attribute_values_to_instance(
+ page, plain_text_attribute_page_type, attribute_value
+ )
+
+ text = "Test plain text translation"
+ attribute_value.translations.create(language_code="pl", plain_text=text)
+
+ page_id = graphene.Node.to_global_id("Page", page.id)
+
+ query = PAGE_ATTRIBUTE_VALUES_TRANSLATION_QUERY
+
+ variables = {
+ "id": page_id,
+ "kind": TranslatableKinds.PAGE.name,
+ "languageCode": LanguageCodeEnum.PL.name,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_translations]
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]
+
+ attribute_value_response = data["translation"]["attributeValues"][0]
+ assert attribute_value_response["name"] == attribute_value.name
+ assert attribute_value_response["plainText"] == attribute_value.plain_text
+ assert attribute_value_response["translation"]["plainText"] == text
diff --git a/saleor/graphql/translations/types.py b/saleor/graphql/translations/types.py
index ace57b6cb5..f4d25b92d5 100644
--- a/saleor/graphql/translations/types.py
+++ b/saleor/graphql/translations/types.py
@@ -69,6 +69,7 @@ class AttributeValueTranslation(BaseTranslationType):
id = graphene.GlobalID(required=True)
name = graphene.String(required=True)
rich_text = JSONString(description="Attribute value." + RICH_CONTENT)
+ plain_text = graphene.String(description="Attribute plain text value.")
class Meta:
model = attribute_models.AttributeValueTranslation
@@ -79,6 +80,7 @@ class AttributeValueTranslatableContent(ModelObjectType):
id = graphene.GlobalID(required=True)
name = graphene.String(required=True)
rich_text = JSONString(description="Attribute value." + RICH_CONTENT)
+ plain_text = graphene.String(description="Attribute plain text value.")
translation = TranslationField(
AttributeValueTranslation, type_name="attribute value"
)
diff --git a/saleor/product/search.py b/saleor/product/search.py
index 86b90512d2..1f2f0cfbe6 100644
--- a/saleor/product/search.py
+++ b/saleor/product/search.py
@@ -122,6 +122,8 @@ def generate_attributes_search_vector_value(
values_list = [
clean_editor_js(value.rich_text, to_string=True) for value in values
]
+ elif input_type == AttributeInputType.PLAIN_TEXT:
+ values_list = [value.plain_text for value in values]
elif input_type == AttributeInputType.NUMERIC:
unit = attribute.unit
values_list = [
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 820076a98d..d103f12634 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -1354,6 +1354,48 @@ def rich_text_attribute_with_many_values(rich_text_attribute):
return rich_text_attribute
+def plain_text_attribute(db):
+ attribute = Attribute.objects.create(
+ slug="plain-text",
+ name="Plain text",
+ type=AttributeType.PRODUCT_TYPE,
+ input_type=AttributeInputType.PLAIN_TEXT,
+ filterable_in_storefront=False,
+ filterable_in_dashboard=False,
+ available_in_grid=False,
+ )
+ text = "Plain text attribute content."
+ AttributeValue.objects.create(
+ attribute=attribute,
+ name=truncatechars(text, 50),
+ slug=f"instance_{attribute.id}",
+ plain_text=text,
+ )
+ return attribute
+
+
+def plain_text_attribute_page_type(db):
+ attribute = Attribute.objects.create(
+ slug="plain-text",
+ name="Plain text",
+ type=AttributeType.PAGE_TYPE,
+ input_type=AttributeInputType.PLAIN_TEXT,
+ filterable_in_storefront=False,
+ filterable_in_dashboard=False,
+ available_in_grid=False,
+ )
+ text = "Plain text attribute content."
+ AttributeValue.objects.create(
+ attribute=attribute,
+ name=truncatechars(text, 50),
+ slug=f"instance_{attribute.id}",
+ plain_text=text,
+ )
+ return attribute
+
+
@pytest.fixture
def color_attribute_without_values(db): # pylint: disable=W0613
return Attribute.objects.create(
@@ -1832,9 +1874,7 @@ def shippable_gift_card_product_type(db):
@pytest.fixture
-def product_type_with_rich_text_attribute(
- rich_text_attribute, color_attribute, size_attribute
-):
+def product_type_with_rich_text_attribute(rich_text_attribute):
product_type = ProductType.objects.create(
name="Default Type",
slug="default-type",