Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Unify country fetching (#13159)
Jakubbe0f43ff152e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1e482a0c2a..969855a29a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,12 @@ All notable, unreleased changes to this project will be documented in this file.- `ProductPricingInfo.priceRangeLocalCurrency`- `VariantPricingInfo.discountLocalCurrency`- `VariantPricingInfo.priceLocalCurrency`+- Change order of resolving country code in checkout - #13159 by @jakubkuc+ - Until now, checkout mutations were ignoring provided shipping address when shipping was not required. After this change, the shipping address is always set when supplied in the input. It might be breaking, as the shipping address affects the country code used for tax calculation.+ - The order of resolving the checkout country code is always as follows:+ 1. Shipping address+ 2. Billing address+ 3. Channel's default country### GraphQL APIdiff --git a/saleor/core/utils/country.py b/saleor/core/utils/country.pynew file mode 100644index 0000000000..d2470d8dc2--- /dev/null+++ b/saleor/core/utils/country.py@@ -0,0 +1,36 @@+from typing import TYPE_CHECKING, Optional++from ...account.models import Address+from ...channel.models import Channel++if TYPE_CHECKING:+ from ...graphql.account.types import AddressInput+++def get_active_country(+ channel: "Channel",+ shipping_address: Optional["Address"] = None,+ billing_address: Optional["Address"] = None,+ address_data: Optional["AddressInput"] = None,+):+ """Get country code for orders, checkouts and tax calculations.++ For checkouts and orders, there are following rules for determining the country+ code that should be used for tax calculations:+ - use country code from shipping address if it's provided in the first place+ - use country code from billing address if shipping address is not provided+ - if both shipping and billing addresses are not provided use the default country+ from channel++ To get country code from address data from mutation input use address_data parameter+ """+ if address_data is not None:+ return address_data.country++ if shipping_address:+ return shipping_address.country.code++ if billing_address:+ return billing_address.country.code++ return channel.default_country.codediff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.pyindex 8d97307e57..08e6be010f 100644--- a/saleor/graphql/checkout/mutations/checkout_create.py+++ b/saleor/graphql/checkout/mutations/checkout_create.py@@ -7,6 +7,7 @@ from ....checkout import AddressType, modelsfrom ....checkout.error_codes import CheckoutErrorCodefrom ....checkout.utils import add_variants_to_checkoutfrom ....core.tracing import traced_atomic_transaction+from ....core.utils.country import get_active_countryfrom ....product import models as product_modelsfrom ....warehouse.reservations import get_reservation_length, is_reservation_enabledfrom ...account.i18n import I18nMixin@@ -278,12 +279,11 @@ class CheckoutCreate(ModelMutation, I18nMixin):shipping_address = cls.retrieve_shipping_address(user, data)billing_address = cls.retrieve_billing_address(user, data)- if shipping_address:- country = shipping_address.country.code- else:- country = channel.default_country-- # Resolve and process the lines, retrieving the variants and quantities+ country = get_active_country(+ channel,+ shipping_address,+ billing_address,+ )lines = data.pop("lines", None)if lines:(@@ -337,7 +337,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):# Save addressesshipping_address = cleaned_input.get("shipping_address")- if shipping_address and instance.is_shipping_required():+ if shipping_address:shipping_address.save()instance.shipping_address = shipping_address.get_copy()diff --git a/saleor/graphql/checkout/mutations/checkout_create_from_order.py b/saleor/graphql/checkout/mutations/checkout_create_from_order.pyindex 732d79e140..c7780cd182 100644--- a/saleor/graphql/checkout/mutations/checkout_create_from_order.py+++ b/saleor/graphql/checkout/mutations/checkout_create_from_order.py@@ -6,6 +6,7 @@ from django.contrib.sites.models import Sitefrom ....checkout import models as checkout_modelsfrom ....checkout.utils import add_variants_to_checkoutfrom ....core.exceptions import InsufficientStock+from ....core.utils.country import get_active_countryfrom ....order import models as order_modelsfrom ....product import models as product_modelsfrom ....product.models import ProductVariant@@ -318,10 +319,9 @@ class CheckoutCreateFromOrder(BaseMutation):],)valid_order_lines: list[order_models.OrderLine] = []- if order.shipping_address:- country = order.shipping_address.country.code- else:- country = order.channel.default_country+ country = get_active_country(+ order.channel, order.shipping_address, order.billing_address+ )try:check_stock_and_preorder_quantity_bulk(variants,diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex f390070e38..179dd0ac77 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -391,7 +391,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(67):+ with django_assert_num_queries(62):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 1@@ -409,7 +409,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(67):+ with django_assert_num_queries(62):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 10@@ -660,7 +660,7 @@ def test_update_checkout_lines_with_reservations(reservation_length=5,)- with django_assert_num_queries(75):+ with django_assert_num_queries(74):variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)variables = {"id": to_global_id_or_none(checkout),@@ -674,7 +674,7 @@ def test_update_checkout_lines_with_reservations(assert not data["errors"]# Updating multiple lines in checkout has same query count as updating one- with django_assert_num_queries(75):+ with django_assert_num_queries(74):variables = {"id": to_global_id_or_none(checkout),"lines": [],@@ -919,7 +919,7 @@ def test_add_checkout_lines_with_reservations(new_lines.append({"quantity": 2, "variantId": variant_id})# Adding multiple lines to checkout has same query count as adding one- with django_assert_num_queries(74):+ with django_assert_num_queries(73):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": [new_lines[0]],@@ -932,7 +932,7 @@ def test_add_checkout_lines_with_reservations(checkout.lines.exclude(id=line.id).delete()- with django_assert_num_queries(74):+ with django_assert_num_queries(73):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": new_lines,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create.pyindex c64995ee41..625444b52a 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py@@ -8,7 +8,6 @@ import pytzfrom django.test import override_settingsfrom django.utils import timezone-from .....account.models import Addressfrom .....channel.utils import DEPRECATION_WARNING_MESSAGEfrom .....checkout import AddressTypefrom .....checkout.error_codes import CheckoutErrorCode@@ -2356,45 +2355,3 @@ def test_checkout_create_with_disabled_fields_normalization_raises_required_erroassert len(data["errors"]) == 1assert data["errors"][0]["field"] == "postalCode"assert data["errors"][0]["code"] == "REQUIRED"--[email protected]("with_shipping_address", (True, False))-def test_create_checkout_with_digital(- api_client,- digital_content,- graphql_address_data,- with_shipping_address,- channel_USD,-):- """Test creating a checkout with a shipping address gets the address ignored."""-- address_count = Address.objects.count()-- variant = digital_content.product_variant- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- checkout_input = {- "channel": channel_USD.slug,- "lines": [{"quantity": 1, "variantId": variant_id}],- "email": "[email protected]",- }-- if with_shipping_address:- checkout_input["shippingAddress"] = graphql_address_data-- get_graphql_content(- api_client.post_graphql(- MUTATION_CHECKOUT_CREATE, {"checkoutInput": checkout_input}- )- )["data"]["checkoutCreate"]-- # Retrieve the created checkout- checkout = Checkout.objects.get()-- # Check that the shipping address was ignored, thus not created- assert (- checkout.shipping_address is None- ), "The address shouldn't have been associated"- assert (- Address.objects.count() == address_count- ), "No address should have been created"diff --git a/saleor/graphql/product/types/channels.py b/saleor/graphql/product/types/channels.pyindex e7ecd20659..6437d8b780 100644--- a/saleor/graphql/product/types/channels.py+++ b/saleor/graphql/product/types/channels.py@@ -5,6 +5,7 @@ from typing import List, Optionalimport graphenefrom promise import Promise+from ....core.utils.country import get_active_countryfrom ....graphql.core.types import Money, MoneyRangefrom ....permission.enums import ProductPermissionsfrom ....product import models@@ -214,14 +215,13 @@ class ProductChannelListing(ModelObjectType[models.ProductChannelListing]):@staticmethoddef resolve_pricing(root: models.ProductChannelListing, info, *, address=None):context = info.context- address_country = address.country if address is not None else Nonechannel = ChannelByIdLoader(context).load(root.channel_id)product = ProductByIdLoader(context).load(root.product_id)def load_tax_configuration(data):channel, product = data- country_code = address_country or channel.default_country.code+ country_code = get_active_country(channel, address_data=address)def load_tax_country_exceptions(tax_config):tax_class = TaxClassByProductIdLoader(info.context).load(product.id)diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex e0e32a980e..89db378103 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -10,6 +10,7 @@ from promise import Promisefrom ....attribute import models as attribute_modelsfrom ....core.utils import build_absolute_uri+from ....core.utils.country import get_active_countryfrom ....core.weight import convert_weight_to_default_weight_unitfrom ....permission.auth_filters import AuthorizationFiltersfrom ....permission.enums import OrderPermissions, ProductPermissions@@ -588,8 +589,6 @@ class ProductVariant(ChannelContextTypeWithMetadata[models.ProductVariant]):channel = ChannelBySlugLoader(context).load(channel_slug)tax_class = TaxClassByVariantIdLoader(context).load(root.node.id)- address_country = address.country if address is not None else None-def load_tax_configuration(data):(product_channel_listing,@@ -600,8 +599,7 @@ class ProductVariant(ChannelContextTypeWithMetadata[models.ProductVariant]):if not variant_channel_listing or not product_channel_listing:return None-- country_code = address_country or channel.default_country.code+ country_code = get_active_country(channel, address_data=address)def load_tax_country_exceptions(tax_config):def load_default_tax_rate(tax_configs_per_country):@@ -1078,7 +1076,6 @@ class Product(ChannelContextTypeWithMetadata[models.Product]):channel_slug = str(root.channel_slug)context = info.context- address_country = address.country if address is not None else Nonechannel = ChannelBySlugLoader(context).load(channel_slug)product_channel_listing = ProductChannelListingByProductIdAndChannelSlugLoader(@@ -1101,8 +1098,7 @@ class Product(ChannelContextTypeWithMetadata[models.Product]):if not variants_channel_listing:return None-- country_code = address_country or channel.default_country.code+ country_code = get_active_country(channel, address_data=address)def load_tax_country_exceptions(tax_config):def load_default_tax_rate(tax_configs_per_country):diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 726e28d337..fa49b5989a 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -11,6 +11,7 @@ from ..account.models import Userfrom ..core.prices import quantize_pricefrom ..core.taxes import zero_moneyfrom ..core.tracing import traced_atomic_transaction+from ..core.utils.country import get_active_countryfrom ..core.utils.translations import get_translationfrom ..core.weight import zero_weightfrom ..discount import DiscountType@@ -31,11 +32,7 @@ from ..shipping.utils import (convert_to_shipping_method_data,initialize_shipping_method_active_status,)-from ..tax.utils import (- get_display_gross_prices,- get_tax_class_kwargs_for_order_line,- get_tax_country,-)+from ..tax.utils import get_display_gross_prices, get_tax_class_kwargs_for_order_linefrom ..warehouse.management import (decrease_allocations,get_order_lines_with_track_inventory,@@ -64,12 +61,9 @@ if TYPE_CHECKING:def get_order_country(order: Order) -> str:"""Return country to which order will be shipped."""- address = order.billing_address- if order.is_shipping_required():- address = order.shipping_address- if address is None:- return order.channel.default_country.code- return address.country.code+ return get_active_country(+ order.channel, order.shipping_address, order.billing_address+ )def order_line_needs_automatic_fulfillment(line_data: OrderLineInfo) -> bool:@@ -1050,9 +1044,8 @@ def update_order_display_gross_prices(order: "Order"):"""channel = order.channeltax_configuration = channel.tax_configuration- country_code = get_tax_country(+ country_code = get_active_country(channel,- order.is_shipping_required(),order.shipping_address,order.billing_address,)diff --git a/saleor/tax/calculations/checkout.py b/saleor/tax/calculations/checkout.pyindex 3f99dfcdef..a674f57ffd 100644--- a/saleor/tax/calculations/checkout.py+++ b/saleor/tax/calculations/checkout.py@@ -6,6 +6,7 @@ from prices import TaxedMoneyfrom ...checkout import base_calculationsfrom ...core.prices import quantize_pricefrom ...core.taxes import zero_taxed_money+from ...core.utils.country import get_active_countryfrom ..models import TaxClassCountryRatefrom ..utils import get_tax_rate_for_tax_class, normalize_tax_rate_for_dbfrom . import calculate_flat_rate_tax@@ -23,9 +24,7 @@ def update_checkout_prices_with_flat_rates(prices_entered_with_tax: bool,address: Optional["Address"] = None,):- country_code = (- address.country.code if address else checkout_info.channel.default_country.code- )+ country_code = get_active_country(checkout_info.channel, address)default_country_rate_obj = TaxClassCountryRate.objects.filter(country=country_code, tax_class=None).first()diff --git a/saleor/tax/tests/test_utils.py b/saleor/tax/tests/test_utils.pyindex 23efdfd508..1806a2cfcd 100644--- a/saleor/tax/tests/test_utils.py+++ b/saleor/tax/tests/test_utils.py@@ -1,4 +1,5 @@-from ..utils import get_charge_taxes, get_display_gross_prices, get_tax_country+from ...core.utils.country import get_active_country+from ..utils import get_charge_taxes, get_display_gross_pricesdef test_get_display_gross_prices(channel_USD):@@ -42,14 +43,11 @@ def test_get_tax_country_use_shipping_address(channel_USD, address_usa, address_other_country):# given- is_shipping_required = Trueshipping_address = address_usabilling_address = address_other_country# when- country = get_tax_country(- channel_USD, is_shipping_required, shipping_address, billing_address- )+ country = get_active_country(channel_USD, shipping_address, billing_address)# thenassert country == address_usa.country.code@@ -59,14 +57,12 @@ def test_get_tax_country_use_billing_address(channel_USD, address_usa, address_other_country):# given- is_shipping_required = False- shipping_address = address_usa++ shipping_address = Nonebilling_address = address_other_country# when- country = get_tax_country(- channel_USD, is_shipping_required, shipping_address, billing_address- )+ country = get_active_country(channel_USD, shipping_address, billing_address)# thenassert country == address_other_country.country.code@@ -78,7 +74,7 @@ def test_get_tax_country_fallbacks_to_channel_country(channel_USD):billing_address = None# when- country = get_tax_country(channel_USD, True, shipping_address, billing_address)+ country = get_active_country(channel_USD, shipping_address, billing_address)# thenassert country == channel_USD.default_country.codediff --git a/saleor/tax/utils.py b/saleor/tax/utils.pyindex c60172cf1b..73644650cb 100644--- a/saleor/tax/utils.py+++ b/saleor/tax/utils.py@@ -3,41 +3,16 @@ from typing import TYPE_CHECKING, Iterable, Optional, Tuplefrom prices import TaxedMoney+from ..core.utils.country import get_active_countryfrom . import TaxCalculationStrategyif TYPE_CHECKING:- from ..account.models import Address- from ..channel.models import Channelfrom ..checkout.fetch import CheckoutInfo, CheckoutLineInfofrom ..order.models import Orderfrom ..tax.models import TaxClass, TaxClassCountryRatefrom .models import TaxConfiguration, TaxConfigurationPerCountry-def get_tax_country(- channel: "Channel",- is_shipping_required: bool,- shipping_address: Optional["Address"] = None,- billing_address: Optional["Address"] = None,-):- """Get country code for tax calculations.-- For checkouts and orders, there are following rules for determining the country- code that should be used for tax calculations:- - when shipping is required, use the shipping address's country code,- - when shipping is not required (e.g. because of having only digital products), use- the billing address's country code,- - fallback to channel's default country when addresses are not provided.- """- if shipping_address and is_shipping_required:- return shipping_address.country.code-- if billing_address and not is_shipping_required:- return billing_address.country.code-- return channel.default_country.code--def get_display_gross_prices(channel_tax_configuration: "TaxConfiguration",country_tax_configuration: Optional["TaxConfigurationPerCountry"],@@ -93,9 +68,8 @@ def get_charge_taxes_for_order(order: "Order") -> bool:"""Get charge_taxes value for order."""channel = order.channeltax_configuration = channel.tax_configuration- country_code = get_tax_country(+ country_code = get_active_country(channel,- order.is_shipping_required(),order.shipping_address,order.billing_address,)@@ -114,9 +88,8 @@ def get_tax_calculation_strategy_for_order(order: "Order"):"""Get tax_calculation_strategy value for order."""channel = order.channeltax_configuration = channel.tax_configuration- country_code = get_tax_country(+ country_code = get_active_country(channel,- order.is_shipping_required(),order.shipping_address,order.billing_address,)@@ -134,12 +107,9 @@ def get_tax_calculation_strategy_for_order(order: "Order"):def _get_tax_configuration_for_checkout(checkout_info: "CheckoutInfo", lines: Iterable["CheckoutLineInfo"]) -> Tuple["TaxConfiguration", Optional["TaxConfigurationPerCountry"]]:- from ..checkout.utils import is_shipping_required-tax_configuration = checkout_info.tax_configuration- country_code = get_tax_country(+ country_code = get_active_country(checkout_info.channel,- is_shipping_required(lines),checkout_info.shipping_address,checkout_info.billing_address,)