Skip to content

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

Fix missing AttributeValueTranslation.name for RichText and PlainText attributes (#11001)

Filip Owczarek5b0e5206c5fd
diff --git a/saleor/attribute/migrations/0022_attribute_value_translations_propagate_names.py b/saleor/attribute/migrations/0022_attribute_value_translations_propagate_names.py
new file mode 100644
index 0000000000..fef0572644
--- /dev/null
+++ b/saleor/attribute/migrations/0022_attribute_value_translations_propagate_names.py
@@ -0,0 +1,149 @@
+# Generated by Django 3.2.16 on 2022-10-17 10:10
+
+import re
+import warnings
+from typing import Dict, Optional
+
+from django.db import migrations
+from django.template.defaultfilters import truncatechars
+from django.utils.html import strip_tags
+from urllib3.util import parse_url
+
+# Start copy of /saleor/core/utils/editorjs.py
+BLACKLISTED_URL_SCHEMES = ("javascript",)
+HYPERLINK_TAG_WITH_URL_PATTERN = r"(.*?<a\s+href=\\?\")(\w+://\S+[^\\])(\\?\">)"
+
+
+def clean_editor_js(definitions: Optional[Dict], *, to_string: bool = False):
+ """Sanitize a given EditorJS JSON definitions.
+
+ Look for not allowed URLs, replaced them with `invalid` value, and clean valid ones.
+
+ `to_string` flag is used for returning concatenated string from all blocks
+ instead of returning json object.
+ """
+ if definitions is None:
+ return "" if to_string else definitions
+
+ blocks = definitions.get("blocks")
+
+ if not blocks or not isinstance(blocks, list):
+ return "" if to_string else definitions
+
+ plain_text_list = []
+
+ for index, block in enumerate(blocks):
+ block_type = block["type"]
+ data = block.get("data")
+ if not data or not isinstance(data, dict):
+ continue
+
+ if block_type == "list":
+ for item_index, item in enumerate(block["data"]["items"]):
+ if not item:
+ continue
+ new_text = clean_text_data(item)
+ if to_string:
+ plain_text_list.append(strip_tags(new_text))
+ else:
+ blocks[index]["data"]["items"][item_index] = new_text
+ else:
+ text = block["data"].get("text")
+ if not text:
+ continue
+ new_text = clean_text_data(text)
+ if to_string:
+ plain_text_list.append(strip_tags(new_text))
+ else:
+ blocks[index]["data"]["text"] = new_text
+
+ return " ".join(plain_text_list) if to_string else definitions
+
+
+def clean_text_data(text: str):
+ """Look for url in text, check if URL is allowed and return the cleaned URL.
+
+ By default, only the protocol ``javascript`` is denied.
+ """
+
+ if not text:
+ return
+
+ end_of_match = 0
+ new_text = ""
+ for match in re.finditer(HYPERLINK_TAG_WITH_URL_PATTERN, text):
+ original_url = match.group(2)
+ original_url.strip()
+
+ url = parse_url(original_url)
+ new_url = url.url
+ if url.scheme in BLACKLISTED_URL_SCHEMES:
+ warnings.warn(
+ f"An invalid url was sent: {original_url} "
+ f"-- Scheme: {url.scheme} is blacklisted"
+ )
+ new_url = "#invalid"
+
+ new_text += match.group(1) + new_url + match.group(3)
+ end_of_match = match.end()
+
+ if end_of_match:
+ new_text += text[end_of_match:]
+
+ return new_text if new_text else text
+
+
+# End copy of /saleor/core/utils/editorjs.py
+
+
+def queryset_in_batches(queryset):
+ """Slice a queryset into batches.
+
+ Input queryset should be sorted be pk.
+ """
+ start_pk = 0
+
+ while True:
+ qs = queryset.filter(pk__gt=start_pk)[:2000]
+ pks = list(qs.values_list("pk", flat=True))
+
+ if not pks:
+ break
+
+ yield pks
+
+ start_pk = pks[-1]
+
+
+def propagate_names_for_rich_text_attribute_value_translations(apps, schema_editor):
+ AttributeValueTranslation = apps.get_model("attribute", "AttributeValueTranslation")
+
+ queryset = (
+ AttributeValueTranslation.objects.exclude(rich_text=None)
+ .filter(name="")
+ .order_by("pk")
+ )
+
+ for batch_pks in queryset_in_batches(queryset):
+ batch = AttributeValueTranslation.objects.filter(pk__in=batch_pks)
+ instances = []
+ for instance in batch:
+ instance.name = truncatechars(
+ clean_editor_js(instance.rich_text, to_string=True), 100
+ )
+ instances.append(instance)
+ AttributeValueTranslation.objects.bulk_update(instances, ["name"])
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("attribute", "0021_auto_20220406_1713"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ propagate_names_for_rich_text_attribute_value_translations,
+ migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/attribute/migrations/0024_merge_20221018_1100.py b/saleor/attribute/migrations/0024_merge_20221018_1100.py
new file mode 100644
index 0000000000..0a8a367a78
--- /dev/null
+++ b/saleor/attribute/migrations/0024_merge_20221018_1100.py
@@ -0,0 +1,13 @@
+# Generated by Django 3.2.16 on 2022-10-18 11:00
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("attribute", "0022_attribute_value_translations_propagate_names"),
+ ("attribute", "0023_lstrip_slash_from_value_file_url"),
+ ]
+
+ operations = []
diff --git a/saleor/attribute/migrations/0025_attribute_value_translations_propagate_names.py b/saleor/attribute/migrations/0025_attribute_value_translations_propagate_names.py
new file mode 100644
index 0000000000..63226cca21
--- /dev/null
+++ b/saleor/attribute/migrations/0025_attribute_value_translations_propagate_names.py
@@ -0,0 +1,147 @@
+# Generated by Django 3.2.16 on 2022-10-18 13:16
+
+import re
+import warnings
+from typing import Dict, Optional
+
+from django.db import migrations
+from django.template.defaultfilters import truncatechars
+from django.utils.html import strip_tags
+from urllib3.util import parse_url
+
+# Start copy of /saleor/core/utils/editorjs.py
+BLACKLISTED_URL_SCHEMES = ("javascript",)
+HYPERLINK_TAG_WITH_URL_PATTERN = r"(.*?<a\s+href=\\?\")(\w+://\S+[^\\])(\\?\">)"
+
+
+def clean_editor_js(definitions: Optional[Dict], *, to_string: bool = False):
+ """Sanitize a given EditorJS JSON definitions.
+
+ Look for not allowed URLs, replaced them with `invalid` value, and clean valid ones.
+
+ `to_string` flag is used for returning concatenated string from all blocks
+ instead of returning json object.
+ """
+ if definitions is None:
+ return "" if to_string else definitions
+
+ blocks = definitions.get("blocks")
+
+ if not blocks or not isinstance(blocks, list):
+ return "" if to_string else definitions
+
+ plain_text_list = []
+
+ for index, block in enumerate(blocks):
+ block_type = block["type"]
+ data = block.get("data")
+ if not data or not isinstance(data, dict):
+ continue
+
+ if block_type == "list":
+ for item_index, item in enumerate(block["data"]["items"]):
+ if not item:
+ continue
+ new_text = clean_text_data(item)
+ if to_string:
+ plain_text_list.append(strip_tags(new_text))
+ else:
+ blocks[index]["data"]["items"][item_index] = new_text
+ else:
+ text = block["data"].get("text")
+ if not text:
+ continue
+ new_text = clean_text_data(text)
+ if to_string:
+ plain_text_list.append(strip_tags(new_text))
+ else:
+ blocks[index]["data"]["text"] = new_text
+
+ return " ".join(plain_text_list) if to_string else definitions
+
+
+def clean_text_data(text: str):
+ """Look for url in text, check if URL is allowed and return the cleaned URL.
+
+ By default, only the protocol ``javascript`` is denied.
+ """
+
+ if not text:
+ return
+
+ end_of_match = 0
+ new_text = ""
+ for match in re.finditer(HYPERLINK_TAG_WITH_URL_PATTERN, text):
+ original_url = match.group(2)
+ original_url.strip()
+
+ url = parse_url(original_url)
+ new_url = url.url
+ if url.scheme in BLACKLISTED_URL_SCHEMES:
+ warnings.warn(
+ f"An invalid url was sent: {original_url} "
+ f"-- Scheme: {url.scheme} is blacklisted"
+ )
+ new_url = "#invalid"
+
+ new_text += match.group(1) + new_url + match.group(3)
+ end_of_match = match.end()
+
+ if end_of_match:
+ new_text += text[end_of_match:]
+
+ return new_text if new_text else text
+
+
+# End copy of /saleor/core/utils/editorjs.py
+
+
+def queryset_in_batches(queryset):
+ """Slice a queryset into batches.
+
+ Input queryset should be sorted be pk.
+ """
+ start_pk = 0
+
+ while True:
+ qs = queryset.filter(pk__gt=start_pk)[:2000]
+ pks = list(qs.values_list("pk", flat=True))
+
+ if not pks:
+ break
+
+ yield pks
+
+ start_pk = pks[-1]
+
+
+def propagate_names_for_plain_text_attribute_value_translations(apps, schema_editor):
+ AttributeValueTranslation = apps.get_model("attribute", "AttributeValueTranslation")
+
+ queryset = (
+ AttributeValueTranslation.objects.exclude(plain_text=None)
+ .filter(name="")
+ .order_by("pk")
+ )
+
+ for batch_pks in queryset_in_batches(queryset):
+ batch = AttributeValueTranslation.objects.filter(pk__in=batch_pks)
+ instances = []
+ for instance in batch:
+ instance.name = truncatechars(instance.plain_text, 100)
+ instances.append(instance)
+ AttributeValueTranslation.objects.bulk_update(instances, ["name"])
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("attribute", "0024_merge_20221018_1100"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ propagate_names_for_plain_text_attribute_value_translations,
+ migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/attribute/migrations/0026_merge_20221019_0937.py b/saleor/attribute/migrations/0026_merge_20221019_0937.py
new file mode 100644
index 0000000000..86d9026a1d
--- /dev/null
+++ b/saleor/attribute/migrations/0026_merge_20221019_0937.py
@@ -0,0 +1,13 @@
+# Generated by Django 3.2.16 on 2022-10-19 09:37
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("attribute", "0024_merge_20221018_0714"),
+ ("attribute", "0025_attribute_value_translations_propagate_names"),
+ ]
+
+ operations = []
diff --git a/saleor/graphql/translations/mutations.py b/saleor/graphql/translations/mutations.py
index 5f8b6a8e6b..b39513ce3f 100644
--- a/saleor/graphql/translations/mutations.py
+++ b/saleor/graphql/translations/mutations.py
@@ -1,11 +1,14 @@
import graphene
from django.core.exceptions import ValidationError
from django.db.models import Model
+from django.template.defaultfilters import truncatechars
from graphql import GraphQLError
+from ...attribute import AttributeInputType
from ...attribute import models as attribute_models
from ...core.permissions import SitePermissions
from ...core.tracing import traced_atomic_transaction
+from ...core.utils.editorjs import clean_editor_js
from ...discount import models as discount_models
from ...menu import models as menu_models
from ...page import models as page_models
@@ -112,12 +115,18 @@ class BaseTranslateMutation(ModelMutation):
def validate_input(cls, input_data):
validate_input_against_model(cls._meta.model, input_data)
+ @classmethod
+ def pre_update_or_create(cls, instance, input_data):
+ return input_data
+
@classmethod
def perform_mutation(cls, _root, info, **data):
node_id, model_type = cls.clean_node_id(**data)
instance = cls.get_node_or_error(info, node_id, only_type=model_type)
cls.validate_input(data["input"])
+ data["input"] = cls.pre_update_or_create(instance, data["input"])
+
translation, created = instance.translations.update_or_create(
language_code=data["language_code"], defaults=data["input"]
)
@@ -321,6 +330,17 @@ class AttributeValueTranslate(BaseTranslateMutation):
error_type_field = "translation_errors"
permissions = (SitePermissions.MANAGE_TRANSLATIONS,)
+ @classmethod
+ def pre_update_or_create(cls, instance, input_data):
+ if "name" not in input_data.keys() or input_data["name"] is None:
+ if instance.attribute.input_type == AttributeInputType.RICH_TEXT:
+ input_data["name"] = truncatechars(
+ clean_editor_js(input_data["rich_text"], to_string=True), 100
+ )
+ elif instance.attribute.input_type == AttributeInputType.PLAIN_TEXT:
+ input_data["name"] = truncatechars(input_data["plain_text"], 100)
+ return input_data
+
class SaleTranslate(BaseTranslateMutation):
class Arguments:
diff --git a/saleor/graphql/translations/tests/test_translations.py b/saleor/graphql/translations/tests/test_translations.py
index a579c59ed4..8283ffd7a7 100644
--- a/saleor/graphql/translations/tests/test_translations.py
+++ b/saleor/graphql/translations/tests/test_translations.py
@@ -1975,15 +1975,20 @@ def test_attribute_update_translation(
ATTRIBUTE_VALUE_TRANSLATE_MUTATION = """
- mutation attributeValueTranslate($attributeValueId: ID!, $name: String) {
+ mutation attributeValueTranslate(
+ $attributeValueId: ID!,
+ $input: AttributeValueTranslationInput!
+ ) {
attributeValueTranslate(
id: $attributeValueId,
languageCode: PL,
- input: { name: $name }
+ input: $input
) {
attributeValue {
translation(languageCode: PL) {
name
+ richText
+ plainText
language {
code
}
@@ -2014,7 +2019,7 @@ def test_attribute_value_create_translation(
)
response = staff_api_client.post_graphql(
ATTRIBUTE_VALUE_TRANSLATE_MUTATION,
- {"attributeValueId": attribute_value_id, "name": "Róż PL"},
+ {"attributeValueId": attribute_value_id, "input": {"name": "Róż PL"}},
permissions=[permission_manage_translations],
)
data = get_graphql_content(response)["data"]["attributeValueTranslate"]
@@ -2033,6 +2038,73 @@ def test_attribute_value_create_translation(
)
+def test_rich_text_attribute_value_create_translation(
+ staff_api_client,
+ product_with_rich_text_attribute,
+ permission_manage_translations,
+):
+ # given
+ assigned_attribute = product_with_rich_text_attribute[0].attributes.first()
+ attribute_value = assigned_attribute.attribute.values.first()
+ attribute_value_id = graphene.Node.to_global_id(
+ "AttributeValue", attribute_value.id
+ )
+ expected_base_text = "Nowy Opis"
+ expected_rich_text = json.dumps(dummy_editorjs(expected_base_text))
+
+ # when
+ response = staff_api_client.post_graphql(
+ ATTRIBUTE_VALUE_TRANSLATE_MUTATION,
+ {
+ "attributeValueId": attribute_value_id,
+ "input": {"richText": expected_rich_text},
+ },
+ permissions=[permission_manage_translations],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["attributeValueTranslate"]
+ assert data["attributeValue"]["translation"]["language"]["code"] == "PL"
+ assert data["attributeValue"]["translation"]["name"] == expected_base_text
+ assert data["attributeValue"]["translation"]["richText"] == expected_rich_text
+
+
+def test_plain_text_attribute_value_create_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
+ )
+ attribute_value_id = graphene.Node.to_global_id(
+ "AttributeValue", attribute_value.id
+ )
+ expected_text = "Nowy Opis"
+
+ # when
+ response = staff_api_client.post_graphql(
+ ATTRIBUTE_VALUE_TRANSLATE_MUTATION,
+ {
+ "attributeValueId": attribute_value_id,
+ "input": {"plainText": expected_text},
+ },
+ permissions=[permission_manage_translations],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["attributeValueTranslate"]
+ assert data["attributeValue"]["translation"]["language"]["code"] == "PL"
+ assert data["attributeValue"]["translation"]["name"] == expected_text
+ assert data["attributeValue"]["translation"]["plainText"] == expected_text
+
+
def test_attribute_value_create_translation_by_translatable_content_id(
staff_api_client, pink_attribute_value, permission_manage_translations
):
@@ -2041,7 +2113,7 @@ def test_attribute_value_create_translation_by_translatable_content_id(
)
response = staff_api_client.post_graphql(
ATTRIBUTE_VALUE_TRANSLATE_MUTATION,
- {"attributeValueId": translatable_content_id, "name": "Róż PL"},
+ {"attributeValueId": translatable_content_id, "input": {"name": "Róż PL"}},
permissions=[permission_manage_translations],
)
data = get_graphql_content(response)["data"]["attributeValueTranslate"]
@@ -2073,7 +2145,7 @@ def test_attribute_value_update_translation(
)
response = staff_api_client.post_graphql(
ATTRIBUTE_VALUE_TRANSLATE_MUTATION,
- {"attributeValueId": attribute_value_id, "name": "Róż PL"},
+ {"attributeValueId": attribute_value_id, "input": {"name": "Róż PL"}},
permissions=[permission_manage_translations],
)
data = get_graphql_content(response)["data"]["attributeValueTranslate"]
@@ -2092,6 +2164,387 @@ def test_attribute_value_update_translation(
)
+def test_rich_text_attribute_value_update_translation_only_rich_text(
+ staff_api_client,
+ product_with_rich_text_attribute,
+ permission_manage_translations,
+):
+ # given
+ base_text = "Base Text"
+ rich_text = dummy_editorjs(base_text)
+ assigned_attribute = product_with_rich_text_attribute[0].attributes.first()
+ attribute_value = assigned_attribute.attribute.values.first()
+ attribute_value.translations.create(
+ language_code="pl", name=base_text, rich_text=rich_text
+ )
+ attribute_value_id = graphene.Node.to_global_id(
+ "AttributeValue", attribute_value.id
+ )
+ expected_base_text = "Nowy Opis"
+ expected_rich_text = json.dumps(dummy_editorjs(expected_base_text))
+
+ # when
+ response = staff_api_client.post_graphql(
+ ATTRIBUTE_VALUE_TRANSLATE_MUTATION,
+ {
+ "attributeValueId": attribute_value_id,
+ "input": {"richText": expected_rich_text},
+ },
+ permissions=[permission_manage_translations],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["attributeValueTranslate"]
+ assert data["attributeValue"]["translation"]["language"]["code"] == "PL"
+ assert data["attributeValue"]["translation"]["name"] == expected_base_text
+ assert data["attributeValue"]["translation"]["richText"] == expected_rich_text
+
+
+def test_rich_text_attribute_value_update_translation_only_rich_text_long_text(
+ staff_api_client,
+ product_with_rich_text_attribute,
+ permission_manage_translations,
+):
+ # given
+ base_text = "Base Text"
+ rich_text = dummy_editorjs(base_text)
+ assigned_attribute = product_with_rich_text_attribute[0].attributes.first()
+ attribute_value = assigned_attribute.attribute.values.first()
+ attribute_value.translations.create(
+ language_code="pl", name=base_text, rich_text=rich_text
+ )
+ attribute_value_id = graphene.Node.to_global_id(
+ "AttributeValue", attribute_value.id
+ )
+ expected_base_text = "Nowy Opis. " * 100
+ expected_rich_text = json.dumps(dummy_editorjs(expected_base_text))
+
+ # when
+ response = staff_api_client.post_graphql(
+ ATTRIBUTE_VALUE_TRANSLATE_MUTATION,
+ {
+ "attributeValueId": attribute_value_id,
+ "input": {"richText": expected_rich_text},
+ },
+ permissions=[permission_manage_translations],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["attributeValueTranslate"]
+ assert data["attributeValue"]["translation"]["language"]["code"] == "PL"
+ assert (
+ data["attributeValue"]["translation"]["name"] == expected_base_text[:99] + "…"
+ )
+ assert data["attributeValue"]["translation"]["richText"] == expected_rich_text
+
+
+def test_rich_text_attribute_value_update_translation_only_rich_text_name_set_manually(
+ staff_api_client,
+ product_with_rich_text_attribute,
+ permission_manage_translations,
+):
+ # given
+ base_text = "Base Text"
+ rich_text = dummy_editorjs(base_text)
+ assigned_attribute = product_with_rich_text_attribute[0].attributes.first()
+ attribute_value = assigned_attribute.attribute.values.first()
+ attribute_value.translations.create(
+ language_code="pl", name=base_text, rich_text=rich_text
+ )
+ attribute_value_id = graphene.Node.to_global_id(
+ "AttributeValue", attribute_value.id
+ )
+ expected_name = "Moja nazwa attrybutu"
+ expected_base_text = "Nowy Opis"
+ expected_rich_text = json.dumps(dummy_editorjs(expected_base_text))
+
+ # when
+ response = staff_api_client.post_graphql(
+ ATTRIBUTE_VALUE_TRANSLATE_MUTATION,
+ {
+ "attributeValueId": attribute_value_id,
+ "input": {"name": expected_name, "richText": expected_rich_text},
+ },
+ permissions=[permission_manage_translations],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["attributeValueTranslate"]
+ assert data["attributeValue"]["translation"]["language"]["code"] == "PL"
+ assert data["attributeValue"]["translation"]["name"] == expected_name
+ assert data["attributeValue"]["translation"]["richText"] == expected_rich_text
+
+
+def test_rich_text_attribute_value_update_translation_only_rich_text_empty_name(
+ staff_api_client,
+ product_with_rich_text_attribute,
+ permission_manage_translations,
+):
+ # given
+ base_text = "Base Text"
+ rich_text = dummy_editorjs(base_text)
+ assigned_attribute = product_with_rich_text_attribute[0].attributes.first()
+ attribute_value = assigned_attribute.attribute.values.first()
+ attribute_value.translations.create(
+ language_code="pl", name=base_text, rich_text=rich_text
+ )
+ attribute_value_id = graphene.Node.to_global_id(
+ "AttributeValue", attribute_value.id
+ )
+ expected_base_text = "Nowy Opis"
+ expected_rich_text = json.dumps(dummy_editorjs(expected_base_text))
+
+ # when
+ response = staff_api_client.post_graphql(
+ ATTRIBUTE_VALUE_TRANSLATE_MUTATION,
+ {
+ "attributeValueId": attribute_value_id,
+ "input": {"name": "", "richText": expected_rich_text},
+ },
+ permissions=[permission_manage_translations],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["attributeValueTranslate"]
+ assert data["attributeValue"]["translation"]["language"]["code"] == "PL"
+ assert data["attributeValue"]["translation"]["name"] == ""
+ assert data["attributeValue"]["translation"]["richText"] == expected_rich_text
+
+
+def test_rich_text_attribute_value_update_translation_only_rich_text_name_null(
+ staff_api_client,
+ product_with_rich_text_attribute,
+ permission_manage_translations,
+):
+ # given
+ base_text = "Base Text"
+ rich_text = dummy_editorjs(base_text)
+ assigned_attribute = product_with_rich_text_attribute[0].attributes.first()
+ attribute_value = assigned_attribute.attribute.values.first()
+ attribute_value.translations.create(
+ language_code="pl", name=base_text, rich_text=rich_text
+ )
+ attribute_value_id = graphene.Node.to_global_id(
+ "AttributeValue", attribute_value.id
+ )
+ expected_base_text = "Nowy Opis"
+ expected_rich_text = json.dumps(dummy_editorjs(expected_base_text))
+
+ # when
+ response = staff_api_client.post_graphql(
+ ATTRIBUTE_VALUE_TRANSLATE_MUTATION,
+ {
+ "attributeValueId": attribute_value_id,
+ "input": {"name": None, "richText": expected_rich_text},
+ },
+ permissions=[permission_manage_translations],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["attributeValueTranslate"]
+ assert data["attributeValue"]["translation"]["language"]["code"] == "PL"
+ assert data["attributeValue"]["translation"]["name"] == expected_base_text
+ assert data["attributeValue"]["translation"]["richText"] == expected_rich_text
+
+
+def test_plain_text_attribute_value_update_translation_only_plain_text(
+ 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 = "Jakiś bazowy opis"
+ attribute_value.translations.create(language_code="pl", plain_text=text)
+ attribute_value_id = graphene.Node.to_global_id(
+ "AttributeValue", attribute_value.id
+ )
+ expected_text = "Nowy Opis"
+
+ # when
+ response = staff_api_client.post_graphql(
+ ATTRIBUTE_VALUE_TRANSLATE_MUTATION,
+ {
+ "attributeValueId": attribute_value_id,
+ "input": {"plainText": expected_text},
+ },
+ permissions=[permission_manage_translations],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["attributeValueTranslate"]
+ assert data["attributeValue"]["translation"]["language"]["code"] == "PL"
+ assert data["attributeValue"]["translation"]["name"] == expected_text
+ assert data["attributeValue"]["translation"]["plainText"] == expected_text
+
+
+def test_plain_text_attribute_value_update_translation_only_plain_text_long_text(
+ 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 = "Jakiś bazowy opis"
+ attribute_value.translations.create(language_code="pl", plain_text=text)
+ attribute_value_id = graphene.Node.to_global_id(
+ "AttributeValue", attribute_value.id
+ )
+ expected_base_text = "Nowy Opis. " * 100
+
+ # when
+ response = staff_api_client.post_graphql(
+ ATTRIBUTE_VALUE_TRANSLATE_MUTATION,
+ {
+ "attributeValueId": attribute_value_id,
+ "input": {"plainText": expected_base_text},
+ },
+ permissions=[permission_manage_translations],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["attributeValueTranslate"]
+ assert data["attributeValue"]["translation"]["language"]["code"] == "PL"
+ assert (
+ data["attributeValue"]["translation"]["name"] == expected_base_text[:99] + "…"
+ )
+ assert data["attributeValue"]["translation"]["plainText"] == expected_base_text
+
+
+def test_plain_text_attribute_value_update_translation_name_set_manually(
+ 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 = "Jakiś bazowy opis"
+ attribute_value.translations.create(language_code="pl", plain_text=text)
+ attribute_value_id = graphene.Node.to_global_id(
+ "AttributeValue", attribute_value.id
+ )
+ expected_name = "Moja nazwa attrybutu"
+ expected_text = "Nowy Opis"
+
+ # when
+ response = staff_api_client.post_graphql(
+ ATTRIBUTE_VALUE_TRANSLATE_MUTATION,
+ {
+ "attributeValueId": attribute_value_id,
+ "input": {"name": expected_name, "plainText": expected_text},
+ },
+ permissions=[permission_manage_translations],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["attributeValueTranslate"]
+ assert data["attributeValue"]["translation"]["language"]["code"] == "PL"
+ assert data["attributeValue"]["translation"]["name"] == expected_name
+ assert data["attributeValue"]["translation"]["plainText"] == expected_text
+
+
+def test_plain_text_attribute_value_update_translation_empty_name(
+ 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 = "Jakiś bazowy opis"
+ attribute_value.translations.create(language_code="pl", plain_text=text)
+ attribute_value_id = graphene.Node.to_global_id(
+ "AttributeValue", attribute_value.id
+ )
+ expected_text = "Nowy Opis"
+
+ # when
+ response = staff_api_client.post_graphql(
+ ATTRIBUTE_VALUE_TRANSLATE_MUTATION,
+ {
+ "attributeValueId": attribute_value_id,
+ "input": {"name": "", "plainText": expected_text},
+ },
+ permissions=[permission_manage_translations],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["attributeValueTranslate"]
+ assert data["attributeValue"]["translation"]["language"]["code"] == "PL"
+ assert data["attributeValue"]["translation"]["name"] == ""
+ assert data["attributeValue"]["translation"]["plainText"] == expected_text
+
+
+def test_plain_text_attribute_value_update_translation_name_null(
+ 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 = "Jakiś bazowy opis"
+ attribute_value.translations.create(language_code="pl", plain_text=text)
+ attribute_value_id = graphene.Node.to_global_id(
+ "AttributeValue", attribute_value.id
+ )
+ expected_text = "Nowy Opis"
+
+ # when
+ response = staff_api_client.post_graphql(
+ ATTRIBUTE_VALUE_TRANSLATE_MUTATION,
+ {
+ "attributeValueId": attribute_value_id,
+ "input": {"name": None, "plainText": expected_text},
+ },
+ permissions=[permission_manage_translations],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["attributeValueTranslate"]
+ assert data["attributeValue"]["translation"]["language"]["code"] == "PL"
+ assert data["attributeValue"]["translation"]["name"] == expected_text
+ assert data["attributeValue"]["translation"]["plainText"] == expected_text
+
+
SHIPPING_PRICE_TRANSLATE = """
mutation shippingPriceTranslate(
$shippingMethodId: ID!, $input: ShippingPriceTranslationInput!