Skip to content

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

Add mutation to set the default address for staff users

Marcin Gębalaae81473c7d02
diff --git a/saleor/graphql/account/mutations.py b/saleor/graphql/account/mutations.py
index 6754ccacce..d2e43f657a 100644
--- a/saleor/graphql/account/mutations.py
+++ b/saleor/graphql/account/mutations.py
@@ -444,41 +444,6 @@ class AddressCreate(ModelMutation):
return user.has_perm('account.manage_users')
-class CustomerAddressCreate(ModelMutation):
- class Arguments:
- input = AddressInput(
- description='Fields required to create address', required=True)
- type = AddressTypeEnum(required=False, description=(
- 'A type of address. If provided, the new address will be '
- 'automatically assigned as the customer\'s default address '
- 'of that type.'))
-
- class Meta:
- description = 'Create a new address for the customer.'
- model = models.Address
- exclude = ['user_addresses']
-
- @classmethod
- def user_is_allowed(cls, user, input):
- return user.is_authenticated
-
- @classmethod
- def mutate(cls, root, info, **data):
- success_response = super().mutate(root, info, **data)
- address_type = data.get('type', None)
- if address_type:
- user = info.context.user
- instance = success_response.address
- utils.change_user_default_address(user, instance, address_type)
- return success_response
-
- @classmethod
- def save(cls, info, instance, cleaned_input):
- super().save(info, instance, cleaned_input)
- user = info.context.user
- instance.user_addresses.add(user)
-
-
class AddressUpdate(ModelMutation):
class Arguments:
id = graphene.ID(
@@ -518,6 +483,86 @@ class AddressDelete(ModelDeleteMutation):
return super().clean_instance(info, instance, errors)
+class AddressSetDefault(BaseMutation):
+ user = graphene.Field(User, description='An updated user instance.')
+
+ class Arguments:
+ address_id = graphene.ID(
+ required=True, description='ID of the address.')
+ user_id = graphene.ID(
+ required=True, description='ID of the user to change the address for.')
+ type = AddressTypeEnum(
+ required=True, description='The type of address.')
+
+ class Meta:
+ description = 'Sets a default address for the given user.'
+
+ @classmethod
+ @permission_required('account.manage_users')
+ def mutate(cls, root, info, address_id, user_id, type):
+ errors = []
+ address = cls.get_node_or_error(info, address_id, errors, 'addressId', Address)
+ if not address:
+ return cls(errors=errors)
+
+ user = cls.get_node_or_error(info, user_id, errors, 'userId', User)
+ if not user:
+ return cls(errors=errors)
+
+ if address not in user.addresses.all():
+ cls.add_error(
+ errors, 'address_id',
+ 'The address doesn\'t belong to that user.')
+ return cls(errors=errors)
+
+ if type == AddressTypeEnum.BILLING.value:
+ address_type = AddressType.BILLING
+ elif type == AddressTypeEnum.SHIPPING.value:
+ address_type = AddressType.SHIPPING
+ else:
+ raise ValueError('Unknown value of AddressTypeEnum: %s' % type)
+
+ utils.change_user_default_address(user, address, address_type)
+ return cls(errors=errors, user=user)
+
+
+# The same as AddressCreate, but for the currenty authenticated user.
+class CustomerAddressCreate(ModelMutation):
+ class Arguments:
+ input = AddressInput(
+ description='Fields required to create address', required=True)
+ type = AddressTypeEnum(required=False, description=(
+ 'A type of address. If provided, the new address will be '
+ 'automatically assigned as the customer\'s default address '
+ 'of that type.'))
+
+ class Meta:
+ description = 'Create a new address for the customer.'
+ model = models.Address
+ exclude = ['user_addresses']
+
+ @classmethod
+ def user_is_allowed(cls, user, input):
+ return user.is_authenticated
+
+ @classmethod
+ def mutate(cls, root, info, **data):
+ success_response = super().mutate(root, info, **data)
+ address_type = data.get('type', None)
+ if address_type:
+ user = info.context.user
+ instance = success_response.address
+ utils.change_user_default_address(user, instance, address_type)
+ return success_response
+
+ @classmethod
+ def save(cls, info, instance, cleaned_input):
+ super().save(info, instance, cleaned_input)
+ user = info.context.user
+ instance.user_addresses.add(user)
+
+
+# The same as SetDefaultAddress, but for the currenty authenticated user.
class CustomerSetDefaultAddress(BaseMutation):
user = graphene.Field(User, description='An updated user instance.')
@@ -528,7 +573,7 @@ class CustomerSetDefaultAddress(BaseMutation):
required=True, description='The type of address.')
class Meta:
- description = 'Sets one of the customer\'s address as default'
+ description = 'Sets a default address for the authenticated user.'
@classmethod
@login_required
@@ -536,11 +581,13 @@ class CustomerSetDefaultAddress(BaseMutation):
errors = []
address = cls.get_node_or_error(info, id, errors, 'id', Address)
if not address:
- return CustomerSetDefaultAddress(errors=errors)
+ return cls(errors=errors)
user = info.context.user
if address not in user.addresses.all():
- raise PermissionDenied()
+ cls.add_error(
+ errors, 'id', 'The address doesn\'t belong to that user.')
+ return cls(errors=errors)
if type == AddressTypeEnum.BILLING.value:
address_type = AddressType.BILLING
@@ -550,4 +597,4 @@ class CustomerSetDefaultAddress(BaseMutation):
raise ValueError('Unknown value of AddressTypeEnum: %s' % type)
utils.change_user_default_address(user, address, address_type)
- return CustomerSetDefaultAddress(errors=errors, user=user)
+ return cls(errors=errors, user=user)
diff --git a/saleor/graphql/account/schema.py b/saleor/graphql/account/schema.py
index 8c0e40ce5b..731ecb82ce 100644
--- a/saleor/graphql/account/schema.py
+++ b/saleor/graphql/account/schema.py
@@ -5,10 +5,11 @@ from ..core.fields import PrefetchingConnectionField
from ..descriptions import DESCRIPTIONS
from .bulk_mutations import CustomerBulkDelete, StaffBulkDelete
from .mutations import (
- AddressCreate, AddressDelete, AddressUpdate, CustomerAddressCreate,
- CustomerCreate, CustomerDelete, CustomerPasswordReset, CustomerRegister,
- CustomerSetDefaultAddress, CustomerUpdate, LoggedUserUpdate, PasswordReset,
- SetPassword, StaffCreate, StaffDelete, StaffUpdate)
+ AddressCreate, AddressDelete, AddressSetDefault, AddressUpdate,
+ CustomerAddressCreate, CustomerCreate, CustomerDelete,
+ CustomerPasswordReset, CustomerRegister, CustomerSetDefaultAddress,
+ CustomerUpdate, LoggedUserUpdate, PasswordReset, SetPassword, StaffCreate,
+ StaffDelete, StaffUpdate)
from .resolvers import (
resolve_address_validator, resolve_customers, resolve_staff_users)
from .types import AddressValidationData, AddressValidationInput, User
@@ -73,3 +74,4 @@ class AccountMutations(graphene.ObjectType):
address_create = AddressCreate.Field()
address_delete = AddressDelete.Field()
address_update = AddressUpdate.Field()
+ address_set_default = AddressSetDefault.Field()
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index b1524d5331..bd664c104c 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -59,6 +59,11 @@ input AddressInput {
phone: String
}
+type AddressSetDefault {
+ errors: [Error!]
+ user: User
+}
+
enum AddressTypeEnum {
BILLING
SHIPPING
@@ -1149,6 +1154,7 @@ type Mutations {
addressCreate(input: AddressCreateInput!): AddressCreate
addressDelete(id: ID!): AddressDelete
addressUpdate(id: ID!, input: AddressInput!): AddressUpdate
+ addressSetDefault(addressId: ID!, type: AddressTypeEnum!, userId: ID!): AddressSetDefault
}
input NameTranslationInput {
diff --git a/tests/api/test_account.py b/tests/api/test_account.py
index c5a03e565d..682816abfc 100644
--- a/tests/api/test_account.py
+++ b/tests/api/test_account.py
@@ -1132,6 +1132,60 @@ def test_customer_delete_address_for_other(
address_obj.refresh_from_db()
+SET_DEFAULT_ADDRESS_MUTATION = """
+mutation($address_id: ID!, $user_id: ID!, $type: AddressTypeEnum!) {
+ addressSetDefault(addressId: $address_id, userId: $user_id, type: $type) {
+ errors {
+ field
+ message
+ }
+ user {
+ defaultBillingAddress {
+ id
+ }
+ defaultShippingAddress {
+ id
+ }
+ }
+ }
+}
+"""
+
+
+def test_set_default_address(
+ staff_api_client, address_other_country, customer_user,
+ permission_manage_users):
+ customer_user.default_billing_address = None
+ customer_user.default_shipping_address = None
+ customer_user.save()
+
+ # try to set an address that doesn't belong to that user
+ address = address_other_country
+
+ variables = {
+ 'address_id': graphene.Node.to_global_id('Address', address.id),
+ 'user_id': graphene.Node.to_global_id('User', customer_user.id),
+ 'type': AddressType.SHIPPING.upper()}
+
+ response = staff_api_client.post_graphql(
+ SET_DEFAULT_ADDRESS_MUTATION, variables,
+ permissions=[permission_manage_users])
+ content = get_graphql_content(response)
+ data = content['data']['addressSetDefault']
+ assert data['errors'][0]['field'] == 'addressId'
+
+ # try to set a new billing address using one of user's addresses
+ address = customer_user.addresses.first()
+ address_id = graphene.Node.to_global_id('Address', address.id)
+
+ variables['address_id'] = address_id
+ response = staff_api_client.post_graphql(
+ SET_DEFAULT_ADDRESS_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content['data']['addressSetDefault']
+ assert data['user']['defaultShippingAddress']['id'] == address_id
+
+
def test_address_validator(user_api_client):
query = """
query getValidator($input: AddressValidationInput!) {
@@ -1409,4 +1463,7 @@ def test_customer_change_default_address_invalid_address(
'id': graphene.Node.to_global_id('Address', address_other_country.id),
'type': AddressType.SHIPPING.upper()}
response = user_api_client.post_graphql(query, variables)
- assert_no_permission(response)
+ content = get_graphql_content(response)
+ assert (
+ content['data']['customerSetDefaultAddress']['errors'][0]['field'] ==
+ 'id')