Skip to content

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

Make possible to add addresses to the user

Adam Janikf5886b0f24ec
diff --git a/saleor/account/models.py b/saleor/account/models.py
index 05112d39bb..10480ed708 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -9,7 +9,7 @@ from django.forms.models import model_to_dict
from django.utils import timezone
from django.utils.translation import pgettext_lazy
from django_countries.fields import Country, CountryField
-from phonenumber_field.modelfields import PhoneNumberField
+from phonenumber_field.modelfields import PhoneNumber, PhoneNumberField
from ..core.models import BaseNote
from .validators import validate_possible_number
@@ -64,6 +64,8 @@ class Address(models.Model):
data = model_to_dict(self, exclude=['id', 'user'])
if isinstance(data['country'], Country):
data['country'] = data['country'].code
+ if isinstance(data['phone'], PhoneNumber):
+ data['phone'] = data['phone'].as_international
return data
def get_copy(self):
diff --git a/saleor/graphql/account/mutations.py b/saleor/graphql/account/mutations.py
index 6a149fa5ff..3b51f68ee5 100644
--- a/saleor/graphql/account/mutations.py
+++ b/saleor/graphql/account/mutations.py
@@ -8,9 +8,9 @@ from graphql_jwt.decorators import permission_required
from ...account import emails, models
from ...core.permissions import MODELS_PERMISSIONS, get_permissions
+from ..account.types import AddressInput
from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ..core.types.common import Error
-from ..order.mutations.draft_orders import AddressInput
from ..utils import get_node
@@ -26,9 +26,13 @@ def send_user_password_reset_email(user, site):
class UserInput(graphene.InputObjectType):
+ default_billing_address = AddressInput(
+ description='Billing address of the customer.')
email = graphene.String(
description='The unique email address of the user.')
note = graphene.String(description='A note about the user.')
+ default_shipping_address = AddressInput(
+ description='Shipping address of the customer.')
class UserCreateInput(UserInput):
@@ -68,6 +72,37 @@ class CustomerCreate(ModelMutation):
def user_is_allowed(cls, user, input):
return user.has_perm('account.manage_users')
+ @classmethod
+ def clean_input(cls, info, instance, input, errors):
+ default_shipping_address = input.pop('default_shipping_address', None)
+ default_billing_address = input.pop('default_billing_address', None)
+ cleaned_input = super().clean_input(info, instance, input, errors)
+
+ if default_shipping_address:
+ default_shipping_address = models.Address(**default_shipping_address)
+ cls.clean_instance(default_shipping_address, errors)
+ cleaned_input['default_shipping_address'] = default_shipping_address
+ if default_billing_address:
+ default_billing_address = models.Address(**default_billing_address)
+ cls.clean_instance(default_billing_address, errors)
+ cleaned_input['default_billing_address'] = default_billing_address
+
+ return cleaned_input
+
+
+ @classmethod
+ def save(cls, info, instance, cleaned_input):
+ default_shipping_address = cleaned_input.get('default_shipping_address')
+ if default_shipping_address:
+ default_shipping_address.save()
+ instance.default_shipping_address = default_shipping_address
+ default_billing_address = cleaned_input.get('default_billing_address')
+ if default_billing_address:
+ default_billing_address.save()
+ instance.default_billing_address = default_billing_address
+ super().save(info, instance, cleaned_input)
+ instance.save(update_fields=['default_billing_address', 'default_shipping_address'])
+
class CustomerUpdate(CustomerCreate):
class Arguments:
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index 047c9bab06..18d739f18b 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -7,6 +7,20 @@ from ..core.types.common import CountableDjangoObjectType, PermissionDisplay
from ..utils import format_permissions_for_display
+class AddressInput(graphene.InputObjectType):
+ first_name = graphene.String(description='Given name.')
+ last_name = graphene.String(description='Family name.')
+ company_name = graphene.String(description='Company or organization.')
+ street_address_1 = graphene.String(description='Address.')
+ street_address_2 = graphene.String(description='Address.')
+ city = graphene.String(description='City.')
+ city_area = graphene.String(description='District.')
+ postal_code = graphene.String(description='Postal code.')
+ country = graphene.String(description='Country.')
+ country_area = graphene.String(description='State or province.')
+ phone = graphene.String(description='Phone number.')
+
+
class Address(CountableDjangoObjectType):
class Meta:
exclude_fields = ['user_set', 'user_addresses']
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index 03b331ec76..5a3e67bc95 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -8,27 +8,14 @@ from ....core.exceptions import InsufficientStock
from ....core.utils.taxes import ZERO_TAXED_MONEY
from ....order import OrderStatus, models
from ....order.utils import add_variant_to_order, recalculate_order
+from ...account.types import AddressInput
from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ...core.types.common import Decimal, Error
from ...product.types import ProductVariant
-from ...utils import get_node, get_nodes
+from ...utils import get_node
from ..types import Order
-class AddressInput(graphene.InputObjectType):
- first_name = graphene.String(description='Given name.')
- last_name = graphene.String(description='Family name.')
- company_name = graphene.String(description='Company or organization.')
- street_address_1 = graphene.String(description='Address.')
- street_address_2 = graphene.String(description='Address.')
- city = graphene.String(description='City.')
- city_area = graphene.String(description='District.')
- postal_code = graphene.String(description='Postal code.')
- country = graphene.String(description='Country.')
- country_area = graphene.String(description='State or province.')
- phone = graphene.String(description='Phone number.')
-
-
class OrderLineInput(graphene.InputObjectType):
variant_id = graphene.ID(
description='Product variant ID.', name='variantId')
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 9631f5571d..2bb532fa8d 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -5,12 +5,12 @@ from payments import PaymentError, PaymentStatus
from ....order import CustomPaymentChoices, models
from ....order.utils import cancel_order
+from ...account.types import AddressInput
from ...core.mutations import BaseMutation, ModelMutation
from ...core.types.common import Decimal, Error
from ...order.mutations.draft_orders import DraftOrderUpdate
from ...order.types import Order
from ...utils import get_node
-from .draft_orders import AddressInput
def try_payment_action(action, money, errors):
diff --git a/tests/api/test_account.py b/tests/api/test_account.py
index f262235f18..fb814f9966 100644
--- a/tests/api/test_account.py
+++ b/tests/api/test_account.py
@@ -7,7 +7,7 @@ import pytest
from django.contrib.auth import get_user_model
from django.shortcuts import reverse
from tests.utils import get_graphql_content
-from .utils import assert_no_permission
+from .utils import assert_no_permission, convert_dict_keys_to_camel_case
from saleor.account.models import Address
from saleor.graphql.account.mutations import SetPassword
@@ -138,7 +138,7 @@ def test_query_user(admin_api_client, customer_user):
assert address['postalCode'] == user_address.postal_code
assert address['country'] == user_address.country.code
assert address['countryArea'] == user_address.country_area
- assert address['phone'] == user_address.phone.raw_input
+ assert address['phone'] == user_address.phone.as_e164
def test_query_users(admin_api_client, user_api_client):
@@ -222,10 +222,16 @@ def test_who_can_see_user(
@patch('saleor.account.emails.send_password_reset_email.delay')
def test_customer_create(
- send_password_reset_mock, admin_api_client, user_api_client):
+ send_password_reset_mock, admin_api_client, user_api_client, address):
query = """
- mutation CreateCustomer($email: String, $note: String, $send_mail: Boolean) {
- customerCreate(input: {email: $email, note: $note, sendPasswordEmail: $send_mail}) {
+ mutation CreateCustomer(
+ $email: String, $note: String, $shipping: AddressInput,
+ $send_mail: Boolean) {
+ customerCreate(
+ input: {
+ email: $email, note: $note, defaultShippingAddress: $shipping,
+ sendPasswordEmail: $send_mail
+ }) {
errors {
field
message
@@ -242,8 +248,11 @@ def test_customer_create(
"""
note = 'Test user'
+ address_data = convert_dict_keys_to_camel_case(address.as_data())
- variables = json.dumps({'email': email, 'note': note, 'send_mail': True})
+ variables = json.dumps({
+ 'email': email, 'note': note, 'shipping': address_data,
+ 'send_mail': True})
response = user_api_client.post(
reverse('api'), {'query': query, 'variables': variables})
@@ -252,6 +261,11 @@ def test_customer_create(
response = admin_api_client.post(
reverse('api'), {'query': query, 'variables': variables})
content = get_graphql_content(response)
+
+ User = get_user_model()
+ customer = User.objects.get(email=email)
+
+ assert customer.default_shipping_address == address
assert 'errors' not in content
data = content['data']['customerCreate']
assert data['errors'] == []
diff --git a/tests/api/utils.py b/tests/api/utils.py
index 40244b69bc..9bb7559715 100644
--- a/tests/api/utils.py
+++ b/tests/api/utils.py
@@ -1,5 +1,6 @@
import json
from tests.utils import get_graphql_content
+from saleor.graphql.core.utils import snake_to_camel_case
def assert_no_permission(response):
@@ -17,3 +18,16 @@ def get_multipart_request_body(query, variables, file, file_name):
return {
'operations': json.dumps({'query': query, 'variables': variables}),
'map': json.dumps({file_name: ['variables.file']}), file_name: file}
+
+
+def convert_dict_keys_to_camel_case(d):
+ """Changes dict fields from d[field_name] to d[fieldName].
+
+ Useful when dealing with dict data such as address that need to be parsed
+ into graphql input.
+ """
+ data = {}
+ for k, v in d.items():
+ new_key = snake_to_camel_case(k)
+ data[new_key] = d[k]
+ return data