Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add possibility to use weighted shipping tax rate (#17726)
Maciej Korycinski07f02e2c40ae
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.pyindex 7b9191315d..0cd3b01a2c 100644--- a/saleor/checkout/calculations.py+++ b/saleor/checkout/calculations.py@@ -360,7 +360,7 @@ def _fetch_checkout_prices_if_expired(tax_configuration = checkout_info.tax_configurationtax_calculation_strategy = get_tax_calculation_strategy_for_checkout(- checkout_info, lines, database_connection_name=database_connection_name+ checkout_info, database_connection_name=database_connection_name)if (@@ -371,11 +371,11 @@ def _fetch_checkout_prices_if_expired(prices_entered_with_tax = tax_configuration.prices_entered_with_taxcharge_taxes = get_charge_taxes_for_checkout(- checkout_info, lines, database_connection_name=database_connection_name+ checkout_info, database_connection_name=database_connection_name)should_charge_tax = charge_taxes and not checkout.tax_exemptiontax_app_identifier = get_tax_app_identifier_for_checkout(- checkout_info, lines, database_connection_name+ checkout_info, database_connection_name)lines = cast(list, lines)@@ -387,9 +387,12 @@ def _fetch_checkout_prices_if_expired()checkout.tax_error = None- if prices_entered_with_tax:- # If prices are entered with tax, we need to always calculate it anyway, to- # display the tax rate to the user.++ no_need_to_calculate_taxes = not prices_entered_with_tax and not should_charge_tax+ if no_need_to_calculate_taxes:+ # Calculate net prices without taxes.+ _set_checkout_base_prices(checkout, checkout_info, lines)+ else:try:_calculate_and_add_tax(tax_calculation_strategy,@@ -417,36 +420,6 @@ def _fetch_checkout_prices_if_expired(# tax from the original gross prices._remove_tax(checkout, lines)- else:- # Prices are entered without taxes.- if should_charge_tax:- # Calculate taxes if charge_taxes is enabled and checkout is not exempt- # from taxes.- try:- _calculate_and_add_tax(- tax_calculation_strategy,- tax_app_identifier,- checkout,- manager,- checkout_info,- lines,- prices_entered_with_tax,- address,- database_connection_name=database_connection_name,- pregenerated_subscription_payloads=pregenerated_subscription_payloads,- )- except TaxDataError as e:- if str(e) != TaxDataErrorMessage.EMPTY:- extra = checkout_info_for_logs(checkout_info, lines)- if e.errors:- extra["errors"] = e.errors- logger.warning(str(e), extra=extra)- _set_checkout_base_prices(checkout, checkout_info, lines)- checkout.tax_error = str(e)- else:- # Calculate net prices without taxes.- _set_checkout_base_prices(checkout, checkout_info, lines)-checkout_update_fields = ["voucher_code","total_net_amount",@@ -503,38 +476,8 @@ def _calculate_and_add_tax():if pregenerated_subscription_payloads is None:pregenerated_subscription_payloads = {}- 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- # configured with Avatax plugin identifier.- if not tax_app_identifier:- # Call the tax plugins.- _apply_tax_data_from_plugins(- checkout, manager, checkout_info, lines, address- )- # Get the taxes calculated with apps and apply to checkout.- # We should allow empty tax_data in case any tax webhook has not been- # configured - handled by `allowed_empty_tax_data`- tax_data = _get_taxes_for_checkout(- checkout_info,- lines,- tax_app_identifier,- manager,- pregenerated_subscription_payloads,- allowed_empty_tax_data=True,- )- _apply_tax_data(checkout, lines, tax_data)- else:- _call_plugin_or_tax_app(- tax_app_identifier,- checkout,- manager,- checkout_info,- lines,- address,- pregenerated_subscription_payloads,- )- else:++ if tax_calculation_strategy != TaxCalculationStrategy.TAX_APP:# Get taxes calculated with flat rates and apply to checkout.update_checkout_prices_with_flat_rates(checkout,@@ -544,6 +487,36 @@ def _calculate_and_add_tax(address,database_connection_name=database_connection_name,)+ return++ # 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+ # configured with Avatax plugin identifier.+ if not tax_app_identifier:+ # Call the tax plugins.+ _apply_tax_data_from_plugins(checkout, manager, checkout_info, lines, address)+ # Get the taxes calculated with apps and apply to checkout.+ # We should allow empty tax_data in case any tax webhook has not been+ # configured - handled by `allowed_empty_tax_data`+ tax_data = _get_taxes_for_checkout(+ checkout_info,+ lines,+ tax_app_identifier,+ manager,+ pregenerated_subscription_payloads,+ allowed_empty_tax_data=True,+ )+ _apply_tax_data(checkout, lines, tax_data)+ else:+ _call_plugin_or_tax_app(+ tax_app_identifier,+ checkout,+ manager,+ checkout_info,+ lines,+ address,+ pregenerated_subscription_payloads,+ )def _call_plugin_or_tax_app(diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.pyindex 2f9d280f88..545fd4f3b7 100644--- a/saleor/checkout/tests/test_calculations.py+++ b/saleor/checkout/tests/test_calculations.py@@ -307,6 +307,75 @@ def test_fetch_checkout_data_flat_rates(assert checkout.shipping_tax_rate == Decimal("0.2300")[email protected]("allow_sync_webhooks", [True, False])+@patch(+ "saleor.checkout.calculations.update_checkout_prices_with_flat_rates",+ wraps=update_checkout_prices_with_flat_rates,+)[email protected]("prices_entered_with_tax", [True, False])+def test_fetch_checkout_data_flat_rates_with_weighted_shipping_tax(+ mocked_update_checkout_prices_with_flat_rates,+ allow_sync_webhooks,+ checkout_with_items_and_shipping,+ address,+ prices_entered_with_tax,+ tax_classes,+ plugins_manager,+):+ # given+ checkout = checkout_with_items_and_shipping++ tc = checkout.channel.tax_configuration+ tc.country_exceptions.all().delete()+ tc.prices_entered_with_tax = prices_entered_with_tax+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES+ tc.use_weighted_tax_for_shipping = True+ tc.save()++ country_code = checkout.shipping_address.country.code+ first_line = checkout.lines.first()+ second_line = checkout.lines.last()+ first_tax_class = first_line.variant.product.tax_class+ first_tax_class.country_rates.filter(country=country_code).update(rate=5)+ first_line.variant.product.tax_class = first_tax_class+ first_line.variant.product.save()++ second_tax_class = tax_classes[0]+ second_tax_class.country_rates.filter(country=country_code).update(rate=60)+ second_line.variant.product.tax_class = second_tax_class+ second_line.variant.product.save()++ third_tax_class = tax_classes[1]+ third_tax_class.country_rates.filter(country=country_code).update(rate=223)+ checkout.shipping_method.tax_class = third_tax_class+ checkout.shipping_method.save()++ lines, _ = fetch_checkout_lines(checkout_with_items_and_shipping)+ checkout_info = fetch_checkout_info(+ checkout_with_items_and_shipping, lines, plugins_manager+ )++ # when+ fetch_checkout_data(+ checkout_info,+ plugins_manager,+ lines,+ allow_sync_webhooks=allow_sync_webhooks,+ address=checkout.shipping_address,+ )++ # then+ checkout.refresh_from_db()+ lines = checkout.lines.all()++ mocked_update_checkout_prices_with_flat_rates.assert_called_once()+ total_weighted = sum(line.total_price.net.amount * line.tax_rate for line in lines)++ assert checkout.shipping_tax_rate == (+ total_weighted / sum(line.total_price.net.amount for line in lines)+ ).quantize(Decimal("0.0001"))++@patch("saleor.checkout.calculations.update_checkout_prices_with_flat_rates",wraps=update_checkout_prices_with_flat_rates,diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex d391f7c986..db8028c578 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -5326,6 +5326,13 @@ type TaxConfiguration implements Node & ObjectWithMetadata @doc(category: "TaxesAdded in Saleor 3.19."""taxAppId: String++ """+ Determines whether to use weighted tax for shipping. When set to true, the tax rate for shipping will be calculated based on the weighted average of tax rates from the order or checkout lines.++ Added in Saleor 3.21.+ """+ useWeightedTaxForShipping: Boolean}enum TaxCalculationStrategy @doc(category: "Taxes") {@@ -5357,6 +5364,13 @@ type TaxConfigurationPerCountry @doc(category: "Taxes") {Added in Saleor 3.19."""taxAppId: String++ """+ Determines whether to use weighted tax for shipping. When set to true, the tax rate for shipping will be calculated based on the weighted average of tax rates from the order or checkout lines.++ Added in Saleor 3.21.+ """+ useWeightedTaxForShipping: Boolean}"""Represents shipping method postal code rule."""@@ -19352,6 +19366,13 @@ input TaxConfigurationUpdateInput @doc(category: "Taxes") {"""List of country codes for which to remove the tax configuration."""removeCountriesConfiguration: [CountryCode!]+ """+ Determines whether to use weighted tax for shipping. When set to true, the tax rate for shipping will be calculated based on the weighted average of tax rates from the order or checkout lines. Default value is `False`.Can be used only with `taxCalculationStrategy` set to `FLAT_RATES`.++ Added in Saleor 3.21.+ """+ useWeightedTaxForShipping: Boolean+"""The tax app `App.identifier` that will be used to calculate the taxes for the given channel. Empty value for `TAX_APP` set as `taxCalculationStrategy` means that Saleor will iterate over all installed tax apps. If multiple tax apps exist with provided tax app id use the `App` with newest `created` date. It's possible to set plugin by using prefix `plugin:` with `PLUGIN_ID` e.g. with Avalara `plugin:mirumee.taxes.avalara`.Will become mandatory in 4.0 for `TAX_APP` `taxCalculationStrategy`.@@ -19383,6 +19404,13 @@ input TaxConfigurationPerCountryInput @doc(category: "Taxes") {Added in Saleor 3.19."""taxAppId: String++ """+ Determines whether to use weighted tax for shipping. When set to true, the tax rate for shipping will be calculated based on the weighted average of tax rates from the order or checkout lines. Default value is `False`.Can be used only with `taxCalculationStrategy` set to `FLAT_RATES`.++ Added in Saleor 3.21.+ """+ useWeightedTaxForShipping: Boolean}"""diff --git a/saleor/graphql/tax/mutations/tax_configuration_update.py b/saleor/graphql/tax/mutations/tax_configuration_update.pyindex 0144582555..f48a470b39 100644--- a/saleor/graphql/tax/mutations/tax_configuration_update.py+++ b/saleor/graphql/tax/mutations/tax_configuration_update.py@@ -1,3 +1,5 @@+from typing import Any+import graphenefrom django.core.exceptions import ValidationError@@ -7,7 +9,7 @@ from ....plugins import PLUGIN_IDENTIFIER_PREFIXfrom ....tax import error_codes, modelsfrom ...account.enums import CountryCodeEnumfrom ...core import ResolveInfo-from ...core.descriptions import ADDED_IN_319+from ...core.descriptions import ADDED_IN_319, ADDED_IN_321from ...core.doc_category import DOC_CATEGORY_TAXESfrom ...core.mutations import DeprecatedModelMutationfrom ...core.types import BaseInputObjectType, Error, NonNullList@@ -52,6 +54,15 @@ class TaxConfigurationPerCountryInput(BaseInputObjectType):"tax configuration." + ADDED_IN_319),)+ use_weighted_tax_for_shipping = graphene.Boolean(+ description=(+ "Determines whether to use weighted tax for shipping. When set to true, "+ "the tax rate for shipping will be calculated based on the weighted average "+ "of tax rates from the order or checkout lines. Default value is `False`."+ "Can be used only with `taxCalculationStrategy` set to `FLAT_RATES`."+ + ADDED_IN_321+ ),+ )class Meta:doc_category = DOC_CATEGORY_TAXES@@ -88,6 +99,15 @@ class TaxConfigurationUpdateInput(BaseInputObjectType):CountryCodeEnum,description="List of country codes for which to remove the tax configuration.",)+ use_weighted_tax_for_shipping = graphene.Boolean(+ description=(+ "Determines whether to use weighted tax for shipping. When set to true, "+ "the tax rate for shipping will be calculated based on the weighted average "+ "of tax rates from the order or checkout lines. Default value is `False`."+ "Can be used only with `taxCalculationStrategy` set to `FLAT_RATES`."+ + ADDED_IN_321+ ),+ )tax_app_id = graphene.String(description=("The tax app `App.identifier` that will be used to calculate the taxes for the given channel. "@@ -135,6 +155,7 @@ class TaxConfigurationUpdate(DeprecatedModelMutation):@classmethoddef clean_input(cls, info: ResolveInfo, instance, data, **kwargs):cls.clean_tax_app_id(info, instance, data)+ cls.clean_use_weighted_tax_for_shipping(info, instance, data)update_countries_configuration = data.get("update_countries_configuration", [])update_country_codes = [item["country_code"] for item in update_countries_configuration@@ -156,6 +177,77 @@ class TaxConfigurationUpdate(DeprecatedModelMutation):return super().clean_input(info, instance, data, **kwargs)+ @classmethod+ def _clean_use_weighted_tax_for_shipping(+ cls,+ instance: models.TaxConfiguration | models.TaxConfigurationPerCountry,+ data: dict[str, Any],+ ):+ use_weighted_tax_for_shipping = data.get("use_weighted_tax_for_shipping")+ if use_weighted_tax_for_shipping is None:+ use_weighted_tax_for_shipping = instance.use_weighted_tax_for_shipping+ if use_weighted_tax_for_shipping:+ current_tax_strategy = (+ data.get("tax_calculation_strategy")+ or instance.tax_calculation_strategy+ )+ if current_tax_strategy != TaxCalculationStrategy.FLAT_RATES.value:+ message = "`useWeightedTaxForShipping` can be used only with `taxCalculationStrategy` set to `FLAT_RATES`."+ raise ValidationError(message=message)++ @classmethod+ def clean_use_weighted_tax_for_shipping(+ cls, info: ResolveInfo, instance: TaxConfiguration, data: dict[str, Any]+ ):+ try:+ cls._clean_use_weighted_tax_for_shipping(instance, data)+ except ValidationError as e:+ raise ValidationError(+ {+ "use_weighted_tax_for_shipping": ValidationError(+ message=e.message,+ code=error_codes.TaxConfigurationUpdateErrorCode.INVALID.value,+ params={"country_codes": []},+ )+ }+ ) from e++ if update_countries_configuration := data.get(+ "update_countries_configuration", []+ ):+ error_country_codes = []+ country_exceptions = instance.country_exceptions.filter(+ country__in=[+ country_data["country_code"]+ for country_data in update_countries_configuration+ ]+ )+ input_country_exception_map = {+ country_data["country_code"]: country_data+ for country_data in update_countries_configuration+ }++ for country_exception in country_exceptions:+ try:+ cls._clean_use_weighted_tax_for_shipping(+ country_exception,+ input_country_exception_map[country_exception.country],+ )+ except ValidationError:+ error_country_codes.append(country_exception.country.code)+ if error_country_codes:+ raise ValidationError(+ {+ "use_weighted_tax_for_shipping": ValidationError(+ message="`useWeightedTaxForShipping` can be used only "+ "with `taxCalculationStrategy` set to `FLAT_RATES` for "+ "country codes: " + ", ".join(error_country_codes),+ code=error_codes.TaxConfigurationUpdateErrorCode.INVALID.value,+ params={"country_codes": error_country_codes},+ )+ }+ )+@classmethoddef clean_tax_app_id(cls, info: ResolveInfo, instance, data):identifiers = []@@ -232,7 +324,14 @@ class TaxConfigurationUpdate(DeprecatedModelMutation):obj.display_gross_prices = data["display_gross_prices"]obj.tax_calculation_strategy = data.get("tax_calculation_strategy")obj.tax_app_id = data.get("tax_app_id")++ if data.get("use_weighted_tax_for_shipping") is not None:+ obj.use_weighted_tax_for_shipping = data[+ "use_weighted_tax_for_shipping"+ ]+updated_countries.append(obj.country.code)+models.TaxConfigurationPerCountry.objects.bulk_update(to_update,fields=(@@ -240,6 +339,7 @@ class TaxConfigurationUpdate(DeprecatedModelMutation):"display_gross_prices","tax_calculation_strategy","tax_app_id",+ "use_weighted_tax_for_shipping",),)@@ -252,6 +352,9 @@ class TaxConfigurationUpdate(DeprecatedModelMutation):tax_calculation_strategy=item.get("tax_calculation_strategy"),display_gross_prices=item["display_gross_prices"],tax_app_id=item.get("tax_app_id"),+ use_weighted_tax_for_shipping=item.get(+ "use_weighted_tax_for_shipping", False+ ),)for item in countries_configurationif item["country_code"] not in updated_countriesdiff --git a/saleor/graphql/tax/tests/fragments.py b/saleor/graphql/tax/tests/fragments.pyindex 27858a3905..f6eeebf355 100644--- a/saleor/graphql/tax/tests/fragments.py+++ b/saleor/graphql/tax/tests/fragments.py@@ -9,6 +9,7 @@ TAX_CONFIGURATION_FRAGMENT = """taxCalculationStrategydisplayGrossPricespricesEnteredWithTax+ useWeightedTaxForShippingcountries {country {code@@ -18,6 +19,7 @@ TAX_CONFIGURATION_FRAGMENT = """taxCalculationStrategydisplayGrossPricestaxAppId+ useWeightedTaxForShipping}taxAppIdmetadata {diff --git a/saleor/graphql/tax/tests/mutations/test_tax_configuration_update.py b/saleor/graphql/tax/tests/mutations/test_tax_configuration_update.pyindex c7630f1899..533b7ac597 100644--- a/saleor/graphql/tax/tests/mutations/test_tax_configuration_update.py+++ b/saleor/graphql/tax/tests/mutations/test_tax_configuration_update.py@@ -176,12 +176,14 @@ def test_create_and_update_country_configurations("chargeTaxes": False,"taxCalculationStrategy": TaxCalculationStrategy.FLAT_RATES.value,"displayGrossPrices": False,+ "useWeightedTaxForShipping": False,}create_DE_data = {"countryCode": "DE","chargeTaxes": False,"taxCalculationStrategy": TaxCalculationStrategy.FLAT_RATES.value,"displayGrossPrices": False,+ "useWeightedTaxForShipping": False,}variables = {@@ -229,11 +231,13 @@ def test_create_and_update_country_configurations_no_tax_calculation_strategy("countryCode": "PL","chargeTaxes": False,"displayGrossPrices": False,+ "useWeightedTaxForShipping": False,}create_PT_data = {"countryCode": "PT","chargeTaxes": False,"displayGrossPrices": False,+ "useWeightedTaxForShipping": False,}variables = {@@ -417,3 +421,316 @@ def test_tax_configuration_update_tax_app_id_with_plugin(data = content["data"]["taxConfigurationUpdate"]["taxConfiguration"]assert not content["data"]["taxConfigurationUpdate"]["errors"]assert data["taxAppId"] == plugin_id+++def test_tax_configuration_update_use_weighted_tax_for_shipping(+ example_tax_configuration, staff_api_client, permission_manage_taxes+):+ # given+ tax_id = graphene.Node.to_global_id(+ "TaxConfiguration", example_tax_configuration.pk+ )+ variables = {+ "id": tax_id,+ "input": {+ "useWeightedTaxForShipping": True,+ "taxCalculationStrategy": TaxCalculationStrategy.FLAT_RATES.value,+ },+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION, variables, permissions=[permission_manage_taxes]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["taxConfigurationUpdate"]+ assert not data["errors"]++ # Verify the value was set correctly in the response+ assert data["taxConfiguration"]["useWeightedTaxForShipping"] is True++ # Verify the value was saved in the database+ example_tax_configuration.refresh_from_db()+ assert example_tax_configuration.use_weighted_tax_for_shipping is True+++def test_tax_configuration_update_turn_off_use_weighted_tax_for_shipping(+ example_tax_configuration, staff_api_client, permission_manage_taxes+):+ # given+ example_tax_configuration.use_weighted_tax_for_shipping = True+ example_tax_configuration.save(update_fields=["use_weighted_tax_for_shipping"])++ tax_id = graphene.Node.to_global_id(+ "TaxConfiguration", example_tax_configuration.pk+ )+ variables = {+ "id": tax_id,+ "input": {+ "useWeightedTaxForShipping": False,+ "taxCalculationStrategy": TaxCalculationStrategy.FLAT_RATES.value,+ },+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION, variables, permissions=[permission_manage_taxes]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["taxConfigurationUpdate"]+ assert not data["errors"]++ # Verify the value was set correctly in the response+ assert data["taxConfiguration"]["useWeightedTaxForShipping"] is False++ # Verify the value was saved in the database+ example_tax_configuration.refresh_from_db()+ assert example_tax_configuration.use_weighted_tax_for_shipping is False+++def test_tax_configuration_update_use_weighted_tax_for_shipping_with_tax_app_included_in_input(+ example_tax_configuration, staff_api_client, permission_manage_taxes+):+ # given+ tax_id = graphene.Node.to_global_id(+ "TaxConfiguration", example_tax_configuration.pk+ )++ variables = {+ "id": tax_id,+ "input": {+ "useWeightedTaxForShipping": True,+ "taxCalculationStrategy": TaxCalculationStrategy.TAX_APP.value,+ },+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION, variables, permissions=[permission_manage_taxes]+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["taxConfigurationUpdate"]["errors"]+ assert errors+ assert errors[0]["field"] == "useWeightedTaxForShipping"+ assert errors[0]["code"] == "INVALID"+ assert errors[0]["countryCodes"] == []+++def test_tax_configuration_update_use_weighted_tax_for_shipping_with_tax_app_already_set(+ example_tax_configuration, staff_api_client, permission_manage_taxes+):+ # given+ tax_id = graphene.Node.to_global_id(+ "TaxConfiguration", example_tax_configuration.pk+ )++ example_tax_configuration.tax_calculation_strategy = (+ TaxCalculationStrategy.TAX_APP.value+ )+ example_tax_configuration.save(update_fields=["tax_calculation_strategy"])++ variables = {+ "id": tax_id,+ "input": {+ "useWeightedTaxForShipping": True,+ },+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION, variables, permissions=[permission_manage_taxes]+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["taxConfigurationUpdate"]["errors"]+ assert errors+ assert errors[0]["field"] == "useWeightedTaxForShipping"+ assert errors[0]["code"] == "INVALID"+ assert errors[0]["countryCodes"] == []+++def test_tax_configuration_per_country_update_use_weighted_tax_for_shipping(+ example_tax_configuration, staff_api_client, permission_manage_taxes+):+ # given+ tax_id = graphene.Node.to_global_id(+ "TaxConfiguration", example_tax_configuration.pk+ )+ country_code = "PL"+ assert example_tax_configuration.country_exceptions.get(country=country_code)++ variables = {+ "id": tax_id,+ "input": {+ "updateCountriesConfiguration": [+ {+ "countryCode": country_code,+ "chargeTaxes": True,+ "displayGrossPrices": True,+ "taxCalculationStrategy": TaxCalculationStrategy.FLAT_RATES.value,+ "useWeightedTaxForShipping": True,+ }+ ],+ },+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION, variables, permissions=[permission_manage_taxes]+ )++ # then+ content = get_graphql_content(response, ignore_errors=True)+ data = content["data"]["taxConfigurationUpdate"]+ assert not data["errors"]++ assert data["taxConfiguration"]["countries"]+ assert data["taxConfiguration"]["countries"][0]["useWeightedTaxForShipping"] is True++ country_exception = example_tax_configuration.country_exceptions.get(+ country=country_code+ )+ assert country_exception.use_weighted_tax_for_shipping is True+++def test_tax_configuration_per_country_update_turn_off_weighted_tax_for_shipping(+ example_tax_configuration, staff_api_client, permission_manage_taxes+):+ # given+ example_tax_configuration.use_weighted_tax_for_shipping = True+ example_tax_configuration.save(update_fields=["use_weighted_tax_for_shipping"])++ tax_id = graphene.Node.to_global_id(+ "TaxConfiguration", example_tax_configuration.pk+ )+ country_code = "PL"+ country_exception = example_tax_configuration.country_exceptions.get(+ country=country_code+ )+ country_exception.use_weighted_tax_for_shipping = True+ country_exception.save(update_fields=["use_weighted_tax_for_shipping"])++ variables = {+ "id": tax_id,+ "input": {+ "updateCountriesConfiguration": [+ {+ "countryCode": country_code,+ "chargeTaxes": True,+ "displayGrossPrices": True,+ "taxCalculationStrategy": TaxCalculationStrategy.FLAT_RATES.value,+ "useWeightedTaxForShipping": False,+ }+ ],+ },+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION, variables, permissions=[permission_manage_taxes]+ )++ # then+ content = get_graphql_content(response, ignore_errors=True)+ data = content["data"]["taxConfigurationUpdate"]+ assert not data["errors"]++ assert data["taxConfiguration"]["countries"]+ assert (+ data["taxConfiguration"]["countries"][0]["useWeightedTaxForShipping"] is False+ )++ country_exception = example_tax_configuration.country_exceptions.get(+ country=country_code+ )+ assert country_exception.use_weighted_tax_for_shipping is False+++def test_tax_configuration_per_country_update_use_weighted_tax_for_shipping_with_tax_app_included_in_input(+ example_tax_configuration, staff_api_client, permission_manage_taxes+):+ # given+ tax_id = graphene.Node.to_global_id(+ "TaxConfiguration", example_tax_configuration.pk+ )+ country_code = "PL"+ assert example_tax_configuration.country_exceptions.get(country=country_code)++ country_config = {+ "countryCode": country_code,+ "chargeTaxes": True,+ "displayGrossPrices": True,+ "useWeightedTaxForShipping": True,+ "taxCalculationStrategy": TaxCalculationStrategy.TAX_APP.value,+ }++ variables = {+ "id": tax_id,+ "input": {+ "updateCountriesConfiguration": [country_config],+ },+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION, variables, permissions=[permission_manage_taxes]+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["taxConfigurationUpdate"]["errors"]+ assert errors+ assert errors[0]["field"] == "useWeightedTaxForShipping"+ assert errors[0]["code"] == "INVALID"+ assert errors[0]["countryCodes"] == [country_code]+++def test_tax_configuration_per_country_update_use_weighted_tax_for_shipping_with_tax_app_already_set(+ example_tax_configuration, staff_api_client, permission_manage_taxes+):+ # given+ tax_id = graphene.Node.to_global_id(+ "TaxConfiguration", example_tax_configuration.pk+ )+ country_code = "PL"+ assert example_tax_configuration.country_exceptions.get(country=country_code)++ country_exception = example_tax_configuration.country_exceptions.get(+ country=country_code,+ )+ country_exception.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP.value+ country_exception.save(update_fields=["tax_calculation_strategy"])++ country_config = {+ "countryCode": country_code,+ "chargeTaxes": True,+ "displayGrossPrices": True,+ "useWeightedTaxForShipping": True,+ }++ variables = {+ "id": tax_id,+ "input": {+ "updateCountriesConfiguration": [country_config],+ },+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION, variables, permissions=[permission_manage_taxes]+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["taxConfigurationUpdate"]["errors"]+ assert errors+ assert errors[0]["field"] == "useWeightedTaxForShipping"+ assert errors[0]["code"] == "INVALID"+ assert errors[0]["countryCodes"] == [country_code]diff --git a/saleor/graphql/tax/tests/queries/test_tax_configuration.py b/saleor/graphql/tax/tests/queries/test_tax_configuration.pyindex f27f3baac5..0342e298b3 100644--- a/saleor/graphql/tax/tests/queries/test_tax_configuration.py+++ b/saleor/graphql/tax/tests/queries/test_tax_configuration.py@@ -27,6 +27,10 @@ def _test_field_resolvers(tax_configuration: TaxConfiguration, data: dict):assert data["displayGrossPrices"] == tax_configuration.display_gross_pricesassert data["pricesEnteredWithTax"] == tax_configuration.prices_entered_with_taxassert data["taxAppId"] == tax_configuration.tax_app_id+ assert (+ data["useWeightedTaxForShipping"]+ == tax_configuration.use_weighted_tax_for_shipping+ )assert len(data["countries"]) == len(country_exceptions)assert data["countries"][0]["country"]["code"] == country_exception.country.codeassert data["countries"][0]["chargeTaxes"] == country_exception.charge_taxes@@ -35,6 +39,10 @@ def _test_field_resolvers(tax_configuration: TaxConfiguration, data: dict):== country_exception.display_gross_prices)assert data["countries"][0]["taxAppId"] == country_exception.tax_app_id+ assert (+ data["countries"][0]["useWeightedTaxForShipping"]+ == country_exception.use_weighted_tax_for_shipping+ )def test_tax_configuration_query_no_permissions(channel_USD, user_api_client):diff --git a/saleor/graphql/tax/types.py b/saleor/graphql/tax/types.pyindex 1ea93c64b4..a8ef538557 100644--- a/saleor/graphql/tax/types.py+++ b/saleor/graphql/tax/types.py@@ -5,7 +5,7 @@ from ..channel.dataloaders import ChannelByIdLoaderfrom ..channel.types import Channelfrom ..core import ResolveInfofrom ..core.connection import CountableConnection-from ..core.descriptions import ADDED_IN_319+from ..core.descriptions import ADDED_IN_319, ADDED_IN_321from ..core.doc_category import DOC_CATEGORY_TAXESfrom ..core.types import BaseObjectType, CountryDisplay, ModelObjectType, NonNullListfrom ..meta.types import ObjectWithMetadata@@ -61,6 +61,13 @@ class TaxConfiguration(ModelObjectType[models.TaxConfiguration]):),required=False,)+ use_weighted_tax_for_shipping = graphene.Boolean(+ description=(+ "Determines whether to use weighted tax for shipping. When set to true, "+ "the tax rate for shipping will be calculated based on the weighted average "+ "of tax rates from the order or checkout lines." + ADDED_IN_321+ ),+ )class Meta:description = "Channel-specific tax configuration."@@ -77,6 +84,12 @@ class TaxConfiguration(ModelObjectType[models.TaxConfiguration]):root.pk)+ @staticmethod+ def resolve_use_weighted_tax_for_shipping(+ root: models.TaxConfiguration, info: ResolveInfo+ ):+ return root.use_weighted_tax_for_shipping+class TaxConfigurationCountableConnection(CountableConnection):class Meta:@@ -117,6 +130,13 @@ class TaxConfigurationPerCountry(ModelObjectType[models.TaxConfigurationPerCount),required=False,)+ use_weighted_tax_for_shipping = graphene.Boolean(+ description=(+ "Determines whether to use weighted tax for shipping. When set to true, "+ "the tax rate for shipping will be calculated based on the weighted average "+ "of tax rates from the order or checkout lines." + ADDED_IN_321+ ),+ )class Meta:description = "Country-specific exceptions of a channel's tax configuration."@@ -127,6 +147,12 @@ class TaxConfigurationPerCountry(ModelObjectType[models.TaxConfigurationPerCountdef resolve_country(root: models.TaxConfigurationPerCountry, _info: ResolveInfo):return CountryDisplay(code=root.country.code, country=root.country.name)+ @staticmethod+ def resolve_use_weighted_tax_for_shipping(+ root: models.TaxConfiguration, info: ResolveInfo+ ):+ return root.use_weighted_tax_for_shipping+class TaxClass(ModelObjectType[models.TaxClass]):name = graphene.String(description="Name of the tax class.", required=True)diff --git a/saleor/graphql/webhook/dataloaders/pregenerated_payload_for_checkout_tax.py b/saleor/graphql/webhook/dataloaders/pregenerated_payload_for_checkout_tax.pyindex c7a0bbb9f3..9f05e6319e 100644--- a/saleor/graphql/webhook/dataloaders/pregenerated_payload_for_checkout_tax.py+++ b/saleor/graphql/webhook/dataloaders/pregenerated_payload_for_checkout_tax.py@@ -21,9 +21,7 @@ from ...core.dataloaders import DataLoaderfrom ..subscription_payload import generate_payload_promise_from_subscriptionfrom ..utils import get_subscription_query_hashfrom .models import WebhooksByEventTypeLoader-from .request_context import (- PayloadsRequestContextByEventTypeLoader,-)+from .request_context import PayloadsRequestContextByEventTypeLoaderclass PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader(DataLoader):@@ -59,12 +57,10 @@ class PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader(DataLoader):checkouts_info, checkout_lines_info, apps, request_context, webhooks = dataapps_map = {app.id: app for app in apps}promises = []- for checkout_info, lines_info in zip(- checkouts_info, checkout_lines_info, strict=False- ):+ for checkout_info in checkouts_info:tax_configuration, country_tax_configuration = (get_tax_configuration_for_checkout(- checkout_info, lines_info, self.database_connection_name+ checkout_info, self.database_connection_name))tax_strategy = get_tax_calculation_strategy(diff --git a/saleor/order/tests/benchmark/test_fetch_order_prices.py b/saleor/order/tests/benchmark/test_fetch_order_prices.pyindex 1ce42fb7e8..cc87cb94bb 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(28):+ with django_assert_num_queries(29):fetch_order_prices_if_expired(order, plugins_manager, None, True)diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.pyindex 526c3ecb2e..8ad803115e 100644--- a/saleor/order/tests/test_calculations.py+++ b/saleor/order/tests/test_calculations.py@@ -17,6 +17,7 @@ from ...core.taxes import ()from ...discount import DiscountValueTypefrom ...graphql.core.utils import to_global_id_or_none+from ...order.utils import get_order_countryfrom ...plugins import PLUGIN_IDENTIFIER_PREFIXfrom ...plugins.avatax.plugin import AvataxPluginfrom ...plugins.avatax.tests.conftest import plugin_configuration # noqa: F401@@ -1661,14 +1662,9 @@ def test_fetch_order_data_tax_data_with_tax_data_error(assert mocked_logger.call_args[1]["extra"]["errors"] == errors- "prices_entered_with_tax",- [True, False],-)@patch.object(logger, "warning")def test_fetch_order_data_tax_data_missing_tax_id_empty_tax_data(mocked_logger,- prices_entered_with_tax,order_with_lines,):# given@@ -1676,7 +1672,7 @@ def test_fetch_order_data_tax_data_missing_tax_id_empty_tax_data(channel = order.channelchannel.tax_configuration.tax_app_id = None- channel.tax_configuration.prices_entered_with_tax = prices_entered_with_tax+ channel.tax_configuration.prices_entered_with_tax = Truechannel.tax_configuration.save()zero_money = zero_taxed_money(order.currency)@@ -1797,3 +1793,69 @@ def test_fetch_order_data_plugin_tax_data_price_overflow(assert order.tax_error == TaxDataErrorMessage.OVERFLOWassert TaxDataErrorMessage.OVERFLOW in caplog.textassert caplog.records[0].order_id == to_global_id_or_none(order)+++@patch(+ "saleor.order.calculations.update_order_prices_with_flat_rates",+ wraps=update_order_prices_with_flat_rates,+)[email protected]("prices_entered_with_tax", [True, False])+def test_fetch_order_prices_flat_rates_with_weighted_shipping_tax(+ mocked_update_order_prices_with_flat_rates,+ order_with_lines_untaxed,+ prices_entered_with_tax,+ tax_classes,+ plugins_manager,+ tax_configuration_flat_rates,+):+ # given+ order = order_with_lines_untaxed++ tax_configuration_flat_rates.use_weighted_tax_for_shipping = True+ tax_configuration_flat_rates.save()++ country = get_order_country(order)++ lines = list(order.lines.all())+ first_line = lines[0]+ second_line = lines[-1]++ # Set different tax rates for different lines+ first_rate = Decimal("5")+ second_rate = Decimal("60")+ shipping_rate = Decimal("223")++ first_line.tax_class.country_rates.filter(country=country).update(rate=first_rate)++ second_tax_class = tax_classes[0]+ second_line.tax_class = second_tax_class+ second_line.save()+ second_tax_class.country_rates.filter(country=country).update(rate=second_rate)++ # Set a different tax rate for shipping+ shipping_tax_class = tax_classes[1]+ shipping_tax_class.country_rates.filter(country=country).update(rate=shipping_rate)++ order.shipping_method.tax_class = shipping_tax_class+ order.shipping_method.save()++ # when+ calculations.fetch_order_prices_if_expired(+ order=order,+ manager=plugins_manager,+ force_update=True,+ )++ # then+ order.refresh_from_db()+ lines = list(order.lines.all())++ mocked_update_order_prices_with_flat_rates.assert_called_once()++ # Calculate the expected weighted tax rate+ total_weighted = sum(line.total_price.net.amount * line.tax_rate for line in lines)+ total_net = sum(line.total_price.net.amount for line in lines)+ expected_tax_rate = (total_weighted / total_net).quantize(Decimal("0.0001"))++ assert order.shipping_tax_rate == expected_tax_rate+ assert order.shipping_tax_rate != shipping_rate / 100diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.pyindex 42a4ea7aba..230cd06441 100644--- a/saleor/plugins/avatax/__init__.py+++ b/saleor/plugins/avatax/__init__.py@@ -287,7 +287,7 @@ def generate_request_data_from_checkout_lines() -> list[dict[str, str | int | bool | None]]:data: list[dict[str, str | int | bool | None]] = []- charge_taxes = get_charge_taxes_for_checkout(checkout_info, lines_info)+ charge_taxes = get_charge_taxes_for_checkout(checkout_info)prices_entered_with_tax = checkout_info.tax_configuration.prices_entered_with_taxvoucher = checkout_info.voucherdiff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.pyindex 095ae2a055..3972e7bc23 100644--- a/saleor/plugins/avatax/plugin.py+++ b/saleor/plugins/avatax/plugin.py@@ -323,8 +323,8 @@ class AvataxPlugin(BasePlugin):if self._skip_plugin(previous_value):return previous_value- tax_strategy = get_tax_calculation_strategy_for_checkout(checkout_info, lines)- tax_app_identifier = get_tax_app_identifier_for_checkout(checkout_info, lines)+ tax_strategy = get_tax_calculation_strategy_for_checkout(checkout_info)+ tax_app_identifier = get_tax_app_identifier_for_checkout(checkout_info)if (tax_strategy == TaxCalculationStrategy.FLAT_RATESor tax_app_identifier is not None@@ -396,7 +396,7 @@ class AvataxPlugin(BasePlugin):address: Optional["Address"],previous_value: TaxedMoney,) -> TaxedMoney:- charge_taxes = get_charge_taxes_for_checkout(checkout_info, lines)+ charge_taxes = get_charge_taxes_for_checkout(checkout_info)if not charge_taxes:return previous_value@@ -538,8 +538,7 @@ class AvataxPlugin(BasePlugin):previous_value: TaxedMoney,) -> TaxedMoney:base_total = previous_value- charge_taxes = get_charge_taxes_for_checkout(checkout_info, lines)-+ charge_taxes = get_charge_taxes_for_checkout(checkout_info)if not charge_taxes:return base_total@@ -681,7 +680,7 @@ class AvataxPlugin(BasePlugin):address: Optional["Address"],previous_value: Decimal,) -> Decimal:- charge_taxes = get_charge_taxes_for_checkout(checkout_info, lines)+ charge_taxes = get_charge_taxes_for_checkout(checkout_info)if not charge_taxes:return previous_value@@ -777,7 +776,7 @@ class AvataxPlugin(BasePlugin):lines_info: list["CheckoutLineInfo"],tax_error_message: str,) -> None:- app_identifier = get_tax_app_identifier_for_checkout(checkout_info, lines_info)+ app_identifier = get_tax_app_identifier_for_checkout(checkout_info)if app_identifier == self.PLUGIN_IDENTIFIER:checkout_info.checkout.tax_error = tax_error_messagediff --git a/saleor/tax/calculations/checkout.py b/saleor/tax/calculations/checkout.pyindex 99cb4b2d66..06b8d4c09f 100644--- a/saleor/tax/calculations/checkout.py+++ b/saleor/tax/calculations/checkout.py@@ -1,4 +1,3 @@-from collections.abc import Iterablefrom decimal import Decimalfrom typing import TYPE_CHECKING, Optional@@ -10,7 +9,11 @@ from ...core.prices import quantize_pricefrom ...core.taxes import zero_taxed_moneyfrom ...core.utils.country import get_active_countryfrom ..models import TaxClassCountryRate-from ..utils import get_tax_rate_for_country, normalize_tax_rate_for_db+from ..utils import (+ get_shipping_tax_rate_for_checkout,+ get_tax_rate_for_country,+ normalize_tax_rate_for_db,+)from . import calculate_flat_rate_taxif TYPE_CHECKING:@@ -42,12 +45,14 @@ def update_checkout_prices_with_flat_rates(for line_info in lines:line = line_info.linetax_class = line_info.tax_class+tax_rate = get_tax_rate_for_country(tax_class.country_rates.all() if tax_class else [],default_tax_rate,country_code,)- line_total_price = calculate_checkout_line_total(++ line_total_price = _calculate_checkout_line_total(checkout_info,lines,line_info,@@ -58,21 +63,14 @@ def update_checkout_prices_with_flat_rates(line.tax_rate = normalize_tax_rate_for_db(tax_rate)# 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,+ shipping_tax_rate = get_shipping_tax_rate_for_checkout(+ checkout_info,+ lines,default_tax_rate,country_code,+ database_connection_name=database_connection_name,)- shipping_price = calculate_checkout_shipping(+ shipping_price = _calculate_checkout_shipping(checkout_info, lines, shipping_tax_rate, prices_entered_with_tax)checkout.shipping_price = shipping_price@@ -86,7 +84,7 @@ def update_checkout_prices_with_flat_rates(checkout.total = subtotal + shipping_price-def calculate_checkout_shipping(+def _calculate_checkout_shipping(checkout_info: "CheckoutInfo",lines: list["CheckoutLineInfo"],tax_rate: Decimal,@@ -101,7 +99,7 @@ def calculate_checkout_shipping(return quantize_price(shipping_price_taxed, shipping_price_taxed.currency)-def calculate_checkout_line_total(+def _calculate_checkout_line_total(checkout_info: "CheckoutInfo",lines: list["CheckoutLineInfo"],checkout_line_info: "CheckoutLineInfo",diff --git a/saleor/tax/calculations/order.py b/saleor/tax/calculations/order.pyindex b2dc6fb93b..cc648a63cf 100644--- a/saleor/tax/calculations/order.py+++ b/saleor/tax/calculations/order.py@@ -13,6 +13,7 @@ from ...order.utils import get_order_countryfrom ..models import TaxClassCountryRatefrom ..utils import (denormalize_tax_rate_from_db,+ get_shipping_tax_rate_for_order,get_tax_rate_for_country,normalize_tax_rate_for_db,)@@ -49,26 +50,13 @@ def update_order_prices_with_flat_rates()# Calculate order shipping.-- 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- and order.shipping_tax_rate is not None- ):- # Use order.shipping_tax_rate if it was ever set before (it's non-null now and- # 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)+ shipping_tax_rate = get_shipping_tax_rate_for_order(+ order,+ lines,+ default_tax_rate,+ country_code,+ database_connection_name=database_connection_name,+ )order.shipping_price = _calculate_order_shipping(order, shipping_tax_rate, prices_entered_with_taxdiff --git a/saleor/tax/migrations/0010_taxconfiguration_use_weighted_tax_for_shipping_and_more.py b/saleor/tax/migrations/0010_taxconfiguration_use_weighted_tax_for_shipping_and_more.pynew file mode 100644index 0000000000..c6fb22343c--- /dev/null+++ b/saleor/tax/migrations/0010_taxconfiguration_use_weighted_tax_for_shipping_and_more.py@@ -0,0 +1,38 @@+# Generated by Django 4.2.20 on 2025-05-13 10:51++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("tax", "0009_alter_taxclasscountryrate_rate"),+ ]++ operations = [+ migrations.AddField(+ model_name="taxconfiguration",+ name="use_weighted_tax_for_shipping",+ field=models.BooleanField(default=False),+ ),+ migrations.AddField(+ model_name="taxconfigurationpercountry",+ name="use_weighted_tax_for_shipping",+ field=models.BooleanField(default=False),+ ),+ migrations.RunSQL(+ """+ ALTER TABLE tax_taxconfiguration+ ALTER COLUMN use_weighted_tax_for_shipping+ SET DEFAULT false;+ """,+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ """+ ALTER TABLE tax_taxconfigurationpercountry+ ALTER COLUMN use_weighted_tax_for_shipping+ SET DEFAULT false;+ """,+ reverse_sql=migrations.RunSQL.noop,+ ),+ ]diff --git a/saleor/tax/migrations/0011_merge_20250530_0929.py b/saleor/tax/migrations/0011_merge_20250530_0929.pynew file mode 100644index 0000000000..652f42b125--- /dev/null+++ b/saleor/tax/migrations/0011_merge_20250530_0929.py@@ -0,0 +1,12 @@+# Generated by Django 5.2.1 on 2025-05-30 09:29++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("tax", "0010_merge_20250527_1210"),+ ("tax", "0010_taxconfiguration_use_weighted_tax_for_shipping_and_more"),+ ]++ operations = []diff --git a/saleor/tax/models.py b/saleor/tax/models.pyindex dc90e37953..3903a10972 100644--- a/saleor/tax/models.py+++ b/saleor/tax/models.py@@ -63,6 +63,7 @@ class TaxConfiguration(ModelWithMetadata):display_gross_prices = models.BooleanField(default=True)prices_entered_with_tax = models.BooleanField(default=True)tax_app_id = models.CharField(blank=True, null=True, max_length=256)+ use_weighted_tax_for_shipping = models.BooleanField(default=False)class Meta:ordering = ("pk",)@@ -79,6 +80,7 @@ class TaxConfigurationPerCountry(models.Model):)display_gross_prices = models.BooleanField(default=True)tax_app_id = models.CharField(blank=True, null=True, max_length=256)+ use_weighted_tax_for_shipping = models.BooleanField(default=False)class Meta:ordering = ("country", "pk")diff --git a/saleor/tax/tests/test_checkout_calculations.py b/saleor/tax/tests/test_checkout_calculations.pyindex f96ea88ae1..fd4259078b 100644--- a/saleor/tax/tests/test_checkout_calculations.py+++ b/saleor/tax/tests/test_checkout_calculations.py@@ -15,25 +15,37 @@ from ...product.models import ProductVariantChannelListingfrom ...tax.models import TaxClassCountryRatefrom .. import TaxCalculationStrategyfrom ..calculations.checkout import (- calculate_checkout_line_total,- calculate_checkout_shipping,+ _calculate_checkout_line_total,+ _calculate_checkout_shipping,update_checkout_prices_with_flat_rates,)-def _enable_flat_rates(checkout, prices_entered_with_tax):+def _enable_flat_rates(+ checkout, prices_entered_with_tax, use_weighted_tax_for_shipping=False+):tc = checkout.channel.tax_configurationtc.country_exceptions.all().delete()tc.prices_entered_with_tax = prices_entered_with_taxtc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES+ tc.use_weighted_tax_for_shipping = use_weighted_tax_for_shippingtc.save()@pytest.mark.parametrize(- ("expected_net", "expected_gross", "voucher_amount", "prices_entered_with_tax"),+ (+ "expected_net",+ "expected_gross",+ "expected_tax_rate",+ "voucher_amount",+ "prices_entered_with_tax",+ "use_weighted_tax_for_shipping",+ ),[- ("40.00", "49.20", "0.0", False),- ("30.08", "37.00", "3.0", True),+ ("40.00", "49.20", "0.230", "0.0", False, False),+ ("30.08", "37.00", "0.230", "3.0", True, False),+ ("40.00", "49.20", "0.230", "0.0", False, True),+ ("30.08", "37.00", "0.230", "3.0", True, True),],)def test_calculate_checkout_total(@@ -43,12 +55,14 @@ def test_calculate_checkout_total(voucher,expected_net,expected_gross,+ expected_tax_rate,voucher_amount,prices_entered_with_tax,+ use_weighted_tax_for_shipping,):# givencheckout = checkout_with_item- _enable_flat_rates(checkout, prices_entered_with_tax)+ _enable_flat_rates(checkout, prices_entered_with_tax, use_weighted_tax_for_shipping)checkout.shipping_address = addressvoucher_amount = Money(voucher_amount, "USD")@@ -70,12 +84,199 @@ def test_calculate_checkout_total(checkout, checkout_info, lines, prices_entered_with_tax, address)+ # then+ for line_info in lines:+ assert line_info.line.tax_rate == Decimal(expected_tax_rate)+ assert checkout.shipping_tax_rate == Decimal(expected_tax_rate)+ assert checkout.total == TaxedMoney(+ net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")+ )+++ (+ "expected_net",+ "expected_gross",+ "prices_entered_with_tax",+ "use_weighted_tax_for_shipping",+ ),+ [+ ("80.00", "92.40", False, False),+ ("69.78", "80.00", True, False),+ ("80.00", "91.54", False, True),+ ("70.46", "80.00", True, True),+ ],+)+def test_calculate_checkout_total_with_multiple_tax_rates(+ checkout_with_items,+ address,+ shipping_zone,+ tax_classes,+ expected_net,+ expected_gross,+ prices_entered_with_tax,+ use_weighted_tax_for_shipping,+):+ # given+ checkout = checkout_with_items+ _enable_flat_rates(checkout, prices_entered_with_tax, use_weighted_tax_for_shipping)++ checkout.shipping_address = address+ checkout.shipping_method = shipping_zone.shipping_methods.get()+ checkout.save()++ first_line = checkout.lines.first()+ second_line = checkout.lines.last()+ first_line.variant.product.tax_class.country_rates.update_or_create(+ country=address.country, rate=23+ )+ assert first_line.variant.product_id != second_line.variant.product_id++ second_tax_class = tax_classes[0]+ second_tax_class.country_rates.filter(country=address.country).update(rate=3)+ second_line.variant.product.tax_class = second_tax_class+ second_line.variant.product.save()++ lines, _ = fetch_checkout_lines(checkout)+ manager = get_plugins_manager(allow_replica=False)+ checkout_info = fetch_checkout_info(checkout, lines, manager)++ # when+ update_checkout_prices_with_flat_rates(+ checkout, checkout_info, lines, prices_entered_with_tax, address+ )+# thenassert checkout.total == TaxedMoney(net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD"))+ (+ "expected_net",+ "expected_gross",+ "prices_entered_with_tax",+ ),+ [+ ("10.00", "12.30", False),+ ("8.13", "10.00", True),+ ],+)+def test_calculate_checkout_shipping_with_not_weighted_taxes(+ checkout_with_items,+ address,+ shipping_zone,+ tax_classes,+ expected_net,+ expected_gross,+ prices_entered_with_tax,+):+ # given+ checkout = checkout_with_items+ _enable_flat_rates(+ checkout, prices_entered_with_tax, use_weighted_tax_for_shipping=False+ )++ checkout.shipping_address = address+ checkout.shipping_method = shipping_zone.shipping_methods.get()+ checkout.save()++ first_line = checkout.lines.first()+ second_line = checkout.lines.last()+ first_line.variant.product.tax_class.country_rates.update_or_create(+ country=address.country, rate=23+ )+ assert first_line.variant.product_id != second_line.variant.product_id++ second_tax_class = tax_classes[0]+ second_tax_class.country_rates.filter(country=address.country).update(rate=3)+ second_line.variant.product.tax_class = second_tax_class+ second_line.variant.product.save()++ lines, _ = fetch_checkout_lines(checkout)+ manager = get_plugins_manager(allow_replica=False)+ checkout_info = fetch_checkout_info(checkout, lines, manager)++ # when+ update_checkout_prices_with_flat_rates(+ checkout, checkout_info, lines, prices_entered_with_tax, address+ )++ # then+ assert checkout.shipping_tax_rate == Decimal("0.2300")+ assert checkout.shipping_price == TaxedMoney(+ net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")+ )+++ (+ "expected_net",+ "expected_gross",+ "prices_entered_with_tax",+ ),+ [+ ("10.00", "11.44", False),+ ("8.81", "10.00", True),+ ],+)+def test_calculate_checkout_shipping_with_weighted_taxes(+ checkout_with_items,+ address,+ shipping_zone,+ tax_classes,+ expected_net,+ expected_gross,+ prices_entered_with_tax,+):+ # given+ checkout = checkout_with_items+ _enable_flat_rates(+ checkout, prices_entered_with_tax, use_weighted_tax_for_shipping=True+ )++ checkout.shipping_address = address+ checkout.shipping_method = shipping_zone.shipping_methods.get()+ checkout.save()++ first_line = checkout.lines.first()+ second_line = checkout.lines.last()+ first_line.variant.product.tax_class.country_rates.update_or_create(+ country=address.country, rate=23+ )+ assert first_line.variant.product_id != second_line.variant.product_id++ second_tax_class = tax_classes[0]+ second_tax_class.country_rates.filter(country=address.country).update(rate=3)+ second_line.variant.product.tax_class = second_tax_class+ second_line.variant.product.save()++ lines, _ = fetch_checkout_lines(checkout)+ manager = get_plugins_manager(allow_replica=False)+ checkout_info = fetch_checkout_info(checkout, lines, manager)++ # when+ update_checkout_prices_with_flat_rates(+ checkout, checkout_info, lines, prices_entered_with_tax, address+ )++ # then+ weighted_tax_amount = sum(+ line_info.line.total_price.net.amount * line_info.line.tax_rate+ for line_info in lines+ )+ weighted_tax_amount = weighted_tax_amount / sum(+ line_info.line.total_price.net.amount for line_info in lines+ )+ assert checkout.shipping_tax_rate == Decimal(weighted_tax_amount).quantize(+ Decimal("0.0001")+ )+ assert checkout.shipping_price == TaxedMoney(+ net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")+ )++@pytest.mark.parametrize(("expected_net", "expected_gross", "voucher_amount", "prices_entered_with_tax"),[@@ -542,7 +743,7 @@ def test_calculate_checkout_line_total(checkout_with_item, shipping_zone, addrescheckout_info = fetch_checkout_info(checkout, lines, manager)checkout_line_info = lines[0]- line_price = calculate_checkout_line_total(+ line_price = _calculate_checkout_line_total(checkout_info, lines, checkout_line_info, rate, prices_entered_with_tax)@@ -588,7 +789,7 @@ def test_calculate_checkout_line_total_voucher_on_entire_order(checkout_line_info = lines[0]# when- line_price = calculate_checkout_line_total(+ line_price = _calculate_checkout_line_total(checkout_info, lines, checkout_line_info, rate, prices_entered_with_tax)@@ -636,7 +837,7 @@ def test_calculate_checkout_line_total_with_voucher_one_line(checkout_line_info = lines[0]# when- line_price = calculate_checkout_line_total(+ line_price = _calculate_checkout_line_total(checkout_info,lines,checkout_line_info,@@ -703,7 +904,7 @@ def test_calculate_checkout_line_total_with_voucher_multiple_lines(checkout_line_info = lines[0]# when- line_total_price = calculate_checkout_line_total(+ line_total_price = _calculate_checkout_line_total(checkout_info,lines,checkout_line_info,@@ -780,7 +981,7 @@ def test_calculate_checkout_line_total_with_voucher_multiple_lines_last_line(checkout_line_info = lines[-1]# when- line_total_price = calculate_checkout_line_total(+ line_total_price = _calculate_checkout_line_total(checkout_info,lines,checkout_line_info,@@ -866,7 +1067,7 @@ def test_calculate_checkout_line_total_with_voucher_for_multiple_lines(result_total_prices = []for line_info in lines:result_total_prices.append(- calculate_checkout_line_total(+ _calculate_checkout_line_total(checkout_info,lines,line_info,@@ -940,7 +1141,7 @@ def test_calculate_checkout_line_total_with_shipping_voucher(checkout_line_info = lines[0]# when- line_total_price = calculate_checkout_line_total(+ line_total_price = _calculate_checkout_line_total(checkout_info,lines,checkout_line_info,@@ -986,7 +1187,7 @@ def test_calculate_checkout_line_total_discount_from_order_promotion(create_checkout_discount_objects_for_order_promotions(checkout_info, lines)# when- line_price = calculate_checkout_line_total(+ line_price = _calculate_checkout_line_total(checkout_info, lines, checkout_line_info, rate, prices_entered_with_tax)@@ -1034,7 +1235,7 @@ def test_calculate_checkout_line_total_discount_for_gift_line(create_checkout_discount_objects_for_order_promotions(checkout_info, lines)# when- line_price = calculate_checkout_line_total(+ line_price = _calculate_checkout_line_total(checkout_info, lines, checkout_line_info, rate, prices_entered_with_tax)@@ -1064,7 +1265,7 @@ def test_calculate_checkout_shipping(checkout_info = fetch_checkout_info(checkout, lines, manager)# when- shipping_price = calculate_checkout_shipping(+ shipping_price = _calculate_checkout_shipping(checkout_info, lines, rate, prices_entered_with_tax)@@ -1095,7 +1296,7 @@ def test_calculate_checkout_shipping_no_shipping_price(checkout_info = fetch_checkout_info(checkout, lines, manager)# when- shipping_price = calculate_checkout_shipping(+ shipping_price = _calculate_checkout_shipping(checkout_info, lines, rate, prices_entered_with_tax)@@ -1136,7 +1337,7 @@ def test_calculate_checkout_shipping_voucher_on_shipping(price = shipping_channel_listings.price# when- shipping_price = calculate_checkout_shipping(+ shipping_price = _calculate_checkout_shipping(checkout_info, lines, rate, prices_entered_with_tax)@@ -1179,7 +1380,7 @@ def test_calculate_checkout_shipping_free_shipping_voucher(checkout_info = fetch_checkout_info(checkout, lines, manager)# when- shipping_price = calculate_checkout_shipping(+ shipping_price = _calculate_checkout_shipping(checkout_info, lines, rate, prices_entered_with_tax)@@ -1217,7 +1418,7 @@ def test_calculate_checkout_shipping_free_entire_order_voucher(checkout_info = fetch_checkout_info(checkout, lines, manager)# when- shipping_price = calculate_checkout_shipping(+ shipping_price = _calculate_checkout_shipping(checkout_info, lines, rate, prices_entered_with_tax)diff --git a/saleor/tax/tests/test_order_calculations.py b/saleor/tax/tests/test_order_calculations.pyindex 7fce8e0ea2..9382628fe5 100644--- a/saleor/tax/tests/test_order_calculations.py+++ b/saleor/tax/tests/test_order_calculations.py@@ -1,5 +1,6 @@from decimal import Decimal+import pytestfrom prices import Money, TaxedMoneyfrom saleor.tax.models import TaxClass, TaxClassCountryRate@@ -21,19 +22,25 @@ from ..calculations.order import ()-def _enable_flat_rates(order, prices_entered_with_tax):+def _enable_flat_rates(+ order, prices_entered_with_tax, use_weighted_tax_for_shipping=False+):tc = order.channel.tax_configurationtc.country_exceptions.all().delete()tc.prices_entered_with_tax = prices_entered_with_taxtc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES+ tc.use_weighted_tax_for_shipping = use_weighted_tax_for_shippingtc.save()-def test_calculations_calculate_order_total(order_with_lines_untaxed):[email protected]("use_weighted_tax_for_shipping", [True, False])+def test_calculations_calculate_order_total(+ order_with_lines_untaxed, use_weighted_tax_for_shipping+):# givenorder = order_with_lines_untaxedprices_entered_with_tax = True- _enable_flat_rates(order, prices_entered_with_tax)+ _enable_flat_rates(order, prices_entered_with_tax, use_weighted_tax_for_shipping)lines = order.lines.all()# when@@ -45,13 +52,172 @@ def test_calculations_calculate_order_total(order_with_lines_untaxed):)+ (+ "expected_net",+ "expected_gross",+ "prices_entered_with_tax",+ "use_weighted_tax_for_shipping",+ ),+ [+ ("80.00", "90.40", False, False),+ ("71.35", "80.00", True, False),+ ("80.00", "89.26", False, True),+ ("72.25", "80.00", True, True),+ ],+)+def test_calculate_order_total_with_multiple_tax_rates(+ order_with_lines_untaxed,+ expected_net,+ expected_gross,+ prices_entered_with_tax,+ use_weighted_tax_for_shipping,+ tax_classes,+):+ # given+ order = order_with_lines_untaxed+ _enable_flat_rates(order, prices_entered_with_tax, use_weighted_tax_for_shipping)++ country = get_order_country(order)++ lines = list(order.lines.all())+ first_line = lines[0]+ second_line = lines[-1]++ # Set different tax rates for different products+ first_line.tax_class.country_rates.update_or_create(country=country, rate=23)++ second_tax_class = tax_classes[0]+ second_tax_class.country_rates.filter(country=country).update(rate=3)+ second_line.tax_class = second_tax_class+ second_line.save()++ # when+ update_order_prices_with_flat_rates(order, lines, prices_entered_with_tax)++ # then+ assert order.total == TaxedMoney(+ net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")+ )+++ (+ "expected_net",+ "expected_gross",+ "prices_entered_with_tax",+ ),+ [+ ("10.00", "12.30", False),+ ("8.13", "10.00", True),+ ],+)+def test_calculate_order_shipping_with_not_weighted_taxes(+ order_with_lines_untaxed,+ shipping_zone,+ expected_net,+ expected_gross,+ prices_entered_with_tax,+ tax_classes,+):+ # given+ order = order_with_lines_untaxed+ _enable_flat_rates(+ order, prices_entered_with_tax, use_weighted_tax_for_shipping=False+ )++ country = get_order_country(order)++ lines = list(order.lines.all())+ first_line = lines[0]+ second_line = lines[-1]++ # Set different tax rates for different products+ first_line.tax_class.country_rates.update_or_create(country=country, rate=23)++ second_tax_class = tax_classes[0]+ second_tax_class.country_rates.filter(country=country).update(rate=3)+ second_line.tax_class = second_tax_class+ second_line.save()++ # when+ update_order_prices_with_flat_rates(order, lines, prices_entered_with_tax)++ # then+ assert order.shipping_tax_rate == Decimal("0.2300")+ assert order.shipping_price == TaxedMoney(+ net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")+ )+++ (+ "expected_net",+ "expected_gross",+ "prices_entered_with_tax",+ "expected_shipping_tax_rate",+ ),+ [+ ("10.00", "11.16", False, "0.1157"),+ ("9.03", "10.00", True, "0.1072"),+ ],+)+def test_calculate_order_shipping_with_weighted_taxes(+ order_with_lines_untaxed,+ expected_net,+ expected_gross,+ prices_entered_with_tax,+ tax_classes,+ expected_shipping_tax_rate,+):+ # given+ order = order_with_lines_untaxed+ _enable_flat_rates(+ order, prices_entered_with_tax, use_weighted_tax_for_shipping=True+ )++ country = get_order_country(order)++ lines = list(order.lines.all())+ first_line = lines[0]+ second_line = lines[-1]++ # Set different tax rates for different products+ first_line.tax_class.country_rates.update_or_create(country=country, rate=23)++ second_tax_class = tax_classes[0]+ second_tax_class.country_rates.filter(country=country).update(rate=3)+ second_line.tax_class = second_tax_class+ second_line.save()++ # when+ update_order_prices_with_flat_rates(order, lines, prices_entered_with_tax)++ # then+ weighted_tax_amount = sum(+ line.total_price.net.amount * line.tax_rate for line in lines+ )+ weighted_tax_amount = weighted_tax_amount / sum(+ line.total_price.net.amount for line in lines+ )+ assert (+ order.shipping_tax_rate+ == Decimal(weighted_tax_amount).quantize(Decimal("0.0001"))+ == Decimal(expected_shipping_tax_rate).quantize(Decimal("0.0001"))+ )+ assert order.shipping_price == TaxedMoney(+ net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")+ )++[email protected]("use_weighted_tax_for_shipping", [True, False])def test_calculations_calculate_order_undiscounted_total(- order_with_lines_untaxed, voucher_shipping_type+ order_with_lines_untaxed, voucher_shipping_type, use_weighted_tax_for_shipping):# givenorder = order_with_lines_untaxedprices_entered_with_tax = True- _enable_flat_rates(order, prices_entered_with_tax)+ _enable_flat_rates(order, prices_entered_with_tax, use_weighted_tax_for_shipping)lines = order.lines.all()order.discounts.create(diff --git a/saleor/tax/tests/test_utils.py b/saleor/tax/tests/test_utils.pyindex 88ac2d89d3..6fa3103e15 100644--- a/saleor/tax/tests/test_utils.py+++ b/saleor/tax/tests/test_utils.py@@ -1,9 +1,17 @@+from decimal import Decimal+import pytest+from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from ...core.prices import Money, TaxedMoneyfrom ...core.utils.country import get_active_country+from ...graphql.tax.enums import TaxCalculationStrategy+from ...order.utils import get_order_countryfrom ..utils import (get_charge_taxes,get_display_gross_prices,+ get_shipping_tax_rate_for_checkout,+ get_shipping_tax_rate_for_order,get_tax_app_id,)@@ -111,3 +119,292 @@ def test_get_tax_country_fallbacks_to_channel_country(channel_USD):# thenassert country == channel_USD.default_country.code+++def test_get_shipping_tax_rate_for_checkout_weighted_tax(+ checkout_with_items, channel_USD, plugins_manager, shipping_method+):+ # given+ checkout = checkout_with_items+ checkout.shipping_method = shipping_method+ checkout.save(update_fields=["shipping_method"])++ tax_configuration = channel_USD.tax_configuration+ tax_configuration.use_weighted_tax_for_shipping = True+ tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES.value+ tax_configuration.save(+ update_fields=["use_weighted_tax_for_shipping", "tax_calculation_strategy"]+ )++ checkout_lines_info, _ = fetch_checkout_lines(checkout, plugins_manager)+ checkout_info = fetch_checkout_info(checkout, checkout_lines_info, plugins_manager)++ # Set the same tax rate for all lines+ expected_tax_rate = Decimal("0.1") # 10%+ for line_info in checkout_lines_info:+ line_info.line.tax_rate = expected_tax_rate+ line_info.line.total_price = TaxedMoney(+ net=Money(Decimal("100"), checkout.currency),+ gross=Money(Decimal("110"), checkout.currency),+ )++ default_tax_rate = Decimal("20")++ # when+ shipping_tax_rate = get_shipping_tax_rate_for_checkout(+ checkout_info, checkout_lines_info, default_tax_rate, "US"+ )++ # then+ # Should use the weighted tax rate (10%) instead of the default (20%)+ assert shipping_tax_rate == expected_tax_rate * 100+++def test_get_shipping_tax_rate_for_checkout_weighted_tax_with_multiple_tax_rates(+ checkout_with_items, channel_USD, plugins_manager+):+ # given+ checkout = checkout_with_items+ tax_configuration = channel_USD.tax_configuration+ tax_configuration.use_weighted_tax_for_shipping = True+ tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES.value+ tax_configuration.save(+ update_fields=["use_weighted_tax_for_shipping", "tax_calculation_strategy"]+ )++ checkout_info = fetch_checkout_info(checkout, [], plugins_manager)+ checkout_lines_info, _ = fetch_checkout_lines(checkout, plugins_manager)++ assert len(checkout_lines_info) == 4++ default_tax_rate = Decimal("20")++ # Set different tax rates for lines+ # First line: 10% tax rate with $10 tax amount+ first_line = checkout_lines_info[0].line+ first_line.tax_rate = Decimal("0.1") # 10%+ first_line.total_price = TaxedMoney(+ net=Money(Decimal("100"), checkout.currency),+ gross=Money(Decimal("110"), checkout.currency),+ )++ # Second line: 5% tax rate with $5 tax amount+ second_line = checkout_lines_info[1].line+ second_line.tax_rate = Decimal("0.05") # 5%+ second_line.total_price = TaxedMoney(+ net=Money(Decimal("100"), checkout.currency),+ gross=Money(Decimal("105"), checkout.currency),+ )++ # Third line: 0% tax rate with $0 tax amount+ third_line = checkout_lines_info[2].line+ third_line.tax_rate = Decimal("0") # 0%+ third_line.total_price = TaxedMoney(+ net=Money(Decimal("100"), checkout.currency),+ gross=Money(Decimal("100"), checkout.currency),+ )++ fourth_line = checkout_lines_info[3].line+ fourth_line.tax_rate = Decimal("0.2") # 20%+ fourth_line.total_price = TaxedMoney(+ net=Money(Decimal("100"), checkout.currency),+ gross=Money(Decimal("120"), checkout.currency),+ )++ # when+ shipping_tax_rate = get_shipping_tax_rate_for_checkout(+ checkout_info, checkout_lines_info, default_tax_rate, "US"+ )++ # then+ total_weighted = sum(+ [+ line.line.total_price.net.amount * line.line.tax_rate * 100+ for line in checkout_lines_info+ ]+ )++ # Expected: (110*10 + 105*5 + 1000*0 + 120*20) / (110 + 105 + 100 + 120) = 4025 / 435 = 9.2529+ expected_rate = (+ total_weighted+ / sum([line.line.total_price.net.amount for line in checkout_lines_info])+ ).quantize(Decimal(".0001"))++ assert shipping_tax_rate == expected_rate == Decimal("8.7500")+++def test_get_shipping_tax_rate_for_checkout_when_weighted_tax_is_disabled(+ checkout_with_items, channel_USD, shipping_method, plugins_manager+):+ # given+ checkout = checkout_with_items+ tax_configuration = channel_USD.tax_configuration+ tax_configuration.use_weighted_tax_for_shipping = False+ tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES.value+ tax_configuration.save(+ update_fields=["use_weighted_tax_for_shipping", "tax_calculation_strategy"]+ )++ checkout.shipping_method = shipping_method+ checkout.save(update_fields=["shipping_method"])++ checkout_info = fetch_checkout_info(checkout, [], plugins_manager)+ checkout_lines_info, _ = fetch_checkout_lines(checkout, plugins_manager)++ first_line = checkout_lines_info[0].line+ first_line.tax_rate = Decimal("0.1") # 10%+ first_line.total_price = TaxedMoney(+ net=Money(Decimal("100"), checkout.currency),+ gross=Money(Decimal("110"), checkout.currency),+ )+ first_line.save(+ update_fields=["tax_rate", "total_price_net_amount", "total_price_gross_amount"]+ )++ default_tax_rate = Decimal("20") # 20%++ # when+ shipping_tax_rate = get_shipping_tax_rate_for_checkout(+ checkout_info, checkout_lines_info, default_tax_rate, "US"+ )++ # then+ # Should return the default tax rate since weighted tax is disabled+ assert shipping_tax_rate == default_tax_rate+++def test_get_shipping_tax_rate_for_order_weighted_tax(+ order_with_lines, channel_USD, shipping_zone, address_usa+):+ # given+ order = order_with_lines+ order.shipping_address = address_usa+ order.save(update_fields=["shipping_address"])++ tax_configuration = channel_USD.tax_configuration+ tax_configuration.use_weighted_tax_for_shipping = True+ tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES.value+ tax_configuration.save(+ update_fields=["use_weighted_tax_for_shipping", "tax_calculation_strategy"]+ )++ default_tax_rate = Decimal("20")+ lines = list(order.lines.all())+ country = get_order_country(order)++ # Set the same tax rate for all lines+ expected_tax_rate = Decimal("0.1") # 10%+ for line in lines:+ line.tax_rate = expected_tax_rate+ line.total_price = TaxedMoney(+ net=Money(Decimal("100"), order.currency),+ gross=Money(Decimal("110"), order.currency),+ )++ # when+ shipping_tax_rate = get_shipping_tax_rate_for_order(+ order, lines, default_tax_rate, country+ )++ # then+ # Should use the weighted tax rate (10%) instead of the default (20%)+ assert shipping_tax_rate == expected_tax_rate * 100+++def test_get_shipping_tax_rate_for_order_weighted_tax_with_multiple_tax_rates(+ order_with_lines, channel_USD, address_usa+):+ # given+ order = order_with_lines+ order.shipping_address = address_usa+ order.save(update_fields=["shipping_address"])++ tax_configuration = channel_USD.tax_configuration+ tax_configuration.use_weighted_tax_for_shipping = True+ tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES.value+ tax_configuration.save(+ update_fields=["use_weighted_tax_for_shipping", "tax_calculation_strategy"]+ )++ lines = list(order.lines.all())+ assert len(lines) == 2++ default_tax_rate = Decimal("20")+ country = get_order_country(order)++ # Set different tax rates for lines+ # First line: 10% tax rate with $10 tax amount+ first_line = lines[0]+ first_line.tax_rate = Decimal("0.1") # 10%+ first_line.total_price = TaxedMoney(+ net=Money(Decimal("100"), order.currency),+ gross=Money(Decimal("110"), order.currency),+ )+ first_line.save(+ update_fields=["tax_rate", "total_price_net_amount", "total_price_gross_amount"]+ )++ # Second line: 5% tax rate with $5 tax amount+ second_line = lines[1]+ second_line.tax_rate = Decimal("0.05") # 5%+ second_line.total_price = TaxedMoney(+ net=Money(Decimal("100"), order.currency),+ gross=Money(Decimal("105"), order.currency),+ )+ second_line.save(+ update_fields=["tax_rate", "total_price_net_amount", "total_price_gross_amount"]+ )++ # when+ shipping_tax_rate = get_shipping_tax_rate_for_order(+ order, lines, default_tax_rate, country+ )++ # then+ # Calculate the expected weighted rate+ total_weighted = sum(+ [line.total_price.net.amount * line.tax_rate * 100 for line in lines]+ )+ total_gross = sum([line.total_price.net.amount for line in lines])+ expected_weighted_rate = (total_weighted / total_gross).quantize(Decimal(".0001"))++ # Verify that the weighted rate is correctly calculated and used+ assert shipping_tax_rate == expected_weighted_rate+++def test_get_shipping_tax_rate_for_order_when_weighted_tax_is_disabled(+ order_with_lines, channel_USD, default_tax_class+):+ # given+ order = order_with_lines++ tax_configuration = channel_USD.tax_configuration+ tax_configuration.use_weighted_tax_for_shipping = False+ tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES.value+ tax_configuration.save(+ update_fields=["use_weighted_tax_for_shipping", "tax_calculation_strategy"]+ )++ lines = list(order.lines.all())+ country = get_order_country(order)++ first_line = lines[0]+ first_line.tax_rate = Decimal("0.1") # 10%+ first_line.total_price = TaxedMoney(+ net=Money(Decimal("100"), order.currency),+ gross=Money(Decimal("110"), order.currency),+ )+ first_line.save(+ update_fields=["tax_rate", "total_price_net_amount", "total_price_gross_amount"]+ )++ default_tax_rate = Decimal("20") # 20%+ order.shipping_tax_class = default_tax_class++ # when+ shipping_tax_rate = get_shipping_tax_rate_for_order(+ order, lines, default_tax_rate, country+ )++ # then+ assert shipping_tax_rate == Decimal("23.000")diff --git a/saleor/tax/utils.py b/saleor/tax/utils.pyindex 5d0e5c7a15..8d90ad38e9 100644--- a/saleor/tax/utils.py+++ b/saleor/tax/utils.py@@ -1,4 +1,5 @@import logging+from collections import defaultdictfrom collections.abc import Iterablefrom decimal import Decimalfrom typing import TYPE_CHECKING, Optional@@ -7,12 +8,13 @@ from django.conf import settingsfrom prices import TaxedMoneyfrom ..core.utils.country import get_active_country+from ..tax.models import TaxClass, TaxClassCountryRatefrom . import TaxCalculationStrategyif TYPE_CHECKING:from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo- from ..order.models import Order- from ..tax.models import TaxClass, TaxClassCountryRate+ from ..checkout.models import CheckoutLine+ from ..order.models import Order, OrderLinefrom .models import TaxConfiguration, TaxConfigurationPerCountry@@ -70,6 +72,23 @@ def get_tax_calculation_strategy() or TaxCalculationStrategy.FLAT_RATES+def should_use_weighted_tax_for_shipping(+ channel_tax_configuration: "TaxConfiguration",+ country_tax_configuration: Optional["TaxConfigurationPerCountry"],+) -> bool:+ """Get use_weighted_tax_for_shipping value for tax channel configuration."""+ tax_calculation_strategy = get_tax_calculation_strategy(+ channel_tax_configuration, country_tax_configuration+ )+ if tax_calculation_strategy != TaxCalculationStrategy.FLAT_RATES:+ return False+ return (+ country_tax_configuration.use_weighted_tax_for_shipping+ if country_tax_configuration+ else channel_tax_configuration.use_weighted_tax_for_shipping+ )++def get_tax_app_id(channel_tax_configuration: "TaxConfiguration",country_tax_configuration: Optional["TaxConfigurationPerCountry"],@@ -134,7 +153,6 @@ def get_tax_app_identifier_for_order(order: "Order"):def get_tax_configuration_for_checkout(checkout_info: "CheckoutInfo",- lines: list["CheckoutLineInfo"],database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> tuple["TaxConfiguration", Optional["TaxConfigurationPerCountry"]]:tax_configuration = checkout_info.tax_configuration@@ -158,45 +176,158 @@ def get_tax_configuration_for_checkout(def get_charge_taxes_for_checkout(checkout_info: "CheckoutInfo",- lines: list["CheckoutLineInfo"],database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Get charge_taxes value for checkout."""tax_configuration, country_tax_configuration = get_tax_configuration_for_checkout(- checkout_info, lines, database_connection_name=database_connection_name+ checkout_info, database_connection_name=database_connection_name)return get_charge_taxes(tax_configuration, country_tax_configuration)def get_tax_calculation_strategy_for_checkout(checkout_info: "CheckoutInfo",- lines: list["CheckoutLineInfo"],database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Get tax_calculation_strategy value for checkout."""tax_configuration, country_tax_configuration = get_tax_configuration_for_checkout(- checkout_info, lines, database_connection_name=database_connection_name+ checkout_info, database_connection_name=database_connection_name)return get_tax_calculation_strategy(tax_configuration, country_tax_configuration)def get_tax_app_identifier_for_checkout(checkout_info: "CheckoutInfo",- lines: list["CheckoutLineInfo"],database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Get tax_app_id value for checkout."""tax_configuration, country_tax_configuration = get_tax_configuration_for_checkout(- checkout_info, lines, database_connection_name=database_connection_name+ checkout_info, database_connection_name=database_connection_name)return get_tax_app_id(tax_configuration, country_tax_configuration)+def should_use_weighted_tax_for_shipping_for_checkout(+ checkout_info: "CheckoutInfo",+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+) -> bool:+ """Get use_weighted_tax_for_shipping value for checkout."""+ tax_configuration, country_tax_configuration = get_tax_configuration_for_checkout(+ checkout_info, database_connection_name=database_connection_name+ )+ return should_use_weighted_tax_for_shipping(+ tax_configuration, country_tax_configuration+ )+++def should_use_weighted_tax_for_shipping_for_order(+ order: "Order",+) -> bool:+ """Get use_weighted_tax_for_shipping value for order."""+ tax_configuration, country_tax_configuration = _get_tax_configuration_for_order(+ order+ )+ return should_use_weighted_tax_for_shipping(+ tax_configuration, country_tax_configuration+ )+++def _get_weighted_tax_rate_for_shipping(+ lines: list["CheckoutLine"] | list["OrderLine"],+ default_tax_rate: Decimal,+):+ tax_rates_with_weights: dict[Decimal, Decimal] = defaultdict(Decimal)+ for line in lines:+ # tax_rate is stored as fractional values in the database+ tax_rate = line.tax_rate or Decimal(0)+ tax_rates_with_weights[tax_rate * 100] += line.total_price.net.amount+ if not tax_rates_with_weights:+ return default_tax_rate++ total_weight = sum(list(tax_rates_with_weights.values()), Decimal(0))+ if total_weight == 0:+ return default_tax_rate++ weighted_sum = sum(+ [rate * weight for rate, weight in tax_rates_with_weights.items()], Decimal(0)+ )++ return (weighted_sum / total_weight).quantize(Decimal(".0001"))+++def get_shipping_tax_rate_for_checkout(+ checkout_info: "CheckoutInfo",+ lines: list["CheckoutLineInfo"],+ default_tax_rate: Decimal,+ country_code: str,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+) -> Decimal:+ should_use_weighted_tax_for_shipping = (+ should_use_weighted_tax_for_shipping_for_checkout(+ checkout_info, database_connection_name=database_connection_name+ )+ )+ if should_use_weighted_tax_for_shipping:+ return _get_weighted_tax_rate_for_shipping(+ [line_info.line for line_info in lines], default_tax_rate+ )+ 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)++ return get_tax_rate_for_country(+ shipping_tax_rates,+ default_tax_rate,+ country_code,+ )+++def get_shipping_tax_rate_for_order(+ order: "Order",+ lines: Iterable["OrderLine"],+ default_tax_rate: Decimal,+ country_code: str,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+) -> Decimal:+ should_use_weighted_tax_for_shipping = (+ should_use_weighted_tax_for_shipping_for_order(order)+ )+ if should_use_weighted_tax_for_shipping:+ return _get_weighted_tax_rate_for_shipping(list(lines), default_tax_rate)++ 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+ and order.shipping_tax_rate is not None+ ):+ # Use order.shipping_tax_rate if it was ever set before (it's non-null now and+ # 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)++ return shipping_tax_rate++def normalize_tax_rate_for_db(tax_rate: Decimal) -> Decimal:# Percentage values are used to represent tax rates in tax apps and flat rates, but# in the database rates are stored as fractional values. Example: tax app returns# `10%` as `10`, but in the database it's stored as `0.1`.- return tax_rate / 100+ return (tax_rate / 100).quantize(Decimal(".0001"))def denormalize_tax_rate_from_db(tax_rate: Decimal) -> Decimal:diff --git a/saleor/webhook/serializers.py b/saleor/webhook/serializers.pyindex 1a063a97b9..536b561160 100644--- a/saleor/webhook/serializers.py+++ b/saleor/webhook/serializers.py@@ -77,7 +77,7 @@ def serialize_checkout_lines_for_tax_calculation(checkout_info: "CheckoutInfo",lines: list["CheckoutLineInfo"],) -> list[dict]:- charge_taxes = get_charge_taxes_for_checkout(checkout_info, lines)+ charge_taxes = get_charge_taxes_for_checkout(checkout_info)return [{**_get_checkout_line_payload_data(line_info),