Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Validate addresses in mutations
Pacu288d6ce4a72db
diff --git a/saleor/graphql/account/mutations.py b/saleor/graphql/account/mutations.pyindex 5911a5c2ae..572df14187 100644--- a/saleor/graphql/account/mutations.py+++ b/saleor/graphql/account/mutations.py@@ -10,6 +10,7 @@ from graphql_jwt.exceptions import PermissionDeniedfrom ...account import emails, modelsfrom ...core.permissions import MODELS_PERMISSIONS, get_permissionsfrom ...dashboard.staff.utils import remove_staff_member+from ..account.i18n import I18nMixinfrom ..account.types import AddressInput, Userfrom ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ..core.types.common import Error@@ -84,7 +85,7 @@ class StaffCreateInput(StaffInput):description='Send an email with a link to set a password')-class CustomerCreate(ModelMutation):+class CustomerCreate(ModelMutation, I18nMixin):class Arguments:input = UserCreateInput(description='Fields required to create a customer.', required=True)@@ -98,37 +99,22 @@ class CustomerCreate(ModelMutation):def user_is_allowed(cls, user, input):return user.has_perm('account.manage_users')- @classmethod- def construct_address(- cls, address_field_name, address_input, user_instance, errors):- if address_field_name not in [- BILLING_ADDRESS_FIELD, SHIPPING_ADDRESS_FIELD]:- raise AssertionError(- 'Wrong address_field_name: %s' % address_field_name)-- address_instance = getattr(user_instance, address_field_name)- if not address_instance:- address_instance = models.Address()-- cls.construct_instance(address_instance, address_input)- cls.clean_instance(address_instance, errors)- return address_instance-@classmethoddef clean_input(cls, info, instance, input, errors):- shipping_address_input = input.pop(SHIPPING_ADDRESS_FIELD, None)- billing_address_input = input.pop(BILLING_ADDRESS_FIELD, None)+ shipping_address_data = input.pop(SHIPPING_ADDRESS_FIELD, None)+ billing_address_data= input.pop(BILLING_ADDRESS_FIELD, None)cleaned_input = super().clean_input(info, instance, input, errors)- if shipping_address_input:- shipping_address = cls.construct_address(- SHIPPING_ADDRESS_FIELD, shipping_address_input, instance,- errors)+ if shipping_address_data:+ shipping_address, errors = cls.validate_address(+ shipping_address_data, errors, SHIPPING_ADDRESS_FIELD,+ instance=getattr(instance, SHIPPING_ADDRESS_FIELD))cleaned_input[SHIPPING_ADDRESS_FIELD] = shipping_address- if billing_address_input:- billing_address = cls.construct_address(- BILLING_ADDRESS_FIELD, billing_address_input, instance, errors)+ if billing_address_data:+ billing_address, errors = cls.validate_address(+ billing_address_data, errors, BILLING_ADDRESS_FIELD,+ instance=getattr(instance, BILLING_ADDRESS_FIELD))cleaned_input[BILLING_ADDRESS_FIELD] = billing_addressreturn cleaned_inputdiff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.pyindex e26cd95fcf..456fb42260 100644--- a/saleor/graphql/account/types.py+++ b/saleor/graphql/account/types.py@@ -20,7 +20,7 @@ class AddressInput(graphene.InputObjectType):city = graphene.String(description='City.')city_area = graphene.String(description='District.')postal_code = graphene.String(description='Postal code.')- country = graphene.String(description='Country.')+ country = graphene.String(required=True, description='Country.')country_area = graphene.String(description='State or province.')phone = graphene.String(description='Phone number.')diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 7bc009edd7..1caad58b19 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -11,6 +11,7 @@ from ...core import analyticsfrom ...core.exceptions import InsufficientStockfrom ...core.utils.taxes import get_taxes_for_addressfrom ...shipping.models import ShippingMethod as ShippingMethodModel+from ..account.i18n import I18nMixinfrom ..account.types import AddressInput, Userfrom ..core.mutations import BaseMutation, ModelMutationfrom ..core.types.common import Error@@ -90,7 +91,7 @@ class CheckoutCreateInput(graphene.InputObjectType):'The mailling address to where the checkout will be shipped.'))-class CheckoutCreate(ModelMutation):+class CheckoutCreate(ModelMutation, I18nMixin):class Arguments:input = CheckoutCreateInput(required=True, description='Fields required to create a Checkout.')@@ -102,7 +103,6 @@ class CheckoutCreate(ModelMutation):@classmethoddef clean_input(cls, info, instance, input, errors):- shipping_address = input.pop('shipping_address', None)cleaned_input = super().clean_input(info, instance, input, errors)lines = input.pop('lines', None)if lines:@@ -119,9 +119,10 @@ class CheckoutCreate(ModelMutation):cleaned_input['variants'] = variantscleaned_input['quantities'] = quantities- if shipping_address:- shipping_address = Address(**shipping_address)- cls.clean_instance(shipping_address, errors)+ shipping_address_data = input.pop('shipping_address', None)+ if shipping_address_data:+ shipping_address, errors = cls.validate_address(+ shipping_address_data, errors)cleaned_input['shipping_address'] = shipping_addressreturn cleaned_input@@ -266,7 +267,7 @@ class CheckoutCustomerDetach(BaseMutation):return CheckoutCustomerDetach(checkout=checkout)-class CheckoutShippingAddressUpdate(BaseMutation):+class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):checkout = graphene.Field(Checkout, description='An updated checkout')class Arguments:@@ -279,20 +280,13 @@ class CheckoutShippingAddressUpdate(BaseMutation):description = 'Update shipping address in the existing Checkout.'@classmethod- def clean_address(cls, address, errors):- if address:- address = Address(**address)- cls.clean_instance(address, errors)- return address-- @classmethod- def mutate(- cls, root, info, checkout_id, shipping_address):+ def mutate(cls, root, info, checkout_id, shipping_address):errors = []checkout = cls.get_node_or_error(info, checkout_id, errors, 'checkout_id', only_type=Checkout)- if shipping_address:- shipping_address = cls.clean_address(shipping_address, errors)++ shipping_address, errors = cls.validate_address(+ shipping_address, errors, instance=checkout.shipping_address)if errors:return CheckoutShippingAddressUpdate(errors=errors)@@ -322,13 +316,14 @@ class CheckoutBillingAddressUpdate(CheckoutShippingAddressUpdate):description = 'Update billing address in the existing Checkout.'@classmethod- def mutate(- cls, root, info, checkout_id, billing_address):+ def mutate(cls, root, info, checkout_id, billing_address):errors = []checkout = cls.get_node_or_error(info, checkout_id, errors, 'checkout_id', only_type=Checkout)+if billing_address:- billing_address = cls.clean_address(billing_address, errors)+ billing_address, errors = cls.validate_address(+ billing_address, errors, instance=checkout.billing_address)if errors:return CheckoutBillingAddressUpdate(errors=errors)diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.pyindex 619004235d..ae7bba4a12 100644--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@ -120,6 +120,28 @@ class BaseMutation(graphene.Mutation):cls.add_error(errors, field, message)return errors+ @classmethod+ def construct_instance(cls, instance, cleaned_data):+ """Fill instance fields with cleaned data.++ The `instance` argument is either an empty instance of a already+ existing one which was fetched from the database. `cleaned_data` is+ data to be set in instance fields. Returns `instance` with filled+ fields, but not saved to the database.+ """+ from django.db import models+ opts = instance._meta++ for f in opts.fields:+ if any([not f.editable, isinstance(f, models.AutoField),+ f.name not in cleaned_data]):+ continue+ data = cleaned_data[f.name]+ if not f.null and data is None:+ data = f._get_default()+ f.save_form_data(instance, data)+ return instance+class ModelMutation(BaseMutation):class Meta:@@ -210,28 +232,6 @@ class ModelMutation(BaseMutation):cleaned_input[field_name] = valuereturn cleaned_input- @classmethod- def construct_instance(cls, instance, cleaned_data):- """Fill instance fields with cleaned data.-- The `instance` argument is either an empty instance of a already- existing one which was fetched from the database. `cleaned_data` is- data to be set in instance fields. Returns `instance` with filled- fields, but not saved to the database.- """- from django.db import models- opts = instance._meta-- for f in opts.fields:- if any([not f.editable, isinstance(f, models.AutoField),- f.name not in cleaned_data]):- continue- data = cleaned_data[f.name]- if not f.null and data is None:- data = f._get_default()- f.save_form_data(instance, data)- return instance-@classmethoddef _save_m2m(cls, info, instance, cleaned_data):opts = instance._metadiff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.pyindex d401943aa4..754d45c60c 100644--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@ -10,6 +10,7 @@ from ....core.utils.taxes import ZERO_TAXED_MONEYfrom ....order import OrderEvents, OrderStatus, modelsfrom ....order.utils import (add_variant_to_order, allocate_stock, recalculate_order)+from ...account.i18n import I18nMixinfrom ...account.types import AddressInputfrom ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ...core.types.common import Decimal, Error@@ -50,7 +51,7 @@ class DraftOrderCreateInput(DraftOrderInput):and quantity of products."""))-class DraftOrderCreate(ModelMutation):+class DraftOrderCreate(ModelMutation, I18nMixin):class Arguments:input = DraftOrderCreateInput(required=True,@@ -88,14 +89,15 @@ class DraftOrderCreate(ModelMutation):'billing_address'] = user.default_billing_addressif shipping_address:- shipping_address = Address(**shipping_address)- cls.clean_instance(shipping_address, errors)+ shipping_address, errors = cls.validate_address(+ shipping_address, errors, 'shipping_address',+ instance=instance.shipping_address)cleaned_input['shipping_address'] = shipping_addressif billing_address:- billing_address = Address(**billing_address)- cls.clean_instance(billing_address, errors)+ billing_address, errors = cls.validate_address(+ billing_address, errors, 'billing_address',+ instance=instance.billing_address)cleaned_input['billing_address'] = billing_address-return cleaned_input@classmethoddiff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex b083f56c3e..21e15bab6f 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -7,6 +7,7 @@ from ...payment import PaymentErrorfrom ...payment.utils import (create_payment_method, gateway_authorize, gateway_capture, gateway_refund,gateway_void)+from ..account.i18n import I18nMixinfrom ..account.types import AddressInputfrom ..checkout.types import Checkoutfrom ..core.mutations import BaseMutation@@ -33,7 +34,7 @@ class PaymentMethodInput(graphene.InputObjectType):description='Store card for further usage.')-class CheckoutPaymentMethodCreate(BaseMutation):+class CheckoutPaymentMethodCreate(BaseMutation, I18nMixin):payment_method = graphene.Field(PaymentMethod, description='Updated payment method')@@ -53,14 +54,15 @@ class CheckoutPaymentMethodCreate(BaseMutation):only_type=Checkout)if not checkout:return CheckoutPaymentMethodCreate(errors=errors)-billing_data = {}- extra_data = cls.get_extra_info(info)if input['billing_address']:- billing_data = cls.clean_billing_address(input['billing_address'])+ billing_address, errors = cls.validate_address(+ input['billing_address'], errors, 'billing_address')+ if not billing_address:+ return CheckoutPaymentMethodCreate(errors=errors)+ billing_data = cls.clean_billing_address(billing_address)- # create payment method- # FIXME should take amount and tax into the consideration+ extra_data = cls.get_extra_info(info)gross = Money(input['amount'], currency=settings.DEFAULT_CURRENCY)tax = Money(input['amount'], currency=settings.DEFAULT_CURRENCY)net = (gross - tax) or grossdiff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 32af056608..d06fc6f71c 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -55,7 +55,7 @@ def validate_payment_method(view):def func(payment_method, *args, **kwargs):if not payment_method.is_active:raise PaymentError('This payment method is no longer active.')- return view(*args, payment_method, **kwargs)+ return view(payment_method, *args, **kwargs)return funcdiff --git a/tests/api/test_account.py b/tests/api/test_account.pyindex f9f991b77e..32d3da62df 100644--- a/tests/api/test_account.py+++ b/tests/api/test_account.py@@ -718,10 +718,11 @@ def test_create_address_mutation(def test_address_update_mutation(- staff_api_client, customer_user, permission_manage_users):+ staff_api_client, customer_user, permission_manage_users,+ graphql_address_data):query = """- mutation updateUserAddress($addressId: ID!, $city: String!) {- addressUpdate(id: $addressId, input: {city: $city}) {+ mutation updateUserAddress($addressId: ID!, $address: AddressInput!) {+ addressUpdate(id: $addressId, input: $address) {address {city}@@ -729,17 +730,16 @@ def test_address_update_mutation(}"""address_obj = customer_user.addresses.first()- new_city = 'Dummy'variables = {'addressId': graphene.Node.to_global_id('Address', address_obj.id),- 'city': new_city}+ 'address': graphql_address_data}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_users])content = get_graphql_content(response)data = content['data']['addressUpdate']- assert data['address']['city'] == new_city+ assert data['address']['city'] == graphql_address_data['city']address_obj.refresh_from_db()- assert address_obj.city == new_city+ assert address_obj.city == graphql_address_data['city']def test_address_delete_mutation(diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.pyindex fc82716f33..e8b50b5072 100644--- a/tests/api/test_checkout.py+++ b/tests/api/test_checkout.py@@ -10,7 +10,7 @@ from saleor.order.models import Orderfrom saleor.payment import TransactionType-def test_checkout_create(user_api_client, variant):+def test_checkout_create(user_api_client, variant, graphql_address_data):"""Create checkout object using GraphQL API."""query = """mutation createCheckout($checkoutInput: CheckoutCreateInput!) {@@ -24,15 +24,7 @@ def test_checkout_create(user_api_client, variant):"""variant_id = graphene.Node.to_global_id('ProductVariant', variant.id)test_email = '[email protected]'- shipping_address = {- 'firstName': "John",- 'lastName': 'Doe',- 'streetAddress1': 'Wall st.',- 'streetAddress2': '',- 'postalCode': '902010',- 'country': 'US',- 'city': 'New York'}-+ shipping_address = graphql_address_datavariables = {'checkoutInput': {'lines': [{@@ -254,7 +246,8 @@ def test_checkout_customer_detach(assert cart.user is None-def test_checkout_shipping_address_update(user_api_client, cart_with_item):+def test_checkout_shipping_address_update(+ user_api_client, cart_with_item, graphql_address_data):cart = cart_with_itemassert cart.shipping_address is Nonecheckout_id = graphene.Node.to_global_id('Checkout', cart.pk)@@ -273,15 +266,7 @@ def test_checkout_shipping_address_update(user_api_client, cart_with_item):}}"""- shipping_address = {- 'firstName': "John",- 'lastName': 'Doe',- 'streetAddress1': 'Wall st.',- 'streetAddress2': '',- 'postalCode': '902010',- 'country': 'US',- 'city': 'New York'}-+ shipping_address = graphql_address_datavariables = {'checkoutId': checkout_id, 'shippingAddress': shipping_address}@@ -302,7 +287,8 @@ def test_checkout_shipping_address_update(user_api_client, cart_with_item):assert cart.shipping_address.city == shipping_address['city']-def test_checkout_billing_address_update(user_api_client, cart_with_item):+def test_checkout_billing_address_update(+ user_api_client, cart_with_item, graphql_address_data):cart = cart_with_itemassert cart.shipping_address is Nonecheckout_id = graphene.Node.to_global_id('Checkout', cart.pk)@@ -321,14 +307,7 @@ def test_checkout_billing_address_update(user_api_client, cart_with_item):}}"""- billing_address = {- 'firstName': "John",- 'lastName': 'Doe',- 'streetAddress1': 'Wall st.',- 'streetAddress2': '',- 'postalCode': '902010',- 'country': 'US',- 'city': 'New York'}+ billing_address = graphql_address_datavariables = {'checkoutId': checkout_id, 'billingAddress': billing_address}diff --git a/tests/api/test_order.py b/tests/api/test_order.pyindex 29e54c545d..fb4b073566 100644--- a/tests/api/test_order.py+++ b/tests/api/test_order.py@@ -235,7 +235,8 @@ def test_non_staff_user_can_only_see_his_order(user_api_client, order):def test_draft_order_create(staff_api_client, permission_manage_orders, customer_user,- product_without_shipping, shipping_method, variant, voucher):+ product_without_shipping, shipping_method, variant, voucher,+ graphql_address_data):variant_0 = variantquery = """mutation draftCreate(@@ -278,7 +279,7 @@ def test_draft_order_create(variant_list = [{'variantId': variant_0_id, 'quantity': 2},{'variantId': variant_1_id, 'quantity': 1}]- shipping_address = {'firstName': 'John', 'country': 'PL'}+ shipping_address = graphql_address_datashipping_id = graphene.Node.to_global_id('ShippingMethod', shipping_method.id)voucher_id = graphene.Node.to_global_id('Voucher', voucher.id)@@ -292,6 +293,7 @@ def test_draft_order_create(response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)+ assert not content['data']['draftOrderCreate']['errors']data = content['data']['draftOrderCreate']['order']assert data['status'] == OrderStatus.DRAFT.upper()assert data['voucher']['code'] == voucher.code@@ -300,8 +302,7 @@ def test_draft_order_create(assert order.user == customer_userassert order.billing_address == customer_user.default_billing_addressassert order.shipping_method == shipping_method- assert order.shipping_address == Address(- **{'first_name': 'John', 'country': 'PL'})+ assert order.shipping_address.first_name == graphql_address_data['firstName']def test_draft_order_update(@@ -677,20 +678,19 @@ def test_require_draft_order_when_removing_lines(def test_order_update(- staff_api_client, permission_manage_orders, order_with_lines):+ staff_api_client, permission_manage_orders, order_with_lines,+ graphql_address_data):order = order_with_linesorder.user = Noneorder.save()query = """mutation orderUpdate(- $id: ID!, $email: String, $first_name: String, $last_name: String,- $country_code: String) {+ $id: ID!, $email: String, $address: AddressInput) {orderUpdate(id: $id, input: {- userEmail: $email, shippingAddress:- {firstName: $first_name, country: $country_code},- billingAddress:- {lastName: $last_name, country: $country_code}}) {+ userEmail: $email,+ shippingAddress: $address,+ billingAddress: $address}) {errors {fieldmessage@@ -702,46 +702,39 @@ def test_order_update(}"""email = '[email protected]'- first_name = 'Test fname'- last_name = 'Test lname'assert not order.user_email == email- assert not order.shipping_address.first_name == first_name- assert not order.billing_address.last_name == last_name+ assert not order.shipping_address.first_name == graphql_address_data['firstName']+ assert not order.billing_address.last_name == graphql_address_data['lastName']order_id = graphene.Node.to_global_id('Order', order.id)variables = {- 'id': order_id,- 'email': email,- 'first_name': first_name,- 'last_name': last_name,- 'country_code': 'PL'}+ 'id': order_id, 'email': email, 'address': graphql_address_data}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)+ assert not content['data']['orderUpdate']['errors']data = content['data']['orderUpdate']['order']assert data['userEmail'] == emailorder.refresh_from_db()- assert order.shipping_address.first_name == first_name- assert order.billing_address.last_name == last_name+ assert order.shipping_address.first_name == graphql_address_data['firstName']+ assert order.billing_address.last_name == graphql_address_data['lastName']assert order.user_email == emailassert order.user is Nonedef test_order_update_anonymous_user_no_user_email(- staff_api_client, order_with_lines, permission_manage_orders):+ staff_api_client, order_with_lines, permission_manage_orders,+ graphql_address_data):order = order_with_linesorder.user = Noneorder.save()query = """mutation orderUpdate(- $id: ID!, $first_name: String, $last_name: String,- $country_code: String) {+ $id: ID!, $address: AddressInput) {orderUpdate(id: $id, input: {- shippingAddress:- {firstName: $first_name, country: $country_code},- billingAddress:- {lastName: $last_name, country: $country_code}}) {+ shippingAddress: $address,+ billingAddress: $address}) {errors {fieldmessage@@ -755,9 +748,7 @@ def test_order_update_anonymous_user_no_user_email(first_name = 'Test fname'last_name = 'Test lname'order_id = graphene.Node.to_global_id('Order', order.id)- variables = {- 'id': order_id, 'first_name': first_name, 'last_name': last_name,- 'country_code': 'PL'}+ variables = {'id': order_id, 'address': graphql_address_data}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)@@ -774,20 +765,17 @@ def test_order_update_anonymous_user_no_user_email(def test_order_update_user_email_existing_user(staff_api_client, order_with_lines, customer_user,- permission_manage_orders):+ permission_manage_orders, graphql_address_data):order = order_with_linesorder.user = Noneorder.save()query = """mutation orderUpdate(- $id: ID!, $email: String, $first_name: String, $last_name: String,- $country_code: String) {+ $id: ID!, $email: String, $address: AddressInput) {orderUpdate(id: $id, input: {- userEmail: $email, shippingAddress:- {firstName: $first_name, country: $country_code},- billingAddress:- {lastName: $last_name, country: $country_code}}) {+ userEmail: $email, shippingAddress: $address,+ billingAddress: $address}) {errors {fieldmessage@@ -799,21 +787,19 @@ def test_order_update_user_email_existing_user(}"""email = customer_user.email- first_name = 'Test fname'- last_name = 'Test lname'order_id = graphene.Node.to_global_id('Order', order.id)variables = {- 'id': order_id, 'email': email, 'first_name': first_name,- 'last_name': last_name, 'country_code': 'PL'}+ 'id': order_id, 'address': graphql_address_data, 'email': email}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)+ assert not content['data']['orderUpdate']['errors']data = content['data']['orderUpdate']['order']assert data['userEmail'] == emailorder.refresh_from_db()- assert order.shipping_address.first_name == first_name- assert order.billing_address.last_name == last_name+ assert order.shipping_address.first_name == graphql_address_data['firstName']+ assert order.billing_address.last_name == graphql_address_data['lastName']assert order.user_email == emailassert order.user == customer_userdiff --git a/tests/conftest.py b/tests/conftest.pyindex 91e4729070..a7be0eb6b7 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -101,14 +101,16 @@ def address(db): # pylint: disable=W0613@pytest.fixturedef graphql_address_data():return {- 'firstName': 'John',- 'lastName': 'Doe',- 'streetAddress1': 'Wall st.',+ 'firstName': 'John Saleor',+ 'lastName': 'Doe Mirumee',+ 'companyName': 'Mirumee Software',+ 'streetAddress1': 'Tęczowa 7','streetAddress2': '',- 'postalCode': '902010',- 'country': 'US',- 'city': 'New York',- 'countryArea': ''}+ 'postalCode': '53-601',+ 'country': 'PL',+ 'city': 'Wrocław',+ 'countryArea': '',+ 'phone': '+48321321888'}@pytest.fixture