Skip to content

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

Allow setting metadata during user creating and updating (#12577)

Iga Karbowiaka5e15537ca44
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 95745ddb48..2592f2474e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,14 @@ All notable, unreleased changes to this project will be documented in this file.
### GraphQL API
- Add `path` field to `ProductVariantBulkError` - #12534 by @SzymJ
+- Allow setting metadata during user creating and updating - #12577 by @IKarbowiak
+ - The following mutations have been updated:
+ - `customerCreate`
+ - `customerUpdate`
+ - `staffCreate`
+ - `staffUpdate`
+ - `accountUpdate`
+ - `customerBulkUpdate`
### Saleor Apps
diff --git a/saleor/graphql/account/bulk_mutations/customer_bulk_update.py b/saleor/graphql/account/bulk_mutations/customer_bulk_update.py
index 2c5cdb1b1d..600d79763c 100644
--- a/saleor/graphql/account/bulk_mutations/customer_bulk_update.py
+++ b/saleor/graphql/account/bulk_mutations/customer_bulk_update.py
@@ -1,5 +1,6 @@
from collections import defaultdict
-from copy import copy
+from copy import deepcopy
+from typing import List
import graphene
from django.core.exceptions import ValidationError
@@ -26,6 +27,7 @@ from ...core.types import (
)
from ...core.utils import get_duplicated_values
from ...core.validators import validate_one_of_args_is_in_mutation
+from ...payment.utils import metadata_contains_empty_key
from ...plugins.dataloaders import get_app_promise, get_plugin_manager_promise
from ..i18n import I18nMixin
from ..mutations.base import BILLING_ADDRESS_FIELD, SHIPPING_ADDRESS_FIELD
@@ -181,6 +183,26 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):
except ValidationError as exc:
cls.format_errors(index, exc, index_error_map, field_prefix=field)
+ @classmethod
+ def clean_metadata(
+ cls,
+ field_name: str,
+ metadata_list: List[dict],
+ errors_count: int,
+ index: int,
+ index_error_map: dict,
+ ):
+ if metadata_contains_empty_key(metadata_list):
+ index_error_map[index].append(
+ CustomerBulkUpdateError(
+ path=f"input.{field_name}",
+ message="Metadata key cannot be empty.",
+ code=CustomerBulkUpdateErrorCode.REQUIRED.value,
+ )
+ )
+ errors_count += 1
+ return errors_count
+
@classmethod
def clean_customers(cls, info, customers_input, index_error_map):
cleaned_inputs_map: dict = {}
@@ -270,6 +292,20 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):
)
base_error_count += 1
+ if metadata := customer_input["input"].get("metadata"):
+ base_error_count = cls.clean_metadata(
+ "metadata", metadata, base_error_count, index, index_error_map
+ )
+
+ if private_metadata := customer_input["input"].get("private_metadata"):
+ base_error_count = cls.clean_metadata(
+ "privateMetadata",
+ private_metadata,
+ base_error_count,
+ index,
+ index_error_map,
+ )
+
if base_error_count > 0:
cleaned_inputs_map[index] = None
else:
@@ -328,6 +364,8 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):
data = cleaned_input["input"]
shipping_address_input = data.pop(SHIPPING_ADDRESS_FIELD, None)
billing_address_input = data.pop(BILLING_ADDRESS_FIELD, None)
+ metadata_list = data.pop("metadata", None)
+ private_metadata_list = data.pop("private_metadata", None)
filtered_customers = list(
filter(
@@ -341,7 +379,7 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):
billing_address = None
old_instance = filtered_customers[0]
- new_instance = cls.construct_instance(copy(old_instance), data)
+ new_instance = cls.construct_instance(deepcopy(old_instance), data)
new_instance.full_clean(exclude=["password"])
if shipping_address_input:
@@ -359,6 +397,14 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):
BILLING_ADDRESS_FIELD,
)
+ if metadata_list is not None:
+ cls.update_metadata(new_instance, metadata_list)
+
+ if private_metadata_list is not None:
+ cls.update_metadata(
+ new_instance, private_metadata_list, is_private=True
+ )
+
instances_data_and_errors_list.append(
{
"instance": new_instance,
@@ -460,6 +506,8 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):
"language_code",
"external_reference",
"updated_at",
+ "metadata",
+ "private_metadata",
],
)
@@ -500,6 +548,7 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):
has_new_email = old_instance.email != new_email
was_activated = not old_instance.is_active and updated_instance.is_active
was_deactivated = old_instance.is_active and not updated_instance.is_active
+ metadata_update = old_instance.metadata != updated_instance.metadata
# Generate the events accordingly
if has_new_email:
@@ -544,6 +593,9 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):
)
)
+ if metadata_update:
+ cls.call_event(manager.customer_metadata_updated, updated_instance)
+
models.CustomerEvent.objects.bulk_create(customer_events)
@classmethod
diff --git a/saleor/graphql/account/mutations/account.py b/saleor/graphql/account/mutations/account.py
index 39488d0ca7..fc6842305e 100644
--- a/saleor/graphql/account/mutations/account.py
+++ b/saleor/graphql/account/mutations/account.py
@@ -20,6 +20,7 @@ from ....order.utils import match_orders_with_new_user
from ....permission.auth_filters import AuthorizationFilters
from ...channel.utils import clean_channel
from ...core import ResolveInfo
+from ...core.descriptions import ADDED_IN_314
from ...core.doc_category import DOC_CATEGORY_USERS
from ...core.enums import LanguageCodeEnum
from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
@@ -172,6 +173,11 @@ class AccountInput(AccountBaseInput):
default_shipping_address = AddressInput(
description="Shipping address of the customer."
)
+ metadata = NonNullList(
+ MetadataInput,
+ description="Fields required to update the user metadata." + ADDED_IN_314,
+ required=False,
+ )
class Meta:
description = "Fields required to update the user."
@@ -194,6 +200,7 @@ class AccountUpdate(BaseCustomerCreate):
permissions = (AuthorizationFilters.AUTHENTICATED_USER,)
error_type_class = AccountError
error_type_field = "account_errors"
+ support_meta_field = True
@classmethod
def perform_mutation(cls, root, info: ResolveInfo, /, **data):
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index a5b4653a36..9509e928ff 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -32,7 +32,7 @@ from ...app.dataloaders import get_app_promise
from ...channel.utils import clean_channel, validate_channel
from ...core import ResolveInfo
from ...core.context import disallow_replica_in_context
-from ...core.descriptions import ADDED_IN_310
+from ...core.descriptions import ADDED_IN_310, ADDED_IN_314
from ...core.doc_category import DOC_CATEGORY_USERS
from ...core.enums import LanguageCodeEnum
from ...core.mutations import (
@@ -41,7 +41,8 @@ from ...core.mutations import (
ModelMutation,
validation_error_to_error_type,
)
-from ...core.types import AccountError, BaseInputObjectType
+from ...core.types import AccountError, BaseInputObjectType, NonNullList
+from ...meta.mutations import MetadataInput
from ...plugins.dataloaders import get_plugin_manager_promise
from .authentication import CreateToken
@@ -458,6 +459,18 @@ class UserInput(BaseInputObjectType):
email = graphene.String(description="The unique email address of the user.")
is_active = graphene.Boolean(required=False, description="User account is active.")
note = graphene.String(description="A note about the user.")
+ metadata = NonNullList(
+ MetadataInput,
+ description="Fields required to update the user metadata." + ADDED_IN_314,
+ required=False,
+ )
+ private_metadata = NonNullList(
+ MetadataInput,
+ description=(
+ "Fields required to update the user private metadata." + ADDED_IN_314
+ ),
+ required=False,
+ )
class Meta:
doc_category = DOC_CATEGORY_USERS
@@ -606,3 +619,9 @@ class BaseCustomerCreate(ModelMutation, I18nMixin):
manager,
channel_slug,
)
+
+ @classmethod
+ def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
+ if cleaned_input.get("metadata"):
+ manager = get_plugin_manager_promise(info.context).get()
+ cls.call_event(manager.customer_metadata_updated, instance)
diff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.py
index ce5da2cc68..13770e0c25 100644
--- a/saleor/graphql/account/mutations/staff.py
+++ b/saleor/graphql/account/mutations/staff.py
@@ -100,6 +100,8 @@ class CustomerCreate(BaseCustomerCreate):
model = models.User
object_type = User
permissions = (AccountPermissions.MANAGE_USERS,)
+ support_meta_field = True
+ support_private_meta_field = True
error_type_class = AccountError
error_type_field = "account_errors"
@@ -124,6 +126,8 @@ class CustomerUpdate(CustomerCreate, ModelWithExtRefMutation):
permissions = (AccountPermissions.MANAGE_USERS,)
error_type_class = AccountError
error_type_field = "account_errors"
+ support_meta_field = True
+ support_private_meta_field = True
@classmethod
def generate_events(
@@ -178,7 +182,13 @@ class CustomerUpdate(CustomerCreate, ModelWithExtRefMutation):
# Clean the input and generate a new instance from the new data
cleaned_input = cls.clean_input(info, original_instance, data)
+ metadata_list = cleaned_input.pop("metadata", None)
+ private_metadata_list = cleaned_input.pop("private_metadata", None)
+
new_instance = cls.construct_instance(copy(original_instance), cleaned_input)
+ cls.validate_and_update_metadata(
+ new_instance, metadata_list, private_metadata_list
+ )
# Save the new instance data
cls.clean_instance(info, new_instance)
@@ -188,6 +198,10 @@ class CustomerUpdate(CustomerCreate, ModelWithExtRefMutation):
# Generate events by comparing the instances
cls.generate_events(info, original_instance, new_instance)
+ if metadata_list:
+ manager = get_plugin_manager_promise(info.context).get()
+ cls.call_event(manager.customer_metadata_updated, new_instance)
+
# Return the response
return cls.success_response(new_instance)
@@ -244,6 +258,8 @@ class StaffCreate(ModelMutation):
permissions = (AccountPermissions.MANAGE_STAFF,)
error_type_class = StaffError
error_type_field = "staff_errors"
+ support_meta_field = True
+ support_private_meta_field = True
@classmethod
def check_permissions(cls, context, permissions=None, **data):
@@ -370,7 +386,11 @@ class StaffCreate(ModelMutation):
instance, send_notification = cls.get_instance(info, **data)
data = data.get("input")
cleaned_input = cls.clean_input(info, instance, data)
+ metadata_list = cleaned_input.pop("metadata", None)
+ private_metadata_list = cleaned_input.pop("private_metadata", None)
instance = cls.construct_instance(instance, cleaned_input)
+
+ cls.validate_and_update_metadata(instance, metadata_list, private_metadata_list)
cls.clean_instance(info, instance)
cls.save(info, instance, cleaned_input, send_notification)
cls._save_m2m(info, instance, cleaned_input)
@@ -397,6 +417,8 @@ class StaffUpdate(StaffCreate):
permissions = (AccountPermissions.MANAGE_STAFF,)
error_type_class = StaffError
error_type_field = "staff_errors"
+ support_meta_field = True
+ support_private_meta_field = True
@classmethod
def clean_input(cls, info: ResolveInfo, instance, data, **kwargs):
diff --git a/saleor/graphql/account/tests/mutations/test_customer_bulk_update.py b/saleor/graphql/account/tests/mutations/test_customer_bulk_update.py
index 712f254dbf..6b299b5725 100644
--- a/saleor/graphql/account/tests/mutations/test_customer_bulk_update.py
+++ b/saleor/graphql/account/tests/mutations/test_customer_bulk_update.py
@@ -6,6 +6,7 @@ from .....account import models
from .....account.error_codes import CustomerBulkUpdateErrorCode
from .....account.events import CustomerEvents
from .....account.search import generate_address_search_document_value
+from ....core.enums import ErrorPolicyEnum
from ....tests.utils import get_graphql_content
from ...tests.utils import convert_dict_keys_to_camel_case
@@ -643,3 +644,138 @@ def test_customers_bulk_update_with_duplicated_external_ref(
data["results"][1]["errors"][0]["code"]
== CustomerBulkUpdateErrorCode.DUPLICATED_INPUT_ITEM.name
)
+
+
+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")
+def test_customers_bulk_update_metadata(
+ mocked_customer_metadata_updated,
+ staff_api_client,
+ customer_users,
+ permission_manage_users,
+):
+ # given
+ customer_1 = customer_users[0]
+ customer_2 = customer_users[1]
+
+ customer_1_id = graphene.Node.to_global_id("User", customer_1.pk)
+ customer_2_id = graphene.Node.to_global_id("User", customer_2.pk)
+
+ metadata_1 = {"key": "test key 1", "value": "test value 1"}
+ private_metadata_1 = {"key": "private test key 1", "value": "private test value 1"}
+ metadata_2 = {"key": "test key 2", "value": "test value 2"}
+ private_metadata_2 = {"key": "private test key 2", "value": "private test value 2"}
+
+ customers_input = [
+ {
+ "id": customer_1_id,
+ "input": {
+ "metadata": [metadata_1],
+ "privateMetadata": [private_metadata_1],
+ },
+ },
+ {
+ "id": customer_2_id,
+ "input": {
+ "metadata": [metadata_2],
+ "privateMetadata": [private_metadata_2],
+ },
+ },
+ ]
+
+ variables = {"customers": customers_input}
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_users)
+ response = staff_api_client.post_graphql(CUSTOMER_BULK_UPDATE_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["customerBulkUpdate"]
+
+ # then
+ customer_1.refresh_from_db()
+ customer_2.refresh_from_db()
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert customer_1.metadata.get(metadata_1["key"]) == metadata_1["value"]
+ assert customer_2.metadata.get(metadata_2["key"]) == metadata_2["value"]
+ assert (
+ customer_1.private_metadata.get(private_metadata_1["key"])
+ == private_metadata_1["value"]
+ )
+ assert (
+ customer_2.private_metadata.get(private_metadata_2["key"])
+ == private_metadata_2["value"]
+ )
+ assert mocked_customer_metadata_updated.call_count == 2
+
+
+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")
+def test_customers_bulk_update_metadata_empty_key_in_one_input(
+ mocked_customer_metadata_updated,
+ staff_api_client,
+ customer_users,
+ permission_manage_users,
+):
+ # given
+ customer_1 = customer_users[0]
+ customer_2 = customer_users[1]
+
+ customer_1_id = graphene.Node.to_global_id("User", customer_1.pk)
+ customer_2_id = graphene.Node.to_global_id("User", customer_2.pk)
+
+ metadata_1 = {"key": "", "value": "test value 1"}
+ private_metadata_1 = {"key": "", "value": "private test value 1"}
+ metadata_2 = {"key": "test key 2", "value": "test value 2"}
+ private_metadata_2 = {"key": "private test key 2", "value": "private test value 2"}
+
+ customers_input = [
+ {
+ "id": customer_1_id,
+ "input": {
+ "metadata": [metadata_1],
+ "privateMetadata": [private_metadata_1],
+ },
+ },
+ {
+ "id": customer_2_id,
+ "input": {
+ "metadata": [metadata_2],
+ "privateMetadata": [private_metadata_2],
+ },
+ },
+ ]
+
+ variables = {
+ "customers": customers_input,
+ "errorPolicy": ErrorPolicyEnum.REJECT_FAILED_ROWS.name,
+ }
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_users)
+ response = staff_api_client.post_graphql(CUSTOMER_BULK_UPDATE_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["customerBulkUpdate"]
+
+ # then
+ customer_1.refresh_from_db()
+ customer_2.refresh_from_db()
+ customer_1_errors = data["results"][0]["errors"]
+ assert len(customer_1_errors) == 2
+ assert {error["code"] for error in customer_1_errors} == {
+ CustomerBulkUpdateErrorCode.REQUIRED.name
+ }
+ assert {error["path"] for error in customer_1_errors} == {
+ "input.metadata",
+ "input.privateMetadata",
+ }
+
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 1
+ assert metadata_1["key"] not in customer_1.metadata
+ assert customer_2.metadata.get(metadata_2["key"]) == metadata_2["value"]
+ assert private_metadata_1["key"] not in customer_1.private_metadata
+ assert (
+ customer_2.private_metadata.get(private_metadata_2["key"])
+ == private_metadata_2["value"]
+ )
+ mocked_customer_metadata_updated.called_once_with(customer_2)
diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.py
index 1c8ff566e8..bdfcab07c6 100644
--- a/saleor/graphql/account/tests/test_account.py
+++ b/saleor/graphql/account/tests/test_account.py
@@ -1534,7 +1534,8 @@ CUSTOMER_CREATE_MUTATION = """
$email: String, $firstName: String, $lastName: String, $channel: String
$note: String, $billing: AddressInput, $shipping: AddressInput,
$redirect_url: String, $languageCode: LanguageCodeEnum,
- $externalReference: String
+ $externalReference: String, $metadata: [MetadataInput!],
+ $privateMetadata: [MetadataInput!],
) {
customerCreate(input: {
email: $email,
@@ -1547,6 +1548,7 @@ CUSTOMER_CREATE_MUTATION = """
languageCode: $languageCode,
channel: $channel,
externalReference: $externalReference
+ metadata: $metadata, privateMetadata: $privateMetadata
}) {
errors {
field
@@ -1569,23 +1571,34 @@ CUSTOMER_CREATE_MUTATION = """
isStaff
note
externalReference
+ metadata {
+ key
+ value
+ }
+ privateMetadata {
+ key
+ value
+ }
}
}
}
"""
+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")
@patch("saleor.account.notifications.default_token_generator.make_token")
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_customer_create(
mocked_notify,
mocked_generator,
+ mocked_customer_metadata_updated,
staff_api_client,
address,
permission_manage_users,
channel_PLN,
site_settings,
):
+ # given
mocked_generator.return_value = "token"
first_name = "api_first_name"
@@ -1597,6 +1610,8 @@ def test_customer_create(
redirect_url = "https://www.example.com"
external_reference = "test-ext-ref"
+ metadata = [{"key": "test key", "value": "test value"}]
+ private_metadata = [{"key": "private test key", "value": "private test value"}]
variables = {
"email": email,
"firstName": first_name,
@@ -1608,11 +1623,16 @@ def test_customer_create(
"languageCode": "PL",
"channel": channel_PLN.slug,
"externalReference": external_reference,
+ "metadata": metadata,
+ "privateMetadata": private_metadata,
}
+ # when
response = staff_api_client.post_graphql(
CUSTOMER_CREATE_MUTATION, variables, permissions=[permission_manage_users]
)
+
+ # then
content = get_graphql_content(response)
new_customer = User.objects.get(email=email)
@@ -1635,6 +1655,8 @@ def test_customer_create(
assert data["user"]["externalReference"] == external_reference
assert not data["user"]["isStaff"]
assert data["user"]["isActive"]
+ assert data["user"]["metadata"] == metadata
+ assert data["user"]["privateMetadata"] == private_metadata
new_user = User.objects.get(email=email)
assert (
@@ -1656,6 +1678,7 @@ def test_customer_create(
payload=expected_payload,
channel_slug=channel_PLN.slug,
)
+ mocked_customer_metadata_updated.assert_called_once_with(new_user)
assert set([shipping_address, billing_address]) == set(new_user.addresses.all())
customer_creation_event = account_events.CustomerEvent.objects.get()
@@ -1708,6 +1731,52 @@ def test_customer_create_send_password_with_url(
)
+def test_customer_create_empty_metadata_key(
+ staff_api_client,
+ address,
+ permission_manage_users,
+ channel_PLN,
+ site_settings,
+):
+ # then
+ email = "[email protected]"
+ first_name = "api_first_name"
+ last_name = "api_last_name"
+ note = "Test user"
+ address_data = convert_dict_keys_to_camel_case(address.as_data())
+ address_data.pop("metadata")
+ address_data.pop("privateMetadata")
+
+ redirect_url = "https://www.example.com"
+ external_reference = "test-ext-ref"
+ metadata = [{"key": "", "value": "test value"}]
+ variables = {
+ "email": email,
+ "firstName": first_name,
+ "lastName": last_name,
+ "note": note,
+ "shipping": address_data,
+ "billing": address_data,
+ "redirect_url": redirect_url,
+ "languageCode": "PL",
+ "channel": channel_PLN.slug,
+ "externalReference": external_reference,
+ "metadata": metadata,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CUSTOMER_CREATE_MUTATION, variables, permissions=[permission_manage_users]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["customerCreate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "input"
+ assert errors[0]["code"] == AccountErrorCode.REQUIRED.name
+
+
def test_customer_create_without_send_password(
staff_api_client, permission_manage_users
):
@@ -1800,29 +1869,17 @@ def test_customer_create_with_non_unique_external_reference(
assert error["message"] == "User with this External reference already exists."
-def test_customer_update(
- staff_api_client, staff_user, customer_user, address, permission_manage_users
-):
- query = """
+CUSTOMER_UPDATE_MUTATION = """
mutation UpdateCustomer(
- $id: ID!, $firstName: String, $lastName: String,
- $isActive: Boolean, $note: String, $billing: AddressInput,
- $shipping: AddressInput, $languageCode: LanguageCodeEnum,
+ $id: ID!
$externalReference: String
+ $input: CustomerInput!
) {
customerUpdate(
id: $id,
- input: {
- isActive: $isActive,
- firstName: $firstName,
- lastName: $lastName,
- note: $note,
- defaultBillingAddress: $billing
- defaultShippingAddress: $shipping,
- languageCode: $languageCode,
- externalReference: $externalReference
- }
- ) {
+ externalReference: $externalReference,
+ input: $input
+ ) {
errors {
field
message
@@ -1841,10 +1898,31 @@ def test_customer_update(
isActive
note
externalReference
+ metadata {
+ key
+ value
+ }
+ privateMetadata {
+ key
+ value
+ }
}
}
}
- """
+"""
+
+
+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")
+def test_customer_update(
+ mocked_customer_metadata_updated,
+ staff_api_client,
+ staff_user,
+ customer_user,
+ address,
+ permission_manage_users,
+):
+ # given
+ query = CUSTOMER_UPDATE_MUTATION
# this test requires addresses to be set and checks whether new address
# instances weren't created, but the existing ones got updated
@@ -1865,28 +1943,50 @@ def test_customer_update(
new_street_address = "Updated street address"
address_data["streetAddress1"] = new_street_address
+ metadata = {"key": "test key", "value": "test value"}
+ private_metadata = {"key": "private test key", "value": "private test value"}
+
variables = {
"id": user_id,
- "firstName": first_name,
- "lastName": last_name,
- "isActive": False,
- "note": note,
- "billing": address_data,
- "shipping": address_data,
- "languageCode": "PL",
- "externalReference": external_reference,
+ "input": {
+ "externalReference": external_reference,
+ "firstName": first_name,
+ "lastName": last_name,
+ "isActive": False,
+ "note": note,
+ "defaultBillingAddress": address_data,
+ "defaultShippingAddress": address_data,
+ "languageCode": "PL",
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ },
}
+
+ # when
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_users]
)
+
+ # then
content = get_graphql_content(response)
- customer = User.objects.get(email=customer_user.email)
+ data = content["data"]["customerUpdate"]
+ assert data["errors"] == []
+ assert data["user"]["firstName"] == first_name
+ assert data["user"]["lastName"] == last_name
+ assert data["user"]["note"] == note
+ assert data["user"]["languageCode"] == "PL"
+ assert data["user"]["externalReference"] == external_reference
+ assert not data["user"]["isActive"]
+ assert metadata in data["user"]["metadata"]
+ assert private_metadata in data["user"]["privateMetadata"]
+
+ customer_user.refresh_from_db()
# check that existing instances are updated
shipping_address, billing_address = (
- customer.default_shipping_address,
- customer.default_billing_address,
+ customer_user.default_shipping_address,
+ customer_user.default_billing_address,
)
assert billing_address.pk == billing_address_pk
assert shipping_address.pk == shipping_address_pk
@@ -1894,15 +1994,6 @@ def test_customer_update(
assert billing_address.street_address_1 == new_street_address
assert shipping_address.street_address_1 == new_street_address
- data = content["data"]["customerUpdate"]
- assert data["errors"] == []
- assert data["user"]["firstName"] == first_name
- assert data["user"]["lastName"] == last_name
- assert data["user"]["note"] == note
- assert data["user"]["languageCode"] == "PL"
- assert data["user"]["externalReference"] == external_reference
- assert not data["user"]["isActive"]
-
(
name_changed_event,
deactivated_event,
@@ -1910,7 +2001,7 @@ def test_customer_update(
assert name_changed_event.type == account_events.CustomerEvents.NAME_ASSIGNED
assert name_changed_event.user.pk == staff_user.pk
- assert name_changed_event.parameters == {"message": customer.get_full_name()}
+ assert name_changed_event.parameters == {"message": customer_user.get_full_name()}
assert deactivated_event.type == account_events.CustomerEvents.ACCOUNT_DEACTIVATED
assert deactivated_event.user.pk == staff_user.pk
@@ -1925,6 +2016,7 @@ def test_customer_update(
generate_address_search_document_value(shipping_address)
in customer_user.search_document
)
+ mocked_customer_metadata_updated.assert_called_once_with(customer_user)
UPDATE_CUSTOMER_BY_EXTERNAL_REFERENCE = """
@@ -2305,6 +2397,7 @@ ACCOUNT_UPDATE_QUERY = """
$firstName: String,
$lastName: String
$languageCode: LanguageCodeEnum
+ $metadata: [MetadataInput!]
) {
accountUpdate(
input: {
@@ -2312,7 +2405,8 @@ ACCOUNT_UPDATE_QUERY = """
defaultShippingAddress: $shipping,
firstName: $firstName,
lastName: $lastName,
- languageCode: $languageCode
+ languageCode: $languageCode,
+ metadata: $metadata
}) {
errors {
field
@@ -2331,6 +2425,10 @@ ACCOUNT_UPDATE_QUERY = """
id
}
languageCode
+ metadata {
+ key
+ value
+ }
}
}
}
@@ -2446,6 +2544,26 @@ def test_logged_customer_update_anonymous_user(api_client):
assert_no_permission(response)
+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")
+def test_logged_customer_updates_metadata(
+ mocked_customer_metadata_updated, user_api_client
+):
+ # given
+ metadata = {"key": "test key", "value": "test value"}
+ variables = {"metadata": [metadata]}
+
+ # when
+ response = user_api_client.post_graphql(ACCOUNT_UPDATE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["accountUpdate"]
+
+ assert not data["errors"]
+ assert metadata in data["user"]["metadata"]
+ mocked_customer_metadata_updated.assert_called_once_with(user_api_client.user)
+
+
ACCOUNT_REQUEST_DELETION_MUTATION = """
mutation accountRequestDeletion($redirectUrl: String!, $channel: String) {
accountRequestDeletion(redirectUrl: $redirectUrl, channel: $channel) {
@@ -2959,11 +3077,11 @@ def test_delete_customer_by_external_reference_not_existing(
STAFF_CREATE_MUTATION = """
mutation CreateStaff(
- $email: String, $redirect_url: String, $add_groups: [ID!]
- ) {
- staffCreate(input: {email: $email, redirectUrl: $redirect_url,
- addGroups: $add_groups}
- ) {
+ $input: StaffCreateInput!
+ ) {
+ staffCreate(
+ input: $input
+ ){
errors {
field
code
@@ -2987,6 +3105,14 @@ STAFF_CREATE_MUTATION = """
avatar {
url
}
+ metadata {
+ key
+ value
+ }
+ privateMetadata {
+ key
+ value
+ }
}
}
}
@@ -3012,10 +3138,16 @@ def test_staff_create(
staff_user.user_permissions.add(permission_manage_products, permission_manage_users)
redirect_url = "https://www.example.com"
+ metadata = [{"key": "test key", "value": "test value"}]
+ private_metadata = [{"key": "private test key", "value": "private test value"}]
variables = {
- "email": email,
- "redirect_url": redirect_url,
- "add_groups": [graphene.Node.to_global_id("Group", group.pk)],
+ "input": {
+ "email": email,
+ "redirectUrl": redirect_url,
+ "addGroups": [graphene.Node.to_global_id("Group", group.pk)],
+ "metadata": metadata,
+ "privateMetadata": private_metadata,
+ }
}
response = staff_api_client.post_graphql(
@@ -3027,6 +3159,8 @@ def test_staff_create(
assert data["user"]["email"] == email
assert data["user"]["isStaff"]
assert data["user"]["isActive"]
+ assert data["user"]["metadata"] == metadata
+ assert data["user"]["privateMetadata"] == private_metadata
expected_perms = {
permission_manage_products.codename,
@@ -3083,9 +3217,11 @@ def test_promote_customer_to_staff_user(
redirect_url = "https://www.example.com"
email = customer_user.email
variables = {
- "email": email,
- "redirect_url": redirect_url,
- "add_groups": [graphene.Node.to_global_id("Group", group.pk)],
+ "input": {
+ "email": email,
+ "redirectUrl": redirect_url,
+ "addGroups": [graphene.Node.to_global_id("Group", group.pk)],
+ }
}
response = staff_api_client.post_graphql(
@@ -3139,11 +3275,13 @@ def test_staff_create_trigger_webhook(
redirect_url = "https://www.example.com"
variables = {
- "email": email,
- "redirect_url": redirect_url,
- "add_groups": [
- graphene.Node.to_global_id("Group", permission_group_manage_users.pk)
- ],
+ "input": {
+ "email": email,
+ "redirectUrl": redirect_url,
+ "addGroups": [
+ graphene.Node.to_global_id("Group", permission_group_manage_users.pk)
+ ],
+ }
}
# when
@@ -3193,9 +3331,11 @@ def test_staff_create_app_no_permission(
staff_user.user_permissions.add(permission_manage_products, permission_manage_users)
variables = {
- "email": email,
- "redirect_url": "https://www.example.com",
- "add_groups": [graphene.Node.to_global_id("Group", group.pk)],
+ "input": {
+ "email": email,
+ "redirectUrl": "https://www.example.com",
+ "addGroups": [graphene.Node.to_global_id("Group", group.pk)],
+ }
}
response = app_api_client.post_graphql(
@@ -3227,11 +3367,13 @@ def test_staff_create_out_of_scope_group(
redirect_url = "https://www.example.com"
variables = {
- "email": email,
- "redirect_url": redirect_url,
- "add_groups": [
- graphene.Node.to_global_id("Group", gr.pk) for gr in [group, group2]
- ],
+ "input": {
+ "email": email,
+ "redirectUrl": redirect_url,
+ "addGroups": [
+ graphene.Node.to_global_id("Group", gr.pk) for gr in [group, group2]
+ ],
+ }
}
# for staff user
@@ -3315,7 +3457,7 @@ def test_staff_create_send_password_with_url(
):
redirect_url = "https://www.example.com"
- variables = {"email": email, "redirect_url": redirect_url}
+ variables = {"input": {"email": email, "redirectUrl": redirect_url}}
response = staff_api_client.post_graphql(
STAFF_CREATE_MUTATION, variables, permissions=[permission_manage_staff]
@@ -3350,7 +3492,7 @@ def test_staff_create_without_send_password(
staff_api_client, media_root, permission_manage_staff
):
- variables = {"email": email}
+ variables = {"input": {"email": email}}
response = staff_api_client.post_graphql(
STAFF_CREATE_MUTATION, variables, permissions=[permission_manage_staff]
)
@@ -3364,7 +3506,7 @@ def test_staff_create_with_invalid_url(
staff_api_client, media_root, permission_manage_staff
):
- variables = {"email": email, "redirect_url": "invalid"}
+ variables = {"input": {"email": email, "redirectUrl": "invalid"}}
response = staff_api_client.post_graphql(
STAFF_CREATE_MUTATION, variables, permissions=[permission_manage_staff]
)
@@ -3384,7 +3526,7 @@ def test_staff_create_with_not_allowed_url(
staff_api_client, media_root, permission_manage_staff
):
- variables = {"email": email, "redirect_url": "https://www.fake.com"}
+ variables = {"input": {"email": email, "redirectUrl": "https://www.fake.com"}}
response = staff_api_client.post_graphql(
STAFF_CREATE_MUTATION, variables, permissions=[permission_manage_staff]
)
@@ -3405,7 +3547,7 @@ def test_staff_create_with_upper_case_email(
):
# given
- variables = {"email": email}
+ variables = {"input": {"email": email}}
# when
response = staff_api_client.post_graphql(
@@ -3441,6 +3583,14 @@ STAFF_UPDATE_MUTATIONS = """
}
isActive
email
+ metadata {
+ key
+ value
+ }
+ privateMetadata {
+ key
+ value
+ }
}
}
}
@@ -3467,6 +3617,54 @@ def test_staff_update(staff_api_client, permission_manage_staff, media_root):
assert not staff_user.search_document
+def test_staff_update_metadata(staff_api_client, permission_manage_staff):
+ # given
+ query = STAFF_UPDATE_MUTATIONS
+ staff_user = User.objects.create(email="[email protected]", is_staff=True)
+ assert not staff_user.search_document
+ id = graphene.Node.to_global_id("User", staff_user.id)
+ metadata = [{"key": "test key", "value": "test value"}]
+ variables = {"id": id, "input": {"metadata": metadata}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_staff]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["staffUpdate"]
+ assert data["errors"] == []
+ assert data["user"]["userPermissions"] == []
+ assert data["user"]["metadata"] == metadata
+ staff_user.refresh_from_db()
+ assert not staff_user.search_document
+
+
+def test_staff_update_private_metadata(staff_api_client, permission_manage_staff):
+ # given
+ query = STAFF_UPDATE_MUTATIONS
+ staff_user = User.objects.create(email="[email protected]", is_staff=True)
+ assert not staff_user.search_document
+ id = graphene.Node.to_global_id("User", staff_user.id)
+ metadata = [{"key": "test key", "value": "test value"}]
+ variables = {"id": id, "input": {"privateMetadata": metadata}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_staff]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["staffUpdate"]
+ assert data["errors"] == []
+ assert data["user"]["userPermissions"] == []
+ assert data["user"]["privateMetadata"] == metadata
+ staff_user.refresh_from_db()
+ assert not staff_user.search_document
+
+
@freeze_time("2018-05-31 12:00:01")
@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index 6d7058551a..1651c20caa 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -782,6 +782,14 @@ class ModelMutation(BaseMutation):
cls.clean_instance(info, instance)
cls.save(info, instance, cleaned_input)
cls._save_m2m(info, instance, cleaned_input)
+
+ # add to cleaned_input popped metadata to allow running post save events
+ # that depends on the metadata inputs
+ if metadata_list:
+ cleaned_input["metadata"] = metadata_list
+ if private_metadata_list:
+ cleaned_input["private_metadata"] = private_metadata_list
+
cls.post_save_action(info, instance, cleaned_input)
return cls.success_response(instance)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index dd41ee1c5f..6c54388358 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -25242,6 +25242,13 @@ input AccountInput @doc(category: "Users") {
"""Shipping address of the customer."""
defaultShippingAddress: AddressInput
+
+ """
+ Fields required to update the user metadata.
+
+ Added in Saleor 3.14.
+ """
+ metadata: [MetadataInput!]
}
"""
@@ -25349,6 +25356,20 @@ input UserCreateInput @doc(category: "Users") {
"""A note about the user."""
note: String
+ """
+ Fields required to update the user metadata.
+
+ Added in Saleor 3.14.
+ """
+ metadata: [MetadataInput!]
+
+ """
+ Fields required to update the user private metadata.
+
+ Added in Saleor 3.14.
+ """
+ privateMetadata: [MetadataInput!]
+
"""User language code."""
languageCode: LanguageCodeEnum
@@ -25403,6 +25424,20 @@ input CustomerInput @doc(category: "Users") {
"""A note about the user."""
note: String
+ """
+ Fields required to update the user metadata.
+
+ Added in Saleor 3.14.
+ """
+ metadata: [MetadataInput!]
+
+ """
+ Fields required to update the user private metadata.
+
+ Added in Saleor 3.14.
+ """
+ privateMetadata: [MetadataInput!]
+
"""User language code."""
languageCode: LanguageCodeEnum
@@ -25552,6 +25587,20 @@ input StaffCreateInput @doc(category: "Users") {
"""A note about the user."""
note: String
+ """
+ Fields required to update the user metadata.
+
+ Added in Saleor 3.14.
+ """
+ metadata: [MetadataInput!]
+
+ """
+ Fields required to update the user private metadata.
+
+ Added in Saleor 3.14.
+ """
+ privateMetadata: [MetadataInput!]
+
"""List of permission group IDs to which user should be assigned."""
addGroups: [ID!]
@@ -25589,6 +25638,20 @@ input StaffUpdateInput @doc(category: "Users") {
"""A note about the user."""
note: String
+ """
+ Fields required to update the user metadata.
+
+ Added in Saleor 3.14.
+ """
+ metadata: [MetadataInput!]
+
+ """
+ Fields required to update the user private metadata.
+
+ Added in Saleor 3.14.
+ """
+ privateMetadata: [MetadataInput!]
+
"""List of permission group IDs to which user should be assigned."""
addGroups: [ID!]
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 67c476892e..11b237bc1b 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -5017,6 +5017,15 @@ def permission_group_manage_users(permission_manage_users, staff_users):
return group
+def permission_group_manage_staff(permission_manage_staff, staff_users):
+ group = Group.objects.create(name="Manage staff groups.")
+ group.permissions.add(permission_manage_staff)
+
+ group.user_set.add(staff_users[1])
+ return group
+
+
@pytest.fixture
def collection(db):
collection = Collection.objects.create(