Skip to content

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

language code for email payload (#6609)

Maciej Korycinski31a660c06504
diff --git a/saleor/account/migrations/0048_user_language_code.py b/saleor/account/migrations/0048_user_language_code.py
new file mode 100644
index 0000000000..34ae035afc
--- /dev/null
+++ b/saleor/account/migrations/0048_user_language_code.py
@@ -0,0 +1,72 @@
+# Generated by Django 3.1.4 on 2020-12-12 11:33
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("account", "0047_auto_20200810_1415"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="user",
+ name="language_code",
+ field=models.CharField(
+ choices=[
+ ("ar", "Arabic"),
+ ("az", "Azerbaijani"),
+ ("bg", "Bulgarian"),
+ ("bn", "Bengali"),
+ ("ca", "Catalan"),
+ ("cs", "Czech"),
+ ("da", "Danish"),
+ ("de", "German"),
+ ("el", "Greek"),
+ ("en", "English"),
+ ("es", "Spanish"),
+ ("es-co", "Colombian Spanish"),
+ ("et", "Estonian"),
+ ("fa", "Persian"),
+ ("fi", "Finnish"),
+ ("fr", "French"),
+ ("hi", "Hindi"),
+ ("hu", "Hungarian"),
+ ("hy", "Armenian"),
+ ("id", "Indonesian"),
+ ("is", "Icelandic"),
+ ("it", "Italian"),
+ ("ja", "Japanese"),
+ ("ka", "Georgian"),
+ ("km", "Khmer"),
+ ("ko", "Korean"),
+ ("lt", "Lithuanian"),
+ ("mn", "Mongolian"),
+ ("my", "Burmese"),
+ ("nb", "Norwegian"),
+ ("nl", "Dutch"),
+ ("pl", "Polish"),
+ ("pt", "Portuguese"),
+ ("pt-br", "Brazilian Portuguese"),
+ ("ro", "Romanian"),
+ ("ru", "Russian"),
+ ("sk", "Slovak"),
+ ("sl", "Slovenian"),
+ ("sq", "Albanian"),
+ ("sr", "Serbian"),
+ ("sv", "Swedish"),
+ ("sw", "Swahili"),
+ ("ta", "Tamil"),
+ ("th", "Thai"),
+ ("tr", "Turkish"),
+ ("uk", "Ukrainian"),
+ ("vi", "Vietnamese"),
+ ("zh-hans", "Simplified Chinese"),
+ ("zh-hant", "Traditional Chinese"),
+ ],
+ default="en",
+ max_length=35,
+ ),
+ ),
+ ]
diff --git a/saleor/account/models.py b/saleor/account/models.py
index e46fb23480..ce44d96a25 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -152,6 +152,9 @@ class User(PermissionsMixin, ModelWithMetadata, AbstractBaseUser):
)
avatar = VersatileImageField(upload_to="user-avatars", blank=True, null=True)
jwt_token_key = models.CharField(max_length=12, default=get_random_string)
+ language_code = models.CharField(
+ max_length=35, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE
+ )
USERNAME_FIELD = "email"
diff --git a/saleor/account/notifications.py b/saleor/account/notifications.py
index 6367bc82ff..53162a3661 100644
--- a/saleor/account/notifications.py
+++ b/saleor/account/notifications.py
@@ -18,6 +18,7 @@ def get_default_user_payload(user: User):
"is_active": user.is_active,
"private_metadata": user.private_metadata,
"metadata": user.metadata,
+ "language_code": user.language_code,
}
diff --git a/saleor/account/tests/test_notifications.py b/saleor/account/tests/test_notifications.py
index c6afe5ee0b..3219b136c6 100644
--- a/saleor/account/tests/test_notifications.py
+++ b/saleor/account/tests/test_notifications.py
@@ -8,6 +8,20 @@ from .. import notifications
from ..notifications import get_default_user_payload
+def test_get_default_user_payload(customer_user):
+ assert get_default_user_payload(customer_user) == {
+ "id": customer_user.id,
+ "email": customer_user.email,
+ "first_name": customer_user.first_name,
+ "last_name": customer_user.last_name,
+ "is_staff": customer_user.is_staff,
+ "is_active": customer_user.is_active,
+ "private_metadata": customer_user.private_metadata,
+ "metadata": customer_user.metadata,
+ "language_code": customer_user.language_code,
+ }
+
+
@freeze_time("2018-05-31 12:00:01")
@mock.patch("saleor.plugins.manager.PluginsManager.notify")
def test_send_email_request_change(mocked_notify, site_settings, customer_user):
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 606572da88..f3bf38596b 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -5,7 +5,6 @@ from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.db import transaction
from django.utils.encoding import smart_text
-from django.utils.translation import get_language
from prices import TaxedMoney
from ..account.error_codes import AccountErrorCode
@@ -211,7 +210,7 @@ def _create_lines_for_order(
:raises InsufficientStock: when there is not enough items in stock for this variant.
"""
- translation_language_code = get_language()
+ translation_language_code = checkout.language_code
country_code = checkout.get_country()
variants = []
quantities = []
@@ -294,7 +293,7 @@ def _prepare_order_data(
order_data.update(_process_user_data_for_order(checkout, manager))
order_data.update(
{
- "language_code": get_language(),
+ "language_code": checkout.language_code,
"tracking_client_id": checkout.tracking_code or "",
"total": taxed_total,
"shipping_tax_rate": shipping_tax_rate,
diff --git a/saleor/checkout/migrations/0031_checkout_language_code.py b/saleor/checkout/migrations/0031_checkout_language_code.py
new file mode 100644
index 0000000000..e6289d7c09
--- /dev/null
+++ b/saleor/checkout/migrations/0031_checkout_language_code.py
@@ -0,0 +1,72 @@
+# Generated by Django 3.1.4 on 2020-12-12 12:27
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("checkout", "0030_checkout_channel_listing"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="checkout",
+ name="language_code",
+ field=models.CharField(
+ choices=[
+ ("ar", "Arabic"),
+ ("az", "Azerbaijani"),
+ ("bg", "Bulgarian"),
+ ("bn", "Bengali"),
+ ("ca", "Catalan"),
+ ("cs", "Czech"),
+ ("da", "Danish"),
+ ("de", "German"),
+ ("el", "Greek"),
+ ("en", "English"),
+ ("es", "Spanish"),
+ ("es-co", "Colombian Spanish"),
+ ("et", "Estonian"),
+ ("fa", "Persian"),
+ ("fi", "Finnish"),
+ ("fr", "French"),
+ ("hi", "Hindi"),
+ ("hu", "Hungarian"),
+ ("hy", "Armenian"),
+ ("id", "Indonesian"),
+ ("is", "Icelandic"),
+ ("it", "Italian"),
+ ("ja", "Japanese"),
+ ("ka", "Georgian"),
+ ("km", "Khmer"),
+ ("ko", "Korean"),
+ ("lt", "Lithuanian"),
+ ("mn", "Mongolian"),
+ ("my", "Burmese"),
+ ("nb", "Norwegian"),
+ ("nl", "Dutch"),
+ ("pl", "Polish"),
+ ("pt", "Portuguese"),
+ ("pt-br", "Brazilian Portuguese"),
+ ("ro", "Romanian"),
+ ("ru", "Russian"),
+ ("sk", "Slovak"),
+ ("sl", "Slovenian"),
+ ("sq", "Albanian"),
+ ("sr", "Serbian"),
+ ("sv", "Swedish"),
+ ("sw", "Swahili"),
+ ("ta", "Tamil"),
+ ("th", "Thai"),
+ ("tr", "Turkish"),
+ ("uk", "Ukrainian"),
+ ("vi", "Vietnamese"),
+ ("zh-hans", "Simplified Chinese"),
+ ("zh-hant", "Traditional Chinese"),
+ ],
+ default="en",
+ max_length=35,
+ ),
+ ),
+ ]
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 2a491d0760..8cdd70dacf 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -89,6 +89,10 @@ class Checkout(ModelWithMetadata):
redirect_url = models.URLField(blank=True, null=True)
tracking_code = models.CharField(max_length=255, blank=True, null=True)
+ language_code = models.CharField(
+ max_length=35, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE
+ )
+
class Meta:
ordering = ("-last_change", "pk")
permissions = (
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index 06ef296642..7240f6667c 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -780,6 +780,7 @@ def test_create_order_use_tanslations(
checkout.shipping_method = shipping_method
checkout.tracking_code = ""
checkout.redirect_url = "https://www.example.com"
+ checkout.language_code = "fr"
checkout.save()
manager = get_plugins_manager()
diff --git a/saleor/graphql/account/mutations/account.py b/saleor/graphql/account/mutations/account.py
index 2037077ac6..742cb56a01 100644
--- a/saleor/graphql/account/mutations/account.py
+++ b/saleor/graphql/account/mutations/account.py
@@ -14,6 +14,7 @@ from ....core.utils.url import validate_storefront_url
from ....settings import JWT_TTL_REQUEST_EMAIL_CHANGE
from ...account.enums import AddressTypeEnum
from ...account.types import Address, AddressInput, User
+from ...core.enums import LanguageCodeEnum
from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ...core.types.common import AccountError
from ..i18n import I18nMixin
@@ -34,6 +35,9 @@ class AccountRegisterInput(graphene.InputObjectType):
),
required=False,
)
+ language_code = graphene.Argument(
+ LanguageCodeEnum, required=False, description="User language code."
+ )
class AccountRegister(ModelMutation):
@@ -88,7 +92,7 @@ class AccountRegister(ModelMutation):
password_validation.validate_password(password, instance)
except ValidationError as error:
raise ValidationError({"password": error})
-
+ data["language_code"] = data.get("language_code") or settings.LANGUAGE_CODE
return super().clean_input(info, instance, data, input_cls=None)
@classmethod
@@ -116,6 +120,9 @@ class AccountInput(graphene.InputObjectType):
default_shipping_address = AddressInput(
description="Shipping address of the customer."
)
+ language_code = graphene.Argument(
+ LanguageCodeEnum, required=False, description="User language code."
+ )
class AccountUpdate(BaseCustomerCreate):
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index 0f0361bbaf..59e4806c08 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -17,6 +17,7 @@ from ....core.utils.url import validate_storefront_url
from ....order.utils import match_orders_with_new_user
from ...account.i18n import I18nMixin
from ...account.types import Address, AddressInput, User
+from ...core.enums import LanguageCodeEnum
from ...core.mutations import (
BaseMutation,
ModelDeleteMutation,
@@ -354,7 +355,9 @@ class UserAddressInput(graphene.InputObjectType):
class CustomerInput(UserInput, UserAddressInput):
- pass
+ language_code = graphene.Field(
+ LanguageCodeEnum, required=False, description="User language code."
+ )
class UserCreateInput(CustomerInput):
diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.py
index c4481fb695..dda748fd9a 100644
--- a/saleor/graphql/account/tests/test_account.py
+++ b/saleor/graphql/account/tests/test_account.py
@@ -91,6 +91,7 @@ FULL_USER_QUERY = """
orders {
totalCount
}
+ languageCode
dateJoined
lastLogin
defaultShippingAddress {
@@ -154,7 +155,12 @@ FULL_USER_QUERY = """
def test_query_customer_user(
- staff_api_client, customer_user, address, permission_manage_users, media_root
+ staff_api_client,
+ customer_user,
+ address,
+ permission_manage_users,
+ media_root,
+ settings,
):
user = customer_user
user.default_shipping_address.country = "US"
@@ -182,6 +188,7 @@ def test_query_customer_user(
assert data["isActive"] == user.is_active
assert data["orders"]["totalCount"] == user.orders.count()
assert data["avatar"]["url"]
+ assert data["languageCode"] == settings.LANGUAGE_CODE.upper()
assert len(data["editableGroups"]) == 0
assert len(data["addresses"]) == user.addresses.count()
@@ -827,13 +834,15 @@ ACCOUNT_REGISTER_MUTATION = """
mutation RegisterAccount(
$password: String!,
$email: String!,
- $redirectUrl: String
+ $redirectUrl: String,
+ $languageCode: LanguageCodeEnum
) {
accountRegister(
input: {
password: $password,
email: $email,
- redirectUrl: $redirectUrl
+ redirectUrl: $redirectUrl,
+ languageCode: $languageCode,
}
) {
accountErrors {
@@ -862,6 +871,7 @@ def test_customer_register(mocked_notify, mocked_generator, api_client):
"email": email,
"password": "Password",
"redirectUrl": redirect_url,
+ "languageCode": "PL",
}
query = ACCOUNT_REGISTER_MUTATION
mutation_name = "accountRegister"
@@ -881,7 +891,7 @@ def test_customer_register(mocked_notify, mocked_generator, api_client):
"site_name": "mirumee.com",
"domain": "mirumee.com",
}
-
+ assert new_user.language_code == "pl"
assert not data["accountErrors"]
mocked_notify.assert_called_once_with(
NotifyEventType.ACCOUNT_CONFIRMATION, payload=expected_payload
@@ -929,15 +939,16 @@ CUSTOMER_CREATE_MUTATION = """
mutation CreateCustomer(
$email: String, $firstName: String, $lastName: String,
$note: String, $billing: AddressInput, $shipping: AddressInput,
- $redirect_url: String) {
+ $redirect_url: String, $languageCode: LanguageCodeEnum) {
customerCreate(input: {
email: $email,
firstName: $firstName,
lastName: $lastName,
note: $note,
defaultShippingAddress: $shipping,
- defaultBillingAddress: $billing
- redirectUrl: $redirect_url
+ defaultBillingAddress: $billing,
+ redirectUrl: $redirect_url,
+ languageCode: $languageCode
}) {
errors {
field
@@ -955,6 +966,7 @@ CUSTOMER_CREATE_MUTATION = """
defaultShippingAddress {
id
}
+ languageCode
email
firstName
lastName
@@ -987,6 +999,7 @@ def test_customer_create(
"shipping": address_data,
"billing": address_data,
"redirect_url": redirect_url,
+ "languageCode": "PL",
}
response = staff_api_client.post_graphql(
@@ -1010,6 +1023,7 @@ def test_customer_create(
assert data["user"]["firstName"] == first_name
assert data["user"]["lastName"] == last_name
assert data["user"]["note"] == note
+ assert data["user"]["languageCode"] == "PL"
assert not data["user"]["isStaff"]
assert data["user"]["isActive"]
@@ -1125,14 +1139,15 @@ def test_customer_update(
mutation UpdateCustomer(
$id: ID!, $firstName: String, $lastName: String,
$isActive: Boolean, $note: String, $billing: AddressInput,
- $shipping: AddressInput) {
+ $shipping: AddressInput, $languageCode: LanguageCodeEnum) {
customerUpdate(id: $id, input: {
isActive: $isActive,
firstName: $firstName,
lastName: $lastName,
note: $note,
defaultBillingAddress: $billing
- defaultShippingAddress: $shipping
+ defaultShippingAddress: $shipping,
+ languageCode: $languageCode
}) {
errors {
field
@@ -1148,6 +1163,7 @@ def test_customer_update(
defaultShippingAddress {
id
}
+ languageCode
isActive
note
}
@@ -1179,6 +1195,7 @@ def test_customer_update(
"note": note,
"billing": address_data,
"shipping": address_data,
+ "languageCode": "PL",
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_users]
@@ -1203,6 +1220,7 @@ def test_customer_update(
assert data["user"]["firstName"] == first_name
assert data["user"]["lastName"] == last_name
assert data["user"]["note"] == note
+ assert data["user"]["languageCode"] == "PL"
assert not data["user"]["isActive"]
# The name was changed, an event should have been triggered
@@ -1296,13 +1314,14 @@ def test_customer_update_without_any_changes_generates_no_event(
ACCOUNT_UPDATE_QUERY = """
mutation accountUpdate(
$billing: AddressInput, $shipping: AddressInput, $firstName: String,
- $lastName: String) {
+ $lastName: String, $languageCode: LanguageCodeEnum) {
accountUpdate(
input: {
defaultBillingAddress: $billing,
defaultShippingAddress: $shipping,
firstName: $firstName,
lastName: $lastName,
+ languageCode: $languageCode
}) {
errors {
field
@@ -1318,12 +1337,29 @@ ACCOUNT_UPDATE_QUERY = """
defaultShippingAddress {
id
}
+ languageCode
}
}
}
"""
+def test_logged_customer_updates_language_code(user_api_client):
+ language_code = "PL"
+ user = user_api_client.user
+ assert user.language_code != language_code
+ variables = {"languageCode": language_code}
+
+ response = user_api_client.post_graphql(ACCOUNT_UPDATE_QUERY, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["accountUpdate"]
+
+ assert not data["errors"]
+ assert data["user"]["languageCode"] == language_code
+ user.refresh_from_db()
+ assert user.language_code == language_code.lower()
+
+
def test_logged_customer_update_names(user_api_client):
first_name = "first"
last_name = "last"
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index a24bbdeb8c..f67731f25d 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -12,10 +12,11 @@ from ...order import models as order_models
from ..checkout.dataloaders import CheckoutByUserAndChannelLoader, CheckoutByUserLoader
from ..checkout.types import Checkout
from ..core.connection import CountableDjangoObjectType
+from ..core.enums import LanguageCodeEnum
from ..core.fields import PrefetchingConnectionField
from ..core.scalars import UUID
from ..core.types import CountryDisplay, Image, Permission
-from ..core.utils import from_global_id_strict_type
+from ..core.utils import from_global_id_strict_type, str_to_enum
from ..decorators import one_of_permissions_required, permission_required
from ..meta.types import ObjectWithMetadata
from ..utils import format_permissions_for_display
@@ -241,6 +242,9 @@ class User(CountableDjangoObjectType):
"saleor.graphql.payment.types.PaymentSource",
description="List of stored payment sources.",
)
+ language_code = graphene.Field(
+ LanguageCodeEnum, description="User language code.", required=True
+ )
class Meta:
description = "Represents user data."
@@ -365,6 +369,10 @@ class User(CountableDjangoObjectType):
return graphene.Node.get_node_from_global_id(_info, root.id)
return get_user_model().objects.get(email=root.email)
+ @staticmethod
+ def resolve_language_code(root, _info, **_kwargs):
+ return LanguageCodeEnum[str_to_enum(root.language_code)]
+
class ChoiceValue(graphene.ObjectType):
raw = graphene.String()
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 3710e02c24..27cde82dd2 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -33,6 +33,7 @@ from ...shipping import models as shipping_models
from ...warehouse.availability import check_stock_quantity_bulk
from ..account.i18n import I18nMixin
from ..account.types import AddressInput
+from ..core.enums import LanguageCodeEnum
from ..core.mutations import BaseMutation, ModelMutation
from ..core.types.common import CheckoutError
from ..core.utils import from_global_id_strict_type
@@ -182,6 +183,9 @@ class CheckoutCreateInput(graphene.InputObjectType):
)
)
billing_address = AddressInput(description="Billing address of the customer.")
+ language_code = graphene.Argument(
+ LanguageCodeEnum, required=False, description="Checkout language code."
+ )
class CheckoutCreate(ModelMutation, I18nMixin):
@@ -316,6 +320,9 @@ class CheckoutCreate(ModelMutation, I18nMixin):
email = data.pop("email", None)
cleaned_input["email"] = email or user.email
+ language_code = data.get("language_code") or settings.LANGUAGE_CODE
+ cleaned_input["language_code"] = language_code
+
return cleaned_input
@classmethod
@@ -689,6 +696,31 @@ class CheckoutBillingAddressUpdate(CheckoutShippingAddressUpdate):
return CheckoutBillingAddressUpdate(checkout=checkout)
+class CheckoutLanguageCodeUpdate(BaseMutation):
+ checkout = graphene.Field(Checkout, description="An updated checkout.")
+
+ class Arguments:
+ checkout_id = graphene.ID(required=True, description="ID of the checkout.")
+ language_code = graphene.Argument(
+ LanguageCodeEnum, required=True, description="New language code."
+ )
+
+ class Meta:
+ description = "Update language code in the existing checkout."
+ error_type_class = CheckoutError
+ error_type_field = "checkout_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, checkout_id, language_code):
+ checkout = cls.get_node_or_error(
+ info, checkout_id, only_type=Checkout, field="checkout_id"
+ )
+ checkout.language_code = language_code
+ checkout.save(update_fields=["language_code", "last_change"])
+ info.context.plugins.checkout_updated(checkout)
+ return CheckoutLanguageCodeUpdate(checkout=checkout)
+
+
class CheckoutEmailUpdate(BaseMutation):
checkout = graphene.Field(Checkout, description="An updated checkout.")
diff --git a/saleor/graphql/checkout/schema.py b/saleor/graphql/checkout/schema.py
index 3122f22fdb..cb0bfb615a 100644
--- a/saleor/graphql/checkout/schema.py
+++ b/saleor/graphql/checkout/schema.py
@@ -13,6 +13,7 @@ from .mutations import (
CheckoutCustomerAttach,
CheckoutCustomerDetach,
CheckoutEmailUpdate,
+ CheckoutLanguageCodeUpdate,
CheckoutLineDelete,
CheckoutLinesAdd,
CheckoutLinesUpdate,
@@ -77,3 +78,4 @@ class CheckoutMutations(graphene.ObjectType):
checkout_payment_create = CheckoutPaymentCreate.Field()
checkout_shipping_address_update = CheckoutShippingAddressUpdate.Field()
checkout_shipping_method_update = CheckoutShippingMethodUpdate.Field()
+ checkout_language_code_update = CheckoutLanguageCodeUpdate.Field()
diff --git a/saleor/graphql/checkout/tests/test_checkout_language_code_update.py b/saleor/graphql/checkout/tests/test_checkout_language_code_update.py
new file mode 100644
index 0000000000..64f29ab5a3
--- /dev/null
+++ b/saleor/graphql/checkout/tests/test_checkout_language_code_update.py
@@ -0,0 +1,40 @@
+import graphene
+
+from saleor.graphql.tests.utils import get_graphql_content
+
+MUTATION_CHECKOUT_UPDATE_LANGUAGE_CODE = """
+mutation checkoutLanguageCodeUpdate($checkoutId: ID!, $languageCode: LanguageCodeEnum!){
+ checkoutLanguageCodeUpdate(checkoutId:$checkoutId, languageCode: $languageCode){
+ checkout{
+ id
+ languageCode
+ }
+ checkoutErrors{
+ field
+ message
+ }
+ }
+}
+"""
+
+
+def test_checkout_update_language_code(
+ user_api_client,
+ checkout_with_gift_card,
+):
+ language_code = "PL"
+ checkout = checkout_with_gift_card
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ variables = {"checkoutId": checkout_id, "languageCode": language_code}
+
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_UPDATE_LANGUAGE_CODE, variables
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLanguageCodeUpdate"]
+ assert not data["checkoutErrors"]
+
+ assert data["checkout"]["languageCode"] == language_code
+ checkout.refresh_from_db()
+ assert checkout.language_code == language_code.lower()
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index dde7762369..cc4fb80be1 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -11,8 +11,10 @@ from ..account.utils import requestor_has_access
from ..channel import ChannelContext
from ..channel.dataloaders import ChannelByCheckoutLineIDLoader, ChannelByIdLoader
from ..core.connection import CountableDjangoObjectType
+from ..core.enums import LanguageCodeEnum
from ..core.scalars import UUID
from ..core.types.money import TaxedMoney
+from ..core.utils import str_to_enum
from ..discount.dataloaders import DiscountsByDateTimeLoader
from ..giftcard.types import GiftCard
from ..meta.types import ObjectWithMetadata
@@ -217,6 +219,9 @@ class Checkout(CountableDjangoObjectType):
"shipping costs, and discounts included."
),
)
+ language_code = graphene.Field(
+ LanguageCodeEnum, required=True, description="Checkout language code."
+ )
class Meta:
only_fields = [
@@ -463,3 +468,7 @@ class Checkout(CountableDjangoObjectType):
.load(root.token)
.then(is_shipping_required)
)
+
+ @staticmethod
+ def resolve_language_code(root, _info, **_kwargs):
+ return LanguageCodeEnum[str_to_enum(root.language_code)]
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index 2723970b22..d0865c2e78 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -1,4 +1,5 @@
import graphene
+from django.conf import settings
from ...account import error_codes as account_error_codes
from ...app import error_codes as app_error_codes
@@ -78,6 +79,11 @@ def to_enum(enum_cls, *, type_name=None, **options) -> graphene.Enum:
return graphene.Enum(type_name, enum_data, **options)
+LanguageCodeEnum = graphene.Enum(
+ "LanguageCodeEnum",
+ [(lang[0].replace("-", "_").upper(), lang[0]) for lang in settings.LANGUAGES],
+)
+
TaxRateType = graphene.Enum(
"TaxRateType", [(str_to_enum(rate[0]), rate[0]) for rate in CoreTaxRateType.CHOICES]
)
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index c8710c0059..50c4407485 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -4,7 +4,6 @@ import graphene
from django.conf import settings
from ....product.templatetags.product_images import get_thumbnail
-from ...translations.enums import LanguageCodeEnum
from ..enums import (
AccountErrorCode,
AppErrorCode,
@@ -17,6 +16,7 @@ from ..enums import (
GiftCardErrorCode,
InvoiceErrorCode,
JobStatusEnum,
+ LanguageCodeEnum,
MenuErrorCode,
MetadataErrorCode,
OrderErrorCode,
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 8a39910bec..1ece83759e 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -253,6 +253,7 @@ query OrdersQuery {
channel {
slug
}
+ languageCodeEnum
statusDisplay
paymentStatus
paymentStatusDisplay
@@ -336,6 +337,7 @@ def test_order_query(
assert order_data["paymentStatusDisplay"] == payment_status_display
assert order_data["isPaid"] == order.is_fully_paid()
assert order_data["userEmail"] == order.user_email
+ assert order_data["languageCodeEnum"] == order.language_code.upper()
expected_price = Money(
amount=str(order_data["shippingPrice"]["gross"]["amount"]), currency="USD"
)
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index d9c9b42f6b..6583e09d73 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -20,8 +20,10 @@ from ..account.utils import requestor_has_access
from ..channel import ChannelContext
from ..channel.dataloaders import ChannelByIdLoader, ChannelByOrderLineIdLoader
from ..core.connection import CountableDjangoObjectType
+from ..core.enums import LanguageCodeEnum
from ..core.types.common import Image
from ..core.types.money import Money, TaxedMoney
+from ..core.utils import str_to_enum
from ..decorators import one_of_permissions_required, permission_required
from ..discount.dataloaders import VoucherByIdLoader
from ..giftcard.types import GiftCard
@@ -434,6 +436,16 @@ class Order(CountableDjangoObjectType):
is_shipping_required = graphene.Boolean(
description="Returns True, if order requires shipping.", required=True
)
+ language_code = graphene.String(
+ deprecation_reason=(
+ "Use the `languageCodeEnum` field to fetch the language code. "
+ "This field will be removed after 2021-06-30"
+ ),
+ required=True,
+ )
+ language_code_enum = graphene.Field(
+ LanguageCodeEnum, description="Order language code.", required=True
+ )
class Meta:
description = "Represents an order in the shop."
@@ -449,7 +461,6 @@ class Order(CountableDjangoObjectType):
"display_gross_prices",
"gift_cards",
"id",
- "language_code",
"shipping_address",
"shipping_method",
"shipping_method_name",
@@ -665,3 +676,7 @@ class Order(CountableDjangoObjectType):
channel = ChannelByIdLoader(info.context).load(root.channel_id)
return Promise.all([voucher, channel]).then(wrap_voucher_with_channel_context)
+
+ @staticmethod
+ def resolve_language_code_enum(root, _info, **_kwargs):
+ return LanguageCodeEnum[str_to_enum(root.language_code)]
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index b003e72e04..451dd4a366 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -74,6 +74,7 @@ input AccountInput {
lastName: String
defaultBillingAddress: AddressInput
defaultShippingAddress: AddressInput
+ languageCode: LanguageCodeEnum
}
type AccountRegister {
@@ -87,6 +88,7 @@ input AccountRegisterInput {
email: String!
password: String!
redirectUrl: String
+ languageCode: LanguageCodeEnum
}
type AccountRequestDeletion {
@@ -876,6 +878,7 @@ type Checkout implements Node & ObjectWithMetadata {
subtotalPrice: TaxedMoney
token: UUID!
totalPrice: TaxedMoney
+ languageCode: LanguageCodeEnum!
}
type CheckoutAddPromoCode {
@@ -922,6 +925,7 @@ input CheckoutCreateInput {
email: String
shippingAddress: AddressInput
billingAddress: AddressInput
+ languageCode: LanguageCodeEnum
}
type CheckoutCustomerAttach {
@@ -974,6 +978,12 @@ enum CheckoutErrorCode {
CHANNEL_INACTIVE
}
+type CheckoutLanguageCodeUpdate {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ checkout: Checkout
+ checkoutErrors: [CheckoutError!]!
+}
+
type CheckoutLine implements Node {
id: ID!
variant: ProductVariant!
@@ -1605,6 +1615,7 @@ input CustomerInput {
email: String
isActive: Boolean
note: String
+ languageCode: LanguageCodeEnum
}
type CustomerUpdate {
@@ -2736,6 +2747,7 @@ type Mutation {
checkoutPaymentCreate(checkoutId: ID!, input: PaymentInput!): CheckoutPaymentCreate
checkoutShippingAddressUpdate(checkoutId: ID!, shippingAddress: AddressInput!): CheckoutShippingAddressUpdate
checkoutShippingMethodUpdate(checkoutId: ID, shippingMethodId: ID!): CheckoutShippingMethodUpdate
+ checkoutLanguageCodeUpdate(checkoutId: ID!, languageCode: LanguageCodeEnum!): CheckoutLanguageCodeUpdate
channelCreate(input: ChannelCreateInput!): ChannelCreate
channelUpdate(id: ID!, input: ChannelUpdateInput!): ChannelUpdate
channelDelete(id: ID!, input: ChannelDeleteInput): ChannelDelete
@@ -2830,7 +2842,6 @@ type Order implements Node & ObjectWithMetadata {
created: DateTime!
status: OrderStatus!
user: User
- languageCode: String!
trackingClientId: String!
billingAddress: Address
shippingAddress: Address
@@ -2871,6 +2882,8 @@ type Order implements Node & ObjectWithMetadata {
totalBalance: Money!
userEmail: String
isShippingRequired: Boolean!
+ languageCode: String! @deprecated(reason: "Use the `languageCodeEnum` field to fetch the language code. This field will be removed after 2021-06-30")
+ languageCodeEnum: LanguageCodeEnum!
}
enum OrderAction {
@@ -5350,6 +5363,7 @@ type User implements Node & ObjectWithMetadata {
avatar(size: Int): Image
events: [CustomerEvent]
storedPaymentSources: [PaymentSource]
+ languageCode: LanguageCodeEnum!
}
type UserAvatarDelete {
@@ -5389,6 +5403,7 @@ input UserCreateInput {
email: String
isActive: Boolean
note: String
+ languageCode: LanguageCodeEnum
redirectUrl: String
}
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index 3dc2dbae3e..c83d6b8397 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -16,14 +16,13 @@ from ..account.types import Address, AddressInput, StaffNotificationRecipient
from ..channel import ChannelContext
from ..checkout.types import PaymentGateway
from ..core.connection import CountableDjangoObjectType
-from ..core.enums import WeightUnitsEnum
+from ..core.enums import LanguageCodeEnum, WeightUnitsEnum
from ..core.types.common import CountryDisplay, LanguageDisplay, Permission
from ..core.utils import str_to_enum
from ..decorators import permission_required
from ..menu.dataloaders import MenuByIdLoader
from ..menu.types import Menu
from ..shipping.types import ShippingMethod
-from ..translations.enums import LanguageCodeEnum
from ..translations.fields import TranslationField
from ..translations.resolvers import resolve_translation
from ..translations.types import ShopTranslation
diff --git a/saleor/graphql/translations/enums.py b/saleor/graphql/translations/enums.py
deleted file mode 100644
index 4d3dbaca01..0000000000
--- a/saleor/graphql/translations/enums.py
+++ /dev/null
@@ -1,7 +0,0 @@
-import graphene
-from django.conf import settings
-
-LanguageCodeEnum = graphene.Enum(
- "LanguageCodeEnum",
- [(lang[0].replace("-", "_").upper(), lang[0]) for lang in settings.LANGUAGES],
-)
diff --git a/saleor/graphql/translations/fields.py b/saleor/graphql/translations/fields.py
index 91502b74d9..b89934ab4d 100644
--- a/saleor/graphql/translations/fields.py
+++ b/saleor/graphql/translations/fields.py
@@ -1,7 +1,7 @@
import graphene
+from ..core.enums import LanguageCodeEnum
from .descriptions import TranslationDescriptions
-from .enums import LanguageCodeEnum
from .resolvers import resolve_translation
diff --git a/saleor/graphql/translations/mutations.py b/saleor/graphql/translations/mutations.py
index 85f29b076f..84a85fbf46 100644
--- a/saleor/graphql/translations/mutations.py
+++ b/saleor/graphql/translations/mutations.py
@@ -9,12 +9,12 @@ from ...page import models as page_models
from ...product import models as product_models
from ...shipping import models as shipping_models
from ..channel import ChannelContext
+from ..core.enums import LanguageCodeEnum
from ..core.mutations import BaseMutation, ModelMutation, registry
from ..core.types.common import TranslationError
from ..core.utils import from_global_id_strict_type
from ..product.types import Product, ProductVariant
from ..shop.types import Shop
-from .enums import LanguageCodeEnum
# discount types need to be imported to get Voucher in the graphene registry
from ..discount import types # noqa # pylint: disable=unused-import, isort:skip
diff --git a/saleor/graphql/translations/tests/test_translations.py b/saleor/graphql/translations/tests/test_translations.py
index 77d98344be..bac45fbded 100644
--- a/saleor/graphql/translations/tests/test_translations.py
+++ b/saleor/graphql/translations/tests/test_translations.py
@@ -2,9 +2,9 @@ import graphene
import pytest
from django.contrib.auth.models import Permission
+from ...core.enums import LanguageCodeEnum
from ...tests.utils import assert_no_permission, get_graphql_content
from ..schema import TranslatableKinds
-from ..types import LanguageCodeEnum
def test_product_translation(user_api_client, product, channel_USD):
diff --git a/saleor/graphql/translations/types.py b/saleor/graphql/translations/types.py
index 038dcc73c8..7bc479fe4b 100644
--- a/saleor/graphql/translations/types.py
+++ b/saleor/graphql/translations/types.py
@@ -11,10 +11,10 @@ from ...shipping import models as shipping_models
from ...site import models as site_models
from ..channel import ChannelContext
from ..core.connection import CountableDjangoObjectType
+from ..core.enums import LanguageCodeEnum
from ..core.types import LanguageDisplay
from ..core.utils import str_to_enum
from ..decorators import permission_required
-from .enums import LanguageCodeEnum
from .fields import TranslationField
BASIC_TRANSLATABLE_FIELDS = ["id", "name"]
diff --git a/saleor/order/migrations/0098_auto_20210120_1727.py b/saleor/order/migrations/0098_auto_20210120_1727.py
new file mode 100644
index 0000000000..d221d5d211
--- /dev/null
+++ b/saleor/order/migrations/0098_auto_20210120_1727.py
@@ -0,0 +1,72 @@
+# Generated by Django 3.1.5 on 2021-01-20 17:27
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0097_auto_20210107_1148"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="order",
+ name="language_code",
+ field=models.CharField(
+ choices=[
+ ("ar", "Arabic"),
+ ("az", "Azerbaijani"),
+ ("bg", "Bulgarian"),
+ ("bn", "Bengali"),
+ ("ca", "Catalan"),
+ ("cs", "Czech"),
+ ("da", "Danish"),
+ ("de", "German"),
+ ("el", "Greek"),
+ ("en", "English"),
+ ("es", "Spanish"),
+ ("es-co", "Colombian Spanish"),
+ ("et", "Estonian"),
+ ("fa", "Persian"),
+ ("fi", "Finnish"),
+ ("fr", "French"),
+ ("hi", "Hindi"),
+ ("hu", "Hungarian"),
+ ("hy", "Armenian"),
+ ("id", "Indonesian"),
+ ("is", "Icelandic"),
+ ("it", "Italian"),
+ ("ja", "Japanese"),
+ ("ka", "Georgian"),
+ ("km", "Khmer"),
+ ("ko", "Korean"),
+ ("lt", "Lithuanian"),
+ ("mn", "Mongolian"),
+ ("my", "Burmese"),
+ ("nb", "Norwegian"),
+ ("nl", "Dutch"),
+ ("pl", "Polish"),
+ ("pt", "Portuguese"),
+ ("pt-br", "Brazilian Portuguese"),
+ ("ro", "Romanian"),
+ ("ru", "Russian"),
+ ("sk", "Slovak"),
+ ("sl", "Slovenian"),
+ ("sq", "Albanian"),
+ ("sr", "Serbian"),
+ ("sv", "Swedish"),
+ ("sw", "Swahili"),
+ ("ta", "Tamil"),
+ ("th", "Thai"),
+ ("tr", "Turkish"),
+ ("uk", "Ukrainian"),
+ ("vi", "Vietnamese"),
+ ("zh-hans", "Simplified Chinese"),
+ ("zh-hant", "Traditional Chinese"),
+ ],
+ default="en",
+ max_length=35,
+ ),
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 640e86bfa5..46e1bc190a 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -87,7 +87,9 @@ class Order(ModelWithMetadata):
related_name="orders",
on_delete=models.SET_NULL,
)
- language_code = models.CharField(max_length=35, default=settings.LANGUAGE_CODE)
+ language_code = models.CharField(
+ max_length=35, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE
+ )
tracking_client_id = models.CharField(max_length=36, blank=True, editable=False)
billing_address = models.ForeignKey(
Address, related_name="+", editable=False, null=True, on_delete=models.SET_NULL
diff --git a/saleor/order/notifications.py b/saleor/order/notifications.py
index d429e6adea..84e40a567f 100644
--- a/saleor/order/notifications.py
+++ b/saleor/order/notifications.py
@@ -87,6 +87,7 @@ ORDER_MODEL_FIELDS = [
"metadata",
"private_metadata",
"user_id",
+ "language_code",
]
diff --git a/saleor/order/tests/test_notifications.py b/saleor/order/tests/test_notifications.py
index f6f1f2501e..e49b60d394 100644
--- a/saleor/order/tests/test_notifications.py
+++ b/saleor/order/tests/test_notifications.py
@@ -97,6 +97,7 @@ def test_get_default_order_payload(order_line):
"lines": [order_line_payload],
"billing_address": get_address_payload(order.billing_address),
"shipping_address": get_address_payload(order.shipping_address),
+ "language_code": order.language_code,
}