Skip to content

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

Possibility to skip address validation for checkout (#10084)

Maciej Korycinski7de33b145467
diff --git a/saleor/account/forms.py b/saleor/account/forms.py
index 4500140e8a..f5999c2974 100644
--- a/saleor/account/forms.py
+++ b/saleor/account/forms.py
@@ -3,7 +3,9 @@ from phonenumbers.phonenumberutil import country_code_for_region
from .i18n import AddressMetaForm, get_address_form_class
-def get_address_form(data, country_code, initial=None, instance=None, **kwargs):
+def get_address_form(
+ data, country_code, initial=None, instance=None, enable_normalization=True, **kwargs
+):
country_form = AddressMetaForm(data, initial=initial)
preview = False
if country_form.is_valid():
@@ -19,13 +21,18 @@ def get_address_form(data, country_code, initial=None, instance=None, **kwargs):
if not preview and instance is not None:
address_form_class = get_address_form_class(instance.country.code)
- address_form = address_form_class(data, instance=instance, **kwargs)
+ address_form = address_form_class(
+ data, instance=instance, enable_normalization=enable_normalization, **kwargs
+ )
else:
initial_address = (
initial if not preview else data.dict() if data is not None else data
)
address_form = address_form_class(
- not preview and data or None, initial=initial_address, **kwargs
+ not preview and data or None,
+ initial=initial_address,
+ enable_normalization=enable_normalization,
+ **kwargs,
)
if hasattr(address_form.fields["country_area"], "choices"):
diff --git a/saleor/account/i18n.py b/saleor/account/i18n.py
index cd27aae1a6..d0d7fdde11 100644
--- a/saleor/account/i18n.py
+++ b/saleor/account/i18n.py
@@ -111,6 +111,7 @@ class AddressForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
autocomplete_type = kwargs.pop("autocomplete_type", None)
+ self.enable_normalization = kwargs.pop("enable_normalization", True)
super().__init__(*args, **kwargs)
# countries order was taken as defined in the model,
# not being sorted accordingly to the selected language
@@ -186,8 +187,10 @@ class CountryAwareAddressForm(AddressForm):
data["street_address_1"],
data["street_address_2"],
)
- data = i18naddress.normalize_address(data)
- del data["sorting_code"]
+ normalized_data = i18naddress.normalize_address(data)
+ if getattr(self, "enable_normalization", True):
+ data = normalized_data
+ del data["sorting_code"]
except i18naddress.InvalidAddress as exc:
self.add_field_errors(exc.errors)
return data
diff --git a/saleor/graphql/account/i18n.py b/saleor/graphql/account/i18n.py
index af57c0e716..b90856a1d4 100644
--- a/saleor/graphql/account/i18n.py
+++ b/saleor/graphql/account/i18n.py
@@ -23,7 +23,13 @@ class I18nMixin:
@classmethod
def validate_address_form(
- cls, address_data: dict, address_type: Optional[str] = None, instance=None
+ cls,
+ address_data: dict,
+ address_type: Optional[str] = None,
+ instance=None,
+ format_check=True,
+ required_check=True,
+ enable_normalization=True,
):
phone = address_data.get("phone", None)
params = {"address_type": address_type} if address_type else {}
@@ -31,33 +37,54 @@ class I18nMixin:
try:
validate_possible_number(phone, address_data.get("country"))
except ValidationError as exc:
- raise ValidationError(
- {
- "phone": ValidationError(
- f"'{phone}' is not a valid phone number.",
- code=exc.code,
- params=params,
- )
- }
- ) from exc
+ if format_check:
+ raise ValidationError(
+ {
+ "phone": ValidationError(
+ f"'{phone}' is not a valid phone number.",
+ code=exc.code,
+ params=params,
+ )
+ }
+ ) from exc
address_form, _ = get_address_form(
- address_data, address_data.get("country"), instance=instance
+ address_data,
+ address_data.get("country"),
+ instance=instance,
+ enable_normalization=enable_normalization,
)
if not address_form.is_valid():
- errors = cls.attach_params_to_address_form_errors(address_form, params)
- raise ValidationError(errors)
+ errors = cls.attach_params_to_address_form_errors(
+ address_form, params, format_check, required_check
+ )
+ if errors:
+ raise ValidationError(errors)
return address_form
@classmethod
- def attach_params_to_address_form_errors(cls, address_form, params: Dict[str, str]):
- errors_dict = address_form.errors.as_data()
- for errors in errors_dict.values():
+ def attach_params_to_address_form_errors(
+ cls,
+ address_form,
+ params: Dict[str, str],
+ values_check=True,
+ required_check=True,
+ ):
+ address_errors_dict = address_form.errors.as_data()
+ errors_dict = {}
+ for field, errors in address_errors_dict.items():
for error in errors:
if not error.params:
error.params = params
else:
error.params.update(params)
+ if error.code != "required":
+ if values_check:
+ errors_dict[field] = errors
+ else:
+ address_form.cleaned_data[field] = address_form.data[field]
+ if required_check and error.code == "required":
+ errors_dict[field] = errors
return errors_dict
@classmethod
@@ -67,7 +94,10 @@ class I18nMixin:
*,
address_type: Optional[str] = None,
instance: Optional[Address] = None,
- info=None
+ info=None,
+ format_check=True,
+ required_check=True,
+ enable_normalization=True
):
if address_data.get("country") is None:
params = {"address_type": address_type} if address_type else {}
@@ -78,7 +108,13 @@ class I18nMixin:
)
}
)
- address_form = cls.validate_address_form(address_data, address_type)
+ address_form = cls.validate_address_form(
+ address_data,
+ address_type,
+ format_check=format_check,
+ required_check=required_check,
+ enable_normalization=enable_normalization,
+ )
if not instance:
instance = Address()
diff --git a/saleor/graphql/checkout/mutations/checkout_billing_address_update.py b/saleor/graphql/checkout/mutations/checkout_billing_address_update.py
index f12c529815..ecd0bfbc37 100644
--- a/saleor/graphql/checkout/mutations/checkout_billing_address_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_billing_address_update.py
@@ -5,10 +5,16 @@ from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.utils import change_billing_address_in_checkout
from ....core.tracing import traced_atomic_transaction
from ...account.types import AddressInput
-from ...core.descriptions import ADDED_IN_34, DEPRECATED_IN_3X_INPUT
+from ...core.descriptions import (
+ ADDED_IN_34,
+ ADDED_IN_35,
+ DEPRECATED_IN_3X_INPUT,
+ PREVIEW_FEATURE,
+)
from ...core.scalars import UUID
from ...core.types import CheckoutError
from ..types import Checkout
+from .checkout_create import CheckoutAddressValidationRules
from .checkout_shipping_address_update import CheckoutShippingAddressUpdate
from .utils import get_checkout
@@ -34,6 +40,14 @@ class CheckoutBillingAddressUpdate(CheckoutShippingAddressUpdate):
billing_address = AddressInput(
required=True, description="The billing address of the checkout."
)
+ validation_rules = CheckoutAddressValidationRules(
+ required=False,
+ description=(
+ "The rules for changing validation for received billing address data."
+ + ADDED_IN_35
+ + PREVIEW_FEATURE
+ ),
+ )
class Meta:
description = "Update billing address in the existing checkout."
@@ -42,7 +56,14 @@ class CheckoutBillingAddressUpdate(CheckoutShippingAddressUpdate):
@classmethod
def perform_mutation(
- cls, _root, info, billing_address, checkout_id=None, token=None, id=None
+ cls,
+ _root,
+ info,
+ billing_address,
+ validation_rules=None,
+ checkout_id=None,
+ token=None,
+ id=None,
):
checkout = get_checkout(
cls,
@@ -53,11 +74,17 @@ class CheckoutBillingAddressUpdate(CheckoutShippingAddressUpdate):
error_class=CheckoutErrorCode,
)
+ address_validation_rules = validation_rules or {}
billing_address = cls.validate_address(
billing_address,
address_type=AddressType.BILLING,
instance=checkout.billing_address,
info=info,
+ format_check=address_validation_rules.get("check_fields_format", True),
+ required_check=address_validation_rules.get("check_required_fields", True),
+ enable_normalization=address_validation_rules.get(
+ "enable_fields_normalization", True
+ ),
)
with traced_atomic_transaction():
billing_address.save()
diff --git a/saleor/graphql/checkout/mutations/checkout_complete.py b/saleor/graphql/checkout/mutations/checkout_complete.py
index 169c18dac8..5c50990f45 100644
--- a/saleor/graphql/checkout/mutations/checkout_complete.py
+++ b/saleor/graphql/checkout/mutations/checkout_complete.py
@@ -1,15 +1,24 @@
+from typing import TYPE_CHECKING, Iterable
+
import graphene
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ValidationError
+from ....checkout import AddressType
from ....checkout.checkout_cleaner import validate_checkout_email
from ....checkout.complete_checkout import complete_checkout
from ....checkout.error_codes import CheckoutErrorCode
-from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ....checkout.fetch import (
+ CheckoutLineInfo,
+ fetch_checkout_info,
+ fetch_checkout_lines,
+)
+from ....checkout.utils import is_shipping_required
from ....core import analytics
from ....core.permissions import AccountPermissions
from ....core.transactions import transaction_with_commit_on_errors
from ....order import models as order_models
+from ...account.i18n import I18nMixin
from ...core.descriptions import ADDED_IN_34, DEPRECATED_IN_3X_INPUT
from ...core.fields import JSONString
from ...core.mutations import BaseMutation
@@ -21,8 +30,11 @@ from ...utils import get_user_or_app_from_context
from ..types import Checkout
from .utils import get_checkout
+if TYPE_CHECKING:
+ from ....account.models import Address
+
-class CheckoutComplete(BaseMutation):
+class CheckoutComplete(BaseMutation, I18nMixin):
order = graphene.Field(Order, description="Placed order.")
confirmation_needed = graphene.Boolean(
required=True,
@@ -87,6 +99,64 @@ class CheckoutComplete(BaseMutation):
error_type_class = CheckoutError
error_type_field = "checkout_errors"
+ @classmethod
+ def validate_checkout_addresses(
+ cls,
+ lines: Iterable[CheckoutLineInfo],
+ shipping_address: "Address",
+ billing_address: "Address",
+ ):
+ """Validate checkout addresses.
+
+ Mutations for updating addresses have option to turn off a validation. To keep
+ consistency, we need to validate it. This will confirm that we have a correct
+ address and we can finalize a checkout. In case when address fields
+ normalization was turned off, we apply it here.
+ Raises ValidationError when any address is not correct.
+ """
+ if is_shipping_required(lines):
+ if not shipping_address:
+ raise ValidationError(
+ {
+ "shipping_address": ValidationError(
+ "Shipping address is not set",
+ code=CheckoutErrorCode.SHIPPING_ADDRESS_NOT_SET.value,
+ )
+ }
+ )
+ shipping_address_data = shipping_address.as_data()
+ cls.validate_address(
+ shipping_address_data,
+ address_type=AddressType.SHIPPING,
+ format_check=True,
+ required_check=True,
+ enable_normalization=True,
+ instance=shipping_address,
+ )
+ if shipping_address_data != shipping_address.as_data():
+ shipping_address.save()
+
+ if not billing_address:
+ raise ValidationError(
+ {
+ "billing_address": ValidationError(
+ "Billing address is not set",
+ code=CheckoutErrorCode.BILLING_ADDRESS_NOT_SET.value,
+ )
+ }
+ )
+ billing_address_data = billing_address.as_data()
+ cls.validate_address(
+ billing_address_data,
+ address_type=AddressType.BILLING,
+ format_check=True,
+ required_check=True,
+ enable_normalization=True,
+ instance=billing_address,
+ )
+ if billing_address_data != billing_address.as_data():
+ billing_address.save()
+
@classmethod
def perform_mutation(
cls, _root, info, store_source, checkout_id=None, token=None, id=None, **data
@@ -165,6 +235,10 @@ class CheckoutComplete(BaseMutation):
checkout, lines, info.context.discounts, manager
)
+ cls.validate_checkout_addresses(
+ lines, checkout_info.shipping_address, checkout_info.billing_address
+ )
+
requestor = get_user_or_app_from_context(info.context)
if requestor.has_perm(AccountPermissions.IMPERSONATE_USER):
# Allow impersonating user and process a checkout by using user details
diff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.py
index e63237bef3..1872595dda 100644
--- a/saleor/graphql/checkout/mutations/checkout_create.py
+++ b/saleor/graphql/checkout/mutations/checkout_create.py
@@ -12,7 +12,12 @@ from ....warehouse.reservations import get_reservation_length, is_reservation_en
from ...account.i18n import I18nMixin
from ...account.types import AddressInput
from ...channel.utils import clean_channel
-from ...core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_FIELD, PREVIEW_FEATURE
+from ...core.descriptions import (
+ ADDED_IN_31,
+ ADDED_IN_35,
+ DEPRECATED_IN_3X_FIELD,
+ PREVIEW_FEATURE,
+)
from ...core.enums import LanguageCodeEnum
from ...core.mutations import ModelMutation
from ...core.scalars import PositiveDecimal
@@ -33,6 +38,49 @@ if TYPE_CHECKING:
from .utils import CheckoutLineData
+class CheckoutAddressValidationRules(graphene.InputObjectType):
+ check_required_fields = graphene.Boolean(
+ description=(
+ "Determines if an error should be raised when the provided address doesn't "
+ "have all the required fields. The list of required fields is dynamic and "
+ "depends on the country code (use the `addressValidationRules` query to "
+ "fetch them). Note: country code is mandatory for all addresses regardless "
+ "of the rules provided in this input."
+ ),
+ default_value=True,
+ )
+ check_fields_format = graphene.Boolean(
+ description=(
+ "Determines if an error should be raised when the provided address doesn't "
+ "match the expected format. Example: using letters for postal code when "
+ "the numbers are expected."
+ ),
+ default_value=True,
+ )
+ enable_fields_normalization = graphene.Boolean(
+ description=(
+ "Determines if Saleor should apply normalization on address fields. "
+ "Example: converting city field to uppercase letters."
+ ),
+ default_value=True,
+ )
+
+
+class CheckoutValidationRules(graphene.InputObjectType):
+ shipping_address = CheckoutAddressValidationRules(
+ description=(
+ "The validation rules that can be applied to provided shipping address"
+ " data."
+ )
+ )
+ billing_address = CheckoutAddressValidationRules(
+ description=(
+ "The validation rules that can be applied to provided billing address"
+ " data."
+ )
+ )
+
+
class CheckoutLineInput(graphene.InputObjectType):
quantity = graphene.Int(required=True, description="The number of items purchased.")
variant_id = graphene.ID(required=True, description="ID of the product variant.")
@@ -72,6 +120,14 @@ class CheckoutCreateInput(graphene.InputObjectType):
language_code = graphene.Argument(
LanguageCodeEnum, required=False, description="Checkout language code."
)
+ validation_rules = CheckoutValidationRules(
+ required=False,
+ description=(
+ "The checkout validation rules that can be changed."
+ + ADDED_IN_35
+ + PREVIEW_FEATURE
+ ),
+ )
class CheckoutCreate(ModelMutation, I18nMixin):
@@ -134,17 +190,39 @@ class CheckoutCreate(ModelMutation, I18nMixin):
@classmethod
def retrieve_shipping_address(cls, user, data: dict) -> Optional["Address"]:
+ address_validation_rules = data.get("validation_rules", {}).get(
+ "shipping_address", {}
+ )
if data.get("shipping_address") is not None:
return cls.validate_address(
- data["shipping_address"], address_type=AddressType.SHIPPING
+ data["shipping_address"],
+ address_type=AddressType.SHIPPING,
+ format_check=address_validation_rules.get("check_fields_format", True),
+ required_check=address_validation_rules.get(
+ "check_required_fields", True
+ ),
+ enable_normalization=address_validation_rules.get(
+ "enable_fields_normalization", True
+ ),
)
return None
@classmethod
def retrieve_billing_address(cls, user, data: dict) -> Optional["Address"]:
+ address_validation_rules = data.get("validation_rules", {}).get(
+ "billing_address", {}
+ )
if data.get("billing_address") is not None:
return cls.validate_address(
- data["billing_address"], address_type=AddressType.BILLING
+ data["billing_address"],
+ address_type=AddressType.BILLING,
+ format_check=address_validation_rules.get("check_fields_format", True),
+ required_check=address_validation_rules.get(
+ "check_required_fields", True
+ ),
+ enable_normalization=address_validation_rules.get(
+ "enable_fields_normalization", True
+ ),
)
return None
diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
index 2e0c168034..143deb11db 100644
--- a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
@@ -20,11 +20,17 @@ from ....product import models as product_models
from ....warehouse.reservations import is_reservation_enabled
from ...account.i18n import I18nMixin
from ...account.types import AddressInput
-from ...core.descriptions import ADDED_IN_34, DEPRECATED_IN_3X_INPUT
+from ...core.descriptions import (
+ ADDED_IN_34,
+ ADDED_IN_35,
+ DEPRECATED_IN_3X_INPUT,
+ PREVIEW_FEATURE,
+)
from ...core.mutations import BaseMutation
from ...core.scalars import UUID
from ...core.types import CheckoutError
from ..types import Checkout
+from .checkout_create import CheckoutAddressValidationRules
from .utils import (
ERROR_DOES_NOT_SHIP,
check_lines_quantity,
@@ -55,6 +61,14 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
required=True,
description="The mailing address to where the checkout will be shipped.",
)
+ validation_rules = CheckoutAddressValidationRules(
+ required=False,
+ description=(
+ "The rules for changing validation for received shipping address data."
+ + ADDED_IN_35
+ + PREVIEW_FEATURE
+ ),
+ )
class Meta:
description = "Update shipping address in the existing checkout."
@@ -91,7 +105,14 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
@classmethod
def perform_mutation(
- cls, _root, info, shipping_address, checkout_id=None, token=None, id=None
+ cls,
+ _root,
+ info,
+ shipping_address,
+ validation_rules=None,
+ checkout_id=None,
+ token=None,
+ id=None,
):
checkout = get_checkout(
cls,
@@ -115,12 +136,17 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
)
}
)
-
- shipping_address = cls.validate_address(
+ address_validation_rules = validation_rules or {}
+ shipping_address_instance = cls.validate_address(
shipping_address,
address_type=AddressType.SHIPPING,
instance=checkout.shipping_address,
info=info,
+ format_check=address_validation_rules.get("check_fields_format", True),
+ required_check=address_validation_rules.get("check_required_fields", True),
+ enable_normalization=address_validation_rules.get(
+ "enable_fields_normalization", True
+ ),
)
discounts = info.context.discounts
@@ -130,7 +156,7 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
checkout, lines, discounts, manager, shipping_channel_listings
)
- country = shipping_address.country.code
+ country = shipping_address_instance.country.code
checkout.set_country(country, commit=True)
# Resolve and process the lines, validating variants quantities
@@ -140,10 +166,10 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
update_checkout_shipping_method_if_invalid(checkout_info, lines)
with traced_atomic_transaction():
- shipping_address.save()
+ shipping_address_instance.save()
change_shipping_address_in_checkout(
checkout_info,
- shipping_address,
+ shipping_address_instance,
lines,
discounts,
manager,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py
index 92c8293ea9..030a7a7eff 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py
@@ -1,13 +1,20 @@
+import pytest
+
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE = """
mutation checkoutBillingAddressUpdate(
- $checkoutId: ID, $id: ID, $billingAddress: AddressInput!) {
+ $checkoutId: ID,
+ $id: ID,
+ $billingAddress: AddressInput!
+ $validationRules: CheckoutAddressValidationRules
+ ) {
checkoutBillingAddressUpdate(
id: $id,
checkoutId: $checkoutId,
billingAddress: $billingAddress
+ validationRules: $validationRules
){
checkout {
token,
@@ -179,3 +186,328 @@ def test_checkout_billing_address_update(
assert checkout.billing_address.country == billing_address["country"]
assert checkout.billing_address.city == billing_address["city"].upper()
assert checkout.last_change != previous_last_change
+
+
+ "address_data",
+ [
+ {"country": "PL"}, # missing postalCode, streetAddress
+ {"country": "PL", "postalCode": "53-601"}, # missing streetAddress
+ {"country": "US"},
+ {
+ "country": "US",
+ "city": "New York",
+ }, # missing postalCode, streetAddress, countryArea
+ ],
+)
+def test_checkout_billing_address_update_with_skip_required_doesnt_raise_error(
+ address_data, checkout_with_items, user_api_client
+):
+ # given
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "billingAddress": address_data,
+ "validationRules": {"checkRequiredFields": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutBillingAddressUpdate"]
+ assert not data["errors"]
+ assert checkout_with_items.billing_address
+
+
+def test_checkout_billing_address_update_with_skip_required_raises_validation_error(
+ checkout_with_items, user_api_client
+):
+ # given
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "billingAddress": {"country": "US", "postalCode": "XX-123"},
+ "validationRules": {"checkRequiredFields": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutBillingAddressUpdate"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == "INVALID"
+ assert data["errors"][0]["field"] == "postalCode"
+ assert not checkout_with_items.billing_address
+
+
+def test_checkout_billing_address_update_with_skip_required_saves_address(
+ checkout_with_items, user_api_client
+):
+ # given
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "billingAddress": {"country": "PL", "postalCode": "53-601"},
+ "validationRules": {"checkRequiredFields": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutBillingAddressUpdate"]
+ assert not data["errors"]
+
+ assert checkout_with_items.billing_address
+ assert checkout_with_items.billing_address.country.code == "PL"
+ assert checkout_with_items.billing_address.postal_code == "53-601"
+
+
+ "address_data",
+ [
+ {
+ "country": "PL",
+ "city": "Wroclaw",
+ "postalCode": "XYZ",
+ "streetAddress1": "Teczowa 7",
+ }, # incorrect postalCode
+ {
+ "country": "US",
+ "city": "New York",
+ "countryArea": "ABC",
+ "streetAddress1": "New street",
+ "postalCode": "53-601",
+ }, # incorrect postalCode
+ ],
+)
+def test_checkout_billing_address_update_with_skip_value_check_doesnt_raise_error(
+ address_data, checkout_with_items, user_api_client
+):
+ # given
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "billingAddress": address_data,
+ "validationRules": {"checkFieldsFormat": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutBillingAddressUpdate"]
+ assert not data["errors"]
+ assert checkout_with_items.billing_address
+
+
+ "address_data",
+ [
+ {
+ "country": "PL",
+ "city": "Wroclaw",
+ "postalCode": "XYZ",
+ }, # incorrect postalCode
+ {
+ "country": "US",
+ "city": "New York",
+ "countryArea": "XYZ",
+ "postalCode": "XYZ",
+ }, # incorrect postalCode
+ ],
+)
+def test_checkout_billing_address_update_with_skip_value_raises_required_fields_error(
+ address_data, checkout_with_items, user_api_client
+):
+ # given
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "billingAddress": address_data,
+ "validationRules": {"checkFieldsFormat": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutBillingAddressUpdate"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == "REQUIRED"
+ assert data["errors"][0]["field"] == "streetAddress1"
+ assert not checkout_with_items.billing_address
+
+
+def test_checkout_billing_address_update_with_skip_value_check_saves_address(
+ checkout_with_items, user_api_client
+):
+ # given
+ city = "Wroclaw"
+ street_address = "Teczowa 7"
+ postal_code = "XX-601" # incorrect format for PL
+ country_code = "PL"
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "billingAddress": {
+ "country": country_code,
+ "city": city,
+ "streetAddress1": street_address,
+ "postalCode": postal_code,
+ },
+ "validationRules": {"checkFieldsFormat": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutBillingAddressUpdate"]
+ assert not data["errors"]
+
+ address = checkout_with_items.billing_address
+ assert address
+
+ assert address.street_address_1 == street_address
+ assert address.city == city
+ assert address.country.code == country_code
+ assert address.postal_code == postal_code
+
+
+ "address_data",
+ [
+ {
+ "country": "PL",
+ "postalCode": "XYZ",
+ }, # incorrect postalCode, missing city, streetAddress
+ {
+ "country": "US",
+ "countryArea": "DC",
+ "postalCode": "XYZ",
+ }, # incorrect postalCode, missing city
+ ],
+)
+def test_checkout_billing_address_update_with_skip_value_and_skip_required_fields(
+ address_data, checkout_with_items, user_api_client
+):
+ # given
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "billingAddress": address_data,
+ "validationRules": {"checkFieldsFormat": False, "checkRequiredFields": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutBillingAddressUpdate"]
+ assert not data["errors"]
+ assert checkout_with_items.billing_address
+
+
+def test_checkout_address_update_with_skip_value_and_skip_required_saves_address(
+ checkout_with_items, user_api_client
+):
+ # given
+ city = "Wroclaw"
+ postal_code = "XX-601" # incorrect format for PL
+ country_code = "PL"
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "billingAddress": {
+ "country": country_code,
+ "city": city,
+ "postalCode": postal_code,
+ },
+ "validationRules": {"checkFieldsFormat": False, "checkRequiredFields": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutBillingAddressUpdate"]
+ address = checkout_with_items.billing_address
+ assert not data["errors"]
+
+ assert address
+ assert address.country.code == country_code
+ assert address.postal_code == postal_code
+ assert address.city == city
+ assert address.street_address_1 == ""
+
+
+def test_checkout_billing_address_update_with_disabled_fields_normalization(
+ checkout_with_items, user_api_client
+):
+ # given
+ address_data = {
+ "country": "US",
+ "city": "Washington",
+ "countryArea": "District of Columbia",
+ "streetAddress1": "1600 Pennsylvania Avenue NW",
+ "postalCode": "20500",
+ }
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "billingAddress": address_data,
+ "validationRules": {"enableFieldsNormalization": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutBillingAddressUpdate"]
+ assert not data["errors"]
+ assert checkout_with_items
+ billing_address = checkout_with_items.billing_address
+ assert billing_address
+ assert billing_address.city == address_data["city"]
+ assert billing_address.country_area == address_data["countryArea"]
+ assert billing_address.postal_code == address_data["postalCode"]
+ assert billing_address.street_address_1 == address_data["streetAddress1"]
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
index 198d822c2e..9b0940a6a8 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
@@ -10,6 +10,7 @@ from django.db.models.aggregates import Sum
from django.utils import timezone
from prices import Money
+from .....account.models import Address
from .....checkout import calculations
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
@@ -2589,3 +2590,368 @@ def test_checkout_complete_0_total_value_from_giftcard(
assert not Checkout.objects.filter(
pk=checkout.pk
).exists(), "Checkout should have been deleted"
+
+
+def test_checkout_complete_error_when_shipping_address_doesnt_have_all_required_fields(
+ user_api_client,
+ checkout_with_item,
+ gift_card,
+ payment_dummy_credit_card,
+ address,
+ shipping_method,
+):
+ # given
+ shipping_address = Address.objects.create(
+ first_name="John",
+ last_name="Doe",
+ company_name="Mirumee Software",
+ street_address_1="Tęczowa 7",
+ city="WROCŁAW",
+ country="PL",
+ phone="+48713988102",
+ ) # missing postalCode
+
+ checkout = checkout_with_item
+ checkout.shipping_address = shipping_address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+ payment = payment_dummy_credit_card
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.token = "123"
+ payment.save()
+ assert not payment.transactions.exists()
+
+ orders_count = Order.objects.count()
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "redirectUrl": "https://www.example.com",
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert len(data["errors"]) == 1
+
+ assert data["errors"][0]["code"] == "REQUIRED"
+ assert data["errors"][0]["field"] == "postalCode"
+ assert Order.objects.count() == orders_count
+
+
+def test_checkout_complete_error_when_shipping_address_doesnt_have_all_valid_fields(
+ user_api_client,
+ checkout_with_item,
+ gift_card,
+ payment_dummy_credit_card,
+ address,
+ shipping_method,
+):
+ # given
+ shipping_address = Address.objects.create(
+ first_name="John",
+ last_name="Doe",
+ company_name="Mirumee Software",
+ street_address_1="Tęczowa 7",
+ city="WROCŁAW",
+ country="PL",
+ phone="+48713988102",
+ postal_code="XX-ABC",
+ ) # incorrect postalCode
+
+ checkout = checkout_with_item
+ checkout.shipping_address = shipping_address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+ payment = payment_dummy_credit_card
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.token = "123"
+ payment.save()
+ assert not payment.transactions.exists()
+
+ orders_count = Order.objects.count()
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "redirectUrl": "https://www.example.com",
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert len(data["errors"]) == 1
+
+ assert data["errors"][0]["code"] == "INVALID"
+ assert data["errors"][0]["field"] == "postalCode"
+ assert Order.objects.count() == orders_count
+
+
+def test_checkout_complete_error_when_billing_address_doesnt_have_all_required_fields(
+ user_api_client,
+ checkout_with_item,
+ gift_card,
+ payment_dummy_credit_card,
+ address,
+ shipping_method,
+):
+ # given
+ billing_address = Address.objects.create(
+ first_name="John",
+ last_name="Doe",
+ company_name="Mirumee Software",
+ street_address_1="Tęczowa 7",
+ city="WROCŁAW",
+ country="PL",
+ phone="+48713988102",
+ ) # missing postalCode
+
+ checkout = checkout_with_item
+ checkout.billing_address = billing_address
+ checkout.shipping_method = shipping_method
+ checkout.shipping_address = address
+ checkout.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+ payment = payment_dummy_credit_card
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.token = "123"
+ payment.save()
+ assert not payment.transactions.exists()
+
+ orders_count = Order.objects.count()
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "redirectUrl": "https://www.example.com",
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == "REQUIRED"
+ assert data["errors"][0]["field"] == "postalCode"
+ assert Order.objects.count() == orders_count
+
+
+def test_checkout_complete_error_when_billing_address_doesnt_have_all_valid_fields(
+ user_api_client,
+ checkout_with_item,
+ gift_card,
+ payment_dummy_credit_card,
+ address,
+ shipping_method,
+):
+ # given
+ billing_address = Address.objects.create(
+ first_name="John",
+ last_name="Doe",
+ company_name="Mirumee Software",
+ street_address_1="Tęczowa 7",
+ city="WROCŁAW",
+ country="PL",
+ phone="+48713988102",
+ postal_code="XX-ABC",
+ ) # incorrect postalCode
+
+ checkout = checkout_with_item
+ checkout.billing_address = billing_address
+ checkout.shipping_method = shipping_method
+ checkout.shipping_address = address
+ checkout.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+ payment = payment_dummy_credit_card
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.token = "123"
+ payment.save()
+ assert not payment.transactions.exists()
+
+ orders_count = Order.objects.count()
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "redirectUrl": "https://www.example.com",
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert len(data["errors"]) == 1
+
+ assert data["errors"][0]["code"] == "INVALID"
+ assert data["errors"][0]["field"] == "postalCode"
+ assert Order.objects.count() == orders_count
+
+
+def test_checkout_complete_with_not_normalized_shipping_address(
+ site_settings,
+ user_api_client,
+ checkout_with_gift_card,
+ gift_card,
+ payment_dummy,
+ address,
+ shipping_method,
+):
+ # given
+ assert not gift_card.last_used_on
+
+ checkout = checkout_with_gift_card
+ shipping_address = Address.objects.create(
+ **{
+ "country": "US",
+ "city": "Washington",
+ "country_area": "District of Columbia",
+ "street_address_1": "1600 Pennsylvania Avenue NW",
+ "postal_code": "20500",
+ }
+ )
+ checkout.shipping_address = shipping_address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+ payment = payment_dummy
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.save()
+ assert not payment.transactions.exists()
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+
+ order = Order.objects.first()
+ shipping_address = order.shipping_address
+ assert shipping_address
+ assert shipping_address.city == "WASHINGTON"
+ assert shipping_address.country_area == "DC"
+
+
+def test_checkout_complete_with_not_normalized_billing_address(
+ site_settings,
+ user_api_client,
+ checkout_with_gift_card,
+ gift_card,
+ payment_dummy,
+ address,
+ shipping_method,
+):
+ # given
+ assert not gift_card.last_used_on
+
+ checkout = checkout_with_gift_card
+ billing_address = Address.objects.create(
+ **{
+ "country": "US",
+ "city": "Washington",
+ "country_area": "District of Columbia",
+ "street_address_1": "1600 Pennsylvania Avenue NW",
+ "postal_code": "20500",
+ }
+ )
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = billing_address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+ payment = payment_dummy
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.save()
+ assert not payment.transactions.exists()
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+
+ order = Order.objects.first()
+ billing_address = order.billing_address
+ assert billing_address
+ assert billing_address.city == "WASHINGTON"
+ assert billing_address.country_area == "DC"
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
index 6dc90ce14b..6beca54709 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
@@ -1586,6 +1586,598 @@ def test_create_checkout_with_unpublished_product(
assert error["code"] == CheckoutErrorCode.PRODUCT_NOT_PUBLISHED.name
+ "address_data, address_input_name, address_db_field_name",
+ [
+ (
+ {"country": "PL"}, # missing postalCode, streetAddress
+ "shippingAddress",
+ "shipping_address",
+ ),
+ (
+ {"country": "PL", "postalCode": "53-601"}, # missing streetAddress
+ "shippingAddress",
+ "shipping_address",
+ ),
+ ({"country": "US"}, "shippingAddress", "shipping_address"),
+ (
+ {
+ "country": "US",
+ "city": "New York",
+ }, # missing postalCode, streetAddress, countryArea
+ "shippingAddress",
+ "shipping_address",
+ ),
+ (
+ {"country": "PL"}, # missing postalCode, streetAddress
+ "billingAddress",
+ "billing_address",
+ ),
+ (
+ {"country": "PL", "postalCode": "53-601"}, # missing streetAddress
+ "billingAddress",
+ "billing_address",
+ ),
+ ({"country": "US"}, "shippingAddress", "shipping_address"),
+ (
+ {
+ "country": "US",
+ "city": "New York",
+ }, # missing postalCode, streetAddress, countryArea
+ "billingAddress",
+ "billing_address",
+ ),
+ ],
+)
+def test_checkout_create_with_skip_required_doesnt_raise_error(
+ address_data,
+ address_input_name,
+ address_db_field_name,
+ api_client,
+ stock,
+ channel_USD,
+):
+ # given
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": "[email protected]",
+ address_input_name: address_data,
+ "validationRules": {address_input_name: {"checkRequiredFields": False}},
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutCreate"]
+ created_checkout = Checkout.objects.first()
+
+ assert not data["errors"]
+ assert created_checkout
+ assert getattr(created_checkout, address_db_field_name)
+
+
+ "address_input_name",
+ ["shippingAddress", "billingAddress"],
+)
+def test_checkout_create_with_skip_required_raises_validation_error(
+ address_input_name, api_client, stock, channel_USD
+):
+ # given
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": "[email protected]",
+ address_input_name: {"country": "US", "postalCode": "XX-123"},
+ "validationRules": {address_input_name: {"checkRequiredFields": False}},
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ # then
+ created_checkout = Checkout.objects.first()
+ data = get_graphql_content(response)["data"]["checkoutCreate"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == "INVALID"
+ assert data["errors"][0]["field"] == "postalCode"
+ assert created_checkout is None
+
+
+ "address_input_name, address_db_field_name",
+ [("shippingAddress", "shipping_address"), ("billingAddress", "billing_address")],
+)
+def test_checkout_create_with_skip_required_saves_address(
+ address_input_name, address_db_field_name, api_client, stock, channel_USD
+):
+ # given
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": "[email protected]",
+ address_input_name: {"country": "PL", "postalCode": "53-601"},
+ "validationRules": {address_input_name: {"checkRequiredFields": False}},
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutCreate"]
+ created_checkout = Checkout.objects.first()
+
+ assert not data["errors"]
+ assert created_checkout is not None
+ assert getattr(created_checkout, address_db_field_name)
+ assert getattr(created_checkout, address_db_field_name).country.code == "PL"
+ assert getattr(created_checkout, address_db_field_name).postal_code == "53-601"
+
+
+ "address_data, address_input_name, address_db_field_name",
+ [
+ (
+ {
+ "country": "PL",
+ "city": "Wroclaw",
+ "postalCode": "XYZ",
+ "streetAddress1": "Teczowa 7",
+ }, # incorrect postalCode
+ "shippingAddress",
+ "shipping_address",
+ ),
+ (
+ {
+ "country": "US",
+ "city": "New York",
+ "countryArea": "ABC",
+ "streetAddress1": "New street",
+ "postalCode": "53-601",
+ }, # incorrect postalCode
+ "shippingAddress",
+ "shipping_address",
+ ),
+ (
+ {
+ "country": "PL",
+ "city": "Wroclaw",
+ "postalCode": "XYZ",
+ "streetAddress1": "Teczowa 7",
+ }, # incorrect postalCode
+ "billingAddress",
+ "billing_address",
+ ),
+ (
+ {
+ "country": "US",
+ "city": "New York",
+ "countryArea": "ABC",
+ "streetAddress1": "New street",
+ "postalCode": "53-601",
+ }, # incorrect postalCode
+ "billingAddress",
+ "billing_address",
+ ),
+ ],
+)
+def test_checkout_create_with_skip_value_check_doesnt_raise_error(
+ address_data,
+ address_input_name,
+ address_db_field_name,
+ api_client,
+ stock,
+ channel_USD,
+):
+ # given
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": "[email protected]",
+ address_input_name: address_data,
+ "validationRules": {address_input_name: {"checkFieldsFormat": False}},
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutCreate"]
+ created_checkout = Checkout.objects.first()
+
+ assert not data["errors"]
+ assert created_checkout
+ assert getattr(created_checkout, address_db_field_name)
+
+
+ "address_data, address_input_name",
+ [
+ (
+ {
+ "country": "PL",
+ "city": "Wroclaw",
+ "postalCode": "XYZ",
+ }, # incorrect postalCode
+ "shippingAddress",
+ ),
+ (
+ {
+ "country": "US",
+ "city": "New York",
+ "countryArea": "XYZ",
+ "postalCode": "XYZ",
+ }, # incorrect postalCode
+ "shippingAddress",
+ ),
+ (
+ {
+ "country": "PL",
+ "city": "Wroclaw",
+ "postalCode": "XYZ",
+ }, # incorrect postalCode
+ "billingAddress",
+ ),
+ (
+ {
+ "country": "US",
+ "city": "New York",
+ "countryArea": "XYZ",
+ "postalCode": "XYZ",
+ }, # incorrect postalCode
+ "billingAddress",
+ ),
+ ],
+)
+def test_checkout_create_with_skip_value_raises_required_fields_error(
+ address_data, address_input_name, api_client, stock, channel_USD
+):
+ # given
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": "[email protected]",
+ address_input_name: address_data,
+ "validationRules": {address_input_name: {"checkFieldsFormat": False}},
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ # then
+ created_checkout = Checkout.objects.first()
+ data = get_graphql_content(response)["data"]["checkoutCreate"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == "REQUIRED"
+ assert data["errors"][0]["field"] == "streetAddress1"
+ assert created_checkout is None
+
+
+ "address_input_name, address_db_field_name",
+ [("shippingAddress", "shipping_address"), ("billingAddress", "billing_address")],
+)
+def test_checkout_create_with_skip_value_check_saves_address(
+ address_input_name, address_db_field_name, api_client, stock, channel_USD
+):
+ # given
+ city = "Wroclaw"
+ street_address = "Teczowa 7"
+ postal_code = "XX-601" # incorrect format for PL
+ country_code = "PL"
+
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": "[email protected]",
+ address_input_name: {
+ "country": country_code,
+ "city": city,
+ "streetAddress1": street_address,
+ "postalCode": postal_code,
+ },
+ "validationRules": {address_input_name: {"checkFieldsFormat": False}},
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ # then
+ created_checkout = Checkout.objects.first()
+ data = get_graphql_content(response)["data"]["checkoutCreate"]
+ assert not data["errors"]
+
+ assert created_checkout
+ assert getattr(created_checkout, address_db_field_name)
+ assert (
+ getattr(created_checkout, address_db_field_name).street_address_1
+ == street_address
+ )
+ assert getattr(created_checkout, address_db_field_name).city == city
+ assert getattr(created_checkout, address_db_field_name).postal_code == postal_code
+ assert getattr(created_checkout, address_db_field_name).country.code == country_code
+
+
+[("shippingAddress", "shipping_address"), ("billingAddress", "billing_address")],
+
+
+ "address_data, address_input_name, address_db_field_name",
+ [
+ (
+ {
+ "country": "PL",
+ "postalCode": "XYZ",
+ }, # incorrect postalCode, missing city, streetAddress
+ "shippingAddress",
+ "shipping_address",
+ ),
+ (
+ {
+ "country": "US",
+ "countryArea": "DC",
+ "postalCode": "XYZ",
+ }, # incorrect postalCode, missing city
+ "shippingAddress",
+ "shipping_address",
+ ),
+ (
+ {
+ "country": "PL",
+ "postalCode": "XYZ",
+ }, # incorrect postalCode, missing city, streetAddress
+ "billingAddress",
+ "billing_address",
+ ),
+ (
+ {
+ "country": "US",
+ "countryArea": "DC",
+ "postalCode": "XYZ",
+ }, # incorrect postalCode, missing city
+ "billingAddress",
+ "billing_address",
+ ),
+ ],
+)
+def test_checkout_create_with_skip_value_and_skip_required_fields(
+ address_data,
+ address_input_name,
+ address_db_field_name,
+ api_client,
+ stock,
+ channel_USD,
+):
+ # given
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": "[email protected]",
+ address_input_name: address_data,
+ "validationRules": {
+ address_input_name: {
+ "checkFieldsFormat": False,
+ "checkRequiredFields": False,
+ }
+ },
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ # then
+ created_checkout = Checkout.objects.first()
+ data = get_graphql_content(response)["data"]["checkoutCreate"]
+ assert not data["errors"]
+ assert getattr(created_checkout, address_db_field_name)
+
+
+ "address_input_name, address_db_field_name",
+ [("shippingAddress", "shipping_address"), ("billingAddress", "billing_address")],
+)
+def test_checkout_create_with_skip_value_and_skip_required_saves_address(
+ address_input_name, address_db_field_name, api_client, stock, channel_USD
+):
+ # given
+ city = "Wroclaw"
+ postal_code = "XX-601" # incorrect format for PL
+ country_code = "PL"
+
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": "[email protected]",
+ address_input_name: {
+ "country": country_code,
+ "city": city,
+ "postalCode": postal_code,
+ },
+ "validationRules": {
+ address_input_name: {
+ "checkFieldsFormat": False,
+ "checkRequiredFields": False,
+ }
+ },
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ # then
+ created_checkout = Checkout.objects.first()
+ data = get_graphql_content(response)["data"]["checkoutCreate"]
+ assert not data["errors"]
+
+ assert created_checkout
+ assert getattr(created_checkout, address_db_field_name)
+ assert getattr(created_checkout, address_db_field_name).country.code == country_code
+ assert getattr(created_checkout, address_db_field_name).postal_code == postal_code
+ assert getattr(created_checkout, address_db_field_name).city == city
+ assert getattr(created_checkout, address_db_field_name).street_address_1 == ""
+
+
+def test_checkout_create_with_shipping_address_disabled_fields_normalization(
+ api_client, stock, channel_USD
+):
+ # given
+ address_data = {
+ "country": "US",
+ "city": "Washington",
+ "countryArea": "District of Columbia",
+ "streetAddress1": "1600 Pennsylvania Avenue NW",
+ "postalCode": "20500",
+ }
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": "[email protected]",
+ "shippingAddress": address_data,
+ "validationRules": {
+ "shippingAddress": {"enableFieldsNormalization": False}
+ },
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutCreate"]
+ assert not data["errors"]
+ created_checkout = Checkout.objects.first()
+ assert created_checkout
+ shipping_address = created_checkout.shipping_address
+ assert shipping_address
+ assert shipping_address.city == address_data["city"]
+ assert shipping_address.country_area == address_data["countryArea"]
+ assert shipping_address.postal_code == address_data["postalCode"]
+ assert shipping_address.street_address_1 == address_data["streetAddress1"]
+
+
+def test_checkout_create_with_billing_address_disabled_fields_normalization(
+ api_client, stock, channel_USD
+):
+ # given
+ address_data = {
+ "country": "US",
+ "city": "Washington",
+ "countryArea": "District of Columbia",
+ "streetAddress1": "1600 Pennsylvania Avenue NW",
+ "postalCode": "20500",
+ }
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": "[email protected]",
+ "billingAddress": address_data,
+ "validationRules": {"billingAddress": {"enableFieldsNormalization": False}},
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutCreate"]
+ assert not data["errors"]
+ created_checkout = Checkout.objects.first()
+ assert created_checkout
+ billing_address = created_checkout.billing_address
+ assert billing_address
+ assert billing_address.city == address_data["city"]
+ assert billing_address.country_area == address_data["countryArea"]
+ assert billing_address.postal_code == address_data["postalCode"]
+ assert billing_address.street_address_1 == address_data["streetAddress1"]
+
+
+def test_checkout_create_with_disabled_fields_normalization_raises_required_error(
+ api_client, stock, channel_USD
+):
+ # given
+ address_data = {
+ "city": "Wroclaw",
+ "country": "PL",
+ "firstName": "John",
+ "lastName": "Doe",
+ "phone": "+12125094995",
+ "streetAddress1": "Teczowa 7",
+ }
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": "[email protected]",
+ "shippingAddress": address_data,
+ "validationRules": {
+ "shippingAddress": {"enableFieldsNormalization": False}
+ },
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutCreate"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "postalCode"
+ assert data["errors"][0]["code"] == "REQUIRED"
+
+
@pytest.mark.parametrize("with_shipping_address", (True, False))
def test_create_checkout_with_digital(
api_client,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
index 7332bf585f..ccb174db6c 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
@@ -4,6 +4,7 @@ from unittest.mock import patch
import graphene
import pytest
+from .....account.models import Address
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID
@@ -356,3 +357,147 @@ def test_checkout_delivery_method_update_shipping_zone_with_channel(
assert not errors
assert checkout.shipping_method == shipping_method
+
+
[email protected]("is_valid_delivery_method", (True, False))
+ "delivery_method, node_name, attribute_name",
+ [
+ ("warehouse", "Warehouse", "collection_point"),
+ ("shipping_method", "ShippingMethod", "shipping_method"),
+ ],
+ indirect=("delivery_method",),
+)
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
+ "clean_delivery_method"
+)
+def test_checkout_delivery_method_update_with_not_all_required_shipping_address_data(
+ mock_clean_delivery,
+ api_client,
+ delivery_method,
+ node_name,
+ attribute_name,
+ checkout_with_item_for_cc,
+ is_valid_delivery_method,
+):
+ # given
+ mock_clean_delivery.return_value = is_valid_delivery_method
+
+ checkout = checkout_with_item_for_cc
+ checkout.shipping_address = Address.objects.create(country="US")
+ checkout.save()
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ shipping_method_data = delivery_method
+ if attribute_name == "shipping_method":
+ shipping_method_data = convert_to_shipping_method_data(
+ delivery_method,
+ delivery_method.channel_listings.get(),
+ )
+ query = MUTATION_UPDATE_DELIVERY_METHOD
+ mock_clean_delivery.return_value = is_valid_delivery_method
+
+ method_id = graphene.Node.to_global_id(node_name, delivery_method.id)
+
+ # when
+ response = api_client.post_graphql(
+ query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ checkout.refresh_from_db()
+
+ mock_clean_delivery.assert_called_once_with(
+ checkout_info=checkout_info, lines=lines, method=shipping_method_data
+ )
+ errors = data["errors"]
+ if is_valid_delivery_method:
+ assert not errors
+ assert getattr(checkout, attribute_name) == delivery_method
+ else:
+ assert len(errors) == 1
+ assert errors[0]["field"] == "deliveryMethodId"
+ assert (
+ errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
+ )
+ assert checkout.shipping_method is None
+ assert checkout.collection_point is None
+
+
[email protected]("is_valid_delivery_method", (True, False))
+ "delivery_method, node_name, attribute_name",
+ [
+ ("warehouse", "Warehouse", "collection_point"),
+ ("shipping_method", "ShippingMethod", "shipping_method"),
+ ],
+ indirect=("delivery_method",),
+)
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
+ "clean_delivery_method"
+)
+def test_checkout_delivery_method_update_with_not_valid_address_data(
+ mock_clean_delivery,
+ api_client,
+ delivery_method,
+ node_name,
+ attribute_name,
+ checkout_with_item_for_cc,
+ is_valid_delivery_method,
+):
+ # given
+ mock_clean_delivery.return_value = is_valid_delivery_method
+
+ checkout = checkout_with_item_for_cc
+ checkout.shipping_address = Address.objects.create(
+ country="US",
+ city="New York",
+ city_area="ABC",
+ street_address_1="New street",
+ postal_code="53-601",
+ )
+ checkout.save()
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ shipping_method_data = delivery_method
+ if attribute_name == "shipping_method":
+ shipping_method_data = convert_to_shipping_method_data(
+ delivery_method,
+ delivery_method.channel_listings.get(),
+ )
+ query = MUTATION_UPDATE_DELIVERY_METHOD
+ mock_clean_delivery.return_value = is_valid_delivery_method
+
+ method_id = graphene.Node.to_global_id(node_name, delivery_method.id)
+
+ # when
+ response = api_client.post_graphql(
+ query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ checkout.refresh_from_db()
+
+ mock_clean_delivery.assert_called_once_with(
+ checkout_info=checkout_info, lines=lines, method=shipping_method_data
+ )
+ errors = data["errors"]
+ if is_valid_delivery_method:
+ assert not errors
+ assert getattr(checkout, attribute_name) == delivery_method
+ else:
+ assert len(errors) == 1
+ assert errors[0]["field"] == "deliveryMethodId"
+ assert (
+ errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
+ )
+ assert checkout.shipping_method is None
+ assert checkout.collection_point is None
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py
index 42bfd934fa..7df3fcca0b 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py
@@ -20,10 +20,12 @@ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE = """
mutation checkoutShippingAddressUpdate(
$id: ID,
$shippingAddress: AddressInput!,
+ $validationRules: CheckoutAddressValidationRules
) {
checkoutShippingAddressUpdate(
id: $id,
shippingAddress: $shippingAddress,
+ validationRules: $validationRules
) {
checkout {
token
@@ -429,6 +431,331 @@ def test_checkout_shipping_address_update_exclude_shipping_method(
assert checkout.shipping_method is None
+ "address_data",
+ [
+ {"country": "PL"}, # missing postalCode, streetAddress
+ {"country": "PL", "postalCode": "53-601"}, # missing streetAddress
+ {"country": "US"},
+ {
+ "country": "US",
+ "city": "New York",
+ }, # missing postalCode, streetAddress, countryArea
+ ],
+)
+def test_checkout_shipping_address_update_with_skip_required_doesnt_raise_error(
+ address_data, checkout_with_items, user_api_client
+):
+ # given
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "shippingAddress": address_data,
+ "validationRules": {"checkRequiredFields": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutShippingAddressUpdate"]
+ assert not data["errors"]
+ assert checkout_with_items.shipping_address
+
+
+def test_checkout_shipping_address_update_with_skip_required_raises_validation_error(
+ checkout_with_items, user_api_client
+):
+ # given
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "shippingAddress": {"country": "US", "postalCode": "XX-123"},
+ "validationRules": {"checkRequiredFields": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutShippingAddressUpdate"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == "INVALID"
+ assert data["errors"][0]["field"] == "postalCode"
+ assert not checkout_with_items.shipping_address
+
+
+def test_checkout_shipping_address_update_with_skip_required_saves_address(
+ checkout_with_items, user_api_client
+):
+ # given
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "shippingAddress": {"country": "PL", "postalCode": "53-601"},
+ "validationRules": {"checkRequiredFields": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutShippingAddressUpdate"]
+ assert not data["errors"]
+
+ assert checkout_with_items.shipping_address
+ assert checkout_with_items.shipping_address.country.code == "PL"
+ assert checkout_with_items.shipping_address.postal_code == "53-601"
+
+
+ "address_data",
+ [
+ {
+ "country": "PL",
+ "city": "Wroclaw",
+ "postalCode": "XYZ",
+ "streetAddress1": "Teczowa 7",
+ }, # incorrect postalCode
+ {
+ "country": "US",
+ "city": "New York",
+ "countryArea": "ABC",
+ "streetAddress1": "New street",
+ "postalCode": "53-601",
+ }, # incorrect postalCode
+ ],
+)
+def test_checkout_shipping_address_update_with_skip_value_check_doesnt_raise_error(
+ address_data, checkout_with_items, user_api_client
+):
+ # given
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "shippingAddress": address_data,
+ "validationRules": {"checkFieldsFormat": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutShippingAddressUpdate"]
+ assert not data["errors"]
+ assert checkout_with_items.shipping_address
+
+
+ "address_data",
+ [
+ {
+ "country": "PL",
+ "city": "Wroclaw",
+ "postalCode": "XYZ",
+ }, # incorrect postalCode
+ {
+ "country": "US",
+ "city": "New York",
+ "countryArea": "XYZ",
+ "postalCode": "XYZ",
+ }, # incorrect postalCode
+ ],
+)
+def test_checkout_shipping_address_update_with_skip_value_raises_required_fields_error(
+ address_data, checkout_with_items, user_api_client
+):
+ # given
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "shippingAddress": address_data,
+ "validationRules": {"checkFieldsFormat": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutShippingAddressUpdate"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == "REQUIRED"
+ assert data["errors"][0]["field"] == "streetAddress1"
+ assert not checkout_with_items.shipping_address
+
+
+def test_checkout_shipping_address_update_with_skip_value_check_saves_address(
+ checkout_with_items, user_api_client
+):
+ # given
+ city = "Wroclaw"
+ street_address = "Teczowa 7"
+ postal_code = "XX-601" # incorrect format for PL
+ country_code = "PL"
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "shippingAddress": {
+ "country": country_code,
+ "city": city,
+ "streetAddress1": street_address,
+ "postalCode": postal_code,
+ },
+ "validationRules": {"checkFieldsFormat": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutShippingAddressUpdate"]
+ assert not data["errors"]
+
+ address = checkout_with_items.shipping_address
+ assert address
+
+ assert address.street_address_1 == street_address
+ assert address.city == city
+ assert address.country.code == country_code
+ assert address.postal_code == postal_code
+
+
+ "address_data",
+ [
+ {
+ "country": "PL",
+ "postalCode": "XYZ",
+ }, # incorrect postalCode, missing city, streetAddress
+ {
+ "country": "US",
+ "countryArea": "DC",
+ "postalCode": "XYZ",
+ }, # incorrect postalCode, missing city
+ ],
+)
+def test_checkout_shipping_address_update_with_skip_value_and_skip_required_fields(
+ address_data, checkout_with_items, user_api_client
+):
+ # given
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "shippingAddress": address_data,
+ "validationRules": {"checkFieldsFormat": False, "checkRequiredFields": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutShippingAddressUpdate"]
+ assert not data["errors"]
+ assert checkout_with_items.shipping_address
+
+
+def test_checkout_address_update_with_skip_value_and_skip_required_saves_address(
+ checkout_with_items, user_api_client
+):
+ # given
+ city = "Wroclaw"
+ postal_code = "XX-601" # incorrect format for PL
+ country_code = "PL"
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "shippingAddress": {
+ "country": country_code,
+ "city": city,
+ "postalCode": postal_code,
+ },
+ "validationRules": {"checkFieldsFormat": False, "checkRequiredFields": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutShippingAddressUpdate"]
+ address = checkout_with_items.shipping_address
+ assert not data["errors"]
+
+ assert address
+ assert address.country.code == country_code
+ assert address.postal_code == postal_code
+ assert address.city == city
+ assert address.street_address_1 == ""
+
+
+def test_checkout_shipping_address_update_with_disabled_fields_normalization(
+ checkout_with_items, user_api_client
+):
+ # given
+ address_data = {
+ "country": "US",
+ "city": "Washington",
+ "countryArea": "District of Columbia",
+ "streetAddress1": "1600 Pennsylvania Avenue NW",
+ "postalCode": "20500",
+ }
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "shippingAddress": address_data,
+ "validationRules": {"enableFieldsNormalization": False},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutShippingAddressUpdate"]
+ assert not data["errors"]
+ assert checkout_with_items
+ shipping_address = checkout_with_items.shipping_address
+ assert shipping_address
+ assert shipping_address.city == address_data["city"]
+ assert shipping_address.country_area == address_data["countryArea"]
+ assert shipping_address.postal_code == address_data["postalCode"]
+ assert shipping_address.street_address_1 == address_data["streetAddress1"]
+
+
def test_checkout_update_shipping_address_with_digital(
api_client, checkout_with_digital_item, graphql_address_data
):
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
index 00923b50e7..328445372c 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
@@ -4,6 +4,7 @@ from unittest.mock import patch
import graphene
import pytest
+from .....account.models import Address
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import (
fetch_checkout_info,
@@ -266,6 +267,70 @@ def test_checkout_shipping_method_update_excluded_postal_code(
)
+def test_checkout_shipping_method_update_with_not_all_required_shipping_address_data(
+ staff_api_client,
+ shipping_method,
+ checkout_with_item,
+):
+ # given
+ checkout = checkout_with_item
+ checkout.shipping_address = Address.objects.create(country="US")
+ checkout.save(update_fields=["shipping_address"])
+ query = MUTATION_UPDATE_SHIPPING_METHOD
+
+ shipping_method.postal_code_rules.create(start="00123", end="12345")
+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
+
+ checkout.refresh_from_db()
+
+ assert not data["errors"]
+ assert checkout.shipping_method == shipping_method
+
+
+def test_checkout_shipping_method_update_with_not_valid_shipping_address_data(
+ staff_api_client,
+ shipping_method,
+ checkout_with_item,
+):
+ # given
+ checkout = checkout_with_item
+ checkout.shipping_address = Address.objects.create(
+ country="US",
+ city="New York",
+ city_area="ABC",
+ street_address_1="New street",
+ postal_code="53-601",
+ ) # incorrect postalCode
+ checkout.save(update_fields=["shipping_address"])
+ query = MUTATION_UPDATE_SHIPPING_METHOD
+
+ shipping_method.postal_code_rules.create(start="00123", end="12345")
+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
+
+ checkout.refresh_from_db()
+
+ assert not data["errors"]
+ assert checkout.shipping_method == shipping_method
+
+
def test_checkout_delivery_method_update_unavailable_variant(
staff_api_client,
shipping_method,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index ca86af9f96..b00674ff74 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -12819,6 +12819,15 @@ type Mutation {
DEPRECATED: this field will be removed in Saleor 4.0. Use `id` instead.
"""
token: UUID
+
+ """
+ The rules for changing validation for received billing address data.
+
+ Added in Saleor 3.5.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ validationRules: CheckoutAddressValidationRules
): CheckoutBillingAddressUpdate
"""
@@ -13145,6 +13154,15 @@ type Mutation {
DEPRECATED: this field will be removed in Saleor 4.0. Use `id` instead.
"""
token: UUID
+
+ """
+ The rules for changing validation for received shipping address data.
+
+ Added in Saleor 3.5.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ validationRules: CheckoutAddressValidationRules
): CheckoutShippingAddressUpdate
"""Updates the shipping method of the checkout."""
@@ -19064,6 +19082,23 @@ type CheckoutBillingAddressUpdate {
errors: [CheckoutError!]!
}
+input CheckoutAddressValidationRules {
+ """
+ Determines if an error should be raised when the provided address doesn't have all the required fields. The list of required fields is dynamic and depends on the country code (use the `addressValidationRules` query to fetch them). Note: country code is mandatory for all addresses regardless of the rules provided in this input.
+ """
+ checkRequiredFields: Boolean = true
+
+ """
+ Determines if an error should be raised when the provided address doesn't match the expected format. Example: using letters for postal code when the numbers are expected.
+ """
+ checkFieldsFormat: Boolean = true
+
+ """
+ Determines if Saleor should apply normalization on address fields. Example: converting city field to uppercase letters.
+ """
+ enableFieldsNormalization: Boolean = true
+}
+
"""
Completes the checkout. As a result a new order is created and a payment charge is made. This action requires a successful payment before it can be performed. In case additional confirmation step as 3D secure is required confirmationNeeded flag will be set to True and no order created until payment is confirmed with second call of this mutation.
"""
@@ -19115,6 +19150,15 @@ input CheckoutCreateInput {
"""Checkout language code."""
languageCode: LanguageCodeEnum
+
+ """
+ The checkout validation rules that can be changed.
+
+ Added in Saleor 3.5.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ validationRules: CheckoutValidationRules
}
input CheckoutLineInput {
@@ -19134,6 +19178,18 @@ input CheckoutLineInput {
price: PositiveDecimal
}
+input CheckoutValidationRules {
+ """
+ The validation rules that can be applied to provided shipping address data.
+ """
+ shippingAddress: CheckoutAddressValidationRules
+
+ """
+ The validation rules that can be applied to provided billing address data.
+ """
+ billingAddress: CheckoutAddressValidationRules
+}
+
"""
Sets the customer as the owner of the checkout.