Skip to content

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

Improve the way of handling tax-class (#17555)

Maciej Korycinski8cdad8b518e3
diff --git a/saleor/graphql/product/tests/test_product_channel_listings_queries.py b/saleor/graphql/product/tests/test_product_channel_listings_queries.py
index 41f90e8bb9..d2f7cafb02 100644
--- a/saleor/graphql/product/tests/test_product_channel_listings_queries.py
+++ b/saleor/graphql/product/tests/test_product_channel_listings_queries.py
@@ -155,9 +155,9 @@ query FetchProduct($id: ID, $channel: String) {
"""
[email protected]("saleor.graphql.product.types.products.get_tax_rate_for_tax_class")
[email protected]("saleor.graphql.product.types.products.get_tax_rate_for_country")
def test_product_channel_listing_pricing_field_no_address(
- mock_get_tax_rate_for_tax_class,
+ mock_get_tax_rate_for_country,
staff_api_client,
permission_manage_products,
channel_USD,
@@ -181,9 +181,7 @@ def test_product_channel_listing_pricing_field_no_address(
)
# then
- assert (
- mock_get_tax_rate_for_tax_class.call_args[0][3] == channel_USD.default_country
- )
+ assert mock_get_tax_rate_for_country.call_args[0][2] == channel_USD.default_country
FRAGMENT_PRICE = """
diff --git a/saleor/graphql/product/tests/test_variant_pricing.py b/saleor/graphql/product/tests/test_variant_pricing.py
index 2bcedef2f3..ecbdfb58fd 100644
--- a/saleor/graphql/product/tests/test_variant_pricing.py
+++ b/saleor/graphql/product/tests/test_variant_pricing.py
@@ -384,10 +384,10 @@ QUERY_GET_PRODUCT_VARIANTS_PRICING_NO_ADDRESS = """
@patch(
- "saleor.graphql.product.types.products.get_tax_rate_for_tax_class",
+ "saleor.graphql.product.types.products.get_tax_rate_for_country",
)
def test_product_variant_price_no_address(
- mock_get_tax_rate_for_tax_class, user_api_client, variant, stock, channel_USD
+ mock_get_tax_rate_for_country, user_api_client, variant, stock, channel_USD
):
channel_USD.default_country = "FR"
channel_USD.save()
@@ -396,9 +396,7 @@ def test_product_variant_price_no_address(
user_api_client.post_graphql(
QUERY_GET_PRODUCT_VARIANTS_PRICING_NO_ADDRESS, variables
)
- assert (
- mock_get_tax_rate_for_tax_class.call_args[0][3] == channel_USD.default_country
- )
+ assert mock_get_tax_rate_for_country.call_args[0][2] == channel_USD.default_country
FRAGMENT_PRICE = """
diff --git a/saleor/graphql/product/types/channels.py b/saleor/graphql/product/types/channels.py
index 2faf2b4f5b..3f27fd4709 100644
--- a/saleor/graphql/product/types/channels.py
+++ b/saleor/graphql/product/types/channels.py
@@ -16,7 +16,7 @@ from ....product.utils.costs import (
from ....tax.utils import (
get_display_gross_prices,
get_tax_calculation_strategy,
- get_tax_rate_for_tax_class,
+ get_tax_rate_for_country,
)
from ...account import types as account_types
from ...channel.dataloaders import ChannelByIdLoader
@@ -28,14 +28,13 @@ from ...core.scalars import Date, DateTime
from ...core.tracing import traced_resolver
from ...core.types import BaseObjectType, ModelObjectType
from ...tax.dataloaders import (
- TaxClassByProductIdLoader,
TaxClassCountryRateByTaxClassIDLoader,
TaxClassDefaultRateByCountryLoader,
+ TaxClassIdByProductIdLoader,
TaxConfigurationByChannelId,
TaxConfigurationPerCountryByTaxConfigurationIDLoader,
)
from ..dataloaders import (
- ProductByIdLoader,
ProductVariantsByProductIdLoader,
VariantChannelListingByVariantIdAndChannelSlugLoader,
VariantsChannelListingByProductIdAndChannelSlugLoader,
@@ -220,22 +219,15 @@ class ProductChannelListing(ModelObjectType[models.ProductChannelListing]):
context = info.context
channel = ChannelByIdLoader(context).load(root.channel_id)
- product = ProductByIdLoader(context).load(root.product_id)
+ tax_class_id_loader = TaxClassIdByProductIdLoader(context).load(root.product_id)
def load_tax_configuration(data):
- channel, product = data
+ channel, tax_class_id = data
country_code = get_active_country(channel, address_data=address)
def load_tax_country_exceptions(tax_config):
- tax_class = TaxClassByProductIdLoader(info.context).load(product.id)
- tax_configs_per_country = (
- TaxConfigurationPerCountryByTaxConfigurationIDLoader(context).load(
- tax_config.id
- )
- )
-
def load_variant_channel_listings(data):
- tax_class, tax_configs_per_country = data
+ tax_configs_per_country = data
def load_default_tax_rate(variants_channel_listing):
if not variants_channel_listing:
@@ -264,8 +256,8 @@ class ProductChannelListing(ModelObjectType[models.ProductChannelListing]):
if default_country_rate_obj
else Decimal(0)
)
- tax_rate = get_tax_rate_for_tax_class(
- tax_class, country_rates, default_tax_rate, country_code
+ tax_rate = get_tax_rate_for_country(
+ country_rates, default_tax_rate, country_code
)
prices_entered_with_tax = tax_config.prices_entered_with_tax
@@ -284,9 +276,9 @@ class ProductChannelListing(ModelObjectType[models.ProductChannelListing]):
country_rates = (
TaxClassCountryRateByTaxClassIDLoader(context).load(
- tax_class.pk
+ tax_class_id
)
- if tax_class
+ if tax_class_id
else []
)
default_country_rate = TaxClassDefaultRateByCountryLoader(
@@ -302,9 +294,11 @@ class ProductChannelListing(ModelObjectType[models.ProductChannelListing]):
.then(load_default_tax_rate)
)
- return Promise.all([tax_class, tax_configs_per_country]).then(
- load_variant_channel_listings
- )
+ return (
+ TaxConfigurationPerCountryByTaxConfigurationIDLoader(context).load(
+ tax_config.id
+ )
+ ).then(load_variant_channel_listings)
return (
TaxConfigurationByChannelId(context)
@@ -312,7 +306,7 @@ class ProductChannelListing(ModelObjectType[models.ProductChannelListing]):
.then(load_tax_country_exceptions)
)
- return Promise.all([channel, product]).then(load_tax_configuration)
+ return Promise.all([channel, tax_class_id_loader]).then(load_tax_configuration)
class PreorderThreshold(BaseObjectType):
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 24a4543dde..a66458312e 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -27,7 +27,7 @@ from ....product.utils.variants import get_variant_selection_attributes
from ....tax.utils import (
get_display_gross_prices,
get_tax_calculation_strategy,
- get_tax_rate_for_tax_class,
+ get_tax_rate_for_country,
)
from ....thumbnail.utils import (
get_image_or_proxy_url,
@@ -94,10 +94,9 @@ from ...site.dataloaders import load_site_callback
from ...tax.dataloaders import (
ProductChargeTaxesByTaxClassIdLoader,
TaxClassByIdLoader,
- TaxClassByProductIdLoader,
- TaxClassByVariantIdLoader,
TaxClassCountryRateByTaxClassIDLoader,
TaxClassDefaultRateByCountryLoader,
+ TaxClassIdByProductIdLoader,
TaxConfigurationByChannelId,
TaxConfigurationPerCountryByTaxConfigurationIDLoader,
)
@@ -628,14 +627,16 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):
context
).load((root.node.id, channel_slug))
channel = ChannelBySlugLoader(context).load(channel_slug)
- tax_class = TaxClassByVariantIdLoader(context).load(root.node.id)
+ tax_class_id_loader = TaxClassIdByProductIdLoader(context).load(
+ root.node.product_id
+ )
def load_tax_configuration(data):
(
product_channel_listing,
variant_channel_listing,
channel,
- tax_class,
+ tax_class_id,
) = data
if not variant_channel_listing or not product_channel_listing:
@@ -664,8 +665,8 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):
if default_country_rate_obj
else Decimal(0)
)
- tax_rate = get_tax_rate_for_tax_class(
- tax_class, country_rates, default_tax_rate, country_code
+ tax_rate = get_tax_rate_for_country(
+ country_rates, default_tax_rate, country_code
)
availability = get_variant_availability(
@@ -683,9 +684,9 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):
country_rates = (
TaxClassCountryRateByTaxClassIDLoader(context).load(
- tax_class.pk
+ tax_class_id
)
- if tax_class
+ if tax_class_id
else []
)
default_rate = TaxClassDefaultRateByCountryLoader(context).load(
@@ -712,7 +713,7 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):
product_channel_listing,
variant_channel_listing,
channel,
- tax_class,
+ tax_class_id_loader,
]
).then(load_tax_configuration)
@@ -1139,14 +1140,14 @@ class Product(ChannelContextType[models.Product]):
(root.node.id, channel_slug)
)
)
- tax_class = TaxClassByProductIdLoader(context).load(root.node.id)
+ tax_class_id_loader = TaxClassIdByProductIdLoader(context).load(root.node.id)
def load_tax_configuration(data):
(
channel,
product_channel_listing,
variants_channel_listing,
- tax_class,
+ tax_class_id,
) = data
if not variants_channel_listing:
@@ -1178,8 +1179,8 @@ class Product(ChannelContextType[models.Product]):
if default_country_rate_obj
else Decimal(0)
)
- tax_rate = get_tax_rate_for_tax_class(
- tax_class, country_rates, default_tax_rate, country_code
+ tax_rate = get_tax_rate_for_country(
+ country_rates, default_tax_rate, country_code
)
availability = get_product_availability(
@@ -1196,9 +1197,9 @@ class Product(ChannelContextType[models.Product]):
country_rates = (
TaxClassCountryRateByTaxClassIDLoader(context).load(
- tax_class.pk
+ tax_class_id
)
- if tax_class
+ if tax_class_id
else []
)
default_rate = TaxClassDefaultRateByCountryLoader(context).load(
@@ -1225,7 +1226,7 @@ class Product(ChannelContextType[models.Product]):
channel,
product_channel_listing,
variants_channel_listing,
- tax_class,
+ tax_class_id_loader,
]
).then(load_tax_configuration)
diff --git a/saleor/graphql/tax/dataloaders.py b/saleor/graphql/tax/dataloaders.py
index 513f5a0807..6fc13ea2ea 100644
--- a/saleor/graphql/tax/dataloaders.py
+++ b/saleor/graphql/tax/dataloaders.py
@@ -80,8 +80,8 @@ class TaxClassByIdLoader(DataLoader):
return [tax_class_map.get(obj_id) for obj_id in keys]
-class TaxClassByProductIdLoader(DataLoader):
- context_key = "tax_class_by_product_id"
+class TaxClassIdByProductIdLoader(DataLoader):
+ context_key = "tax_class_id_by_product_id"
def batch_load(self, keys):
products = ProductByIdLoader(self.context).load_many(keys)
@@ -99,12 +99,7 @@ class TaxClassByProductIdLoader(DataLoader):
tax_class_id = product.tax_class_id or product_type.tax_class_id
tax_class_ids_map[product_id] = tax_class_id
- return [
- TaxClassByIdLoader(self.context).load(tax_class_ids_map[product_id])
- if tax_class_ids_map[product_id]
- else None
- for product_id in keys
- ]
+ return [tax_class_ids_map[product_id] for product_id in keys]
return Promise.all([products, product_types]).then(load_tax_classes)
@@ -129,9 +124,11 @@ class TaxClassByVariantIdLoader(DataLoader):
tax_class_ids_map[variant_pk] = tax_class_id
return [
- TaxClassByIdLoader(self.context).load(tax_class_ids_map[variant_id])
- if tax_class_ids_map[variant_id]
- else None
+ (
+ TaxClassByIdLoader(self.context).load(tax_class_ids_map[variant_id])
+ if tax_class_ids_map[variant_id]
+ else None
+ )
for variant_id in keys
]
@@ -157,8 +154,10 @@ class ProductChargeTaxesByTaxClassIdLoader(DataLoader):
.in_bulk(keys)
)
return [
- tax_class_map[tax_class_id].charge_taxes
- if tax_class_map.get(tax_class_id)
- else False
+ (
+ tax_class_map[tax_class_id].charge_taxes
+ if tax_class_map.get(tax_class_id)
+ else False
+ )
for tax_class_id in keys
]
diff --git a/saleor/order/tests/benchmark/test_fetch_order_prices.py b/saleor/order/tests/benchmark/test_fetch_order_prices.py
index e980a630cd..1ce42fb7e8 100644
--- a/saleor/order/tests/benchmark/test_fetch_order_prices.py
+++ b/saleor/order/tests/benchmark/test_fetch_order_prices.py
@@ -18,5 +18,5 @@ def test_fetch_order_prices(
order.status = OrderStatus.UNCONFIRMED
# when & then
- with django_assert_num_queries(32):
+ with django_assert_num_queries(28):
fetch_order_prices_if_expired(order, plugins_manager, None, True)
diff --git a/saleor/tax/calculations/checkout.py b/saleor/tax/calculations/checkout.py
index 1ddab3e8bf..99cb4b2d66 100644
--- a/saleor/tax/calculations/checkout.py
+++ b/saleor/tax/calculations/checkout.py
@@ -1,3 +1,4 @@
+from collections.abc import Iterable
from decimal import Decimal
from typing import TYPE_CHECKING, Optional
@@ -9,7 +10,7 @@ from ...core.prices import quantize_price
from ...core.taxes import zero_taxed_money
from ...core.utils.country import get_active_country
from ..models import TaxClassCountryRate
-from ..utils import get_tax_rate_for_tax_class, normalize_tax_rate_for_db
+from ..utils import get_tax_rate_for_country, normalize_tax_rate_for_db
from . import calculate_flat_rate_tax
if TYPE_CHECKING:
@@ -41,8 +42,7 @@ def update_checkout_prices_with_flat_rates(
for line_info in lines:
line = line_info.line
tax_class = line_info.tax_class
- tax_rate = get_tax_rate_for_tax_class(
- tax_class,
+ tax_rate = get_tax_rate_for_country(
tax_class.country_rates.all() if tax_class else [],
default_tax_rate,
country_code,
@@ -57,12 +57,18 @@ def update_checkout_prices_with_flat_rates(
line.total_price = line_total_price
line.tax_rate = normalize_tax_rate_for_db(tax_rate)
- # Calculate shipping price.
- shipping_method = checkout_info.get_delivery_method_info().delivery_method
- tax_class = getattr(shipping_method, "tax_class", None)
- shipping_tax_rate = get_tax_rate_for_tax_class(
- tax_class,
- tax_class.country_rates.all() if tax_class else [],
+ # Calculate shipping details.
+ shipping_tax_rates: Iterable[TaxClassCountryRate] = []
+ if shipping_method := checkout_info.shipping_method:
+ # external shipping methods do not have a way to provide tax-class
+ tax_class_id = shipping_method.tax_class_id
+ if tax_class_id:
+ shipping_tax_rates = TaxClassCountryRate.objects.using(
+ database_connection_name
+ ).filter(tax_class_id=tax_class_id)
+
+ shipping_tax_rate = get_tax_rate_for_country(
+ shipping_tax_rates,
default_tax_rate,
country_code,
)
diff --git a/saleor/tax/calculations/order.py b/saleor/tax/calculations/order.py
index a4f80b33b5..b2dc6fb93b 100644
--- a/saleor/tax/calculations/order.py
+++ b/saleor/tax/calculations/order.py
@@ -1,11 +1,11 @@
+from collections import defaultdict
from collections.abc import Iterable
from decimal import Decimal
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, cast
from django.conf import settings
from prices import TaxedMoney
-from ...core.db.connection import allow_writer
from ...core.prices import quantize_price
from ...core.taxes import zero_taxed_money
from ...order import base_calculations
@@ -13,7 +13,7 @@ from ...order.utils import get_order_country
from ..models import TaxClassCountryRate
from ..utils import (
denormalize_tax_rate_from_db,
- get_tax_rate_for_tax_class,
+ get_tax_rate_for_country,
normalize_tax_rate_for_db,
)
from . import calculate_flat_rate_tax
@@ -40,24 +40,26 @@ def update_order_prices_with_flat_rates(
# Calculate order line taxes.
_, undiscounted_subtotal = update_taxes_for_order_lines(
- order, lines, country_code, default_tax_rate, prices_entered_with_tax
+ order,
+ lines,
+ country_code,
+ default_tax_rate,
+ prices_entered_with_tax,
+ database_connection_name=database_connection_name,
)
# Calculate order shipping.
- with allow_writer():
- # allow writer as this action directly fetches the shipping method from the
- # writer. Will be solved by the task:
- # https://linear.app/saleor/issue/EXT-1990/update-order-prices-with-flat-rates-
- # makes-db-writer-to-get-shipping
- shipping_method = order.shipping_method
- shipping_tax_class = getattr(shipping_method, "tax_class", None)
-
- if shipping_tax_class:
- shipping_tax_rate = get_tax_rate_for_tax_class(
- shipping_tax_class,
- shipping_tax_class.country_rates.using(database_connection_name).all(),
- default_tax_rate,
- country_code,
+
+ shipping_tax_rate = default_tax_rate
+
+ if order.shipping_tax_class_id:
+ shipping_tax_rates = TaxClassCountryRate.objects.using(
+ database_connection_name
+ ).filter(tax_class_id=order.shipping_tax_class_id)
+ shipping_tax_rate = get_tax_rate_for_country(
+ tax_class_country_rates=shipping_tax_rates,
+ default_tax_rate=default_tax_rate,
+ country_code=country_code,
)
elif (
order.shipping_tax_class_name is not None
@@ -67,8 +69,6 @@ def update_order_prices_with_flat_rates(
# the name is non-null). This is a valid case when recalculating shipping price
# and the tax class is null, because it was removed from the system.
shipping_tax_rate = denormalize_tax_rate_from_db(order.shipping_tax_rate)
- else:
- shipping_tax_rate = default_tax_rate
order.shipping_price = _calculate_order_shipping(
order, shipping_tax_rate, prices_entered_with_tax
@@ -140,22 +140,34 @@ def update_taxes_for_order_lines(
country_code: str,
default_tax_rate: Decimal,
prices_entered_with_tax: bool,
+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
) -> tuple[Iterable["OrderLine"], TaxedMoney]:
currency = order.currency
lines = list(lines)
undiscounted_subtotal = zero_taxed_money(order.currency)
+ tax_class_ids: set[int] = {
+ line.tax_class_id for line in lines if line.tax_class_id is not None
+ }
+
+ tax_rates_per_tax_class_ic: dict[int, list[TaxClassCountryRate]] = defaultdict(list)
+ for rate in TaxClassCountryRate.objects.using(database_connection_name).filter(
+ tax_class_id__in=tax_class_ids
+ ):
+ rate_tax_class_id = cast(int, rate.tax_class_id)
+ tax_rates_per_tax_class_ic[rate_tax_class_id].append(rate)
+
for line in lines:
variant = line.variant
if not variant:
continue
- tax_class = line.tax_class
- if tax_class:
- tax_rate = get_tax_rate_for_tax_class(
- tax_class,
- tax_class.country_rates.all() if tax_class else [],
+ tax_rate = default_tax_rate
+ tax_class_id = line.tax_class_id
+ if tax_class_id:
+ tax_rate = get_tax_rate_for_country(
+ tax_rates_per_tax_class_ic.get(tax_class_id, []),
default_tax_rate,
country_code,
)
@@ -165,8 +177,6 @@ def update_taxes_for_order_lines(
# try to use line.tax_rate which stores the denormalized tax rate value
# that was originally provided by the tax class.
tax_rate = denormalize_tax_rate_from_db(line.tax_rate)
- else:
- tax_rate = default_tax_rate
undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
price_with_discounts = (
diff --git a/saleor/tax/tests/test_order_calculations.py b/saleor/tax/tests/test_order_calculations.py
index 8b1d5d4282..7fce8e0ea2 100644
--- a/saleor/tax/tests/test_order_calculations.py
+++ b/saleor/tax/tests/test_order_calculations.py
@@ -2,7 +2,7 @@ from decimal import Decimal
from prices import Money, TaxedMoney
-from saleor.tax.models import TaxClassCountryRate
+from saleor.tax.models import TaxClass, TaxClassCountryRate
from ...core.prices import quantize_price
from ...core.taxes import zero_money, zero_taxed_money
@@ -335,6 +335,7 @@ def test_calculate_order_shipping(order_line, shipping_zone):
order.shipping_address = order.billing_address.get_copy()
order.shipping_method_name = method.name
order.shipping_method = method
+ order.shipping_tax_class = method.tax_class
base_shipping_price = method.channel_listings.get(channel=order.channel).price
order.base_shipping_price = base_shipping_price
order.undiscounted_base_shipping_price = base_shipping_price
@@ -665,19 +666,10 @@ def test_use_original_tax_rate_when_tax_class_is_removed_from_order_line(
)
# when
- for line in lines:
- tax_class = line.variant.product.tax_class
- if tax_class:
- tax_class.delete()
- tax_class = line.variant.product.product_type.tax_class
- if tax_class:
- tax_class.delete()
- line.refresh_from_db()
-
- shipping_tax_class = order.shipping_method.tax_class
- if shipping_tax_class:
- shipping_tax_class.delete()
- order.shipping_method.refresh_from_db()
+ TaxClass.objects.all().delete()
+
+ order.refresh_from_db()
+ lines = order.lines.all()
update_order_prices_with_flat_rates(order, lines, prices_entered_with_tax)
diff --git a/saleor/tax/utils.py b/saleor/tax/utils.py
index 73a740d0ff..7223670a57 100644
--- a/saleor/tax/utils.py
+++ b/saleor/tax/utils.py
@@ -218,17 +218,22 @@ def calculate_tax_rate(price: TaxedMoney) -> Decimal:
return tax_rate
-def get_tax_rate_for_tax_class(
- tax_class: Optional["TaxClass"],
+def get_tax_rate_for_country(
tax_class_country_rates: Iterable["TaxClassCountryRate"],
default_tax_rate: Decimal,
country_code: str,
) -> Decimal:
+ """Get tax rate for provided country code.
+
+ Function returns the tax rate for provided country code. If not found, the default
+ one will be returned.
+ `tax_class_country_rates` is the iterable set of rates assigned to single
+ `TaxClass`.
+ """
tax_rate = default_tax_rate
- if tax_class:
- for country_rate in tax_class_country_rates:
- if country_rate.country == country_code:
- tax_rate = country_rate.rate
+ for country_rate in tax_class_country_rates:
+ if country_rate.country == country_code:
+ tax_rate = country_rate.rate
return tax_rate