Skip to content

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

Add bulk translate mutations for Product and ProductVariant (#13329)

SzymJ9a21d33b4237
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1c59a0f217..20ab0198a0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -67,6 +67,8 @@ All notable, unreleased changes to this project will be documented in this file.
- Remove `Preview feature` label from `metafield`, `metafields`, `metadata`,
`privateMetafield`, `privateMetafields` and `privateMetadata` fields - #13245 by @korycins
- Add `search` to `giftCards` query - #13173 by @zedzior
+- Add `ProductBulkTranslate` mutation - #13329 by @SzymJ
+- Add `ProductVariantBulkTranslate` mutation - #13329 by @SzymJ
### Saleor Apps
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index 380e5050d6..d7cfce7d02 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -225,6 +225,19 @@ PageErrorCode.doc_category = DOC_CATEGORY_PAGES
PaymentErrorCode = graphene.Enum.from_enum(payment_error_codes.PaymentErrorCode)
PaymentErrorCode.doc_category = DOC_CATEGORY_PAYMENTS
+
+ProductTranslateErrorCode = graphene.Enum.from_enum(
+ translatable_error_codes.ProductTranslateErrorCode
+)
+ProductTranslateErrorCode.doc_category = DOC_CATEGORY_PRODUCTS
+
+
+ProductVariantTranslateErrorCode = graphene.Enum.from_enum(
+ translatable_error_codes.ProductVariantTranslateErrorCode
+)
+ProductVariantTranslateErrorCode.doc_category = DOC_CATEGORY_PRODUCTS
+
+
TransactionCreateErrorCode = graphene.Enum.from_enum(
payment_error_codes.TransactionCreateErrorCode
)
diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.py
index 71611c40a0..b2db4748da 100644
--- a/saleor/graphql/core/types/__init__.py
+++ b/saleor/graphql/core/types/__init__.py
@@ -44,9 +44,11 @@ from .common import (
PriceInput,
PriceRangeInput,
ProductBulkCreateError,
+ ProductBulkTranslateError,
ProductChannelListingError,
ProductError,
ProductVariantBulkError,
+ ProductVariantBulkTranslateError,
ProductWithoutVariantError,
SeoInput,
ShippingError,
@@ -134,8 +136,10 @@ __all__ = [
"ProductChannelListingError",
"ProductError",
"ProductBulkCreateError",
+ "ProductBulkTranslateError",
"ProductWithoutVariantError",
"ProductVariantBulkError",
+ "ProductVariantBulkTranslateError",
"ReducedRate",
"SeoInput",
"ShippingError",
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 925448a8a0..273d46a7e6 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -66,7 +66,9 @@ from ..enums import (
PluginErrorCode,
ProductBulkCreateErrorCode,
ProductErrorCode,
+ ProductTranslateErrorCode,
ProductVariantBulkErrorCode,
+ ProductVariantTranslateErrorCode,
ShippingErrorCode,
ShopErrorCode,
StockBulkUpdateErrorCode,
@@ -575,6 +577,16 @@ class PaymentError(Error):
doc_category = DOC_CATEGORY_PAYMENTS
+class ProductBulkTranslateError(BulkError):
+ code = ProductTranslateErrorCode(description="The error code.", required=True)
+
+
+class ProductVariantBulkTranslateError(BulkError):
+ code = ProductVariantTranslateErrorCode(
+ description="The error code.", required=True
+ )
+
+
class TransactionCreateError(Error):
code = TransactionCreateErrorCode(description="The error code.", required=True)
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index 83e9a80d7b..94105c30d9 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -27,7 +27,9 @@ from ..core.validators import validate_one_of_args_is_in_query
from ..translations.mutations import (
CategoryTranslate,
CollectionTranslate,
+ ProductBulkTranslate,
ProductTranslate,
+ ProductVariantBulkTranslate,
ProductVariantTranslate,
)
from ..utils import get_user_or_app_from_context
@@ -584,6 +586,7 @@ class ProductMutations(graphene.ObjectType):
product_bulk_create = ProductBulkCreate.Field()
product_bulk_delete = ProductBulkDelete.Field()
product_update = ProductUpdate.Field()
+ product_bulk_translate = ProductBulkTranslate.Field()
product_translate = ProductTranslate.Field()
product_channel_listing_update = ProductChannelListingUpdate.Field()
@@ -619,6 +622,7 @@ class ProductMutations(graphene.ObjectType):
product_variant_update = ProductVariantUpdate.Field()
product_variant_set_default = ProductVariantSetDefault.Field()
product_variant_translate = ProductVariantTranslate.Field()
+ product_variant_bulk_translate = ProductVariantBulkTranslate.Field()
product_variant_channel_listing_update = ProductVariantChannelListingUpdate.Field()
product_variant_reorder_attribute_values = (
ProductVariantReorderAttributeValues.Field()
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 75bb88c952..b6f5b45640 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -14283,6 +14283,27 @@ type Mutation {
input: ProductInput!
): ProductUpdate @doc(category: "Products")
+ """
+ Creates/updates translations for products.
+
+ Added in Saleor 3.15.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires one of the following permissions: MANAGE_TRANSLATIONS.
+
+ Triggers the following webhook events:
+ - TRANSLATION_CREATED (async): Called when a translation was created.
+ - TRANSLATION_UPDATED (async): Called when a translation was updated.
+ """
+ productBulkTranslate(
+ """Policies of error handling. DEFAULT: REJECT_EVERYTHING"""
+ errorPolicy: ErrorPolicyEnum
+
+ """List of product translations."""
+ translations: [ProductBulkTranslateInput!]!
+ ): ProductBulkTranslate @doc(category: "Products") @webhookEventsInfo(asyncEvents: [TRANSLATION_CREATED, TRANSLATION_UPDATED], syncEvents: [])
+
"""
Creates/updates translations for a product.
@@ -14692,6 +14713,27 @@ type Mutation {
languageCode: LanguageCodeEnum!
): ProductVariantTranslate @doc(category: "Products")
+ """
+ Creates/updates translations for products variants.
+
+ Added in Saleor 3.15.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires one of the following permissions: MANAGE_TRANSLATIONS.
+
+ Triggers the following webhook events:
+ - TRANSLATION_CREATED (async): A translation was created.
+ - TRANSLATION_UPDATED (async): A translation was updated.
+ """
+ productVariantBulkTranslate(
+ """Policies of error handling. DEFAULT: REJECT_EVERYTHING"""
+ errorPolicy: ErrorPolicyEnum
+
+ """List of products variants translations."""
+ translations: [ProductVariantBulkTranslateInput!]!
+ ): ProductVariantBulkTranslate @doc(category: "Products") @webhookEventsInfo(asyncEvents: [TRANSLATION_CREATED, TRANSLATION_UPDATED], syncEvents: [])
+
"""
Manage product variant prices in channels.
@@ -20697,6 +20739,71 @@ input ProductInput @doc(category: "Products") {
externalReference: String
}
+"""
+Creates/updates translations for products.
+
+Added in Saleor 3.15.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+Requires one of the following permissions: MANAGE_TRANSLATIONS.
+
+Triggers the following webhook events:
+- TRANSLATION_CREATED (async): Called when a translation was created.
+- TRANSLATION_UPDATED (async): Called when a translation was updated.
+"""
+type ProductBulkTranslate @doc(category: "Products") @webhookEventsInfo(asyncEvents: [TRANSLATION_CREATED, TRANSLATION_UPDATED], syncEvents: []) {
+ """Returns how many translations were created/updated."""
+ count: Int!
+
+ """List of the translations."""
+ results: [ProductBulkTranslateResult!]!
+ errors: [ProductBulkTranslateError!]!
+}
+
+type ProductBulkTranslateResult @doc(category: "Products") {
+ """Product translation data."""
+ translation: ProductTranslation
+
+ """List of errors occurred on translation attempt."""
+ errors: [ProductBulkTranslateError!]
+}
+
+type ProductBulkTranslateError {
+ """
+ Path to field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.
+ """
+ path: String
+
+ """The error message."""
+ message: String
+
+ """The error code."""
+ code: ProductTranslateErrorCode!
+}
+
+"""An enumeration."""
+enum ProductTranslateErrorCode @doc(category: "Products") {
+ GRAPHQL_ERROR
+ INVALID
+ NOT_FOUND
+ REQUIRED
+}
+
+input ProductBulkTranslateInput @doc(category: "Products") {
+ """Product ID."""
+ id: ID
+
+ """External reference of an product."""
+ externalReference: String
+
+ """Translation language code."""
+ languageCode: LanguageCodeEnum!
+
+ """Translation fields."""
+ translationFields: TranslationInput!
+}
+
"""
Creates/updates translations for a product.
@@ -21665,6 +21772,71 @@ input NameTranslationInput {
name: String
}
+"""
+Creates/updates translations for products variants.
+
+Added in Saleor 3.15.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+Requires one of the following permissions: MANAGE_TRANSLATIONS.
+
+Triggers the following webhook events:
+- TRANSLATION_CREATED (async): A translation was created.
+- TRANSLATION_UPDATED (async): A translation was updated.
+"""
+type ProductVariantBulkTranslate @doc(category: "Products") @webhookEventsInfo(asyncEvents: [TRANSLATION_CREATED, TRANSLATION_UPDATED], syncEvents: []) {
+ """Returns how many translations were created/updated."""
+ count: Int!
+
+ """List of the translations."""
+ results: [ProductVariantBulkTranslateResult!]!
+ errors: [ProductVariantBulkTranslateError!]!
+}
+
+type ProductVariantBulkTranslateResult @doc(category: "Products") {
+ """Product variant translation data."""
+ translation: ProductVariantTranslation
+
+ """List of errors occurred on translation attempt."""
+ errors: [ProductVariantBulkTranslateError!]
+}
+
+type ProductVariantBulkTranslateError {
+ """
+ Path to field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.
+ """
+ path: String
+
+ """The error message."""
+ message: String
+
+ """The error code."""
+ code: ProductVariantTranslateErrorCode!
+}
+
+"""An enumeration."""
+enum ProductVariantTranslateErrorCode @doc(category: "Products") {
+ GRAPHQL_ERROR
+ INVALID
+ NOT_FOUND
+ REQUIRED
+}
+
+input ProductVariantBulkTranslateInput @doc(category: "Products") {
+ """Product variant ID."""
+ id: ID
+
+ """External reference of a product variant."""
+ externalReference: String
+
+ """Translation language code."""
+ languageCode: LanguageCodeEnum!
+
+ """Translation fields."""
+ translationFields: NameTranslationInput!
+}
+
"""
Manage product variant prices in channels.
diff --git a/saleor/graphql/translations/mutations/__init__.py b/saleor/graphql/translations/mutations/__init__.py
index 7fbbff3c2a..6f19c3e221 100644
--- a/saleor/graphql/translations/mutations/__init__.py
+++ b/saleor/graphql/translations/mutations/__init__.py
@@ -6,7 +6,9 @@ from .category_translate import CategoryTranslate
from .collection_translate import CollectionTranslate
from .menu_item_translate import MenuItemTranslate
from .page_translate import PageTranslate
+from .product_bulk_translate import ProductBulkTranslate
from .product_translate import ProductTranslate
+from .product_variant_bulk_translate import ProductVariantBulkTranslate
from .product_variant_translate import ProductVariantTranslate
from .sale_translate import SaleTranslate
from .shipping_price_translate import ShippingPriceTranslate
@@ -23,7 +25,9 @@ __all__ = [
"MenuItemTranslate",
"PageTranslate",
"ProductTranslate",
+ "ProductBulkTranslate",
"ProductVariantTranslate",
+ "ProductVariantBulkTranslate",
"SaleTranslate",
"ShippingPriceTranslate",
"ShopSettingsTranslate",
diff --git a/saleor/graphql/translations/mutations/product_bulk_translate.py b/saleor/graphql/translations/mutations/product_bulk_translate.py
new file mode 100644
index 0000000000..c15822b040
--- /dev/null
+++ b/saleor/graphql/translations/mutations/product_bulk_translate.py
@@ -0,0 +1,143 @@
+import graphene
+from django.core.exceptions import ValidationError
+from graphql.error import GraphQLError
+
+from ....permission.enums import SitePermissions
+from ....product import models
+from ...core.descriptions import ADDED_IN_315, PREVIEW_FEATURE
+from ...core.doc_category import DOC_CATEGORY_PRODUCTS
+from ...core.enums import LanguageCodeEnum, ProductTranslateErrorCode
+from ...core.types import (
+ BaseInputObjectType,
+ BaseObjectType,
+ NonNullList,
+ ProductBulkTranslateError,
+)
+from ...core.utils import (
+ WebhookEventAsyncType,
+ WebhookEventInfo,
+ from_global_id_or_error,
+)
+from ...core.validators import validate_one_of_args_is_in_mutation
+from ...translations.types import ProductTranslation
+from .utils import BaseBulkTranslateMutation, TranslationInput
+
+
+class ProductBulkTranslateResult(BaseObjectType):
+ translation = graphene.Field(
+ ProductTranslation, description="Product translation data."
+ )
+ errors = NonNullList(
+ ProductBulkTranslateError,
+ required=False,
+ description="List of errors occurred on translation attempt.",
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PRODUCTS
+
+
+class ProductBulkTranslateInput(BaseInputObjectType):
+ id = graphene.ID(
+ required=False,
+ description="Product ID.",
+ )
+ external_reference = graphene.String(
+ required=False,
+ description="External reference of an product.",
+ )
+ language_code = LanguageCodeEnum(
+ required=True, description="Translation language code."
+ )
+ translation_fields = TranslationInput(
+ required=True,
+ description="Translation fields.",
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PRODUCTS
+
+
+class ProductBulkTranslate(BaseBulkTranslateMutation):
+ results = NonNullList(
+ ProductBulkTranslateResult,
+ required=True,
+ default_value=[],
+ description="List of the translations.",
+ )
+
+ class Arguments(BaseBulkTranslateMutation.Arguments):
+ translations = NonNullList(
+ ProductBulkTranslateInput,
+ required=True,
+ description="List of product translations.",
+ )
+
+ class Meta:
+ description = (
+ "Creates/updates translations for products."
+ + ADDED_IN_315
+ + PREVIEW_FEATURE
+ )
+ base_model = models.Product
+ translation_model = models.ProductTranslation
+ translation_fields = ["name", "description", "seo_description", "seo_title"]
+ base_model_relation_field = "product"
+ result_type = ProductBulkTranslateResult
+ error_type_class = ProductBulkTranslateError
+ permissions = (SitePermissions.MANAGE_TRANSLATIONS,)
+ webhook_events_info = [
+ WebhookEventInfo(
+ type=WebhookEventAsyncType.TRANSLATION_CREATED,
+ description="Called when a translation was created.",
+ ),
+ WebhookEventInfo(
+ type=WebhookEventAsyncType.TRANSLATION_UPDATED,
+ description="Called when a translation was updated.",
+ ),
+ ]
+
+ @classmethod
+ def clean_translations(cls, data_inputs, index_error_map):
+ cleaned_inputs_map: dict = {}
+
+ for index, data in enumerate(data_inputs):
+ global_id = data.get("id")
+ external_ref = data.get("external_reference")
+
+ try:
+ validate_one_of_args_is_in_mutation(
+ "id",
+ global_id,
+ "external_reference",
+ external_ref,
+ use_camel_case=True,
+ )
+ except ValidationError as exc:
+ index_error_map[index].append(
+ ProductBulkTranslateError(
+ message=exc.message,
+ code=ProductTranslateErrorCode.INVALID.value,
+ )
+ )
+ cleaned_inputs_map[index] = None
+ continue
+
+ if global_id:
+ try:
+ obj_type, id = from_global_id_or_error(
+ global_id, only_type="Product"
+ )
+ except GraphQLError as exc:
+ index_error_map[index].append(
+ ProductBulkTranslateError(
+ message=str(exc),
+ code=ProductTranslateErrorCode.INVALID.value,
+ )
+ )
+ cleaned_inputs_map[index] = None
+ continue
+ data["id"] = id
+
+ cleaned_inputs_map[index] = data
+ return cleaned_inputs_map
diff --git a/saleor/graphql/translations/mutations/product_variant_bulk_translate.py b/saleor/graphql/translations/mutations/product_variant_bulk_translate.py
new file mode 100644
index 0000000000..932413619c
--- /dev/null
+++ b/saleor/graphql/translations/mutations/product_variant_bulk_translate.py
@@ -0,0 +1,143 @@
+import graphene
+from django.core.exceptions import ValidationError
+from graphql.error import GraphQLError
+
+from ....permission.enums import SitePermissions
+from ....product import models
+from ...core.descriptions import ADDED_IN_315, PREVIEW_FEATURE
+from ...core.doc_category import DOC_CATEGORY_PRODUCTS
+from ...core.enums import LanguageCodeEnum, ProductVariantTranslateErrorCode
+from ...core.types import (
+ BaseInputObjectType,
+ BaseObjectType,
+ NonNullList,
+ ProductVariantBulkTranslateError,
+)
+from ...core.utils import (
+ WebhookEventAsyncType,
+ WebhookEventInfo,
+ from_global_id_or_error,
+)
+from ...core.validators import validate_one_of_args_is_in_mutation
+from ...translations.types import ProductVariantTranslation
+from .utils import BaseBulkTranslateMutation, NameTranslationInput
+
+
+class ProductVariantBulkTranslateResult(BaseObjectType):
+ translation = graphene.Field(
+ ProductVariantTranslation, description="Product variant translation data."
+ )
+ errors = NonNullList(
+ ProductVariantBulkTranslateError,
+ required=False,
+ description="List of errors occurred on translation attempt.",
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PRODUCTS
+
+
+class ProductVariantBulkTranslateInput(BaseInputObjectType):
+ id = graphene.ID(
+ required=False,
+ description="Product variant ID.",
+ )
+ external_reference = graphene.String(
+ required=False,
+ description="External reference of a product variant.",
+ )
+ language_code = LanguageCodeEnum(
+ required=True, description="Translation language code."
+ )
+ translation_fields = NameTranslationInput(
+ required=True,
+ description="Translation fields.",
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PRODUCTS
+
+
+class ProductVariantBulkTranslate(BaseBulkTranslateMutation):
+ results = NonNullList(
+ ProductVariantBulkTranslateResult,
+ required=True,
+ default_value=[],
+ description="List of the translations.",
+ )
+
+ class Arguments(BaseBulkTranslateMutation.Arguments):
+ translations = NonNullList(
+ ProductVariantBulkTranslateInput,
+ required=True,
+ description="List of products variants translations.",
+ )
+
+ class Meta:
+ description = (
+ "Creates/updates translations for products variants."
+ + ADDED_IN_315
+ + PREVIEW_FEATURE
+ )
+ base_model = models.ProductVariant
+ translation_model = models.ProductVariantTranslation
+ translation_fields = ["name"]
+ base_model_relation_field = "product_variant"
+ result_type = ProductVariantBulkTranslateResult
+ error_type_class = ProductVariantBulkTranslateError
+ permissions = (SitePermissions.MANAGE_TRANSLATIONS,)
+ webhook_events_info = [
+ WebhookEventInfo(
+ type=WebhookEventAsyncType.TRANSLATION_CREATED,
+ description="A translation was created.",
+ ),
+ WebhookEventInfo(
+ type=WebhookEventAsyncType.TRANSLATION_UPDATED,
+ description="A translation was updated.",
+ ),
+ ]
+
+ @classmethod
+ def clean_translations(cls, data_inputs, index_error_map):
+ cleaned_inputs_map: dict = {}
+
+ for index, data in enumerate(data_inputs):
+ global_id = data.get("id")
+ external_ref = data.get("external_reference")
+
+ try:
+ validate_one_of_args_is_in_mutation(
+ "id",
+ global_id,
+ "external_reference",
+ external_ref,
+ use_camel_case=True,
+ )
+ except ValidationError as exc:
+ index_error_map[index].append(
+ ProductVariantBulkTranslateError(
+ message=exc.message,
+ code=ProductVariantTranslateErrorCode.INVALID.value,
+ )
+ )
+ cleaned_inputs_map[index] = None
+ continue
+
+ if global_id:
+ try:
+ obj_type, id = from_global_id_or_error(
+ global_id, only_type="ProductVariant"
+ )
+ except GraphQLError as exc:
+ index_error_map[index].append(
+ ProductVariantBulkTranslateError(
+ message=str(exc),
+ code=ProductVariantTranslateErrorCode.INVALID.value,
+ )
+ )
+ cleaned_inputs_map[index] = None
+ continue
+ data["id"] = id
+
+ cleaned_inputs_map[index] = data
+ return cleaned_inputs_map
diff --git a/saleor/graphql/translations/mutations/utils.py b/saleor/graphql/translations/mutations/utils.py
index baf84d7288..3e0d334f1b 100644
--- a/saleor/graphql/translations/mutations/utils.py
+++ b/saleor/graphql/translations/mutations/utils.py
@@ -271,7 +271,7 @@ class BaseBulkTranslateMutation(BaseMutation):
if not base_object:
index_error_map[index].append(
cls._meta.error_type_class(
- message="Couldn't resolve to an attribute.",
+ message="Couldn't resolve to an object.",
code=TranslationErrorCode.NOT_FOUND.value,
path="id" if pk else "externalReference",
)
diff --git a/saleor/graphql/translations/tests/mutations/test_attribute_bulk_translate.py b/saleor/graphql/translations/tests/mutations/test_attribute_bulk_translate.py
index 2096165a36..018f375162 100644
--- a/saleor/graphql/translations/tests/mutations/test_attribute_bulk_translate.py
+++ b/saleor/graphql/translations/tests/mutations/test_attribute_bulk_translate.py
@@ -298,7 +298,7 @@ def test_attribute_bulk_translate_return_error_when_invalid_attr_id(
# then
assert data["count"] == 0
- message = "Couldn't resolve to an attribute."
+ message = "Couldn't resolve to an object."
error = data["results"][0]["errors"][0]
assert error["code"] == TranslationErrorCode.NOT_FOUND.name
assert error["message"] == message
@@ -333,7 +333,7 @@ def test_attribute_bulk_translate_return_error_when_invalid_attr_external_ref(
# then
assert data["count"] == 0
- message = "Couldn't resolve to an attribute."
+ message = "Couldn't resolve to an object."
error = data["results"][0]["errors"][0]
assert error["code"] == TranslationErrorCode.NOT_FOUND.name
assert error["message"] == message
diff --git a/saleor/graphql/translations/tests/mutations/test_attribute_value_bulk_transalte.py b/saleor/graphql/translations/tests/mutations/test_attribute_value_bulk_transalte.py
index 8add964e1c..47ae5f6f0b 100644
--- a/saleor/graphql/translations/tests/mutations/test_attribute_value_bulk_transalte.py
+++ b/saleor/graphql/translations/tests/mutations/test_attribute_value_bulk_transalte.py
@@ -343,7 +343,7 @@ def test_attribute_value_bulk_translate_return_error_when_invalid_value_id(
# then
assert data["count"] == 0
- message = "Couldn't resolve to an attribute."
+ message = "Couldn't resolve to an object."
error = data["results"][0]["errors"][0]
assert error["code"] == TranslationErrorCode.NOT_FOUND.name
assert error["message"] == message
@@ -378,7 +378,7 @@ def test_attribute_value_bulk_translate_return_error_when_invalid_value_external
# then
assert data["count"] == 0
- message = "Couldn't resolve to an attribute."
+ message = "Couldn't resolve to an object."
error = data["results"][0]["errors"][0]
assert error["code"] == TranslationErrorCode.NOT_FOUND.name
assert error["message"] == message
diff --git a/saleor/graphql/translations/tests/mutations/test_product_bulk_translate.py b/saleor/graphql/translations/tests/mutations/test_product_bulk_translate.py
new file mode 100644
index 0000000000..bc3a22ef37
--- /dev/null
+++ b/saleor/graphql/translations/tests/mutations/test_product_bulk_translate.py
@@ -0,0 +1,343 @@
+from unittest.mock import patch
+
+import graphene
+
+from .....tests.utils import dummy_editorjs
+from ....core.enums import LanguageCodeEnum, TranslationErrorCode
+from ....tests.utils import get_graphql_content
+
+PRODUCT_BULK_TRANSLATE_MUTATION = """
+ mutation ProductBulkTranslate(
+ $translations: [ProductBulkTranslateInput!]!
+ ) {
+ productBulkTranslate(translations: $translations) {
+ results {
+ errors {
+ path
+ code
+ message
+ }
+ translation {
+ id
+ name
+ description
+ language {
+ code
+ }
+ }
+ }
+ count
+ }
+ }
+"""
+
+description_pl = dummy_editorjs("description PL", True)
+description_de = dummy_editorjs("description DE", True)
+
+
+@patch("saleor.plugins.manager.PluginsManager.translation_created")
+def test_product_bulk_translate_creates_translations(
+ created_webhook_mock,
+ staff_api_client,
+ product,
+ permission_manage_translations,
+ settings,
+):
+ # given
+ assert product.translations.count() == 0
+
+ product_global_id = graphene.Node.to_global_id("Product", product.id)
+ translations = [
+ {
+ "id": product_global_id,
+ "languageCode": LanguageCodeEnum.PL.name,
+ "translationFields": {"name": "Product PL", "description": description_pl},
+ },
+ {
+ "id": product_global_id,
+ "languageCode": LanguageCodeEnum.DE.name,
+ "translationFields": {"name": "Product DE", "description": description_de},
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_translations)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_TRANSLATE_MUTATION,
+ {"translations": translations},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkTranslate"]
+
+ # then
+
+ assert product.translations.count() == 2
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert data["results"][0]["translation"]["name"] == "Product PL"
+ assert data["results"][0]["translation"]["description"] == description_pl
+ assert data["results"][1]["translation"]["name"] == "Product DE"
+ assert data["results"][1]["translation"]["description"] == description_de
+ assert created_webhook_mock.call_count == 2
+
+
+@patch("saleor.plugins.manager.PluginsManager.translation_updated")
+def test_product_bulk_translate_updates_translations(
+ updated_webhook_mock,
+ staff_api_client,
+ product_with_translations,
+ permission_manage_translations,
+ settings,
+):
+ # given
+ assert product_with_translations.translations.count() == 2
+
+ product_global_id = graphene.Node.to_global_id(
+ "Product", product_with_translations.id
+ )
+ translations = [
+ {
+ "id": product_global_id,
+ "languageCode": LanguageCodeEnum.PL.name,
+ "translationFields": {
+ "name": "NewProduct PL",
+ },
+ },
+ {
+ "id": product_global_id,
+ "languageCode": LanguageCodeEnum.DE.name,
+ "translationFields": {
+ "name": "NewProduct DE",
+ },
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_translations)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_TRANSLATE_MUTATION,
+ {"translations": translations},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkTranslate"]
+
+ # then
+
+ assert product_with_translations.translations.count() == 2
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert data["results"][0]["translation"]["name"] == "NewProduct PL"
+ assert data["results"][1]["translation"]["name"] == "NewProduct DE"
+ assert updated_webhook_mock.call_count == 2
+
+
+@patch("saleor.plugins.manager.PluginsManager.translation_created")
+def test_product_bulk_translate_creates_translations_using_attr_external_ref(
+ created_webhook_mock,
+ staff_api_client,
+ product,
+ permission_manage_translations,
+ settings,
+):
+ # given
+ assert product.translations.count() == 0
+ product.external_reference = "product-external-reference"
+ product.save(update_fields=["external_reference"])
+
+ translations = [
+ {
+ "externalReference": product.external_reference,
+ "languageCode": LanguageCodeEnum.PL.name,
+ "translationFields": {"name": "Product PL", "description": description_pl},
+ },
+ {
+ "externalReference": product.external_reference,
+ "languageCode": LanguageCodeEnum.DE.name,
+ "translationFields": {"name": "Product DE", "description": description_de},
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_translations)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_TRANSLATE_MUTATION,
+ {"translations": translations},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkTranslate"]
+
+ # then
+ assert product.translations.count() == 2
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert data["results"][0]["translation"]["name"] == "Product PL"
+ assert data["results"][0]["translation"]["description"] == description_pl
+ assert data["results"][1]["translation"]["name"] == "Product DE"
+ assert data["results"][1]["translation"]["description"] == description_de
+ assert created_webhook_mock.call_count == 2
+
+
+@patch("saleor.plugins.manager.PluginsManager.translation_updated")
+def test_product_bulk_translate_updates_translations_using_attr_external_ref(
+ updated_webhook_mock,
+ staff_api_client,
+ product_with_translations,
+ permission_manage_translations,
+ settings,
+):
+ # given
+ assert product_with_translations.translations.count() == 2
+ product_with_translations.external_reference = "product-external-reference"
+ product_with_translations.save(update_fields=["external_reference"])
+
+ translations = [
+ {
+ "externalReference": product_with_translations.external_reference,
+ "languageCode": LanguageCodeEnum.PL.name,
+ "translationFields": {
+ "name": "NewProduct PL",
+ "description": description_pl,
+ },
+ },
+ {
+ "externalReference": product_with_translations.external_reference,
+ "languageCode": LanguageCodeEnum.DE.name,
+ "translationFields": {
+ "name": "NewProduct DE",
+ "description": description_de,
+ },
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_translations)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_TRANSLATE_MUTATION,
+ {"translations": translations},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkTranslate"]
+
+ # then
+
+ assert product_with_translations.translations.count() == 2
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert data["results"][0]["translation"]["name"] == "NewProduct PL"
+ assert data["results"][0]["translation"]["description"] == description_pl
+ assert data["results"][1]["translation"]["name"] == "NewProduct DE"
+ assert data["results"][1]["translation"]["description"] == description_de
+ assert updated_webhook_mock.call_count == 2
+
+
+def test_product_bulk_translate_return_error_when_attr_id_and_external_ref(
+ staff_api_client,
+ product,
+ permission_manage_translations,
+ settings,
+):
+ # given
+ assert product.translations.count() == 0
+ product.external_reference = "product_pl"
+ product.save(update_fields=["external_reference"])
+ product_global_id = graphene.Node.to_global_id("Product", product.id)
+
+ translations = [
+ {
+ "id": product_global_id,
+ "externalReference": product.external_reference,
+ "languageCode": LanguageCodeEnum.PL.name,
+ "translationFields": {
+ "name": "Product PL",
+ },
+ }
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_translations)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_TRANSLATE_MUTATION,
+ {"translations": translations},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkTranslate"]
+
+ # then
+ assert product.translations.count() == 0
+ assert data["count"] == 0
+ message = "Argument 'id' cannot be combined with 'externalReference'"
+ error = data["results"][0]["errors"][0]
+ assert error["code"] == TranslationErrorCode.INVALID.name
+ assert error["message"] == message
+
+
+def test_product_bulk_translate_return_error_when_invalid_attr_id(
+ staff_api_client,
+ permission_manage_translations,
+ settings,
+):
+ # given
+ translations = [
+ {
+ "id": graphene.Node.to_global_id("Product", -1),
+ "languageCode": LanguageCodeEnum.PL.name,
+ "translationFields": {
+ "name": "Product PL",
+ },
+ }
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_translations)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_TRANSLATE_MUTATION,
+ {"translations": translations},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkTranslate"]
+
+ # then
+ assert data["count"] == 0
+ message = "Couldn't resolve to an object."
+ error = data["results"][0]["errors"][0]
+ assert error["code"] == TranslationErrorCode.NOT_FOUND.name
+ assert error["message"] == message
+ assert error["path"] == "id"
+
+
+def test_product_bulk_translate_return_error_when_invalid_attr_external_ref(
+ staff_api_client,
+ permission_manage_translations,
+ settings,
+):
+ # given
+ translations = [
+ {
+ "externalReference": "invalid_reference",
+ "languageCode": LanguageCodeEnum.PL.name,
+ "translationFields": {
+ "name": "Product PL",
+ },
+ }
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_translations)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_TRANSLATE_MUTATION,
+ {"translations": translations},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkTranslate"]
+
+ # then
+ assert data["count"] == 0
+ message = "Couldn't resolve to an object."
+ error = data["results"][0]["errors"][0]
+ assert error["code"] == TranslationErrorCode.NOT_FOUND.name
+ assert error["message"] == message
+ assert error["path"] == "externalReference"
diff --git a/saleor/graphql/translations/tests/mutations/test_product_variant_bulk_translate.py b/saleor/graphql/translations/tests/mutations/test_product_variant_bulk_translate.py
new file mode 100644
index 0000000000..8d643a1e11
--- /dev/null
+++ b/saleor/graphql/translations/tests/mutations/test_product_variant_bulk_translate.py
@@ -0,0 +1,334 @@
+from unittest.mock import patch
+
+import graphene
+
+from ....core.enums import LanguageCodeEnum, TranslationErrorCode
+from ....tests.utils import get_graphql_content
+
+PRODUCT_VARIANT_BULK_TRANSLATE_MUTATION = """
+ mutation ProductVariantBulkTranslate(
+ $translations: [ProductVariantBulkTranslateInput!]!
+ ) {
+ productVariantBulkTranslate(translations: $translations) {
+ results {
+ errors {
+ path
+ code
+ message
+ }
+ translation {
+ id
+ name
+ language {
+ code
+ }
+ }
+ }
+ count
+ }
+ }
+"""
+
+
+@patch("saleor.plugins.manager.PluginsManager.translation_created")
+def test_product_variant_variant_bulk_translate_creates_translations(
+ created_webhook_mock,
+ staff_api_client,
+ variant,
+ permission_manage_translations,
+ settings,
+):
+ # given
+ assert variant.translations.count() == 0
+
+ variant_global_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ translations = [
+ {
+ "id": variant_global_id,
+ "languageCode": LanguageCodeEnum.PL.name,
+ "translationFields": {"name": "Product PL"},
+ },
+ {
+ "id": variant_global_id,
+ "languageCode": LanguageCodeEnum.DE.name,
+ "translationFields": {"name": "Product DE"},
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_translations)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_TRANSLATE_MUTATION,
+ {"translations": translations},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkTranslate"]
+
+ # then
+
+ assert variant.translations.count() == 2
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert data["results"][0]["translation"]["name"] == "Product PL"
+ assert data["results"][1]["translation"]["name"] == "Product DE"
+ assert created_webhook_mock.call_count == 2
+
+
+@patch("saleor.plugins.manager.PluginsManager.translation_updated")
+def test_product_variant_bulk_translate_updates_translations(
+ updated_webhook_mock,
+ staff_api_client,
+ variant_with_translations,
+ permission_manage_translations,
+ settings,
+):
+ # given
+ assert variant_with_translations.translations.count() == 2
+
+ variant_global_id = graphene.Node.to_global_id(
+ "ProductVariant", variant_with_translations.id
+ )
+ translations = [
+ {
+ "id": variant_global_id,
+ "languageCode": LanguageCodeEnum.PL.name,
+ "translationFields": {
+ "name": "NewVariant PL",
+ },
+ },
+ {
+ "id": variant_global_id,
+ "languageCode": LanguageCodeEnum.DE.name,
+ "translationFields": {
+ "name": "NewVariant DE",
+ },
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_translations)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_TRANSLATE_MUTATION,
+ {"translations": translations},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkTranslate"]
+
+ # then
+
+ assert variant_with_translations.translations.count() == 2
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert data["results"][0]["translation"]["name"] == "NewVariant PL"
+ assert data["results"][1]["translation"]["name"] == "NewVariant DE"
+ assert updated_webhook_mock.call_count == 2
+
+
+@patch("saleor.plugins.manager.PluginsManager.translation_created")
+def test_product_variant_bulk_translate_creates_translations_using_attr_external_ref(
+ created_webhook_mock,
+ staff_api_client,
+ variant,
+ permission_manage_translations,
+ settings,
+):
+ # given
+ assert variant.translations.count() == 0
+ variant.external_reference = "variant-external-reference"
+ variant.save(update_fields=["external_reference"])
+
+ translations = [
+ {
+ "externalReference": variant.external_reference,
+ "languageCode": LanguageCodeEnum.PL.name,
+ "translationFields": {
+ "name": "Variant PL",
+ },
+ },
+ {
+ "externalReference": variant.external_reference,
+ "languageCode": LanguageCodeEnum.DE.name,
+ "translationFields": {
+ "name": "Variant DE",
+ },
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_translations)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_TRANSLATE_MUTATION,
+ {"translations": translations},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkTranslate"]
+
+ # then
+ assert variant.translations.count() == 2
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert data["results"][0]["translation"]["name"] == "Variant PL"
+ assert data["results"][1]["translation"]["name"] == "Variant DE"
+ assert created_webhook_mock.call_count == 2
+
+
+@patch("saleor.plugins.manager.PluginsManager.translation_updated")
+def test_product_variant_bulk_translate_updates_translations_using_attr_external_ref(
+ updated_webhook_mock,
+ staff_api_client,
+ variant_with_translations,
+ permission_manage_translations,
+ settings,
+):
+ # given
+ assert variant_with_translations.translations.count() == 2
+ variant_with_translations.external_reference = "variant-external-reference"
+ variant_with_translations.save(update_fields=["external_reference"])
+
+ translations = [
+ {
+ "externalReference": variant_with_translations.external_reference,
+ "languageCode": LanguageCodeEnum.PL.name,
+ "translationFields": {
+ "name": "NewVariant PL",
+ },
+ },
+ {
+ "externalReference": variant_with_translations.external_reference,
+ "languageCode": LanguageCodeEnum.DE.name,
+ "translationFields": {
+ "name": "NewVariant DE",
+ },
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_translations)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_TRANSLATE_MUTATION,
+ {"translations": translations},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkTranslate"]
+
+ # then
+
+ assert variant_with_translations.translations.count() == 2
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert data["results"][0]["translation"]["name"] == "NewVariant PL"
+ assert data["results"][1]["translation"]["name"] == "NewVariant DE"
+ assert updated_webhook_mock.call_count == 2
+
+
+def test_product_variant_bulk_translate_return_error_when_attr_id_and_external_ref(
+ staff_api_client,
+ variant,
+ permission_manage_translations,
+ settings,
+):
+ # given
+ assert variant.translations.count() == 0
+ variant.external_reference = "variant-external-reference"
+ variant.save(update_fields=["external_reference"])
+ variant_global_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ translations = [
+ {
+ "id": variant_global_id,
+ "externalReference": variant.external_reference,
+ "languageCode": LanguageCodeEnum.PL.name,
+ "translationFields": {
+ "name": "Variant PL",
+ },
+ }
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_translations)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_TRANSLATE_MUTATION,
+ {"translations": translations},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkTranslate"]
+
+ # then
+ assert variant.translations.count() == 0
+ assert data["count"] == 0
+ message = "Argument 'id' cannot be combined with 'externalReference'"
+ error = data["results"][0]["errors"][0]
+ assert error["code"] == TranslationErrorCode.INVALID.name
+ assert error["message"] == message
+
+
+def test_product_variant_bulk_translate_return_error_when_invalid_attr_id(
+ staff_api_client,
+ permission_manage_translations,
+ settings,
+):
+ # given
+ translations = [
+ {
+ "id": graphene.Node.to_global_id("ProductVariant", -1),
+ "languageCode": LanguageCodeEnum.PL.name,
+ "translationFields": {
+ "name": "Variant PL",
+ },
+ }
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_translations)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_TRANSLATE_MUTATION,
+ {"translations": translations},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkTranslate"]
+
+ # then
+ assert data["count"] == 0
+ message = "Couldn't resolve to an object."
+ error = data["results"][0]["errors"][0]
+ assert error["code"] == TranslationErrorCode.NOT_FOUND.name
+ assert error["message"] == message
+ assert error["path"] == "id"
+
+
+def test_product_variant_bulk_translate_return_error_when_invalid_attr_external_ref(
+ staff_api_client,
+ permission_manage_translations,
+ settings,
+):
+ # given
+ translations = [
+ {
+ "externalReference": "invalid_reference",
+ "languageCode": LanguageCodeEnum.PL.name,
+ "translationFields": {
+ "name": "Product PL",
+ },
+ }
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_translations)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_TRANSLATE_MUTATION,
+ {"translations": translations},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkTranslate"]
+
+ # then
+ assert data["count"] == 0
+ message = "Couldn't resolve to an object."
+ error = data["results"][0]["errors"][0]
+ assert error["code"] == TranslationErrorCode.NOT_FOUND.name
+ assert error["message"] == message
+ assert error["path"] == "externalReference"
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 9f55df8a51..e35811e097 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -2485,6 +2485,14 @@ def product(product_type, category, warehouse, channel_USD, default_tax_class):
return product
+def product_with_translations(product):
+ product.translations.create(language_code="pl", name="OldProduct PL")
+ product.translations.create(language_code="de", name="OldProduct DE")
+
+ return product
+
+
@pytest.fixture
def shippable_gift_card_product(
shippable_gift_card_product_type, category, warehouse, channel_USD
@@ -3043,6 +3051,13 @@ def variant(product, channel_USD) -> ProductVariant:
return product_variant
+def variant_with_translations(variant):
+ variant.translations.create(language_code="pl", name="OldVariant PL")
+ variant.translations.create(language_code="de", name="OldVariant DE")
+ return variant
+
+
@pytest.fixture
def variant_with_image(variant, image_list, media_root):
media = ProductMedia.objects.create(product=variant.product, image=image_list[0])
diff --git a/saleor/translations/error_codes.py b/saleor/translations/error_codes.py
index 9188a75bcd..86f0c226da 100644
--- a/saleor/translations/error_codes.py
+++ b/saleor/translations/error_codes.py
@@ -13,3 +13,17 @@ class AttributeValueTranslateErrorCode(Enum):
INVALID = "invalid"
NOT_FOUND = "not_found"
REQUIRED = "required"
+
+
+class ProductTranslateErrorCode(Enum):
+ GRAPHQL_ERROR = "graphql_error"
+ INVALID = "invalid"
+ NOT_FOUND = "not_found"
+ REQUIRED = "required"
+
+
+class ProductVariantTranslateErrorCode(Enum):
+ GRAPHQL_ERROR = "graphql_error"
+ INVALID = "invalid"
+ NOT_FOUND = "not_found"
+ REQUIRED = "required"