Skip to content

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

Skip address validation. (#16162)

Piotr Zabieglik69bc54b62ad5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ad69f36b7d..6f346e036e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -50,6 +50,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Add taxes to undiscounted prices - #14095 by @jakubkuc
- Mark as deprecated: `ordersTotal`, `reportProductSales` and `homepageEvents` - #14806 by @8r2y5
- Add `identifier` field to App graphql object. Identifier field is the same as Manifest.id field (explicit ID set by the app).
+- Add `skipValidation` field to `AddressInput` - #15985 by @zedzior
### Saleor Apps
@@ -71,6 +72,8 @@ All notable, unreleased changes to this project will be documented in this file.
- Added new parameter `identifier` for `create_app` command.
- When `taxAppId` is provided for `TaxConfiguration` do not allow to finalize `checkoutComplete` or `draftOrderComplete` mutations if Tax App or Avatax plugin didn't respond.
- Add `unique_type` to `OrderLineDiscount` and `CheckoutLineDiscount` models - #15774 by @zedzior
+- Allow to skip address validation - #15985 by @zedzior
+ - Added new field `Address.validation_skipped`.
# 3.18.0
diff --git a/saleor/account/i18n.py b/saleor/account/i18n.py
index 4b414d9801..dcb2445a24 100644
--- a/saleor/account/i18n.py
+++ b/saleor/account/i18n.py
@@ -1,3 +1,4 @@
+import logging
from collections import defaultdict
import i18naddress
@@ -14,6 +15,7 @@ from .widgets import DatalistTextWidget
COUNTRY_FORMS = {}
UNKNOWN_COUNTRIES = set()
+ADDRESS_FIELDS_TO_LOG = ["country_area", "city_area", "city", "postal_code"]
AREA_TYPE = {
"area": "Area",
@@ -38,6 +40,8 @@ AREA_TYPE = {
"zip": "ZIP code",
}
+logger = logging.getLogger(__name__)
+
class PossiblePhoneNumberFormField(forms.CharField):
"""A phone input field."""
@@ -187,6 +191,7 @@ class CountryAwareAddressForm(AddressForm):
del data["sorting_code"]
except i18naddress.InvalidAddressError as exc:
self.add_field_errors(exc.errors)
+ self.log_errors()
return data
def clean(self):
@@ -205,6 +210,17 @@ class CountryAwareAddressForm(AddressForm):
if actual_value in mapping:
data[field_name] = mapping[actual_value]
+ def log_errors(self):
+ errors = self.errors
+ fields = {}
+ for field, _ in errors.items():
+ fields[field] = (
+ self.data.get(field) if field in ADDRESS_FIELDS_TO_LOG else "invalid"
+ )
+ fields["skip_validation"] = self.data.get("skip_validation")
+ fields["country"] = self.data.get("country")
+ logger.warning("Invalid address input: %s", fields)
+
def get_address_form_class(country_code):
return COUNTRY_FORMS.get(country_code, AddressForm)
diff --git a/saleor/account/migrations/0085_address_validation_skipped.py b/saleor/account/migrations/0085_address_validation_skipped.py
new file mode 100644
index 0000000000..ac2e369731
--- /dev/null
+++ b/saleor/account/migrations/0085_address_validation_skipped.py
@@ -0,0 +1,25 @@
+# Generated by Django 3.2.24 on 2024-05-17 12:12
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("account", "0084_merge_20240229_1435"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="address",
+ name="validation_skipped",
+ field=models.BooleanField(default=False),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE account_address
+ ALTER COLUMN validation_skipped
+ SET DEFAULT false;
+ """,
+ reverse_sql=migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/account/models.py b/saleor/account/models.py
index b248fe3a65..d8f0bc899f 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -67,6 +67,7 @@ class Address(ModelWithMetadata):
country = CountryField()
country_area = models.CharField(max_length=128, blank=True)
phone = PossiblePhoneNumberField(blank=True, default="", db_index=True)
+ validation_skipped = models.BooleanField(default=False)
objects = AddressManager()
@@ -110,7 +111,7 @@ class Address(ModelWithMetadata):
data = model_to_dict(self, exclude=["id", "user"])
if isinstance(data["country"], Country):
data["country"] = data["country"].code
- if isinstance(data["phone"], PhoneNumber):
+ if isinstance(data["phone"], PhoneNumber) and not data["validation_skipped"]:
data["phone"] = data["phone"].as_e164
return data
diff --git a/saleor/account/tests/test_account.py b/saleor/account/tests/test_account.py
index e21b1b3226..76418dd9c2 100644
--- a/saleor/account/tests/test_account.py
+++ b/saleor/account/tests/test_account.py
@@ -213,6 +213,7 @@ def test_address_as_data(address):
"phone": "+48713988102",
"metadata": {},
"private_metadata": {},
+ "validation_skipped": False,
}
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index 6e0e9302a9..327b5ec819 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -1,3 +1,4 @@
+import logging
from collections.abc import Iterable
from decimal import Decimal
from typing import TYPE_CHECKING, Optional, cast
@@ -32,6 +33,8 @@ if TYPE_CHECKING:
from ..plugins.manager import PluginsManager
from .fetch import CheckoutInfo, CheckoutLineInfo
+logger = logging.getLogger(__name__)
+
def checkout_shipping_price(
*,
@@ -355,6 +358,8 @@ def _calculate_and_add_tax(
address: Optional["Address"] = None,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
+ from .utils import log_address_if_validation_skipped_for_checkout
+
if tax_calculation_strategy == TaxCalculationStrategy.TAX_APP:
# If taxAppId is not configured run all active plugins and tax apps.
# If taxAppId is provided run tax plugin or Tax App. taxAppId can be
@@ -368,6 +373,8 @@ def _calculate_and_add_tax(
tax_data = manager.get_taxes_for_checkout(
checkout_info, lines, tax_app_identifier
)
+ if not tax_data:
+ log_address_if_validation_skipped_for_checkout(checkout_info, logger)
_apply_tax_data(checkout, lines, tax_data)
else:
_call_plugin_or_tax_app(
@@ -398,6 +405,8 @@ def _call_plugin_or_tax_app(
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"] = None,
):
+ from .utils import log_address_if_validation_skipped_for_checkout
+
if tax_app_identifier.startswith(PLUGIN_IDENTIFIER_PREFIX):
plugin_ids = [tax_app_identifier.replace(PLUGIN_IDENTIFIER_PREFIX, "")]
plugins = manager.get_plugins(
@@ -422,6 +431,7 @@ def _call_plugin_or_tax_app(
checkout_info, lines, tax_app_identifier
)
if tax_data is None:
+ log_address_if_validation_skipped_for_checkout(checkout_info, logger)
raise TaxEmptyData("Empty tax data.")
_apply_tax_data(checkout, lines, tax_data)
diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.py
index 3655031613..b16005eaad 100644
--- a/saleor/checkout/tests/test_calculations.py
+++ b/saleor/checkout/tests/test_calculations.py
@@ -702,3 +702,54 @@ def test_external_shipping_method_called_only_once_during_tax_calculations(
assert checkout_with_single_item.shipping_price == TaxedMoney(
net=Money("1337.00", "USD"), gross=Money("1443.96", "USD")
)
+
+
[email protected]("tax_app_id", [None, "test.app"])
+def test_calculate_and_add_tax_empty_tax_data_logging_address(
+ tax_app_id, checkout_with_single_item, address, caplog
+):
+ # given
+ checkout = checkout_with_single_item
+
+ address.validation_skipped = True
+ address.postal_code = "invalid postal code"
+ address.save(update_fields=["postal_code", "validation_skipped"])
+
+ checkout.shipping_address = address
+ checkout.billing_address = address
+ checkout.save(update_fields=["billing_address", "shipping_address"])
+
+ checkout.channel.tax_configuration.tax_app_id = tax_app_id
+ checkout.channel.tax_configuration.save()
+
+ zero_money = zero_taxed_money(checkout.currency)
+ manager_methods = {
+ "calculate_checkout_total": Mock(return_value=zero_money),
+ "calculate_checkout_subtotal": Mock(return_value=zero_money),
+ "calculate_checkout_line_total": Mock(return_value=zero_money),
+ "calculate_checkout_shipping": Mock(return_value=zero_money),
+ "get_checkout_shipping_tax_rate": Mock(return_value=Decimal("0.00")),
+ "get_checkout_line_tax_rate": Mock(return_value=Decimal("0.00")),
+ "get_taxes_for_checkout": Mock(return_value=None),
+ }
+ manager = Mock(**manager_methods)
+
+ checkout_lines_info, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, checkout_lines_info, manager)
+
+ # when
+ _calculate_and_add_tax(
+ TaxCalculationStrategy.TAX_APP,
+ None,
+ checkout,
+ manager,
+ checkout_info,
+ checkout_lines_info,
+ prices_entered_with_tax=False,
+ )
+
+ # then
+ assert (
+ f"Fetching tax data for checkout with address validation skipped. "
+ f"Address ID: {address.pk}" in caplog.text
+ )
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 0360b423f4..d6e2dc34a4 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -1073,3 +1073,22 @@ def get_checkout_line_weight(line_info: "CheckoutLineInfo"):
or line_info.product.weight
or line_info.product_type.weight
)
+
+
+def log_address_if_validation_skipped_for_checkout(
+ checkout_info: "CheckoutInfo", logger
+):
+ address = get_address_for_checkout_taxes(checkout_info)
+ if address and address.validation_skipped:
+ logger.warning(
+ "Fetching tax data for checkout with address validation skipped. "
+ "Address ID: %s",
+ address.id,
+ )
+
+
+def get_address_for_checkout_taxes(
+ checkout_info: "CheckoutInfo",
+) -> Optional["Address"]:
+ shipping_address = checkout_info.delivery_method_info.shipping_address
+ return shipping_address or checkout_info.billing_address
diff --git a/saleor/graphql/account/bulk_mutations/customer_bulk_update.py b/saleor/graphql/account/bulk_mutations/customer_bulk_update.py
index 2bd1b2f81e..ad9d5c0c6a 100644
--- a/saleor/graphql/account/bulk_mutations/customer_bulk_update.py
+++ b/saleor/graphql/account/bulk_mutations/customer_bulk_update.py
@@ -181,20 +181,22 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):
field,
index,
index_error_map,
+ info,
format_check=True,
required_check=True,
enable_normalization=True,
):
try:
- address_form = cls.validate_address_form(
+ address = cls.validate_address(
address_data,
- address_type,
+ address_type=address_type,
format_check=format_check,
required_check=required_check,
enable_normalization=enable_normalization,
+ info=info,
)
- return address_form.cleaned_data
+ return address.as_data()
except ValidationError as exc:
cls.format_errors(index, exc, index_error_map, field_prefix=field)
@@ -281,6 +283,7 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):
field=SHIPPING_ADDRESS_FIELD,
index=index,
index_error_map=index_error_map,
+ info=info,
)
customer_input["input"][SHIPPING_ADDRESS_FIELD] = clean_shipping_address
@@ -291,6 +294,7 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):
field=BILLING_ADDRESS_FIELD,
index=index,
index_error_map=index_error_map,
+ info=info,
)
customer_input["input"][BILLING_ADDRESS_FIELD] = clean_billing_address
@@ -510,6 +514,7 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):
"country_area",
"phone",
"metadata",
+ "validation_skipped",
],
)
diff --git a/saleor/graphql/account/i18n.py b/saleor/graphql/account/i18n.py
index ec9aa6185d..ea9c233ad2 100644
--- a/saleor/graphql/account/i18n.py
+++ b/saleor/graphql/account/i18n.py
@@ -5,8 +5,56 @@ from django.core.exceptions import ValidationError
from ...account.forms import get_address_form
from ...account.models import Address
from ...account.validators import validate_possible_number
+from ...core.exceptions import PermissionDenied
+from ...permission.auth_filters import AuthorizationFilters
+from ...permission.enums import (
+ AccountPermissions,
+ BasePermissionEnum,
+ CheckoutPermissions,
+ OrderPermissions,
+ ProductPermissions,
+ SitePermissions,
+)
+from ...permission.utils import all_permissions_required
from ..core import ResolveInfo
+SKIP_ADDRESS_VALIDATION_PERMISSION_MAP: dict[str, list[BasePermissionEnum]] = {
+ "addressCreate": [AccountPermissions.MANAGE_USERS],
+ "addressUpdate": [AccountPermissions.MANAGE_USERS],
+ "customerBulkUpdate": [AccountPermissions.MANAGE_USERS],
+ "draftOrderCreate": [OrderPermissions.MANAGE_ORDERS],
+ "draftOrderUpdate": [OrderPermissions.MANAGE_ORDERS],
+ "orderUpdate": [OrderPermissions.MANAGE_ORDERS],
+ "orderBulkCreate": [OrderPermissions.MANAGE_ORDERS_IMPORT],
+ "createWarehouse": [ProductPermissions.MANAGE_PRODUCTS],
+ "updateWarehouse": [ProductPermissions.MANAGE_PRODUCTS],
+ "shopAddressUpdate": [SitePermissions.MANAGE_SETTINGS],
+ "checkoutCreate": [
+ CheckoutPermissions.HANDLE_CHECKOUTS,
+ AuthorizationFilters.AUTHENTICATED_APP,
+ ],
+ "checkoutShippingAddressUpdate": [
+ CheckoutPermissions.HANDLE_CHECKOUTS,
+ AuthorizationFilters.AUTHENTICATED_APP,
+ ],
+ "checkoutBillingAddressUpdate": [
+ CheckoutPermissions.HANDLE_CHECKOUTS,
+ AuthorizationFilters.AUTHENTICATED_APP,
+ ],
+ "accountAddressCreate": [
+ AuthorizationFilters.AUTHENTICATED_APP,
+ AccountPermissions.IMPERSONATE_USER,
+ ],
+ "accountUpdate": [
+ AuthorizationFilters.AUTHENTICATED_APP,
+ AccountPermissions.IMPERSONATE_USER,
+ ],
+ "accountAddressUpdate": [
+ AccountPermissions.MANAGE_USERS,
+ AuthorizationFilters.AUTHENTICATED_APP,
+ ],
+}
+
class I18nMixin:
"""A mixin providing methods necessary to fulfill the internationalization process.
@@ -23,7 +71,7 @@ class I18nMixin:
pass
@classmethod
- def validate_address_form(
+ def _validate_address_form(
cls,
address_data: dict,
address_type: Optional[str] = None,
@@ -55,7 +103,9 @@ class I18nMixin:
instance=instance,
enable_normalization=enable_normalization,
)
+ validation_skipped = False
if not address_form.is_valid():
+ validation_skipped = True
errors = cls.attach_params_to_address_form_errors(
address_form, params, format_check, required_check
)
@@ -66,6 +116,7 @@ class I18nMixin:
address_form.cleaned_data["metadata"] = {}
if address_form.cleaned_data["private_metadata"] is None:
address_form.cleaned_data["private_metadata"] = {}
+ address_form.cleaned_data["validation_skipped"] = validation_skipped
return address_form
@@ -120,16 +171,47 @@ class I18nMixin:
)
}
)
- address_form = cls.validate_address_form(
+
+ if address_data.get("skip_validation"):
+ cls.can_skip_address_validation(info)
+ format_check = False
+
+ address_form = cls._validate_address_form(
address_data,
address_type,
format_check=format_check,
required_check=required_check,
enable_normalization=enable_normalization,
)
+ address_data = address_form.cleaned_data
+
if not instance:
instance = Address()
- cls.construct_instance(instance, address_form.cleaned_data)
+ cls.construct_instance(instance, address_data)
cls.clean_instance(info, instance)
return instance
+
+ @classmethod
+ def can_skip_address_validation(cls, info: Optional[ResolveInfo]):
+ required_permissions = None
+ if info:
+ mutation_name = info.field_name
+ required_permissions = SKIP_ADDRESS_VALIDATION_PERMISSION_MAP.get(
+ mutation_name
+ )
+
+ if not required_permissions:
+ raise ValidationError(
+ {
+ "skip_validation": ValidationError(
+ "This mutation doesn't allow to skip address validation.",
+ code="invalid",
+ )
+ }
+ )
+ elif info and not all_permissions_required(info.context, required_permissions):
+ raise PermissionDenied(
+ f"To skip address validation, you need following permissions: "
+ f"{', '.join(perm.name for perm in required_permissions)}.",
+ )
diff --git a/saleor/graphql/account/mixins.py b/saleor/graphql/account/mixins.py
index 7711b9d0fb..524dafed18 100644
--- a/saleor/graphql/account/mixins.py
+++ b/saleor/graphql/account/mixins.py
@@ -1,5 +1,45 @@
+from ...account import models
+from ...account.error_codes import AccountErrorCode
+from ...app.models import App
+from ...core.exceptions import PermissionDenied
+from ...permission.enums import AccountPermissions
+from ..core.utils import raise_validation_error
+from ..utils import get_user_or_app_from_context
+
+
class AddressMetadataMixin:
@classmethod
def construct_instance(cls, instance, cleaned_data):
cls.update_metadata(instance, cleaned_data.pop("metadata", list())) # type: ignore[attr-defined] # noqa: E501
return super().construct_instance(instance, cleaned_data) # type: ignore[misc] # noqa: E501
+
+
+class AppImpersonateMixin:
+ @classmethod
+ def get_user_instance(cls, info, customer_id):
+ requester = get_user_or_app_from_context(info.context)
+ user = None
+ if isinstance(requester, models.User):
+ if customer_id:
+ raise_validation_error(
+ field="customerId",
+ code=AccountErrorCode.INVALID,
+ message="This field can be used by apps only.",
+ )
+ user = requester
+ elif isinstance(requester, App):
+ if not requester.has_perm(AccountPermissions.IMPERSONATE_USER):
+ raise PermissionDenied(
+ permissions=[AccountPermissions.IMPERSONATE_USER]
+ )
+ if not customer_id:
+ raise_validation_error(
+ field="customerId",
+ code=AccountErrorCode.REQUIRED,
+ message="This field is required when the mutation is run by app.",
+ )
+ else:
+ user = cls.get_node_or_error( # type: ignore[attr-defined]
+ info, customer_id, only_type="User", field="customerId"
+ )
+ return user
diff --git a/saleor/graphql/account/mutations/account/account_address_create.py b/saleor/graphql/account/mutations/account/account_address_create.py
index 9b509d8113..e8cf774168 100644
--- a/saleor/graphql/account/mutations/account/account_address_create.py
+++ b/saleor/graphql/account/mutations/account/account_address_create.py
@@ -10,6 +10,7 @@ from .....core.tracing import traced_atomic_transaction
from .....permission.auth_filters import AuthorizationFilters
from .....webhook.event_types import WebhookEventAsyncType
from ....core import ResolveInfo
+from ....core.descriptions import ADDED_IN_319
from ....core.doc_category import DOC_CATEGORY_USERS
from ....core.mutations import ModelMutation
from ....core.types import AccountError
@@ -17,11 +18,13 @@ from ....core.utils import WebhookEventInfo
from ....plugins.dataloaders import get_plugin_manager_promise
from ...enums import AddressTypeEnum
from ...i18n import I18nMixin
-from ...mixins import AddressMetadataMixin
+from ...mixins import AddressMetadataMixin, AppImpersonateMixin
from ...types import Address, AddressInput, User
-class AccountAddressCreate(AddressMetadataMixin, ModelMutation, I18nMixin):
+class AccountAddressCreate(
+ AddressMetadataMixin, ModelMutation, I18nMixin, AppImpersonateMixin
+):
user = graphene.Field(
User, description="A user instance for which the address was created."
)
@@ -38,15 +41,32 @@ class AccountAddressCreate(AddressMetadataMixin, ModelMutation, I18nMixin):
"of that type."
),
)
+ customer_id = graphene.ID(
+ required=False,
+ description=(
+ "ID of customer the application is impersonating. "
+ "The field can be used and is required by apps only. "
+ "Requires IMPERSONATE_USER and AUTHENTICATED_APP permission."
+ + ADDED_IN_319
+ ),
+ )
class Meta:
- description = "Create a new address for the customer."
+ auto_permission_message = False
+ description = (
+ "Create a new address for the customer.\n\n"
+ "Requires one of following set of permissions: "
+ "AUTHENTICATED_USER or AUTHENTICATED_APP + IMPERSONATE_USER."
+ )
doc_category = DOC_CATEGORY_USERS
model = models.Address
object_type = Address
error_type_class = AccountError
error_type_field = "account_errors"
- permissions = (AuthorizationFilters.AUTHENTICATED_USER,)
+ permissions = (
+ AuthorizationFilters.AUTHENTICATED_USER,
+ AuthorizationFilters.AUTHENTICATED_APP,
+ )
webhook_events_info = [
WebhookEventInfo(
type=WebhookEventAsyncType.CUSTOMER_UPDATED,
@@ -60,15 +80,18 @@ class AccountAddressCreate(AddressMetadataMixin, ModelMutation, I18nMixin):
@classmethod
def perform_mutation( # type: ignore[override]
- cls, _root, info: ResolveInfo, /, *, input, type=None
+ cls, _root, info: ResolveInfo, /, *, input, type=None, customer_id=None
):
address_type = type
- user = info.context.user
- user = cast(models.User, user)
cleaned_input = cls.clean_input(info=info, instance=Address(), data=input)
+ user = cls.get_user_instance(info, customer_id)
+ user = cast(models.User, user)
with traced_atomic_transaction():
- address = cls.validate_address(cleaned_input, address_type=address_type)
+ address = cls.validate_address(
+ cleaned_input, address_type=address_type, info=info
+ )
cls.clean_instance(info, address)
+ cleaned_input["user"] = user
cls.save(info, address, cleaned_input)
cls._save_m2m(info, address, cleaned_input)
if address_type:
@@ -78,9 +101,8 @@ class AccountAddressCreate(AddressMetadataMixin, ModelMutation, I18nMixin):
@classmethod
def save(cls, info: ResolveInfo, instance, cleaned_input):
+ user = cleaned_input.pop("user")
super().save(info, instance, cleaned_input)
- user = info.context.user
- user = cast(models.User, user)
remove_the_oldest_user_address_if_address_limit_is_reached(user)
instance.user_addresses.add(user)
user.search_document = search.prepare_user_search_document_value(user)
diff --git a/saleor/graphql/account/mutations/account/account_update.py b/saleor/graphql/account/mutations/account/account_update.py
index 8d9c0520ad..a379e3b3f1 100644
--- a/saleor/graphql/account/mutations/account/account_update.py
+++ b/saleor/graphql/account/mutations/account/account_update.py
@@ -7,11 +7,12 @@ from .....permission.auth_filters import AuthorizationFilters
from .....webhook.event_types import WebhookEventAsyncType
from ....account.mixins import AddressMetadataMixin
from ....core import ResolveInfo
-from ....core.descriptions import ADDED_IN_314
+from ....core.descriptions import ADDED_IN_314, ADDED_IN_319
from ....core.doc_category import DOC_CATEGORY_USERS
from ....core.types import AccountError, NonNullList
from ....core.utils import WebhookEventInfo
from ....meta.inputs import MetadataInput
+from ...mixins import AppImpersonateMixin
from ...types import AddressInput, User
from ..base import BaseCustomerCreate
from .base import AccountBaseInput
@@ -35,20 +36,37 @@ class AccountInput(AccountBaseInput):
doc_category = DOC_CATEGORY_USERS
-class AccountUpdate(AddressMetadataMixin, BaseCustomerCreate):
+class AccountUpdate(AddressMetadataMixin, BaseCustomerCreate, AppImpersonateMixin):
class Arguments:
input = AccountInput(
description="Fields required to update the account of the logged-in user.",
required=True,
)
+ customer_id = graphene.ID(
+ required=False,
+ description=(
+ "ID of customer the application is impersonating. "
+ "The field can be used and is required by apps only. "
+ "Requires IMPERSONATE_USER and AUTHENTICATED_APP permission."
+ + ADDED_IN_319
+ ),
+ )
class Meta:
- description = "Updates the account of the logged-in user."
+ auto_permission_message = False
+ description = (
+ "Updates the account of the logged-in user.\n\n"
+ "Requires one of following set of permissions: "
+ "AUTHENTICATED_USER or AUTHENTICATED_APP + IMPERSONATE_USER."
+ )
doc_category = DOC_CATEGORY_USERS
exclude = ["password"]
model = models.User
object_type = User
- permissions = (AuthorizationFilters.AUTHENTICATED_USER,)
+ permissions = (
+ AuthorizationFilters.AUTHENTICATED_USER,
+ AuthorizationFilters.AUTHENTICATED_APP,
+ )
error_type_class = AccountError
error_type_field = "account_errors"
support_meta_field = True
@@ -65,7 +83,8 @@ class AccountUpdate(AddressMetadataMixin, BaseCustomerCreate):
@classmethod
def perform_mutation(cls, root, info: ResolveInfo, /, **data):
- user = info.context.user
+ customer_id = data.get("customer_id")
+ user = cls.get_user_instance(info, customer_id)
user = cast(models.User, user)
data["id"] = graphene.Node.to_global_id("User", user.id)
return super().perform_mutation(root, info, **data)
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index 3c3429a110..34f179b5b8 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -96,7 +96,7 @@ class BaseAddressUpdate(ModelMutation, I18nMixin):
info=info, instance=instance, data=data.get("input")
)
cls.update_metadata(instance, cleaned_input.pop("metadata", list()))
- address = cls.validate_address(cleaned_input, instance=instance)
+ address = cls.validate_address(cleaned_input, instance=instance, info=info)
cls.clean_instance(info, address)
cls.save(info, address, cleaned_input)
cls._save_m2m(info, address, cleaned_input)
diff --git a/saleor/graphql/account/mutations/staff/address_create.py b/saleor/graphql/account/mutations/staff/address_create.py
index 48b2ba55c3..9eb08d8c43 100644
--- a/saleor/graphql/account/mutations/staff/address_create.py
+++ b/saleor/graphql/account/mutations/staff/address_create.py
@@ -55,7 +55,7 @@ class AddressCreate(AddressMetadataMixin, ModelMutation, I18nMixin):
data = data.get("input")
with traced_atomic_transaction():
cleaned_input = cls.clean_input(info, instance, data)
- instance = cls.validate_address(cleaned_input, instance=instance)
+ instance = cls.validate_address(cleaned_input, instance=instance, info=info)
cls.clean_instance(info, instance)
cls.save(info, instance, cleaned_input)
cls.post_save_action(info, instance, cleaned_input)
diff --git a/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py b/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py
index 7dcad99e75..41cbaf26e2 100644
--- a/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py
+++ b/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py
@@ -32,12 +32,14 @@ CUSTOMER_BULK_UPDATE_MUTATION = """
key
value
}
+ postalCode
}
defaultBillingAddress {
metadata {
key
value
}
+ postalCode
}
}
}
@@ -538,6 +540,7 @@ def test_customers_bulk_update_with_address(
address_data = convert_dict_keys_to_camel_case(address.as_data())
address_data.pop("metadata")
address_data.pop("privateMetadata")
+ address_data.pop("validationSkipped")
new_street_address = "Updated street address"
address_data["streetAddress1"] = new_street_address
@@ -597,6 +600,7 @@ def test_customers_bulk_update_with_address_when_no_default(
customer_id = graphene.Node.to_global_id("User", customer_user.pk)
address_data = convert_dict_keys_to_camel_case(shipping_address.as_data())
+ address_data.pop("validationSkipped")
address_data.pop("metadata")
address_data.pop("privateMetadata")
@@ -647,6 +651,7 @@ def test_customers_bulk_update_with_invalid_address(
customer_id = graphene.Node.to_global_id("User", customer_user.pk)
address_data = convert_dict_keys_to_camel_case(address.as_data())
+ address_data.pop("validationSkipped")
address_data.pop("metadata")
address_data.pop("privateMetadata")
address_data.pop("country")
@@ -914,3 +919,54 @@ def test_customers_bulk_update_trigger_gift_card_search_vector_update(
for card in gift_card_list:
card.refresh_from_db()
assert card.search_index_dirty is True
+
+
+def test_customers_bulk_update_skip_address_validation(
+ staff_api_client,
+ customer_user,
+ graphql_address_data_skipped_validation,
+ permission_manage_users,
+):
+ # given
+ shipping_address, billing_address = (
+ customer_user.default_shipping_address,
+ customer_user.default_billing_address,
+ )
+ assert shipping_address
+ assert billing_address
+
+ staff_api_client.user.user_permissions.add(permission_manage_users)
+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)
+ address_data = graphql_address_data_skipped_validation
+ wrong_postal_code = "wrong postal code"
+ address_data["postalCode"] = wrong_postal_code
+
+ customers_input = [
+ {
+ "id": customer_id,
+ "input": {
+ "defaultBillingAddress": address_data,
+ "defaultShippingAddress": address_data,
+ },
+ }
+ ]
+
+ variables = {"customers": customers_input}
+
+ # when
+ response = staff_api_client.post_graphql(CUSTOMER_BULK_UPDATE_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["customerBulkUpdate"]
+ assert data["count"] == 1
+ assert not data["results"][0]["errors"]
+ customer_data = data["results"][0]["customer"]
+ assert customer_data["defaultShippingAddress"]["postalCode"] == wrong_postal_code
+ assert customer_data["defaultBillingAddress"]["postalCode"] == wrong_postal_code
+ shipping_address.refresh_from_db()
+ assert shipping_address.postal_code == wrong_postal_code
+ assert shipping_address.validation_skipped is True
+ billing_address.refresh_from_db()
+ assert billing_address.postal_code == wrong_postal_code
+ assert billing_address.validation_skipped is True
diff --git a/saleor/graphql/account/tests/mutations/account/test_account_address_create.py b/saleor/graphql/account/tests/mutations/account/test_account_address_create.py
index b49707fe6d..22874f8302 100644
--- a/saleor/graphql/account/tests/mutations/account/test_account_address_create.py
+++ b/saleor/graphql/account/tests/mutations/account/test_account_address_create.py
@@ -14,15 +14,19 @@ from .....tests.utils import assert_no_permission, get_graphql_content
from ..utils import generate_address_webhook_call_args
ACCOUNT_ADDRESS_CREATE_MUTATION = """
-mutation($addressInput: AddressInput!, $addressType: AddressTypeEnum) {
- accountAddressCreate(input: $addressInput, type: $addressType) {
+mutation($addressInput: AddressInput!, $addressType: AddressTypeEnum, $customerId: ID) {
+ accountAddressCreate(
+ input: $addressInput, type: $addressType, customerId: $customerId
+ ) {
address {
- id,
+ id
city
metadata {
key
value
}
+ firstName
+ postalCode
}
user {
email
@@ -31,6 +35,7 @@ mutation($addressInput: AddressInput!, $addressType: AddressTypeEnum) {
code
field
addressType
+ message
}
}
}
@@ -54,9 +59,9 @@ def test_customer_create_address(user_api_client, graphql_address_data):
user.refresh_from_db()
- assert user.addresses.exclude(id__in=user_addresses_ids).first().metadata == {
- "public": "public_value"
- }
+ address = user.addresses.exclude(id__in=user_addresses_ids).first()
+ assert address.metadata == {"public": "public_value"}
+ assert address.validation_skipped is False
assert user.addresses.count() == user_addresses_count + 1
assert (
generate_address_search_document_value(user.addresses.last())
@@ -199,3 +204,185 @@ def test_address_not_created_after_validation_fails(
assert data["errors"][0]["addressType"] == address_type
user.refresh_from_db()
assert user.addresses.count() == user_addresses_count
+
+
+def test_customer_create_address_skip_validation(
+ user_api_client,
+ graphql_address_data_skipped_validation,
+):
+ # given
+ query = ACCOUNT_ADDRESS_CREATE_MUTATION
+ address_data = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+ variables = {"addressInput": address_data}
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_account_address_create_by_app(
+ app_api_client, graphql_address_data, permission_impersonate_user, customer_user
+):
+ # given
+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)
+ new_first_name = "Andrew"
+ graphql_address_data["firstName"] = new_first_name
+ variables = {"addressInput": graphql_address_data, "customerId": customer_id}
+
+ # when
+ response = app_api_client.post_graphql(
+ ACCOUNT_ADDRESS_CREATE_MUTATION,
+ variables,
+ permissions=[permission_impersonate_user],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["accountAddressCreate"]
+ assert not data["errors"]
+ assert data["address"]["firstName"] == new_first_name
+
+
+def test_account_address_create_by_app_no_permissions(
+ app_api_client, graphql_address_data, customer_user
+):
+ # given
+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)
+ variables = {"addressInput": graphql_address_data, "customerId": customer_id}
+
+ # when
+ response = app_api_client.post_graphql(ACCOUNT_ADDRESS_CREATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_account_address_create_by_user_with_customer_id(
+ user_api_client, graphql_address_data, customer_user
+):
+ # given
+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)
+ variables = {"addressInput": graphql_address_data, "customerId": customer_id}
+
+ # when
+ response = user_api_client.post_graphql(
+ ACCOUNT_ADDRESS_CREATE_MUTATION,
+ variables,
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["accountAddressCreate"]
+ assert not data["address"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "customerId"
+ assert errors[0]["code"] == AccountErrorCode.INVALID.name
+
+
+def test_account_address_create_by_app_invalid_customer_id(
+ app_api_client, graphql_address_data, permission_impersonate_user, customer_user
+):
+ # given
+ customer_id = graphene.Node.to_global_id("Address", customer_user.pk)
+ variables = {"addressInput": graphql_address_data, "customerId": customer_id}
+
+ # when
+ response = app_api_client.post_graphql(
+ ACCOUNT_ADDRESS_CREATE_MUTATION,
+ variables,
+ permissions=[permission_impersonate_user],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["accountAddressCreate"]
+ assert not data["address"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "customerId"
+ assert errors[0]["code"] == AccountErrorCode.GRAPHQL_ERROR.name
+
+
+def test_account_address_create_by_app_no_customer_id(
+ app_api_client, graphql_address_data, permission_impersonate_user
+):
+ # given
+ variables = {"addressInput": graphql_address_data}
+
+ # when
+ response = app_api_client.post_graphql(
+ ACCOUNT_ADDRESS_CREATE_MUTATION,
+ variables,
+ permissions=[permission_impersonate_user],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["accountAddressCreate"]
+ assert not data["address"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "customerId"
+ assert errors[0]["code"] == AccountErrorCode.REQUIRED.name
+
+
+def test_account_address_create_by_app_skip_validation(
+ app_api_client,
+ permission_impersonate_user,
+ customer_user,
+ graphql_address_data_skipped_validation,
+):
+ # given
+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)
+ invalid_postal_code = "invalid postal code"
+ address_data = graphql_address_data_skipped_validation
+ address_data["postalCode"] = invalid_postal_code
+ address_type = AddressType.SHIPPING.upper()
+ variables = {
+ "addressInput": address_data,
+ "customerId": customer_id,
+ "addressType": address_type,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ ACCOUNT_ADDRESS_CREATE_MUTATION,
+ variables,
+ permissions=[permission_impersonate_user],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["accountAddressCreate"]
+ assert not data["errors"]
+ assert data["address"]["postalCode"] == invalid_postal_code
+ customer_user.refresh_from_db()
+ assert customer_user.default_shipping_address.postal_code == invalid_postal_code
+ assert customer_user.default_shipping_address.validation_skipped is True
+
+
+def test_account_address_create_by_app_skip_validation_no_permissions(
+ app_api_client, customer_user, graphql_address_data_skipped_validation
+):
+ # given
+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)
+ invalid_postal_code = "invalid postal code"
+ address_data = graphql_address_data_skipped_validation
+ address_data["postalCode"] = invalid_postal_code
+ address_type = AddressType.SHIPPING.upper()
+ variables = {
+ "addressInput": address_data,
+ "customerId": customer_id,
+ "addressType": address_type,
+ }
+
+ # when
+ response = app_api_client.post_graphql(ACCOUNT_ADDRESS_CREATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/account/tests/mutations/account/test_account_address_update.py b/saleor/graphql/account/tests/mutations/account/test_account_address_update.py
index 83fb6e3832..bd219cda7e 100644
--- a/saleor/graphql/account/tests/mutations/account/test_account_address_update.py
+++ b/saleor/graphql/account/tests/mutations/account/test_account_address_update.py
@@ -17,10 +17,15 @@ ACCOUNT_ADDRESS_UPDATE_MUTATION = """
key
value
}
+ postalCode
}
user {
id
}
+ errors {
+ code
+ field
+ }
}
}
"""
@@ -48,6 +53,7 @@ def test_customer_update_own_address(
address_obj.refresh_from_db()
assert address_obj.city == address_data["city"].upper()
assert address_obj.metadata == {"public": "public_value"}
+ assert address_obj.validation_skipped is False
user.refresh_from_db()
assert generate_address_search_document_value(address_obj) in user.search_document
@@ -143,3 +149,109 @@ def test_customer_update_address_for_other(
}
response = user_api_client.post_graphql(ACCOUNT_ADDRESS_UPDATE_MUTATION, variables)
assert_no_permission(response)
+
+
+def test_customer_update_address_skip_validation(
+ user_api_client, customer_user, graphql_address_data_skipped_validation
+):
+ # given
+ query = ACCOUNT_ADDRESS_UPDATE_MUTATION
+ address_obj = customer_user.addresses.first()
+ address_data = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+
+ variables = {
+ "addressId": graphene.Node.to_global_id("Address", address_obj.id),
+ "address": address_data,
+ }
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_account_address_update_by_app(
+ app_api_client, customer_user, graphql_address_data, permission_manage_users
+):
+ # given
+ query = ACCOUNT_ADDRESS_UPDATE_MUTATION
+ address_obj = customer_user.addresses.first()
+ address_data = graphql_address_data
+ new_city = "Poznań"
+ address_data["city"] = new_city
+ assert address_data["city"] != address_obj.city
+
+ variables = {
+ "addressId": graphene.Node.to_global_id("Address", address_obj.id),
+ "address": address_data,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_users]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["accountAddressUpdate"]
+ assert data["address"]["city"] == address_data["city"].upper()
+ address_obj.refresh_from_db()
+ assert address_obj.city == address_data["city"].upper()
+ assert address_obj.validation_skipped is False
+
+
+def test_account_address_update_by_app_skip_validation(
+ app_api_client,
+ customer_user,
+ graphql_address_data_skipped_validation,
+ permission_manage_users,
+):
+ # given
+ query = ACCOUNT_ADDRESS_UPDATE_MUTATION
+ address_obj = customer_user.addresses.first()
+ invalid_postal_code = "invalid postal code"
+ address_data = graphql_address_data_skipped_validation
+ address_data["postalCode"] = invalid_postal_code
+
+ variables = {
+ "addressId": graphene.Node.to_global_id("Address", address_obj.id),
+ "address": address_data,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_users]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["accountAddressUpdate"]
+ assert data["address"]["postalCode"] == invalid_postal_code
+ address_obj.refresh_from_db()
+ assert address_obj.postal_code == invalid_postal_code
+ assert address_obj.validation_skipped is True
+
+
+def test_account_address_update_by_app_skip_validation_no_permissions(
+ app_api_client, customer_user, graphql_address_data_skipped_validation
+):
+ # given
+ query = ACCOUNT_ADDRESS_UPDATE_MUTATION
+ address_obj = customer_user.addresses.first()
+ invalid_postal_code = "invalid postal code"
+ address_data = graphql_address_data_skipped_validation
+ address_data["postalCode"] = invalid_postal_code
+
+ variables = {
+ "addressId": graphene.Node.to_global_id("Address", address_obj.id),
+ "address": address_data,
+ }
+
+ # when
+ response = app_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/account/tests/mutations/account/test_account_update.py b/saleor/graphql/account/tests/mutations/account/test_account_update.py
index 3eb04a8c16..f300cc45b2 100644
--- a/saleor/graphql/account/tests/mutations/account/test_account_update.py
+++ b/saleor/graphql/account/tests/mutations/account/test_account_update.py
@@ -1,5 +1,7 @@
from unittest.mock import patch
+import graphene
+
from ......account.error_codes import AccountErrorCode
from ......account.models import User
from ......checkout import AddressType
@@ -14,6 +16,7 @@ ACCOUNT_UPDATE_QUERY = """
$lastName: String
$languageCode: LanguageCodeEnum
$metadata: [MetadataInput!]
+ $customerId: ID
) {
accountUpdate(
input: {
@@ -22,8 +25,10 @@ ACCOUNT_UPDATE_QUERY = """
firstName: $firstName,
lastName: $lastName,
languageCode: $languageCode,
- metadata: $metadata
- }) {
+ metadata: $metadata,
+ },
+ customerId: $customerId
+ ) {
errors {
field
code
@@ -40,6 +45,8 @@ ACCOUNT_UPDATE_QUERY = """
key
value
}
+ city
+ postalCode
}
defaultShippingAddress {
id
@@ -47,6 +54,7 @@ ACCOUNT_UPDATE_QUERY = """
key
value
}
+ postalCode
}
languageCode
metadata {
@@ -130,6 +138,9 @@ def test_logged_customer_update_addresses(user_api_client, graphql_address_data)
assert user.default_billing_address.metadata == {"public": "public_value"}
assert user.default_shipping_address.metadata == {"public": "public_value"}
+ assert user.default_billing_address.validation_skipped is False
+ assert user.default_shipping_address.validation_skipped is False
+
def test_logged_customer_update_addresses_invalid_shipping_address(
user_api_client, graphql_address_data
@@ -220,3 +231,188 @@ def test_logged_customer_update_names_trigger_gift_card_search_vector_update(
for card in gift_cards:
card.refresh_from_db()
assert card.search_index_dirty is True
+
+
+def test_logged_customer_update_address_skip_validation(
+ user_api_client,
+ graphql_address_data_skipped_validation,
+):
+ # given
+ query = ACCOUNT_UPDATE_QUERY
+ address_data = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+ variables = {"shipping": address_data, "billing": address_data}
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_account_update_by_app(
+ app_api_client, customer_user, permission_impersonate_user, graphql_address_data
+):
+ # given
+ new_city = "WARSZAWA"
+ address_input = graphql_address_data
+ address_input["city"] = new_city
+ user = customer_user
+ user_id = graphene.Node.to_global_id("User", user.pk)
+ assert user.default_billing_address.city != new_city
+ variables = {"billing": address_input, "customerId": user_id}
+
+ # when
+ response = app_api_client.post_graphql(
+ ACCOUNT_UPDATE_QUERY, variables, permissions=[permission_impersonate_user]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["accountUpdate"]
+ assert not data["errors"]
+ assert data["user"]["defaultBillingAddress"]["city"] == new_city
+ user.refresh_from_db()
+ assert user.default_billing_address.city == new_city
+
+
+def test_account_update_by_app_no_permissions(
+ app_api_client, graphql_address_data, customer_user
+):
+ # given
+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)
+ variables = {"billing": graphql_address_data, "customerId": customer_id}
+
+ # when
+ response = app_api_client.post_graphql(ACCOUNT_UPDATE_QUERY, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_account_update_by_user_with_customer_id(
+ user_api_client, graphql_address_data, customer_user
+):
+ # given
+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)
+ variables = {"billing": graphql_address_data, "customerId": customer_id}
+
+ # when
+ response = user_api_client.post_graphql(ACCOUNT_UPDATE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["accountUpdate"]
+ assert not data["user"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "customerId"
+ assert errors[0]["code"] == AccountErrorCode.INVALID.name
+
+
+def test_account_address_create_by_app_invalid_customer_id(
+ app_api_client, graphql_address_data, permission_impersonate_user, customer_user
+):
+ # given
+ customer_id = graphene.Node.to_global_id("Address", customer_user.pk)
+ variables = {"addressInput": graphql_address_data, "customerId": customer_id}
+
+ # when
+ response = app_api_client.post_graphql(
+ ACCOUNT_UPDATE_QUERY,
+ variables,
+ permissions=[permission_impersonate_user],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["accountUpdate"]
+ assert not data["user"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "customerId"
+ assert errors[0]["code"] == AccountErrorCode.GRAPHQL_ERROR.name
+
+
+def test_account_address_create_by_app_no_customer_id(
+ app_api_client, graphql_address_data, permission_impersonate_user
+):
+ # given
+ variables = {"billing": graphql_address_data}
+
+ # when
+ response = app_api_client.post_graphql(
+ ACCOUNT_UPDATE_QUERY,
+ variables,
+ permissions=[permission_impersonate_user],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["accountUpdate"]
+ assert not data["user"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "customerId"
+ assert errors[0]["code"] == AccountErrorCode.REQUIRED.name
+
+
+def test_account_update_address_by_app_skip_validation(
+ app_api_client,
+ customer_user,
+ graphql_address_data_skipped_validation,
+ permission_impersonate_user,
+):
+ # given
+ query = ACCOUNT_UPDATE_QUERY
+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)
+ address_data = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+ variables = {
+ "shipping": address_data,
+ "billing": address_data,
+ "customerId": customer_id,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_impersonate_user]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["accountUpdate"]
+ assert not data["errors"]
+ assert data["user"]["defaultBillingAddress"]["postalCode"] == invalid_postal_code
+ assert data["user"]["defaultShippingAddress"]["postalCode"] == invalid_postal_code
+ customer_user.refresh_from_db()
+ assert customer_user.default_billing_address.postal_code == invalid_postal_code
+ assert customer_user.default_billing_address.validation_skipped is True
+ assert customer_user.default_shipping_address.postal_code == invalid_postal_code
+ assert customer_user.default_shipping_address.validation_skipped is True
+
+
+def test_account_update_address_by_app_skip_validation_no_permissions(
+ app_api_client,
+ customer_user,
+ graphql_address_data_skipped_validation,
+):
+ # given
+ query = ACCOUNT_UPDATE_QUERY
+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)
+ address_data = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+ variables = {
+ "shipping": address_data,
+ "billing": address_data,
+ "customerId": customer_id,
+ }
+
+ # when
+ response = app_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/account/tests/mutations/staff/test_address_create.py b/saleor/graphql/account/tests/mutations/staff/test_address_create.py
index 41d2bb3705..1726e282d1 100644
--- a/saleor/graphql/account/tests/mutations/staff/test_address_create.py
+++ b/saleor/graphql/account/tests/mutations/staff/test_address_create.py
@@ -16,6 +16,7 @@ ADDRESS_CREATE_MUTATION = """
errors {
field
message
+ code
}
address {
id
@@ -27,6 +28,8 @@ ADDRESS_CREATE_MUTATION = """
key
value
}
+ postalCode
+ phone
}
user {
id
@@ -59,6 +62,7 @@ def test_create_address_mutation(
assert address_obj.metadata == {"public": "public_value"}
assert address_obj.user_addresses.first() == customer_user
+ assert address_obj.validation_skipped is False
assert data["user"]["id"] == user_id
customer_user.refresh_from_db()
@@ -173,3 +177,33 @@ def test_create_address_validation_fails(
assert len(data["errors"]) == 1
assert data["errors"][0]["field"] == "postalCode"
assert data["address"] is None
+
+
+def test_create_address_skip_validation(
+ staff_api_client,
+ customer_user,
+ graphql_address_data_skipped_validation,
+ permission_manage_users,
+):
+ # given
+ query = ADDRESS_CREATE_MUTATION
+ address_data = graphql_address_data_skipped_validation
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ wrong_postal_code = "wrong postal code"
+ address_data["postalCode"] = wrong_postal_code
+ variables = {"user": user_id, "address": address_data}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_users]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["addressCreate"]
+ assert not data["errors"]
+ assert data["address"]["postalCode"] == wrong_postal_code
+ new_address = Address.objects.last()
+ assert new_address.postal_code == wrong_postal_code
+ assert new_address.validation_skipped is True
+ assert new_address.metadata == {"public": "public_value"}
diff --git a/saleor/graphql/account/tests/mutations/staff/test_address_update.py b/saleor/graphql/account/tests/mutations/staff/test_address_update.py
index 8b0f1ff00c..0f3a0c3eef 100644
--- a/saleor/graphql/account/tests/mutations/staff/test_address_update.py
+++ b/saleor/graphql/account/tests/mutations/staff/test_address_update.py
@@ -12,6 +12,7 @@ ADDRESS_UPDATE_MUTATION = """
mutation updateUserAddress($addressId: ID!, $address: AddressInput!) {
addressUpdate(id: $addressId, input: $address) {
address {
+ postalCode
city
metadata {
key
@@ -21,6 +22,9 @@ ADDRESS_UPDATE_MUTATION = """
user {
id
}
+ errors {
+ code
+ }
}
}
"""
@@ -45,6 +49,7 @@ def test_address_update_mutation(
assert data["address"]["city"] == graphql_address_data["city"].upper()
address_obj.refresh_from_db()
assert address_obj.city == graphql_address_data["city"].upper()
+ assert address_obj.validation_skipped is False
customer_user.refresh_from_db()
assert (
generate_address_search_document_value(address_obj)
@@ -137,3 +142,70 @@ def test_customer_update_address_for_other(
}
response = user_api_client.post_graphql(ADDRESS_UPDATE_MUTATION, variables)
assert_no_permission(response)
+
+
+def test_address_update_skip_validation(
+ staff_api_client,
+ customer_user,
+ permission_manage_users,
+ graphql_address_data_skipped_validation,
+):
+ # given
+ query = ADDRESS_UPDATE_MUTATION
+ address_obj = customer_user.addresses.first()
+ address_data = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+ variables = {
+ "addressId": graphene.Node.to_global_id("Address", address_obj.id),
+ "address": address_data,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_users]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["addressUpdate"]
+ assert not data["errors"]
+ assert data["address"]["postalCode"] == invalid_postal_code
+ address_obj.refresh_from_db()
+ assert address_obj.postal_code == invalid_postal_code
+ assert address_obj.validation_skipped is True
+
+
+def test_address_update_address_with_skipped_validation(
+ staff_api_client,
+ customer_user,
+ permission_manage_users,
+ graphql_address_data,
+):
+ # given
+ query = ADDRESS_UPDATE_MUTATION
+ address_obj = customer_user.addresses.first()
+ address_obj.postal_code = "invalid postal code"
+ address_obj.validation_skipped = True
+ address_obj.save(update_fields=["postal_code", "validation_skipped"])
+
+ address_data = graphql_address_data
+ valid_postal_code = address_data["postalCode"]
+ variables = {
+ "addressId": graphene.Node.to_global_id("Address", address_obj.id),
+ "address": address_data,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_users]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["addressUpdate"]
+ assert not data["errors"]
+ assert data["address"]["postalCode"] == valid_postal_code
+ address_obj.refresh_from_db()
+ assert address_obj.postal_code == valid_postal_code
+ assert address_obj.validation_skipped is False
diff --git a/saleor/graphql/account/tests/mutations/staff/test_customer_create.py b/saleor/graphql/account/tests/mutations/staff/test_customer_create.py
index 66cfac4f8d..f5d966e14e 100644
--- a/saleor/graphql/account/tests/mutations/staff/test_customer_create.py
+++ b/saleor/graphql/account/tests/mutations/staff/test_customer_create.py
@@ -109,6 +109,7 @@ def test_customer_create(
stored_metadata = {"test key": "test value"}
address_data["metadata"] = metadata
address_data.pop("privateMetadata")
+ address_data.pop("validationSkipped")
redirect_url = "https://www.example.com"
external_reference = "test-ext-ref"
@@ -221,6 +222,7 @@ def test_customer_create_as_app(
stored_metadata = {"test key": "test value"}
address_data["metadata"] = metadata
address_data.pop("privateMetadata")
+ address_data.pop("validationSkipped")
redirect_url = "https://www.example.com"
external_reference = "test-ext-ref"
@@ -372,6 +374,7 @@ def test_customer_create_empty_metadata_key(
address_data = convert_dict_keys_to_camel_case(address.as_data())
address_data.pop("metadata")
address_data.pop("privateMetadata")
+ address_data.pop("validationSkipped")
redirect_url = "https://www.example.com"
external_reference = "test-ext-ref"
@@ -514,6 +517,7 @@ def test_customer_create_webhook_event_triggered(
address_data = convert_dict_keys_to_camel_case(address.as_data())
address_data.pop("privateMetadata")
+ address_data.pop("validationSkipped")
variables = {
"email": email,
diff --git a/saleor/graphql/account/tests/mutations/staff/test_customer_update.py b/saleor/graphql/account/tests/mutations/staff/test_customer_update.py
index f4f5e2c482..bca9e5d71b 100644
--- a/saleor/graphql/account/tests/mutations/staff/test_customer_update.py
+++ b/saleor/graphql/account/tests/mutations/staff/test_customer_update.py
@@ -91,6 +91,7 @@ def test_customer_update(
address_data["metadata"] = metadata
stored_metadata = {"test key": "test value"}
address_data.pop("privateMetadata")
+ address_data.pop("validationSkipped")
new_street_address = "Updated street address"
address_data["streetAddress1"] = new_street_address
diff --git a/saleor/graphql/account/tests/test_i18n.py b/saleor/graphql/account/tests/test_i18n.py
index a8d5bd9d9b..e02122f70e 100644
--- a/saleor/graphql/account/tests/test_i18n.py
+++ b/saleor/graphql/account/tests/test_i18n.py
@@ -1,9 +1,17 @@
+import logging
+from unittest import mock
+
+import graphene
import pytest
from django.core.exceptions import ValidationError
+from ....account.models import Address
from ....checkout import AddressType
+from ...tests.utils import get_graphql_content
from ..i18n import I18nMixin
+logger = logging.getLogger(__name__)
+
def test_validate_address():
# given
@@ -95,3 +103,228 @@ def test_validate_address_no_city():
# then
assert len(error.value.error_dict["city"]) == 1
+
+
+ADDRESS_CREATE_MUTATION = """
+ mutation CreateUserAddress($user: ID!, $address: AddressInput!) {
+ addressCreate(userId: $user, input: $address) {
+ errors {
+ field
+ code
+ message
+ }
+ address {
+ id
+ city
+ postalCode
+ phone
+ country {
+ code
+ }
+ }
+ }
+ }
+"""
+
+
[email protected]("saleor.graphql.account.i18n.SKIP_ADDRESS_VALIDATION_PERMISSION_MAP", {})
+def test_skip_address_validation_mutation_not_supported(
+ staff_api_client,
+ customer_user,
+ graphql_address_data_skipped_validation,
+ permission_manage_users,
+):
+ # given
+ query = ADDRESS_CREATE_MUTATION
+ address_data = graphql_address_data_skipped_validation
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ wrong_postal_code = "wrong postal code"
+ address_data["postalCode"] = wrong_postal_code
+ variables = {"user": user_id, "address": address_data}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_users]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["addressCreate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "skipValidation"
+ assert errors[0]["code"] == "INVALID"
+ assert (
+ errors[0]["message"]
+ == "This mutation doesn't allow to skip address validation."
+ )
+
+
+def test_skip_validation_multiple_invalid_fields(
+ staff_api_client,
+ customer_user,
+ permission_manage_users,
+):
+ # given
+ query = ADDRESS_CREATE_MUTATION
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ invalid_name = "invalid name"
+ address_data = {
+ "firstName": invalid_name,
+ "lastName": invalid_name,
+ "companyName": invalid_name,
+ "streetAddress1": invalid_name,
+ "streetAddress2": invalid_name,
+ "postalCode": invalid_name,
+ "country": "US",
+ "city": invalid_name,
+ "countryArea": invalid_name,
+ "metadata": [{"key": "public", "value": "public_value"}],
+ "skipValidation": True,
+ }
+ variables = {"user": user_id, "address": address_data}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_users]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["addressCreate"]
+ assert not data["errors"]
+ assert data["address"]["country"]["code"] == "US"
+ assert data["address"]["postalCode"] == invalid_name
+ db_address = Address.objects.get(first_name=invalid_name)
+ assert db_address.postal_code == invalid_name
+ assert db_address.country_area == invalid_name
+ assert db_address.city == invalid_name
+ assert db_address.validation_skipped is True
+
+
[email protected]("street", [None, "", " "])
+def test_skip_address_validation_missing_required_fields(
+ street,
+ staff_api_client,
+ customer_user,
+ permission_manage_users,
+ graphql_address_data_skipped_validation,
+):
+ # given
+ query = ADDRESS_CREATE_MUTATION
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ address_data = graphql_address_data_skipped_validation
+ address_data["streetAddress1"] = street
+ variables = {"user": user_id, "address": address_data}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_users]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["addressCreate"]
+ assert not data["address"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "streetAddress1"
+ assert errors[0]["code"] == "REQUIRED"
+
+
+def test_skip_address_validation_with_correct_input_run_normalization(
+ staff_api_client,
+ customer_user,
+ permission_manage_users,
+ graphql_address_data_skipped_validation,
+):
+ # given
+ query = ADDRESS_CREATE_MUTATION
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ address_data = graphql_address_data_skipped_validation
+ variables = {"user": user_id, "address": address_data}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_users]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["addressCreate"]
+ assert not data["errors"]
+ assert data["address"]["city"] != address_data["city"]
+ assert data["address"]["city"] == address_data["city"].upper()
+ global_id = data["address"]["id"]
+ _, id = graphene.Node.from_global_id(global_id)
+ address_db = Address.objects.get(id=id)
+ assert address_db.city != address_data["city"]
+ assert address_db.city == address_data["city"].upper()
+ assert address_db.validation_skipped is False
+
+
+def test_skip_address_validation_with_incorrect_input_skip_normalization(
+ staff_api_client,
+ customer_user,
+ permission_manage_users,
+ graphql_address_data_skipped_validation,
+):
+ # given
+ query = ADDRESS_CREATE_MUTATION
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ address_data = graphql_address_data_skipped_validation
+ invalid_name = "invalid name"
+ address_data["postalCode"] = invalid_name
+ variables = {"user": user_id, "address": address_data}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_users]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["addressCreate"]
+ assert not data["errors"]
+ assert data["address"]["city"] != address_data["city"].upper()
+ assert data["address"]["city"] == address_data["city"]
+ assert data["address"]["postalCode"] == invalid_name
+ global_id = data["address"]["id"]
+ _, id = graphene.Node.from_global_id(global_id)
+ address_db = Address.objects.get(id=id)
+ assert address_db.city != address_data["city"].upper()
+ assert address_db.city == address_data["city"]
+ assert address_db.postal_code == invalid_name
+ assert address_db.validation_skipped is True
+
+
+def test_skip_address_validation_logging(
+ staff_api_client,
+ customer_user,
+ permission_manage_users,
+ graphql_address_data_skipped_validation,
+ caplog,
+):
+ # given
+ query = ADDRESS_CREATE_MUTATION
+ caplog.set_level(logging.WARNING)
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ address_data = graphql_address_data_skipped_validation
+ invalid_name = "wrong name"
+ address_data["country"] = "IE"
+ address_data["postalCode"] = invalid_name
+ address_data["countryArea"] = invalid_name
+ variables = {"user": user_id, "address": address_data}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_users]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["addressCreate"]
+ assert not data["errors"]
+ assert "'country_area': 'wrong name'" in caplog.text
+ assert "'postal_code': 'wrong name'" in caplog.text
+ assert "'skip_validation': True" in caplog.text
+ assert "'country': 'IE'" in caplog.text
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index d7cafc98c0..883669e93b 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -14,7 +14,11 @@ from ...graphql.meta.inputs import MetadataInput
from ...order import OrderStatus
from ...payment.interface import ListStoredPaymentMethodsRequestData
from ...permission.auth_filters import AuthorizationFilters
-from ...permission.enums import AccountPermissions, AppPermission, OrderPermissions
+from ...permission.enums import (
+ AccountPermissions,
+ AppPermission,
+ OrderPermissions,
+)
from ...plugins.manager import PluginsManager
from ...thumbnail.utils import (
get_image_or_proxy_url,
@@ -36,6 +40,7 @@ from ..core.descriptions import (
ADDED_IN_310,
ADDED_IN_314,
ADDED_IN_315,
+ ADDED_IN_319,
DEPRECATED_IN_3X_FIELD,
PREVIEW_FEATURE,
)
@@ -92,12 +97,25 @@ class AddressInput(BaseInputObjectType):
"[libphonenumber](https://github.com/google/libphonenumber) library."
)
)
-
metadata = graphene.List(
graphene.NonNull(MetadataInput),
description="Address public metadata." + ADDED_IN_315,
required=False,
)
+ skip_validation = graphene.Boolean(
+ description=(
+ "Determine if the address should be validated. "
+ "By default, Saleor accepts only address inputs matching ruleset from "
+ "[Google Address Data]{https://chromium-i18n.appspot.com/ssl-address), "
+ "using [i18naddress](https://github.com/mirumee/google-i18n-address) "
+ "library. Some mutations may require additional permissions to use the "
+ "the field. More info about permissions can be found in relevant mutation."
+ )
+ + ADDED_IN_319
+ + PREVIEW_FEATURE,
+ default_value=False,
+ required=False,
+ )
@federated_entity("id")
diff --git a/saleor/graphql/checkout/mutations/checkout_complete.py b/saleor/graphql/checkout/mutations/checkout_complete.py
index 2afe632dba..4c9c7fef9b 100644
--- a/saleor/graphql/checkout/mutations/checkout_complete.py
+++ b/saleor/graphql/checkout/mutations/checkout_complete.py
@@ -191,14 +191,15 @@ class CheckoutComplete(BaseMutation, I18nMixin):
clean_checkout_shipping(checkout_info, lines, CheckoutErrorCode)
if shipping_address:
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 not shipping_address.validation_skipped:
+ 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()
@@ -212,14 +213,15 @@ class CheckoutComplete(BaseMutation, I18nMixin):
}
)
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 not billing_address.validation_skipped:
+ 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()
diff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.py
index ead0c8656f..fc3026d7f3 100644
--- a/saleor/graphql/checkout/mutations/checkout_create.py
+++ b/saleor/graphql/checkout/mutations/checkout_create.py
@@ -147,10 +147,16 @@ class CheckoutCreateInput(BaseInputObjectType):
description=(
"The mailing address to where the checkout will be shipped. "
"Note: the address will be ignored if the checkout "
- "doesn't contain shippable items."
+ "doesn't contain shippable items. `skipValidation` requires "
+ "HANDLE_CHECKOUTS and AUTHENTICATED_APP permissions."
+ )
+ )
+ billing_address = AddressInput(
+ description=(
+ "Billing address of the customer. `skipValidation` requires "
+ "HANDLE_CHECKOUTS and AUTHENTICATED_APP permissions."
)
)
- billing_address = AddressInput(description="Billing address of the customer.")
language_code = graphene.Argument(
LanguageCodeEnum, required=False, description="Checkout language code."
)
@@ -182,7 +188,10 @@ class CheckoutCreate(ModelMutation, I18nMixin):
)
class Meta:
- description = "Create a new checkout."
+ description = (
+ "Create a new checkout.\n\n`skipValidation` field requires "
+ "HANDLE_CHECKOUTS and AUTHENTICATED_APP permissions."
+ )
doc_category = DOC_CATEGORY_CHECKOUT
model = models.Checkout
object_type = Checkout
@@ -239,7 +248,9 @@ class CheckoutCreate(ModelMutation, I18nMixin):
return variants, checkout_lines_data
@classmethod
- def retrieve_shipping_address(cls, user, data: dict) -> Optional["Address"]:
+ def retrieve_shipping_address(
+ cls, user, data: dict, info: ResolveInfo
+ ) -> Optional["Address"]:
address_validation_rules = data.get("validation_rules", {}).get(
"shipping_address", {}
)
@@ -254,11 +265,14 @@ class CheckoutCreate(ModelMutation, I18nMixin):
enable_normalization=address_validation_rules.get(
"enable_fields_normalization", True
),
+ info=info,
)
return None
@classmethod
- def retrieve_billing_address(cls, user, data: dict) -> Optional["Address"]:
+ def retrieve_billing_address(
+ cls, user, data: dict, info: ResolveInfo
+ ) -> Optional["Address"]:
address_validation_rules = data.get("validation_rules", {}).get(
"billing_address", {}
)
@@ -273,6 +287,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):
enable_normalization=address_validation_rules.get(
"enable_fields_normalization", True
),
+ info=info,
)
return None
@@ -294,8 +309,8 @@ class CheckoutCreate(ModelMutation, I18nMixin):
if data.get("billing_address")
else None
)
- shipping_address = cls.retrieve_shipping_address(user, data)
- billing_address = cls.retrieve_billing_address(user, data)
+ shipping_address = cls.retrieve_shipping_address(user, data, info)
+ billing_address = cls.retrieve_billing_address(user, data, info)
if shipping_address:
cls.update_metadata(shipping_address, shipping_address_metadata)
if billing_address:
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 14f075bbf7..ec8f9bea45 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
@@ -4,7 +4,7 @@ import pytest
from .....checkout.utils import invalidate_checkout
from ....core.utils import to_global_id_or_none
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE = """
mutation checkoutBillingAddressUpdate(
@@ -64,6 +64,7 @@ def test_checkout_billing_address_update_by_id(
assert checkout.billing_address.postal_code == billing_address["postalCode"]
assert checkout.billing_address.country == billing_address["country"]
assert checkout.billing_address.city == billing_address["city"].upper()
+ assert checkout.billing_address.validation_skipped is False
def test_checkout_billing_address_update_by_id_without_required_fields(
@@ -582,3 +583,58 @@ def test_with_active_problems_flow(
# then
assert not content["data"]["checkoutBillingAddressUpdate"]["errors"]
+
+
+def test_checkout_billing_address_skip_validation_by_customer(
+ checkout_with_items, user_api_client, graphql_address_data_skipped_validation
+):
+ # given
+ address_data = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "billingAddress": address_data,
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_checkout_billing_address_skip_validation_by_app(
+ checkout_with_items,
+ app_api_client,
+ graphql_address_data_skipped_validation,
+ permission_handle_checkouts,
+):
+ # given
+ checkout = checkout_with_items
+ address_data = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "billingAddress": address_data,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["checkoutBillingAddressUpdate"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ assert checkout.billing_address.postal_code == invalid_postal_code
+ assert checkout.billing_address.validation_skipped is True
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
index 8bf41182b5..fea7af4ef9 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
@@ -4640,3 +4640,57 @@ def test_checkout_complete_line_deleted_in_the_meantime(
assert not data["errors"]
assert Order.objects.count() == orders_count + 1
assert not Checkout.objects.filter(pk=checkout.pk).exists()
+
+
+def test_checkout_complete_with_invalid_address(
+ api_client, checkout_with_item, address, payment_dummy, shipping_method
+):
+ """Check if checkout can be completed with invalid address.
+
+ After introducing `AddressInput.skip_validation`, Saleor may have invalid address
+ stored in database.
+ """
+ # given
+ checkout = checkout_with_item
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "redirectUrl": "https://www.example.com",
+ }
+
+ invalid_postal_code = "invalid postal code"
+ address.postal_code = invalid_postal_code
+ address.validation_skipped = True
+ address.save(update_fields=["validation_skipped", "postal_code"])
+
+ checkout.billing_address = address
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.save(
+ update_fields=["billing_address", "shipping_address", "shipping_method"]
+ )
+
+ # Create a dummy payment to charge
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ total = calculations.checkout_total(
+ manager=manager, checkout_info=checkout_info, lines=lines, address=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()
+
+ # when
+ response = api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+ content = get_graphql_content(response)["data"]["checkoutComplete"]
+
+ # then
+ assert not content["errors"]
+ order = Order.objects.get(checkout_token=checkout.token)
+ assert order.shipping_address.postal_code == invalid_postal_code
+ assert order.billing_address.postal_code == invalid_postal_code
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
index c51c3c8f8e..c48d7a3503 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
@@ -3827,3 +3827,64 @@ def test_checkout_complete_line_deleted_in_the_meantime(
assert not data["errors"]
assert Order.objects.count() == 1
assert not Checkout.objects.filter(pk=checkout.pk).exists()
+
+
+def test_checkout_complete_with_invalid_address(
+ user_api_client,
+ checkout_with_item,
+ transaction_item_generator,
+ address,
+ shipping_method,
+):
+ """Check if checkout can be completed with invalid address.
+
+ After introducing `AddressInput.skip_validation`, Saleor may have invalid address
+ stored in database.
+ """
+ # given
+ checkout = checkout_with_item
+
+ invalid_postal_code = "invalid postal code"
+ address.postal_code = invalid_postal_code
+ address.validation_skipped = True
+ address.save(update_fields=["validation_skipped", "postal_code"])
+
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.tax_exemption = True
+ checkout.save()
+
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.allow_unpaid_orders = True
+ channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
+ channel.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ 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
+ )
+
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=total.gross,
+ checkout_has_lines=bool(lines),
+ )
+
+ 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)
+
+ order = Order.objects.get()
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+ assert order.shipping_address.postal_code == invalid_postal_code
+ assert order.billing_address.postal_code == invalid_postal_code
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
index 8db4f831aa..d34c0f8a4b 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
@@ -106,35 +106,6 @@ def test_checkout_create_with_default_channel(
)
-def test_checkout_create_with_variant_without_sku(
- api_client, stock, graphql_address_data, channel_USD
-):
- variant = stock.product_variant
- variant.sku = None
- variant.save()
- variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
- test_email = "[email protected]"
- shipping_address = graphql_address_data
- quantity = 1
- variables = {
- "checkoutInput": {
- "channel": channel_USD.slug,
- "lines": [{"quantity": quantity, "variantId": variant_id}],
- "email": test_email,
- "shippingAddress": shipping_address,
- }
- }
- assert not Checkout.objects.exists()
- response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
- get_graphql_content(response)["data"]["checkoutCreate"]
-
- new_checkout = Checkout.objects.first()
- lines, _ = fetch_checkout_lines(new_checkout)
- assert new_checkout.channel == channel_USD
- assert calculate_checkout_quantity(lines) == quantity
- assert lines[0].variant.sku is None
-
-
def test_checkout_create_with_inactive_channel(
api_client, stock, graphql_address_data, channel_USD
):
@@ -439,6 +410,35 @@ def test_checkout_create_with_multiple_channel_with_channel_slug(
assert checkout_line.quantity == 1
+def test_checkout_create_with_variant_without_sku(
+ api_client, stock, graphql_address_data, channel_USD
+):
+ variant = stock.product_variant
+ variant.sku = None
+ variant.save()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ quantity = 1
+ variables = {
+ "checkoutInput": {
+ "channel": channel_USD.slug,
+ "lines": [{"quantity": quantity, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+ assert not Checkout.objects.exists()
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+ get_graphql_content(response)["data"]["checkoutCreate"]
+
+ new_checkout = Checkout.objects.first()
+ lines, _ = fetch_checkout_lines(new_checkout)
+ assert new_checkout.channel == channel_USD
+ assert calculate_checkout_quantity(lines) == quantity
+ assert lines[0].variant.sku is None
+
+
def test_checkout_create_with_existing_checkout_in_other_channel(
user_api_client, stock, graphql_address_data, channel_USD, user_checkout_PLN
):
@@ -547,6 +547,9 @@ def test_checkout_create(api_client, stock, graphql_address_data, channel_USD):
assert new_checkout.shipping_address.metadata == {"shipping": "shipping_value"}
assert new_checkout.billing_address.metadata == {"billing": "billing_value"}
+ assert new_checkout.billing_address.validation_skipped is False
+ assert new_checkout.shipping_address.validation_skipped is False
+
def test_checkout_create_with_custom_price(
app_api_client,
@@ -2404,3 +2407,161 @@ def test_checkout_create_with_disabled_fields_normalization_raises_required_erro
assert len(data["errors"]) == 1
assert data["errors"][0]["field"] == "postalCode"
assert data["errors"][0]["code"] == "REQUIRED"
+
+
+MUTATION_CHECKOUT_CREATE_WITH_ADDRESSES = """
+ mutation createCheckout($checkoutInput: CheckoutCreateInput!) {
+ checkoutCreate(input: $checkoutInput) {
+ checkout {
+ id
+ shippingAddress {
+ postalCode
+ }
+ billingAddress {
+ postalCode
+ }
+ }
+ errors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
+def test_checkout_create_skip_validation_shipping_address_by_customer(
+ api_client, stock, graphql_address_data_skipped_validation, channel_USD
+):
+ # given
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ shipping_address = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ shipping_address["postalCode"] = invalid_postal_code
+
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": "[email protected]",
+ "shippingAddress": shipping_address,
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_CHECKOUT_CREATE_WITH_ADDRESSES, variables
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_checkout_create_skip_validation_shipping_address_by_app(
+ app_api_client,
+ stock,
+ graphql_address_data_skipped_validation,
+ channel_USD,
+ permission_handle_checkouts,
+):
+ # given
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ shipping_address = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ shipping_address["postalCode"] = invalid_postal_code
+
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": "[email protected]",
+ "shippingAddress": shipping_address,
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_CHECKOUT_CREATE_WITH_ADDRESSES,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["checkoutCreate"]
+ assert not data["errors"]
+ assert data["checkout"]["shippingAddress"]["postalCode"] == invalid_postal_code
+ new_checkout = Checkout.objects.first()
+ assert new_checkout.shipping_address.postal_code == invalid_postal_code
+ assert new_checkout.shipping_address.validation_skipped is True
+
+
+def test_checkout_create_skip_validation_billing_address_by_customer(
+ api_client, stock, graphql_address_data_skipped_validation, channel_USD
+):
+ # given
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ billing_address = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ billing_address["postalCode"] = invalid_postal_code
+
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": "[email protected]",
+ "billingAddress": billing_address,
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_CHECKOUT_CREATE_WITH_ADDRESSES, variables
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_checkout_create_skip_validation_billing_address_by_app(
+ app_api_client,
+ stock,
+ graphql_address_data_skipped_validation,
+ channel_USD,
+ permission_handle_checkouts,
+):
+ # given
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ billing_address = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ billing_address["postalCode"] = invalid_postal_code
+
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": "[email protected]",
+ "billingAddress": billing_address,
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_CHECKOUT_CREATE_WITH_ADDRESSES,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["checkoutCreate"]
+ assert not data["errors"]
+ assert data["checkout"]["billingAddress"]["postalCode"] == invalid_postal_code
+ new_checkout = Checkout.objects.first()
+ assert new_checkout.billing_address.postal_code == invalid_postal_code
+ assert new_checkout.billing_address.validation_skipped is True
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 ee3eadd1ca..7b78c2a98d 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
@@ -17,7 +17,7 @@ from .....plugins.base_plugin import ExcludedShippingMethod
from .....plugins.manager import get_plugins_manager
from .....warehouse.models import Reservation, Stock
from ....core.utils import to_global_id_or_none
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
from ...mutations.utils import update_checkout_shipping_method_if_invalid
MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE = """
@@ -132,6 +132,7 @@ def test_checkout_shipping_address_with_metadata_update(
assert checkout.shipping_address.postal_code == shipping_address["postalCode"]
assert checkout.shipping_address.country == shipping_address["country"]
assert checkout.shipping_address.city == shipping_address["city"].upper()
+ assert checkout.shipping_address.validation_skipped is False
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
@@ -1015,3 +1016,58 @@ def test_checkout_shipping_address_update_with_collection_point_already_set(
errors = data["errors"]
assert errors[0]["code"] == CheckoutErrorCode.SHIPPING_CHANGE_FORBIDDEN.name
assert errors[0]["field"] == "shippingAddress"
+
+
+def test_checkout_shipping_address_skip_validation_by_customer(
+ checkout_with_items, user_api_client, graphql_address_data_skipped_validation
+):
+ # given
+ address_data = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "shippingAddress": address_data,
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_checkout_shipping_address_skip_validation_by_app(
+ checkout_with_items,
+ app_api_client,
+ graphql_address_data_skipped_validation,
+ permission_handle_checkouts,
+):
+ # given
+ checkout = checkout_with_items
+ address_data = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_items),
+ "shippingAddress": address_data,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["checkoutShippingAddressUpdate"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ assert checkout.shipping_address.postal_code == invalid_postal_code
+ assert checkout.shipping_address.validation_skipped is True
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index 5e5e3f4674..13557f7952 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -173,6 +173,7 @@ class BaseMutation(graphene.Mutation):
support_private_meta_field=False,
auto_webhook_events_message: bool = True,
webhook_events_info: Optional[list[WebhookEventInfo]] = None,
+ exclude=None,
**options,
):
if not _meta:
@@ -186,6 +187,9 @@ class BaseMutation(graphene.Mutation):
cls._validate_permissions(permissions)
+ if exclude is None:
+ exclude = []
+
_meta.auto_permission_message = auto_permission_message
_meta.error_type_class = error_type_class
_meta.error_type_field = error_type_field
@@ -193,6 +197,7 @@ class BaseMutation(graphene.Mutation):
_meta.permissions = permissions
_meta.support_meta_field = support_meta_field
_meta.support_private_meta_field = support_private_meta_field
+ _meta.exclude = exclude
if permissions and auto_permission_message:
permissions_msg = message_one_of_permissions_required(permissions)
@@ -651,7 +656,6 @@ class ModelMutation(BaseMutation):
cls,
arguments=None,
model=None,
- exclude=None,
return_field_name=None,
object_type=None,
_meta=None,
@@ -666,9 +670,6 @@ class ModelMutation(BaseMutation):
if "doc_category" not in options and doc_category_key in DOC_CATEGORY_MAP:
options["doc_category"] = DOC_CATEGORY_MAP[doc_category_key]
- if exclude is None:
- exclude = []
-
if not return_field_name:
return_field_name = get_model_name(model)
if arguments is None:
@@ -677,7 +678,6 @@ class ModelMutation(BaseMutation):
_meta.model = model
_meta.object_type = object_type
_meta.return_field_name = return_field_name
- _meta.exclude = exclude
super().__init_subclass_with_meta__(_meta=_meta, **options)
model_type = cls.get_type_for_model()
diff --git a/saleor/graphql/order/bulk_mutations/order_bulk_create.py b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
index 87a370bcca..f28d9d0d1b 100644
--- a/saleor/graphql/order/bulk_mutations/order_bulk_create.py
+++ b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
@@ -929,6 +929,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
order_input: dict[str, Any],
order_data: OrderBulkCreateData,
object_storage: dict[str, Any],
+ info: ResolveInfo,
):
"""Get all instances of objects needed to create an order."""
user = cls.get_instance_with_errors(
@@ -966,7 +967,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
metadata_list = billing_address_input.pop("metadata", None)
private_metadata_list = billing_address_input.pop("private_metadata", None)
try:
- billing_address = cls.validate_address(billing_address_input)
+ billing_address = cls.validate_address(billing_address_input, info=info)
cls.validate_and_update_metadata(
billing_address, metadata_list, private_metadata_list
)
@@ -985,7 +986,9 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
metadata_list = shipping_address_input.pop("metadata", None)
private_metadata_list = shipping_address_input.pop("private_metadata", None)
try:
- shipping_address = cls.validate_address(shipping_address_input)
+ shipping_address = cls.validate_address(
+ shipping_address_input, info=info
+ )
cls.validate_and_update_metadata(
shipping_address, metadata_list, private_metadata_list
)
@@ -1861,7 +1864,10 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def create_single_order(
- cls, order_input, object_storage: dict[str, Any]
+ cls,
+ order_input,
+ object_storage: dict[str, Any],
+ info: ResolveInfo,
) -> OrderBulkCreateData:
order_data = OrderBulkCreateData()
cls.validate_order_input(order_input, order_data, object_storage)
@@ -1873,6 +1879,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
order_input=order_input,
order_data=order_data,
object_storage=object_storage,
+ info=info,
)
is_shipping_required = cls.is_shipping_required(order_input)
@@ -2238,7 +2245,9 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
# - key for shipping prices: "shipping_price.{shipping_method_id}"
object_storage: dict[str, Any] = cls.get_all_instances(orders_input)
for order_input in orders_input:
- orders_data.append(cls.create_single_order(order_input, object_storage))
+ orders_data.append(
+ cls.create_single_order(order_input, object_storage, info)
+ )
error_policy = data.get("error_policy") or ErrorPolicy.REJECT_EVERYTHING
stock_update_policy = (
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
index fe860ed265..ce7a610e27 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
@@ -1451,3 +1451,42 @@ def test_draft_order_complete_with_catalogue_and_gift_discount(
)
assert order_data["total"]["net"]["amount"] == total
assert total == line_2_total + line_1_total + order.base_shipping_price_amount
+
+
+def test_draft_order_complete_with_invalid_address(
+ staff_api_client,
+ permission_group_manage_orders,
+ staff_user,
+ draft_order,
+ address,
+):
+ """Check if draft order can be completed with invalid address.
+
+ After introducing `AddressInput.skip_validation`, Saleor may have invalid address
+ stored in database.
+ """
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = draft_order
+ wrong_postal_code = "wrong postal code"
+ address.postal_code = wrong_postal_code
+
+ order.shipping_address = address.get_copy()
+ order.billing_address = address.get_copy()
+ order.save(update_fields=["shipping_address", "billing_address"])
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["draftOrderComplete"]["order"]
+ order.refresh_from_db()
+
+ assert data["status"] == order.status.upper()
+ assert data["origin"] == OrderOrigin.DRAFT.upper()
+ assert order.shipping_address.postal_code == wrong_postal_code
+ assert order.billing_address.postal_code == wrong_postal_code
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
index c9a55c243d..543c1e9782 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -242,6 +242,8 @@ def test_draft_order_create_with_voucher(
assert order.shipping_address
assert order.billing_address.metadata == stored_metadata
assert order.shipping_address.metadata == stored_metadata
+ assert order.billing_address.validation_skipped is False
+ assert order.shipping_address.validation_skipped is False
assert order.search_vector
assert order.external_reference == external_reference
shipping_total = shipping_method.channel_listings.get(
@@ -2163,6 +2165,58 @@ def test_draft_order_create_invalid_shipping_address(
assert errors[0]["addressType"] == AddressType.SHIPPING.upper()
+def test_draft_order_create_invalid_address_skip_validation(
+ staff_api_client,
+ permission_group_manage_orders,
+ customer_user,
+ shipping_method,
+ variant,
+ channel_USD,
+ graphql_address_data_skipped_validation,
+):
+ # given
+ query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variant_list = [{"variantId": variant_id, "quantity": 2}]
+
+ address_data = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ redirect_url = "https://www.example.com"
+
+ variables = {
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ "billingAddress": address_data,
+ "shippingAddress": address_data,
+ "shippingMethod": shipping_id,
+ "channelId": channel_id,
+ "redirectUrl": redirect_url,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["draftOrderCreate"]
+ assert not data["errors"]
+ assert data["order"]["shippingAddress"]["postalCode"] == invalid_postal_code
+ assert data["order"]["billingAddress"]["postalCode"] == invalid_postal_code
+ order = Order.objects.last()
+ assert order.shipping_address.postal_code == invalid_postal_code
+ assert order.shipping_address.validation_skipped is True
+ assert order.billing_address.postal_code == invalid_postal_code
+ assert order.billing_address.validation_skipped is True
+
+
@patch("saleor.order.calculations.fetch_order_prices_if_expired")
def test_draft_order_create_price_recalculation(
mock_fetch_order_prices_if_expired,
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_update.py b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
index 88eb7fa835..25e96ca74a 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
@@ -236,6 +236,8 @@ def test_draft_order_update_with_voucher(
order.refresh_from_db()
assert order.billing_address.metadata == stored_metadata
assert order.shipping_address.metadata == stored_metadata
+ assert order.billing_address.validation_skipped is False
+ assert order.shipping_address.validation_skipped is False
assert order.voucher_code == voucher.code
assert order.customer_note == customer_note
assert order.search_vector
@@ -864,6 +866,45 @@ def test_draft_order_update_invalid_address(
assert {error["field"] for error in data["errors"]} == {"postalCode"}
+def test_draft_order_update_invalid_address_skip_validation(
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ graphql_address_data_skipped_validation,
+):
+ # given
+ order = draft_order
+ address_data = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ query = DRAFT_ORDER_UPDATE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "shippingAddress": address_data,
+ "billingAddress": address_data,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["draftOrderUpdate"]
+ assert not data["errors"]
+ assert data["order"]["shippingAddress"]["postalCode"] == invalid_postal_code
+ assert data["order"]["billingAddress"]["postalCode"] == invalid_postal_code
+ order.refresh_from_db()
+ assert order.shipping_address.postal_code == invalid_postal_code
+ assert order.shipping_address.validation_skipped is True
+ assert order.billing_address.postal_code == invalid_postal_code
+ assert order.billing_address.validation_skipped is True
+
+
def test_draft_order_update_by_user_no_channel_access(
staff_api_client,
permission_group_all_perms_channel_USD_only,
diff --git a/saleor/graphql/order/tests/mutations/test_order_bulk_create.py b/saleor/graphql/order/tests/mutations/test_order_bulk_create.py
index 093dd45f44..e3da0e3646 100644
--- a/saleor/graphql/order/tests/mutations/test_order_bulk_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_bulk_create.py
@@ -594,6 +594,8 @@ def test_order_bulk_create(
assert db_order.private_metadata["pmd key"] == "pmd value"
assert db_order.total_authorized_amount == Decimal("10")
assert db_order.authorize_status == OrderAuthorizeStatus.PARTIAL.lower()
+ assert db_order.shipping_address.validation_skipped is False
+ assert db_order.billing_address.validation_skipped is False
order_line = order["lines"][0]
assert order_line["variant"]["id"] == graphene.Node.to_global_id(
@@ -3714,3 +3716,43 @@ def test_order_bulk_create_error_invalid_status(
assert error["message"] == "Invalid order status."
assert error["path"] == "status"
assert error["code"] == OrderBulkCreateErrorCode.INVALID.name
+
+
+def test_order_bulk_create_skip_address_validation(
+ staff_api_client,
+ permission_manage_orders,
+ permission_manage_orders_import,
+ order_bulk_input,
+ graphql_address_data_skipped_validation,
+):
+ # given
+ order = order_bulk_input
+ invalid_postal_code = "invalid_postal_code"
+ address_data = graphql_address_data_skipped_validation
+ address_data["postalCode"] = invalid_postal_code
+ order["billingAddress"] = address_data
+ order["shippingAddress"] = address_data
+
+ staff_api_client.user.user_permissions.add(
+ permission_manage_orders_import,
+ permission_manage_orders,
+ )
+ variables = {
+ "orders": [order],
+ "stockUpdatePolicy": StockUpdatePolicyEnum.SKIP.name,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_BULK_CREATE, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderBulkCreate"]["results"][0]
+ assert not data["errors"]
+ assert data["order"]["shippingAddress"]["postalCode"] == invalid_postal_code
+ assert data["order"]["billingAddress"]["postalCode"] == invalid_postal_code
+ db_order = Order.objects.last()
+ assert db_order.shipping_address.postal_code == invalid_postal_code
+ assert db_order.shipping_address.validation_skipped is True
+ assert db_order.billing_address.postal_code == invalid_postal_code
+ assert db_order.billing_address.validation_skipped is True
diff --git a/saleor/graphql/order/tests/mutations/test_order_confirm.py b/saleor/graphql/order/tests/mutations/test_order_confirm.py
index c67f81326f..54124f6ac0 100644
--- a/saleor/graphql/order/tests/mutations/test_order_confirm.py
+++ b/saleor/graphql/order/tests/mutations/test_order_confirm.py
@@ -376,3 +376,56 @@ def test_order_confirm_by_app(
site_settings,
payment_txn_preauth.gateway,
)
+
+
+@patch("saleor.order.actions.handle_fully_paid_order")
+@patch("saleor.plugins.manager.PluginsManager.notify")
+@patch("saleor.payment.gateway.capture")
+def test_order_confirm_skip_address_validation(
+ capture_mock,
+ mocked_notify,
+ handle_fully_paid_order_mock,
+ staff_api_client,
+ order_unconfirmed,
+ permission_group_manage_orders,
+ payment_txn_preauth,
+ site_settings,
+ graphql_address_data,
+):
+ # given
+ order = order_unconfirmed
+ payment_txn_preauth.order = order
+ payment_txn_preauth.captured_amount = order.total.gross.amount
+ payment_txn_preauth.total = order.total.gross.amount
+ payment_txn_preauth.save(update_fields=["order", "captured_amount", "total"])
+
+ address_data = graphql_address_data
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+
+ shipping_address = order.shipping_address
+ shipping_address.postal_code = invalid_postal_code
+ shipping_address.save(update_fields=["postal_code"])
+ billing_address = order.billing_address
+ billing_address.postal_code = invalid_postal_code
+ billing_address.save(update_fields=["postal_code"])
+
+ order.total_charged = order.total.gross
+ order.save(update_fields=["total_charged_amount"])
+ updates_amounts_for_order(order)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(
+ ORDER_CONFIRM_MUTATION,
+ {"id": graphene.Node.to_global_id("Order", order.id)},
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderConfirm"]
+ assert not data["errors"]
+ order.refresh_from_db()
+ assert order.shipping_address.postal_code == invalid_postal_code
+ assert order.billing_address.postal_code == invalid_postal_code
+ assert order.status == OrderStatus.UNFULFILLED
diff --git a/saleor/graphql/order/tests/mutations/test_order_update.py b/saleor/graphql/order/tests/mutations/test_order_update.py
index b971e5e25e..dca2b87b13 100644
--- a/saleor/graphql/order/tests/mutations/test_order_update.py
+++ b/saleor/graphql/order/tests/mutations/test_order_update.py
@@ -75,6 +75,8 @@ def test_order_update(
order.billing_address.refresh_from_db()
assert order.shipping_address.first_name == graphql_address_data["firstName"]
assert order.billing_address.last_name == graphql_address_data["lastName"]
+ assert order.shipping_address.validation_skipped is False
+ assert order.billing_address.validation_skipped is False
assert order.user_email == email
assert order.user is None
assert order.status == OrderStatus.UNFULFILLED
@@ -450,3 +452,61 @@ def test_order_update_with_non_unique_external_reference(
assert error["field"] == "externalReference"
assert error["code"] == OrderErrorCode.UNIQUE.name
assert error["message"] == "Order with this External reference already exists."
+
+
+ORDER_UPDATE_MUTATION_WITH_ADDRESS = """
+ mutation orderUpdate($id: ID!, $address: AddressInput) {
+ orderUpdate(
+ id: $id,
+ input: {
+ shippingAddress: $address,
+ billingAddress: $address
+ }
+ ) {
+ errors {
+ field
+ code
+ }
+ order {
+ shippingAddress {
+ postalCode
+ }
+ billingAddress {
+ postalCode
+ }
+ }
+ }
+ }
+"""
+
+
+def test_order_update_invalid_address_skip_validation(
+ staff_api_client,
+ permission_group_manage_orders,
+ order,
+ graphql_address_data_skipped_validation,
+):
+ # given
+ address_data = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ query = ORDER_UPDATE_MUTATION_WITH_ADDRESS
+ order_id = graphene.Node.to_global_id("Order", order.id)
+
+ variables = {"id": order_id, "address": address_data}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderUpdate"]
+ assert not data["errors"]
+ assert data["order"]["shippingAddress"]["postalCode"] == invalid_postal_code
+ assert data["order"]["billingAddress"]["postalCode"] == invalid_postal_code
+ order.refresh_from_db()
+ assert order.shipping_address.postal_code == invalid_postal_code
+ assert order.shipping_address.validation_skipped is True
+ assert order.billing_address.postal_code == invalid_postal_code
+ assert order.billing_address.validation_skipped is True
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index ed04970d6b..9da51a949a 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -7983,6 +7983,15 @@ input AddressInput {
Added in Saleor 3.15.
"""
metadata: [MetadataInput!]
+
+ """
+ Determine if the address should be validated. By default, Saleor accepts only address inputs matching ruleset from [Google Address Data]{https://chromium-i18n.appspot.com/ssl-address), using [i18naddress](https://github.com/mirumee/google-i18n-address) library. Some mutations may require additional permissions to use the the field. More info about permissions can be found in relevant mutation.
+
+ Added in Saleor 3.19.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ skipValidation: Boolean = false
}
input MetadataInput {
@@ -18932,6 +18941,8 @@ type Mutation {
"""
Create a new checkout.
+ `skipValidation` field requires HANDLE_CHECKOUTS and AUTHENTICATED_APP permissions.
+
Triggers the following webhook events:
- CHECKOUT_CREATED (async): A checkout was created.
"""
@@ -20121,15 +20132,22 @@ type Mutation {
): ConfirmEmailChange @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_UPDATED, NOTIFY_USER, ACCOUNT_EMAIL_CHANGED], syncEvents: [])
"""
- Create a new address for the customer.
+ Create a new address for the customer.
- Requires one of the following permissions: AUTHENTICATED_USER.
+ Requires one of following set of permissions: AUTHENTICATED_USER or AUTHENTICATED_APP + IMPERSONATE_USER.
Triggers the following webhook events:
- CUSTOMER_UPDATED (async): A customer account was updated.
- ADDRESS_CREATED (async): An address was created.
"""
accountAddressCreate(
+ """
+ ID of customer the application is impersonating. The field can be used and is required by apps only. Requires IMPERSONATE_USER and AUTHENTICATED_APP permission.
+
+ Added in Saleor 3.19.
+ """
+ customerId: ID
+
"""Fields required to create address."""
input: AddressInput!
@@ -20194,15 +20212,22 @@ type Mutation {
): AccountRegister @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_CREATED, NOTIFY_USER, ACCOUNT_CONFIRMATION_REQUESTED], syncEvents: [])
"""
- Updates the account of the logged-in user.
+ Updates the account of the logged-in user.
- Requires one of the following permissions: AUTHENTICATED_USER.
+ Requires one of following set of permissions: AUTHENTICATED_USER or AUTHENTICATED_APP + IMPERSONATE_USER.
Triggers the following webhook events:
- CUSTOMER_UPDATED (async): A customer account was updated.
- CUSTOMER_METADATA_UPDATED (async): Optionally called when customer's metadata was updated.
"""
accountUpdate(
+ """
+ ID of customer the application is impersonating. The field can be used and is required by apps only. Requires IMPERSONATE_USER and AUTHENTICATED_APP permission.
+
+ Added in Saleor 3.19.
+ """
+ customerId: ID
+
"""Fields required to update the account of the logged-in user."""
input: AccountInput!
): AccountUpdate @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_UPDATED, CUSTOMER_METADATA_UPDATED], syncEvents: [])
@@ -29244,6 +29269,8 @@ type CheckoutComplete @doc(category: "Checkout") @webhookEventsInfo(asyncEvents:
"""
Create a new checkout.
+`skipValidation` field requires HANDLE_CHECKOUTS and AUTHENTICATED_APP permissions.
+
Triggers the following webhook events:
- CHECKOUT_CREATED (async): A checkout was created.
"""
@@ -29270,11 +29297,13 @@ input CheckoutCreateInput @doc(category: "Checkout") {
email: String
"""
- The mailing address to where the checkout will be shipped. Note: the address will be ignored if the checkout doesn't contain shippable items.
+ The mailing address to where the checkout will be shipped. Note: the address will be ignored if the checkout doesn't contain shippable items. `skipValidation` requires HANDLE_CHECKOUTS and AUTHENTICATED_APP permissions.
"""
shippingAddress: AddressInput
- """Billing address of the customer."""
+ """
+ Billing address of the customer. `skipValidation` requires HANDLE_CHECKOUTS and AUTHENTICATED_APP permissions.
+ """
billingAddress: AddressInput
"""Checkout language code."""
@@ -31445,9 +31474,9 @@ type ConfirmEmailChange @doc(category: "Users") @webhookEventsInfo(asyncEvents:
}
"""
-Create a new address for the customer.
+Create a new address for the customer.
-Requires one of the following permissions: AUTHENTICATED_USER.
+Requires one of following set of permissions: AUTHENTICATED_USER or AUTHENTICATED_APP + IMPERSONATE_USER.
Triggers the following webhook events:
- CUSTOMER_UPDATED (async): A customer account was updated.
@@ -31552,9 +31581,9 @@ input AccountRegisterInput @doc(category: "Users") {
}
"""
-Updates the account of the logged-in user.
+Updates the account of the logged-in user.
-Requires one of the following permissions: AUTHENTICATED_USER.
+Requires one of following set of permissions: AUTHENTICATED_USER or AUTHENTICATED_APP + IMPERSONATE_USER.
Triggers the following webhook events:
- CUSTOMER_UPDATED (async): A customer account was updated.
diff --git a/saleor/graphql/shop/resolvers.py b/saleor/graphql/shop/resolvers.py
index ff0a7b4849..25c2bed015 100644
--- a/saleor/graphql/shop/resolvers.py
+++ b/saleor/graphql/shop/resolvers.py
@@ -21,6 +21,7 @@ def resolve_available_shipping_methods(info, *, channel_slug: str, address):
available = available.filter(
shipping_zone__countries__contains=address.country,
)
+ address.pop("skip_validation", None)
available = filter_shipping_methods_by_postal_code_rules(
available, Address(**address)
)
diff --git a/saleor/graphql/shop/tests/mutations/test_shop_address_update.py b/saleor/graphql/shop/tests/mutations/test_shop_address_update.py
index 026737e185..5efa7c1621 100644
--- a/saleor/graphql/shop/tests/mutations/test_shop_address_update.py
+++ b/saleor/graphql/shop/tests/mutations/test_shop_address_update.py
@@ -47,6 +47,7 @@ def test_mutation_update_company_address(
assert site_settings.company_address.city == address.city
assert site_settings.company_address.country.code == address.country.code
assert site_settings.company_address.metadata == {"meta": "data"}
+ assert site_settings.company_address.validation_skipped is False
def test_mutation_update_company_address_remove_address(
@@ -92,3 +93,29 @@ def test_mutation_update_company_address_remove_address_without_address(
site_settings.refresh_from_db()
assert not site_settings.company_address
+
+
+def test_shop_address_update_skip_validation(
+ staff_api_client,
+ graphql_address_data_skipped_validation,
+ permission_manage_settings,
+ site_settings,
+):
+ # given
+ query = MUTATION_SHOP_ADDRESS_UPDATE
+ address_data = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+ variables = {"input": address_data}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_settings]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ assert "errors" not in content["data"]
+ site_settings.refresh_from_db()
+ assert site_settings.company_address.postal_code == invalid_postal_code
+ assert site_settings.company_address.validation_skipped is True
diff --git a/saleor/graphql/warehouse/mutations/base.py b/saleor/graphql/warehouse/mutations/base.py
index b41498668c..cab3badbf5 100644
--- a/saleor/graphql/warehouse/mutations/base.py
+++ b/saleor/graphql/warehouse/mutations/base.py
@@ -59,8 +59,3 @@ class WarehouseMixin:
},
)
return cleaned_input
-
- @classmethod
- def construct_instance(cls, instance, cleaned_data):
- cleaned_data["address"] = cls.prepare_address(cleaned_data, instance) # type: ignore[attr-defined] # mixing # noqa: E501
- return super().construct_instance(instance, cleaned_data) # type: ignore[misc] # mixing # noqa: E501
diff --git a/saleor/graphql/warehouse/mutations/warehouse_create.py b/saleor/graphql/warehouse/mutations/warehouse_create.py
index 38a59cff45..4aa2e6bcbf 100644
--- a/saleor/graphql/warehouse/mutations/warehouse_create.py
+++ b/saleor/graphql/warehouse/mutations/warehouse_create.py
@@ -25,17 +25,25 @@ class WarehouseCreate(AddressMetadataMixin, WarehouseMixin, ModelMutation, I18nM
error_type_field = "warehouse_errors"
@classmethod
- def prepare_address(cls, cleaned_data, *args):
- address_data = cleaned_data.get("address")
- address_metadata = list()
- if address_data:
- address_metadata = address_data.pop("metadata", list())
- address_form = cls.validate_address_form(cleaned_data["address"])
- if address_metadata:
- cls.update_metadata(address_form.instance, address_metadata)
- return address_form.save()
+ def prepare_address(cls, cleaned_input, info):
+ address_data = cleaned_input["address"]
+ address_instance = cls.validate_address(address_data, info=info)
+ address_instance.save()
+ return address_instance
@classmethod
def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
manager = get_plugin_manager_promise(info.context).get()
cls.call_event(manager.warehouse_created, instance)
+
+ @classmethod
+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
+ instance = cls.get_instance(info, **data)
+ data = data.get("input")
+ cleaned_input = cls.clean_input(info, instance, data)
+ cleaned_input["address"] = cls.prepare_address(cleaned_input, info)
+ instance = cls.construct_instance(instance, cleaned_input)
+ cls.clean_instance(info, instance)
+ cls.save(info, instance, cleaned_input)
+ cls.post_save_action(info, instance, cleaned_input)
+ return cls.success_response(instance)
diff --git a/saleor/graphql/warehouse/mutations/warehouse_update.py b/saleor/graphql/warehouse/mutations/warehouse_update.py
index e7aa20489e..0fd9a6880d 100644
--- a/saleor/graphql/warehouse/mutations/warehouse_update.py
+++ b/saleor/graphql/warehouse/mutations/warehouse_update.py
@@ -3,6 +3,7 @@ import graphene
from ....permission.enums import ProductPermissions
from ....warehouse import models
from ...account.i18n import I18nMixin
+from ...account.mixins import AddressMetadataMixin
from ...core import ResolveInfo
from ...core.descriptions import ADDED_IN_316
from ...core.mutations import ModelWithExtRefMutation
@@ -12,7 +13,9 @@ from ..types import Warehouse, WarehouseUpdateInput
from .base import WarehouseMixin
-class WarehouseUpdate(WarehouseMixin, ModelWithExtRefMutation):
+class WarehouseUpdate(
+ AddressMetadataMixin, WarehouseMixin, ModelWithExtRefMutation, I18nMixin
+):
class Meta:
model = models.Warehouse
object_type = Warehouse
@@ -32,20 +35,30 @@ class WarehouseUpdate(WarehouseMixin, ModelWithExtRefMutation):
)
@classmethod
- def prepare_address(cls, cleaned_data, instance):
- address_data = cleaned_data.get("address")
- address_metadata = list()
- if address_data:
- address_metadata = address_data.pop("metadata", list())
- address = instance.address
- if address_data is None:
- return address
- address_form = I18nMixin.validate_address_form(address_data, instance=address)
- if address_metadata:
- cls.update_metadata(address, address_metadata)
- return address_form.save()
+ def prepare_address(cls, cleaned_input, instance, info):
+ address_instance = instance.address
+ address_data = cleaned_input.get("address", {})
+ if not address_data:
+ return address_instance
+ address_instance = cls.validate_address(
+ address_data, info=info, instance=address_instance
+ )
+ address_instance.save()
+ return address_instance
@classmethod
def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
manager = get_plugin_manager_promise(info.context).get()
cls.call_event(manager.warehouse_updated, instance)
+
+ @classmethod
+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
+ instance = cls.get_instance(info, **data)
+ data = data.get("input")
+ cleaned_input = cls.clean_input(info, instance, data)
+ cleaned_input["address"] = cls.prepare_address(cleaned_input, instance, info)
+ instance = cls.construct_instance(instance, cleaned_input)
+ cls.clean_instance(info, instance)
+ cls.save(info, instance, cleaned_input)
+ cls.post_save_action(info, instance, cleaned_input)
+ return cls.success_response(instance)
diff --git a/saleor/graphql/warehouse/tests/mutations/test_warehouse_create.py b/saleor/graphql/warehouse/tests/mutations/test_warehouse_create.py
index ad118558ac..c4b15388a8 100644
--- a/saleor/graphql/warehouse/tests/mutations/test_warehouse_create.py
+++ b/saleor/graphql/warehouse/tests/mutations/test_warehouse_create.py
@@ -25,6 +25,7 @@ mutation createWarehouse($input: WarehouseCreateInput!) {
address {
id
countryArea
+ postalCode
metadata {
key
value
@@ -92,6 +93,7 @@ def test_mutation_create_warehouse(
assert created_warehouse["externalReference"] == warehouse.external_reference
assert created_warehouse["address"]["metadata"] == metadata
assert address.metadata == {"public": "public_value"}
+ assert address.validation_skipped is False
def test_mutation_create_warehouse_shipping_zone_provided(
@@ -389,3 +391,38 @@ def test_create_warehouse_with_address_item_from_valid_address_extension_map(
address_db = Warehouse.objects.first().address
assert address_db.country_area == cleaned_country_area
+
+
+def test_create_warehouse_invalid_address_skip_validation(
+ staff_api_client,
+ permission_manage_products,
+ graphql_address_data_skipped_validation,
+):
+ # given
+ address_data = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+ variables = {
+ "input": {
+ "name": "Test warehouse",
+ "email": "[email protected]",
+ "address": address_data,
+ }
+ }
+ assert not Address.objects.exists()
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_CREATE_WAREHOUSE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["createWarehouse"]
+ assert not data["errors"]
+ assert data["warehouse"]["address"]["postalCode"] == invalid_postal_code
+ address = Address.objects.get()
+ assert address.postal_code == invalid_postal_code
+ assert address.validation_skipped is True
diff --git a/saleor/graphql/warehouse/tests/mutations/test_warehouse_update.py b/saleor/graphql/warehouse/tests/mutations/test_warehouse_update.py
index 1723d72257..32da4efe0b 100644
--- a/saleor/graphql/warehouse/tests/mutations/test_warehouse_update.py
+++ b/saleor/graphql/warehouse/tests/mutations/test_warehouse_update.py
@@ -32,6 +32,7 @@ mutation updateWarehouse($input: WarehouseUpdateInput!, $id: ID!) {
id
streetAddress1
streetAddress2
+ postalCode
metadata {
key
value
@@ -76,6 +77,7 @@ def test_mutation_update_warehouse(
{"key": "public", "value": "public_value"}
]
assert warehouse.address.metadata == {"public": "public_value"}
+ assert warehouse.address.validation_skipped is False
assert not (warehouse.name == warehouse_old_name)
assert warehouse.name == "New name"
assert warehouse.slug == warehouse_slug
@@ -578,3 +580,40 @@ def test_update_product_external_reference_not_existing(
data["errors"][0]["message"]
== f"Couldn't resolve to a node: {external_reference}"
)
+
+
+def test_update_warehouse_invalid_address_skip_validation(
+ staff_api_client,
+ warehouse,
+ permission_manage_products,
+ graphql_address_data_skipped_validation,
+):
+ # given
+ address_data = graphql_address_data_skipped_validation
+ invalid_postal_code = "invalid_postal_code"
+ address_data["postalCode"] = invalid_postal_code
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+
+ variables = {
+ "id": warehouse_id,
+ "input": {
+ "name": warehouse.name,
+ "address": address_data,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_WAREHOUSE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["updateWarehouse"]
+ assert not data["errors"]
+ assert data["warehouse"]["address"]["postalCode"] == invalid_postal_code
+ warehouse.refresh_from_db()
+ assert warehouse.address.postal_code == invalid_postal_code
+ assert warehouse.address.validation_skipped is True
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index 1e87078bf2..fe882fe613 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -1,3 +1,4 @@
+import logging
from collections.abc import Iterable
from decimal import Decimal
from typing import Optional
@@ -29,6 +30,9 @@ from .base_calculations import apply_order_discounts, base_order_line_total
from .fetch import DraftOrderLineInfo, fetch_draft_order_lines_info
from .interface import OrderTaxedPricesData
from .models import Order, OrderLine
+from .utils import log_address_if_validation_skipped_for_order
+
+logger = logging.getLogger(__name__)
def fetch_order_prices_if_expired(
@@ -230,6 +234,8 @@ def _calculate_and_add_tax(
_recalculate_with_plugins(manager, order, lines, prices_entered_with_tax)
# Get the taxes calculated with apps and apply to order.
tax_data = manager.get_taxes_for_order(order, tax_app_identifier)
+ if not tax_data:
+ log_address_if_validation_skipped_for_order(order, logger)
_apply_tax_data(order, lines, tax_data)
else:
_call_plugin_or_tax_app(
@@ -275,6 +281,7 @@ def _call_plugin_or_tax_app(
else:
tax_data = manager.get_taxes_for_order(order, tax_app_identifier)
if tax_data is None:
+ log_address_if_validation_skipped_for_order(order, logger)
raise TaxEmptyData("Empty tax data.")
_apply_tax_data(order, lines, tax_data)
diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.py
index f2c0c78b76..859888393d 100644
--- a/saleor/order/tests/test_calculations.py
+++ b/saleor/order/tests/test_calculations.py
@@ -1239,3 +1239,46 @@ def test_fetch_order_data_calls_inactive_plugin(
# then
assert order_with_lines.tax_error == "Empty tax data."
+
+
[email protected]("tax_app_id", [None, "test.app"])
+def test_recalculate_prices_empty_tax_data_logging_address(
+ tax_app_id, draft_order, order_lines, address, caplog
+):
+ # given
+ order = draft_order
+
+ address.validation_skipped = True
+ address.postal_code = "invalid postal code"
+ address.save(update_fields=["postal_code", "validation_skipped"])
+
+ order.shipping_address = address
+ order.billing_address = address
+ order.save(update_fields=["billing_address", "shipping_address"])
+
+ order.channel.tax_configuration.tax_app_id = tax_app_id
+ order.channel.tax_configuration.save()
+
+ zero_money = zero_taxed_money(order.currency)
+ zero_prices = OrderTaxedPricesData(
+ undiscounted_price=zero_money,
+ price_with_discounts=zero_money,
+ )
+ manager_methods = {
+ "calculate_order_line_unit": Mock(side_effect=TaxError()),
+ "calculate_order_line_total": Mock(return_value=zero_prices),
+ "get_order_shipping_tax_rate": Mock(return_value=Decimal("0.00")),
+ "get_order_line_tax_rate": Mock(return_value=Decimal("0.00")),
+ "calculate_order_shipping": Mock(return_value=zero_money),
+ "get_taxes_for_order": Mock(return_value=None),
+ }
+ manager = Mock(**manager_methods)
+
+ # when
+ calculations._recalculate_prices(order, manager, order_lines)
+
+ # then
+ assert (
+ f"Fetching tax data for order with address validation skipped. "
+ f"Address ID: {address.pk}" in caplog.text
+ )
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index c16620909d..86c52f1ea7 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -1200,3 +1200,21 @@ def calculate_order_granted_refund_status(
if with_save and current_granted_refund_status != granted_refund.status:
granted_refund.save(update_fields=["status"])
+
+
+def log_address_if_validation_skipped_for_order(order: "Order", logger):
+ address = get_address_for_order_taxes(order)
+ if address and address.validation_skipped:
+ logger.warning(
+ "Fetching tax data for order with address validation skipped. "
+ "Address ID: %s",
+ address.id,
+ )
+
+
+def get_address_for_order_taxes(order: "Order"):
+ if order.collection_point_id:
+ address = order.collection_point.address # type: ignore[union-attr]
+ else:
+ address = order.shipping_address or order.billing_address
+ return address
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index 1835589b9c..932b119040 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -317,6 +317,7 @@ class AddressData:
phone: str
metadata: Optional[dict]
private_metadata: Optional[dict]
+ validation_skipped: bool = False
class StorePaymentMethodEnum(str, Enum):
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index 27c0bbc659..2e80477856 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -15,12 +15,16 @@ from requests.auth import HTTPBasicAuth
from ...account.models import Address
from ...checkout import base_calculations
-from ...checkout.utils import is_shipping_required
+from ...checkout.utils import get_address_for_checkout_taxes, is_shipping_required
from ...core.http_client import HTTPClient
from ...core.taxes import TaxError
from ...discount import DiscountType, VoucherType
from ...order import base_calculations as base_order_calculations
-from ...order.utils import get_total_order_discount_excluding_shipping
+from ...order.utils import (
+ get_address_for_order_taxes,
+ get_total_order_discount_excluding_shipping,
+ log_address_if_validation_skipped_for_order,
+)
from ...shipping.models import ShippingMethod
from ...tax.utils import get_charge_taxes_for_checkout
from ...warehouse.models import Warehouse
@@ -508,8 +512,7 @@ def generate_request_data_from_checkout(
transaction_token=None,
transaction_type=TransactionType.ORDER,
):
- shipping_address = checkout_info.delivery_method_info.shipping_address
- address = shipping_address or checkout_info.billing_address
+ address = get_address_for_checkout_taxes(checkout_info)
lines = generate_request_data_from_checkout_lines(checkout_info, lines_info, config)
if not lines:
return {}
@@ -615,11 +618,7 @@ def get_checkout_tax_data(
def get_order_request_data(order: "Order", config: AvataxConfiguration):
- if order.collection_point_id:
- address: Address = order.collection_point.address # type: ignore
- else:
- address = order.shipping_address or order.billing_address # type: ignore
-
+ address = get_address_for_order_taxes(order)
transaction = (
TransactionType.INVOICE
if not (order.is_draft() or order.is_unconfirmed())
@@ -652,6 +651,15 @@ def get_order_tax_data(
data, f"order_{order.id}", config, force_refresh
)
if response and "error" in response:
+ msg = response.get("error", {}).get("message", "")
+ error_code = response.get("error", {}).get("code", "")
+ logger.warning(
+ "Unable to calculate taxes for order %s, error_code: %s, error_msg: %s",
+ order.id,
+ error_code,
+ msg,
+ )
+ log_address_if_validation_skipped_for_order(order, logger)
raise TaxError(response.get("error"))
return response
diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.py
index c6456613f9..4c86fd879b 100644
--- a/saleor/plugins/avatax/plugin.py
+++ b/saleor/plugins/avatax/plugin.py
@@ -15,6 +15,7 @@ from prices import Money, TaxedMoney, TaxedMoneyRange
from ...checkout import base_calculations
from ...checkout.fetch import fetch_checkout_lines
+from ...checkout.utils import log_address_if_validation_skipped_for_checkout
from ...core.taxes import TaxError, TaxType, zero_taxed_money
from ...order import base_calculations as order_base_calculation
from ...order.interface import OrderTaxedPricesData
@@ -361,6 +362,7 @@ class AvataxPlugin(BasePlugin):
error_code,
msg,
)
+ log_address_if_validation_skipped_for_checkout(checkout_info, logger)
customer_msg = CustomerErrors.get_error_msg(response.get("error", {}))
raise TaxError(customer_msg)
return previous_value
diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_get_order_tax_data_address_error_logging.yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_get_order_tax_data_address_error_logging.yaml
new file mode 100644
index 0000000000..b49d874e46
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_get_order_tax_data_address_error_logging.yaml
@@ -0,0 +1,65 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesInvoice",
+ "lines": [{"quantity": 3, "amount": "36.900", "taxCode": "O9999999", "taxIncluded":
+ true, "itemCode": "SKU_A", "discounted": false, "description": "Test product"}],
+ "code": "596b2c00-cab7-4c94-8775-b267c45da927", "date": "2024-06-06", "customerCode":
+ 0, "discount": null, "addresses": {"singleLocation": {"line1": "T\u0119czowa
+ 7", "line2": "", "city": "WROC\u0141AW", "region": "", "country": "PL", "postalCode":
+ "invalid postal code"}}, "commit": false, "currencyCode": "USD", "email": "[email protected]"}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '586'
+ User-Agent:
+ - Saleor/3.19
+ method: POST
+ uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust
+ response:
+ body:
+ string: '{"error":{"code":"StringLengthError","message":"Field ''postalCode''
+ has an invalid length.","target":"IncorrectData","details":[{"code":"StringLengthError","number":13,"message":"Field
+ ''postalCode'' has an invalid length.","description":"Field ''postalCode''
+ must be between 0 and 11 characters in length.","faultCode":"Client","helpLink":"https://developer.avalara.com/avatax/errors/StringLengthError","severity":"Error"}]}}'
+ headers:
+ Connection:
+ - keep-alive
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Thu, 06 Jun 2024 12:24:47 GMT
+ ServerDuration:
+ - '00:00:00.0003073'
+ Transfer-Encoding:
+ - chunked
+ X-Content-Type-Options:
+ - nosniff
+ api-supported-versions:
+ - '2.0'
+ cache-control:
+ - private, no-cache, no-store
+ referrer-policy:
+ - same-origin
+ strict-transport-security:
+ - max-age=31536000; includeSubdomains
+ x-avalara-uid:
+ - de3ef2ed-f864-4a20-8801-74ec8ccc9490
+ x-correlation-id:
+ - de3ef2ed-f864-4a20-8801-74ec8ccc9490
+ x-frame-options:
+ - sameorigin
+ x-permitted-cross-domain-policies:
+ - none
+ x-xss-protection:
+ - 1; mode=block
+ status:
+ code: 400
+ message: Bad Request
+version: 1
diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_preprocess_order_creation_address_error_logging.yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_preprocess_order_creation_address_error_logging.yaml
new file mode 100644
index 0000000000..dc59053ddc
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_preprocess_order_creation_address_error_logging.yaml
@@ -0,0 +1,69 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
+ "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
+ true, "itemCode": "123", "discounted": false, "description": "Test product",
+ "ref1": "123"}, {"quantity": 1, "amount": "10.000", "taxCode": "FR000000", "taxIncluded":
+ true, "itemCode": "Shipping", "discounted": false, "description": null}], "code":
+ "c0693e39-78fc-4516-8c3f-6813012c5b9f", "date": "2024-06-06", "customerCode":
+ 0, "discount": null, "addresses": {"shipFrom": {"line1": "Teczowa 7", "line2":
+ "", "city": "Wroclaw", "region": "", "country": "PL", "postalCode": "53-601"},
+ "shipTo": {"line1": "T\u0119czowa 7", "line2": "", "city": "WROC\u0141AW", "region":
+ "", "country": "PL", "postalCode": "invalid postal code"}}, "commit": false,
+ "currencyCode": "USD", "email": "[email protected]"}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '856'
+ User-Agent:
+ - Saleor/3.19
+ method: POST
+ uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust
+ response:
+ body:
+ string: '{"error":{"code":"StringLengthError","message":"Field ''postalCode''
+ has an invalid length.","target":"IncorrectData","details":[{"code":"StringLengthError","number":13,"message":"Field
+ ''postalCode'' has an invalid length.","description":"Field ''postalCode''
+ must be between 0 and 11 characters in length.","faultCode":"Client","helpLink":"https://developer.avalara.com/avatax/errors/StringLengthError","severity":"Error"}]}}'
+ headers:
+ Connection:
+ - keep-alive
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Thu, 06 Jun 2024 12:13:39 GMT
+ ServerDuration:
+ - '00:00:00.0005438'
+ Transfer-Encoding:
+ - chunked
+ X-Content-Type-Options:
+ - nosniff
+ api-supported-versions:
+ - '2.0'
+ cache-control:
+ - private, no-cache, no-store
+ referrer-policy:
+ - same-origin
+ strict-transport-security:
+ - max-age=31536000; includeSubdomains
+ x-avalara-uid:
+ - 86c131e6-dba9-49ff-a50a-9f085f72ccbb
+ x-correlation-id:
+ - 86c131e6-dba9-49ff-a50a-9f085f72ccbb
+ x-frame-options:
+ - sameorigin
+ x-permitted-cross-domain-policies:
+ - none
+ x-xss-protection:
+ - 1; mode=block
+ status:
+ code: 400
+ message: Bad Request
+version: 1
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index 6d8ffd72e3..bd86a7b407 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -3541,6 +3541,47 @@ def test_preprocess_order_creation_shipping_voucher_no_tax_class_on_delivery_met
manager.preprocess_order_creation(checkout_info)
+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+def test_preprocess_order_creation_address_error_logging(
+ checkout_with_item,
+ monkeypatch,
+ address,
+ shipping_zone,
+ plugin_configuration,
+ caplog,
+):
+ # given
+ checkout = checkout_with_item
+ plugin_configuration()
+ monkeypatch.setattr(
+ "saleor.plugins.avatax.plugin.get_cached_tax_codes_or_fetch",
+ lambda _: {"PC040156": "desc"},
+ )
+ manager = get_plugins_manager(allow_replica=False)
+
+ address.validation_skipped = True
+ address.postal_code = "invalid postal code"
+ address.save(update_fields=["postal_code", "validation_skipped"])
+
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.save()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
+ with pytest.raises(TaxError):
+ manager.preprocess_order_creation(checkout_info, lines)
+
+ # then
+ assert f"Unable to calculate taxes for checkout {checkout.pk}" in caplog.text
+ assert (
+ f"Fetching tax data for checkout with address validation skipped. "
+ f"Address ID: {address.pk}" in caplog.text
+ )
+
+
@pytest.mark.vcr
def test_get_cached_tax_codes_or_fetch(monkeypatch, avatax_config):
monkeypatch.setattr("saleor.plugins.avatax.cache.get", lambda x, y: {})
@@ -5425,6 +5466,39 @@ def test_get_order_tax_data_raised_error(
assert e._excinfo[1].args[0] == return_value["error"]
+@patch("saleor.plugins.avatax.cache.set")
+def test_get_order_tax_data_address_error_logging(
+ mock_cache_set,
+ order_line,
+ avatax_config,
+ address,
+ caplog,
+):
+ # given
+ order = order_line.order
+ invalid_postal_code = "invalid postal code"
+ address.validation_skipped = True
+ address.postal_code = invalid_postal_code
+ address.save(update_fields=["postal_code", "validation_skipped"])
+ order.shipping_address = address
+ order.billing_address = address
+ order.save(update_fields=["shipping_address", "billing_address"])
+
+ avatax_config.from_postal_code = invalid_postal_code
+
+ # when
+ with pytest.raises(TaxError):
+ get_order_tax_data(order, avatax_config)
+
+ # then
+ assert f"Unable to calculate taxes for order {order.pk}" in caplog.text
+ assert (
+ f"Fetching tax data for order with address validation skipped. "
+ f"Address ID: {address.pk}" in caplog.text
+ )
+
+
@pytest.mark.parametrize(
(
"shipping_address_none",
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index c25837c309..f0cd337b4d 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -1197,6 +1197,12 @@ def graphql_address_data():
}
+def graphql_address_data_skipped_validation(graphql_address_data):
+ graphql_address_data["skipValidation"] = True
+ return graphql_address_data
+
+
@pytest.fixture
def customer_user(address): # pylint: disable=W0613
default_address = address.get_copy()