Skip to content

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

Add plugin to tax configuration (#15460)

Krzysztof Waliczek08f74e0239fe
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 83e1f91f30..2a43d85186 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -50,7 +50,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Added new field `taxAppId` in `TaxConfiguration` and `TaxConfigurationPerCountry`.
- Added new input `AppInput.identifier`.
- Added new parameter `identifier` for `create_app` command.
- - When `taxAppId` is provided for `TaxConfiguration` do not allow to finalize `checkoutComplete` or `draftOrderComplete` mutations if Tax App doesn't respond.
+ - When `taxAppId` is provided for `TaxConfiguration` do not allow to finalize `checkoutComplete` or `draftOrderComplete` mutations if Tax App or Avatax plugin didn't respond.
# 3.18.0
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index 4c1af21d0a..cfa6852b22 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -3,17 +3,17 @@ from decimal import Decimal
from typing import TYPE_CHECKING, Optional, cast
from django.conf import settings
-from django.core.exceptions import ValidationError
from django.utils import timezone
from prices import Money, TaxedMoney
from ..checkout import base_calculations
from ..core.prices import quantize_price
-from ..core.taxes import EmptyTaxData, TaxData, zero_money, zero_taxed_money
+from ..core.taxes import TaxData, TaxEmptyData, zero_money, zero_taxed_money
from ..discount.utils import (
create_or_update_discount_objects_from_promotion_for_checkout,
)
from ..payment.models import TransactionItem
+from ..plugins import PLUGIN_IDENTIFIER_PREFIX
from ..tax import TaxCalculationStrategy
from ..tax.calculations.checkout import update_checkout_prices_with_flat_rates
from ..tax.utils import (
@@ -22,7 +22,6 @@ from ..tax.utils import (
get_tax_calculation_strategy_for_checkout,
normalize_tax_rate_for_db,
)
-from .error_codes import CheckoutErrorCode
from .fetch import find_checkout_line_info
from .models import Checkout
from .payment_utils import update_checkout_payment_statuses
@@ -39,7 +38,6 @@ def checkout_shipping_price(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
- need_tax_calculation: bool = False,
) -> "TaxedMoney":
"""Return checkout shipping price.
@@ -51,7 +49,6 @@ def checkout_shipping_price(
manager=manager,
lines=lines,
address=address,
- need_tax_calculation=need_tax_calculation,
)
return quantize_price(checkout_info.checkout.shipping_price, currency)
@@ -62,7 +59,6 @@ def checkout_shipping_tax_rate(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
- need_tax_calculation: bool = False,
) -> Decimal:
"""Return checkout shipping tax rate.
@@ -73,7 +69,6 @@ def checkout_shipping_tax_rate(
manager=manager,
lines=lines,
address=address,
- need_tax_calculation=need_tax_calculation,
)
return checkout_info.checkout.shipping_tax_rate
@@ -84,7 +79,6 @@ def checkout_subtotal(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
- need_tax_calculation: bool = False,
) -> "TaxedMoney":
"""Return the total cost of all the checkout lines, taxes included.
@@ -96,7 +90,6 @@ def checkout_subtotal(
manager=manager,
lines=lines,
address=address,
- need_tax_calculation=need_tax_calculation,
)
return quantize_price(checkout_info.checkout.subtotal, currency)
@@ -126,7 +119,6 @@ def checkout_total(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
- need_tax_calculation: bool = False,
) -> "TaxedMoney":
"""Return the total cost of the checkout.
@@ -141,7 +133,6 @@ def checkout_total(
manager=manager,
lines=lines,
address=address,
- need_tax_calculation=need_tax_calculation,
)
return quantize_price(checkout_info.checkout.total, currency)
@@ -152,7 +143,6 @@ def checkout_line_total(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
checkout_line_info: "CheckoutLineInfo",
- need_tax_calculation: bool = False,
) -> TaxedMoney:
"""Return the total price of provided line, taxes included.
@@ -165,7 +155,6 @@ def checkout_line_total(
manager=manager,
lines=lines,
address=address,
- need_tax_calculation=need_tax_calculation,
)
checkout_line = find_checkout_line_info(lines, checkout_line_info.line.id).line
return quantize_price(checkout_line.total_price, currency)
@@ -177,7 +166,6 @@ def checkout_line_unit_price(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
checkout_line_info: "CheckoutLineInfo",
- need_tax_calculation: bool = False,
) -> TaxedMoney:
"""Return the unit price of provided line, taxes included.
@@ -190,7 +178,6 @@ def checkout_line_unit_price(
manager=manager,
lines=lines,
address=address,
- need_tax_calculation=need_tax_calculation,
)
checkout_line = find_checkout_line_info(lines, checkout_line_info.line.id).line
unit_price = checkout_line.total_price / checkout_line.quantity
@@ -203,7 +190,6 @@ def checkout_line_tax_rate(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
checkout_line_info: "CheckoutLineInfo",
- need_tax_calculation: bool = False,
) -> Decimal:
"""Return the tax rate of provided line.
@@ -215,7 +201,6 @@ def checkout_line_tax_rate(
manager=manager,
lines=lines,
address=address,
- need_tax_calculation=need_tax_calculation,
)
checkout_line_info = find_checkout_line_info(lines, checkout_line_info.line.id)
return checkout_line_info.line.tax_rate
@@ -227,13 +212,11 @@ def _fetch_checkout_prices_if_expired(
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"] = None,
force_update: bool = False,
- need_tax_calculation: bool = False,
) -> tuple["CheckoutInfo", Iterable["CheckoutLineInfo"]]:
"""Fetch checkout prices with taxes.
First calculate and apply all checkout prices with taxes separately,
- then apply tax data as well if we receive one. If need_tax_calculation is set
- to True, we will raise error if we didn't receive tax data.
+ then apply tax data as well if we receive one.
Prices can be updated only if force_update == True, or if time elapsed from the
last price update is greater than settings.CHECKOUT_PRICES_TTL.
@@ -270,7 +253,7 @@ def _fetch_checkout_prices_if_expired(
prices_entered_with_tax,
address,
)
- except EmptyTaxData as e:
+ except TaxEmptyData as e:
checkout.tax_error = str(e)
if not should_charge_tax:
@@ -294,21 +277,12 @@ def _fetch_checkout_prices_if_expired(
prices_entered_with_tax,
address,
)
- except EmptyTaxData as e:
+ except TaxEmptyData as e:
checkout.tax_error = str(e)
else:
# Calculate net prices without taxes.
_get_checkout_base_prices(checkout, checkout_info, lines)
- # raise an error if recorded tax_error and taxes are needed for process completion
- if checkout.tax_error and need_tax_calculation:
- checkout.save(update_fields=["tax_error"])
-
- raise ValidationError(
- "Configured Tax App didn't responded.",
- code=CheckoutErrorCode.TAX_ERROR.value,
- )
-
checkout_update_fields = [
"voucher_code",
"total_net_amount",
@@ -355,17 +329,28 @@ def _calculate_and_add_tax(
address: Optional["Address"] = None,
):
if tax_calculation_strategy == TaxCalculationStrategy.TAX_APP:
- # 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.
- tax_data = manager.get_taxes_for_checkout(
- checkout_info, lines, tax_app_identifier
- )
- # If taxAppId is not configured we will for now allow to finalize process for
- # backward compatibility.
- if tax_data is None and tax_app_identifier is not None:
- raise EmptyTaxData("Empty tax data.")
- _apply_tax_data(checkout, lines, tax_data)
+ # 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.
+ tax_data = manager.get_taxes_for_checkout(
+ checkout_info, lines, tax_app_identifier
+ )
+ _apply_tax_data(checkout, lines, tax_data)
+ else:
+ _call_plugin_or_tax_app(
+ tax_app_identifier,
+ checkout,
+ manager,
+ checkout_info,
+ lines,
+ address,
+ )
else:
# Get taxes calculated with flat rates and apply to checkout.
update_checkout_prices_with_flat_rates(
@@ -373,6 +358,42 @@ def _calculate_and_add_tax(
)
+def _call_plugin_or_tax_app(
+ tax_app_identifier: str,
+ checkout: "Checkout",
+ manager: "PluginsManager",
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ address: Optional["Address"] = None,
+):
+ if tax_app_identifier.startswith(PLUGIN_IDENTIFIER_PREFIX):
+ plugin_ids = [tax_app_identifier.replace(PLUGIN_IDENTIFIER_PREFIX, "")]
+ plugins = manager.get_plugins(
+ checkout_info.channel.slug,
+ active_only=True,
+ plugin_ids=plugin_ids,
+ )
+ if not plugins:
+ raise TaxEmptyData("Empty tax data.")
+ _apply_tax_data_from_plugins(
+ checkout,
+ manager,
+ checkout_info,
+ lines,
+ address,
+ plugin_ids=plugin_ids,
+ )
+ if checkout.tax_error:
+ raise TaxEmptyData("Empty tax data.")
+ else:
+ tax_data = manager.get_taxes_for_checkout(
+ checkout_info, lines, tax_app_identifier
+ )
+ if tax_data is None:
+ raise TaxEmptyData("Empty tax data.")
+ _apply_tax_data(checkout, lines, tax_data)
+
+
def _remove_tax(checkout, lines_info):
checkout.total_gross_amount = checkout.total_net_amount
checkout.subtotal_gross_amount = checkout.subtotal_net_amount
@@ -441,6 +462,7 @@ def _apply_tax_data_from_plugins(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
+ plugin_ids: Optional[list[str]] = None,
) -> None:
for line_info in lines:
line = line_info.line
@@ -450,6 +472,7 @@ def _apply_tax_data_from_plugins(
lines,
line_info,
address,
+ plugin_ids=plugin_ids,
)
line.total_price = total_price
@@ -459,18 +482,24 @@ def _apply_tax_data_from_plugins(
line_info,
address,
total_price,
+ plugin_ids=plugin_ids,
)
checkout.shipping_price = manager.calculate_checkout_shipping(
- checkout_info, lines, address
+ checkout_info, lines, address, plugin_ids=plugin_ids
)
checkout.shipping_tax_rate = manager.get_checkout_shipping_tax_rate(
- checkout_info, lines, address, checkout.shipping_price
+ checkout_info, lines, address, checkout.shipping_price, plugin_ids=plugin_ids
)
checkout.subtotal = manager.calculate_checkout_subtotal(
- checkout_info, lines, address
+ checkout_info, lines, address, plugin_ids=plugin_ids
+ )
+ checkout.total = manager.calculate_checkout_total(
+ checkout_info,
+ lines,
+ address,
+ plugin_ids=plugin_ids,
)
- checkout.total = manager.calculate_checkout_total(checkout_info, lines, address)
def _get_checkout_base_prices(
@@ -524,15 +553,11 @@ def fetch_checkout_data(
force_update: bool = False,
checkout_transactions: Optional[Iterable["TransactionItem"]] = None,
force_status_update: bool = False,
- need_tax_calculation: bool = False,
):
"""Fetch checkout data.
This function refreshes prices if they have expired. If the checkout total has
changed as a result, it will update the payment statuses accordingly.
-
- need_tax_calculation: Set to true if fetching data should fail when received tax data
- is invalid. Otherwise will only collect error message to checkout.tax_error field.
"""
previous_total_gross = checkout_info.checkout.total.gross
checkout_info, lines = _fetch_checkout_prices_if_expired(
@@ -541,7 +566,6 @@ def fetch_checkout_data(
lines=lines,
address=address,
force_update=force_update,
- need_tax_calculation=need_tax_calculation,
)
current_total_gross = checkout_info.checkout.total.gross
if current_total_gross != previous_total_gross or force_status_update:
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 3530b821ba..0cdd879529 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -231,7 +231,6 @@ def _create_line_for_order(
checkout_info=checkout_info,
lines=lines,
checkout_line_info=checkout_line_info,
- need_tax_calculation=True,
)
# unit price after applying all discounts - sales and vouchers
unit_price = calculations.checkout_line_unit_price(
@@ -239,14 +238,12 @@ def _create_line_for_order(
checkout_info=checkout_info,
lines=lines,
checkout_line_info=checkout_line_info,
- need_tax_calculation=True,
)
tax_rate = calculations.checkout_line_tax_rate(
manager=manager,
checkout_info=checkout_info,
lines=lines,
checkout_line_info=checkout_line_info,
- need_tax_calculation=True,
)
# unit price before applying discounts
undiscounted_unit_price = get_taxed_undiscounted_price(
@@ -458,14 +455,12 @@ def _prepare_order_data(
checkout_info=checkout_info,
lines=lines,
address=address,
- need_tax_calculation=True,
)
shipping_tax_rate = calculations.checkout_shipping_tax_rate(
manager=manager,
checkout_info=checkout_info,
lines=lines,
address=address,
- need_tax_calculation=True,
)
order_data.update(
_process_shipping_data_for_order(
@@ -518,7 +513,6 @@ def _prepare_order_data(
checkout_info=checkout_info,
lines=lines,
address=address,
- need_tax_calculation=True,
)
+ shipping_total
- checkout.discount
@@ -878,7 +872,7 @@ def complete_checkout_pre_payment_part(
if site_settings is None:
site_settings = Site.objects.get_current().settings
- fetch_checkout_data(checkout_info, manager, lines, need_tax_calculation=True)
+ fetch_checkout_data(checkout_info, manager, lines)
checkout = checkout_info.checkout
channel_slug = checkout_info.channel.slug
@@ -1177,14 +1171,12 @@ def _create_order_from_checkout(
checkout_info=checkout_info,
lines=checkout_lines_info,
address=address,
- need_tax_calculation=True,
)
shipping_tax_rate = calculations.checkout_shipping_tax_rate(
manager=manager,
checkout_info=checkout_info,
lines=checkout_lines_info,
address=address,
- need_tax_calculation=True,
)
# status
@@ -1421,8 +1413,12 @@ def complete_checkout(
manager,
lines,
force_update=force_update,
- need_tax_calculation=True,
)
+ if checkout_info.checkout.tax_error is not None:
+ raise ValidationError(
+ "Configured Tax App didn't responded.",
+ code=CheckoutErrorCode.TAX_ERROR.value,
+ )
# When checkout is zero, we don't need any transaction to cover the checkout total.
# We check if checkout is zero, and we also check what flow for marking an order as
diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.py
index a577ef0df6..f37fd52f2b 100644
--- a/saleor/checkout/tests/test_calculations.py
+++ b/saleor/checkout/tests/test_calculations.py
@@ -3,6 +3,7 @@ from typing import Literal, Union
from unittest.mock import Mock, patch
import pytest
+from django.test import override_settings
from django.utils import timezone
from freezegun import freeze_time
from prices import Money, TaxedMoney
@@ -10,7 +11,9 @@ from prices import Money, TaxedMoney
from ...checkout.utils import add_promo_code_to_checkout
from ...core.prices import quantize_price
from ...core.taxes import TaxData, TaxLineData, zero_taxed_money
+from ...plugins import PLUGIN_IDENTIFIER_PREFIX
from ...plugins.manager import get_plugins_manager
+from ...plugins.tests.sample_plugins import PluginSample
from ...tax import TaxCalculationStrategy
from ...tax.calculations.checkout import update_checkout_prices_with_flat_rates
from ..base_calculations import (
@@ -521,3 +524,112 @@ def test_fetch_checkout_prices_when_tax_exemption_and_not_include_taxes_in_price
assert checkout.total == shipping_price + all_lines_total_price
assert checkout.subtotal == all_lines_total_price
+
+
+@freeze_time()
+@patch("saleor.plugins.manager.PluginsManager.calculate_checkout_total")
+@patch("saleor.plugins.manager.PluginsManager.get_taxes_for_checkout")
+@override_settings(PLUGINS=["saleor.plugins.tests.sample_plugins.PluginSample"])
+def test_fetch_checkout_data_calls_plugin(
+ mock_get_taxes,
+ mock_calculate_checkout_total,
+ checkout_with_items,
+):
+ # given
+ checkout = checkout_with_items
+ checkout.price_expiration = timezone.now()
+ checkout.save()
+
+ price = Money("10.0", currency=checkout.currency)
+ mock_calculate_checkout_total.return_value = TaxedMoney(price, price)
+
+ checkout.channel.tax_configuration.tax_app_id = (
+ PLUGIN_IDENTIFIER_PREFIX + PluginSample.PLUGIN_ID
+ )
+ checkout.channel.tax_configuration.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines_info, _ = fetch_checkout_lines(checkout)
+
+ fetch_kwargs = {
+ "checkout_info": fetch_checkout_info(checkout, lines_info, manager),
+ "manager": manager,
+ "lines": lines_info,
+ "address": checkout.shipping_address or checkout.billing_address,
+ }
+
+ # when
+ fetch_checkout_data(**fetch_kwargs)
+
+ # then
+ mock_calculate_checkout_total.assert_called_once()
+ mock_get_taxes.assert_not_called()
+
+
+@freeze_time()
+@patch("saleor.plugins.manager.PluginsManager.calculate_checkout_total")
+@patch("saleor.plugins.manager.PluginsManager.get_taxes_for_checkout")
+@patch("saleor.checkout.calculations._apply_tax_data")
+@override_settings(PLUGINS=["saleor.plugins.tests.sample_plugins.PluginSample"])
+def test_fetch_checkout_data_calls_tax_app(
+ mock_apply_tax_data,
+ mock_get_taxes,
+ mock_calculate_checkout_total,
+ fetch_kwargs,
+ checkout_with_items,
+):
+ # given
+ checkout = checkout_with_items
+ checkout.price_expiration = timezone.now()
+ checkout.save()
+
+ checkout.channel.tax_configuration.tax_app_id = "test.app"
+ checkout.channel.tax_configuration.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines_info, _ = fetch_checkout_lines(checkout)
+
+ fetch_kwargs = {
+ "checkout_info": fetch_checkout_info(checkout, lines_info, manager),
+ "manager": manager,
+ "lines": lines_info,
+ "address": checkout.shipping_address or checkout.billing_address,
+ }
+
+ # when
+ fetch_checkout_data(**fetch_kwargs)
+
+ # then
+ mock_get_taxes.assert_called_once()
+ mock_apply_tax_data.assert_called_once()
+ mock_calculate_checkout_total.assert_not_called()
+
+
+@freeze_time()
+def test_fetch_checkout_data_calls_inactive_plugin(
+ fetch_kwargs,
+ checkout_with_items,
+):
+ # given
+ checkout = checkout_with_items
+ checkout.price_expiration = timezone.now()
+ checkout.save()
+
+ checkout.channel.tax_configuration.tax_app_id = "plugin:test"
+ checkout.channel.tax_configuration.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines_info, _ = fetch_checkout_lines(checkout)
+
+ fetch_kwargs = {
+ "checkout_info": fetch_checkout_info(checkout, lines_info, manager),
+ "manager": manager,
+ "lines": lines_info,
+ "address": checkout.shipping_address or checkout.billing_address,
+ }
+
+ # when
+ fetch_checkout_data(**fetch_kwargs)
+
+ # then
+ assert checkout_with_items.tax_error == "Empty tax data."
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index 3f5a850f45..2a5f46cdbe 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -1765,11 +1765,15 @@ def test_create_order_store_shipping_prices(
assert order.base_shipping_price == expected_base_shipping_price
assert order.shipping_price == expected_shipping_price
manager.calculate_checkout_shipping.assert_called_once_with(
- checkout_info, lines, checkout.shipping_address
+ checkout_info, lines, checkout.shipping_address, plugin_ids=None
)
assert order.shipping_tax_rate == expected_shipping_tax_rate
manager.get_checkout_shipping_tax_rate.assert_called_once_with(
- checkout_info, lines, checkout.shipping_address, expected_shipping_price
+ checkout_info,
+ lines,
+ checkout.shipping_address,
+ expected_shipping_price,
+ plugin_ids=None,
)
@@ -1815,11 +1819,15 @@ def test_create_order_store_shipping_prices_with_free_shipping_voucher(
assert order.base_shipping_price == expected_base_shipping_price
assert order.shipping_price == expected_shipping_price
manager.calculate_checkout_shipping.assert_called_once_with(
- checkout_info, lines, checkout.shipping_address
+ checkout_info, lines, checkout.shipping_address, plugin_ids=None
)
assert order.shipping_tax_rate == expected_shipping_tax_rate
manager.get_checkout_shipping_tax_rate.assert_called_once_with(
- checkout_info, lines, checkout.shipping_address, expected_shipping_price
+ checkout_info,
+ lines,
+ checkout.shipping_address,
+ expected_shipping_price,
+ plugin_ids=None,
)
diff --git a/saleor/checkout/tests/test_order_from_checkout.py b/saleor/checkout/tests/test_order_from_checkout.py
index f4f7b494cd..2c0714f777 100644
--- a/saleor/checkout/tests/test_order_from_checkout.py
+++ b/saleor/checkout/tests/test_order_from_checkout.py
@@ -673,11 +673,15 @@ def test_create_order_from_checkout_store_shipping_prices(
assert order.base_shipping_price == expected_base_shipping_price
assert order.shipping_price == expected_shipping_price
manager.calculate_checkout_shipping.assert_called_once_with(
- mock.ANY, lines, checkout.shipping_address
+ mock.ANY, lines, checkout.shipping_address, plugin_ids=None
)
assert order.shipping_tax_rate == expected_shipping_tax_rate
manager.get_checkout_shipping_tax_rate.assert_called_once_with(
- mock.ANY, lines, checkout.shipping_address, expected_shipping_price
+ mock.ANY,
+ lines,
+ checkout.shipping_address,
+ expected_shipping_price,
+ plugin_ids=None,
)
@@ -772,11 +776,15 @@ def test_create_order_from_store_shipping_prices_with_free_shipping_voucher(
assert order.base_shipping_price == expected_base_shipping_price
assert order.shipping_price == expected_shipping_price
manager.calculate_checkout_shipping.assert_called_once_with(
- mock.ANY, lines, checkout.shipping_address
+ mock.ANY, lines, checkout.shipping_address, plugin_ids=None
)
assert order.shipping_tax_rate == expected_shipping_tax_rate
manager.get_checkout_shipping_tax_rate.assert_called_once_with(
- mock.ANY, lines, checkout.shipping_address, expected_shipping_price
+ mock.ANY,
+ lines,
+ checkout.shipping_address,
+ expected_shipping_price,
+ plugin_ids=None,
)
diff --git a/saleor/core/taxes.py b/saleor/core/taxes.py
index ec8986d69d..ba802c158c 100644
--- a/saleor/core/taxes.py
+++ b/saleor/core/taxes.py
@@ -8,7 +8,7 @@ class TaxError(Exception):
"""Default tax error."""
-class EmptyTaxData(Exception):
+class TaxEmptyData(Exception):
"""Empty tax data received from Tax App error."""
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
index ad398fbe27..e43785cced 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
@@ -5,7 +5,7 @@ import pytest
from django.test import override_settings
from django.utils import timezone
from freezegun import freeze_time
-from prices import Money
+from prices import Money, TaxedMoney
from .....checkout import calculations
from .....checkout.error_codes import CheckoutErrorCode
@@ -16,7 +16,9 @@ from .....core.models import EventDelivery
from .....order import OrderStatus
from .....order.models import Order
from .....payment.model_helpers import get_subtotal
+from .....plugins import PLUGIN_IDENTIFIER_PREFIX
from .....plugins.manager import get_plugins_manager
+from .....plugins.tests.sample_plugins import PluginSample
from .....plugins.webhook.conftest import ( # noqa: F401
tax_data_response,
tax_line_data_response,
@@ -398,6 +400,7 @@ def test_checkout_complete_fails_with_invalid_tax_app(
address,
tax_app,
tax_data_response, # noqa: F811
+ settings,
):
# given
mock_request.return_value = tax_data_response
@@ -433,6 +436,7 @@ def test_checkout_complete_fails_with_invalid_tax_app(
assert not EventDelivery.objects.exists()
checkout.refresh_from_db()
+ assert checkout.price_expiration == timezone.now() + settings.CHECKOUT_PRICES_TTL
assert checkout.tax_error == "Empty tax data."
@@ -487,6 +491,62 @@ def test_checkout_complete_calls_correct_tax_app(
assert checkout.tax_error is None
+@freeze_time()
+ "saleor.plugins.tests.sample_plugins.PluginSample.calculate_checkout_line_total"
+)
+@override_settings(PLUGINS=["saleor.plugins.tests.sample_plugins.PluginSample"])
+def test_checkout_complete_calls_failing_plugin(
+ mock_calculate_checkout_line_total,
+ user_api_client,
+ checkout_without_shipping_required,
+ channel_USD,
+ address,
+ settings,
+):
+ # given
+ def side_effect(checkout_info, *args, **kwargs):
+ price = Money("10.0", checkout_info.checkout.currency)
+ checkout_info.checkout.tax_error = "Test error"
+ return TaxedMoney(price, price)
+
+ mock_calculate_checkout_line_total.side_effect = side_effect
+
+ checkout = checkout_without_shipping_required
+ checkout.billing_address = address
+ checkout.price_expiration = timezone.now()
+ checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
+ checkout.metadata_storage.store_value_in_private_metadata(
+ items={"accepted": "false"}
+ )
+ checkout.metadata_storage.save()
+ checkout.save()
+
+ channel_USD.tax_configuration.tax_app_id = (
+ PLUGIN_IDENTIFIER_PREFIX + PluginSample.PLUGIN_ID
+ )
+ channel_USD.tax_configuration.save()
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "redirectUrl": "https://www.example.com",
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["checkoutComplete"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == CheckoutErrorCode.TAX_ERROR.name
+ assert data["errors"][0]["message"] == "Configured Tax App didn't responded."
+
+ checkout.refresh_from_db()
+ assert checkout.price_expiration == timezone.now() + settings.CHECKOUT_PRICES_TTL
+ assert checkout.tax_error == "Empty tax data."
+
+
@freeze_time()
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.py
index 0acdc35f9f..08c610d654 100644
--- a/saleor/graphql/order/mutations/draft_order_complete.py
+++ b/saleor/graphql/order/mutations/draft_order_complete.py
@@ -101,8 +101,13 @@ class DraftOrderComplete(BaseMutation):
cls.check_channel_permissions(info, [order.channel_id])
force_update = order.tax_error is not None
order, _ = fetch_order_prices_if_expired(
- order, manager, force_update=force_update, need_tax_calculation=True
+ order, manager, force_update=force_update
)
+ if order.tax_error is not None:
+ raise ValidationError(
+ "Configured Tax App didn't responded.",
+ code=OrderErrorCode.TAX_ERROR.value,
+ )
cls.validate_order(order)
country = get_order_country(order)
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
index 9e3bac307a..e568f56cf2 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
@@ -6,6 +6,7 @@ import pytz
from django.db.models import Sum
from django.test import override_settings
from freezegun import freeze_time
+from prices import Money, TaxedMoney
from .....core import EventDeliveryStatus
from .....core.models import EventDelivery
@@ -14,9 +15,12 @@ from .....discount.models import VoucherCustomer
from .....order import OrderOrigin, OrderStatus
from .....order import events as order_events
from .....order.error_codes import OrderErrorCode
+from .....order.interface import OrderTaxedPricesData
from .....order.models import OrderEvent
from .....payment.model_helpers import get_subtotal
+from .....plugins import PLUGIN_IDENTIFIER_PREFIX
from .....plugins.base_plugin import ExcludedShippingMethod
+from .....plugins.tests.sample_plugins import PluginSample
from .....plugins.webhook.conftest import ( # noqa: F401
tax_data_response,
tax_line_data_response,
@@ -1048,7 +1052,7 @@ def test_draft_order_complete_fails_with_invalid_tax_app(
assert not EventDelivery.objects.exists()
order.refresh_from_db()
- assert order.should_refresh_prices
+ assert not order.should_refresh_prices
assert order.tax_error == "Empty tax data."
@@ -1139,3 +1143,53 @@ def test_draft_order_complete_calls_correct_tax_app(
order.refresh_from_db()
assert not order.should_refresh_prices
assert not order.tax_error
+
+
+@freeze_time()
+@patch("saleor.plugins.tests.sample_plugins.PluginSample.calculate_order_line_total")
+@override_settings(PLUGINS=["saleor.plugins.tests.sample_plugins.PluginSample"])
+def test_draft_order_complete_calls_failing_plugin(
+ mock_calculate_order_line_total,
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ channel_USD,
+):
+ # given
+ def side_effect(order, *args, **kwargs):
+ price = Money("10.0", order.currency)
+ order.tax_error = "Test error"
+ return OrderTaxedPricesData(
+ price_with_discounts=TaxedMoney(price, price),
+ undiscounted_price=TaxedMoney(price, price),
+ )
+
+ mock_calculate_order_line_total.side_effect = side_effect
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ order = draft_order
+ order.should_refresh_prices = True
+ order.save()
+
+ channel_USD.tax_configuration.tax_app_id = (
+ PLUGIN_IDENTIFIER_PREFIX + PluginSample.PLUGIN_ID
+ )
+ channel_USD.tax_configuration.save()
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["draftOrderComplete"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == OrderErrorCode.TAX_ERROR.name
+ assert data["errors"][0]["message"] == "Configured Tax App didn't responded."
+
+ order.refresh_from_db()
+ assert not order.should_refresh_prices
+ assert order.tax_error == "Empty tax data."
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 97b5696b86..c6d4a98567 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -20881,7 +20881,7 @@ input TaxConfigurationUpdateInput @doc(category: "Taxes") {
removeCountriesConfiguration: [CountryCode!]
"""
- The tax app id 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. Will become mandatory in 4.0 for `TAX_APP` `taxCalculationStrategy`.
+ The tax app id 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`.
Added in Saleor 3.19.
"""
diff --git a/saleor/graphql/tax/mutations/tax_configuration_update.py b/saleor/graphql/tax/mutations/tax_configuration_update.py
index 4d8fd1367e..489e79f98c 100644
--- a/saleor/graphql/tax/mutations/tax_configuration_update.py
+++ b/saleor/graphql/tax/mutations/tax_configuration_update.py
@@ -3,6 +3,7 @@ from django.core.exceptions import ValidationError
from ....app.utils import get_active_tax_apps
from ....permission.enums import CheckoutPermissions
+from ....plugins import PLUGIN_IDENTIFIER_PREFIX
from ....tax import error_codes, models
from ...account.enums import CountryCodeEnum
from ...core import ResolveInfo
@@ -11,6 +12,7 @@ from ...core.doc_category import DOC_CATEGORY_TAXES
from ...core.mutations import ModelMutation
from ...core.types import BaseInputObjectType, Error, NonNullList
from ...core.utils import get_duplicates_items
+from ...plugins.dataloaders import get_plugin_manager_promise
from ..enums import TaxCalculationStrategy
from ..types import TaxConfiguration
@@ -91,7 +93,9 @@ class TaxConfigurationUpdateInput(BaseInputObjectType):
"The tax app id 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. "
+ "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`."
+ ADDED_IN_319
),
@@ -130,7 +134,7 @@ class TaxConfigurationUpdate(ModelMutation):
@classmethod
def clean_input(cls, info: ResolveInfo, instance, data, **kwargs):
- cls.clean_tax_app_id(info, data)
+ cls.clean_tax_app_id(info, instance, data)
update_countries_configuration = data.get("update_countries_configuration", [])
update_country_codes = [
item["country_code"] for item in update_countries_configuration
@@ -153,26 +157,46 @@ class TaxConfigurationUpdate(ModelMutation):
return super().clean_input(info, instance, data, **kwargs)
@classmethod
- def clean_tax_app_id(cls, info: ResolveInfo, data):
+ def clean_tax_app_id(cls, info: ResolveInfo, instance, data):
identifiers = []
- if app_identifier := data.get("tax_app_id"):
+ if (app_identifier := data.get("tax_app_id")) is not None:
identifiers.append(app_identifier)
update_countries_configuration = data.get("update_countries_configuration", [])
for country in update_countries_configuration:
- if app_identifier := country.get("tax_app_id"):
- identifiers.append(app_identifier)
+ if (country_app_identifier := country.get("tax_app_id")) is not None:
+ identifiers.append(country_app_identifier)
active_tax_apps = list(get_active_tax_apps(identifiers))
+ active_tax_app_identifiers = [app.identifier for app in active_tax_apps]
- if app_identifier := data.get("tax_app_id"):
- cls.__verify_tax_app_id(info, app_identifier, active_tax_apps)
+ # include plugin in list of possible tax apps
+ manager = get_plugin_manager_promise(info.context).get()
+ plugin_ids = [
+ identifier.replace(PLUGIN_IDENTIFIER_PREFIX, "")
+ for identifier in identifiers
+ if identifier.startswith(PLUGIN_IDENTIFIER_PREFIX)
+ ]
+ valid_plugins = manager.get_plugins(
+ instance.channel.slug, active_only=True, plugin_ids=plugin_ids
+ )
+ valid_plugin_identifiers = [
+ PLUGIN_IDENTIFIER_PREFIX + plugin.PLUGIN_ID for plugin in valid_plugins
+ ]
+ active_tax_app_identifiers.extend(valid_plugin_identifiers)
+
+ # validate input
+ if app_identifier is not None:
+ cls.__verify_tax_app_id(info, app_identifier, active_tax_app_identifiers)
update_countries_configuration = data.get("update_countries_configuration", [])
for country in update_countries_configuration:
- if app_identifier := country.get("tax_app_id"):
+ if (country_app_identifier := country.get("tax_app_id")) is not None:
cls.__verify_tax_app_id(
- info, app_identifier, active_tax_apps, [country["country_code"]]
+ info,
+ country_app_identifier,
+ active_tax_app_identifiers,
+ [country["country_code"]],
)
@classmethod
@@ -180,11 +204,10 @@ class TaxConfigurationUpdate(ModelMutation):
cls,
info: ResolveInfo,
app_identifier,
- active_tax_apps,
+ active_tax_app_identifiers,
country_codes=[],
):
- identifiers = [app.identifier for app in active_tax_apps]
- if app_identifier not in identifiers:
+ if app_identifier not in active_tax_app_identifiers:
message = "Did not found Tax App with provided taxAppId."
code = error_codes.TaxConfigurationUpdateErrorCode.NOT_FOUND.value
params = {"country_codes": country_codes}
diff --git a/saleor/graphql/tax/tests/mutations/test_tax_configuration_update.py b/saleor/graphql/tax/tests/mutations/test_tax_configuration_update.py
index 17d15555ca..c7630f1899 100644
--- a/saleor/graphql/tax/tests/mutations/test_tax_configuration_update.py
+++ b/saleor/graphql/tax/tests/mutations/test_tax_configuration_update.py
@@ -1,7 +1,10 @@
import graphene
import pytest
+from django.test import override_settings
from .....core.tests.test_taxes import app_factory, tax_app_factory # noqa: F401
+from .....plugins import PLUGIN_IDENTIFIER_PREFIX
+from .....plugins.tests.sample_plugins import PluginSample
from .....tax.error_codes import TaxConfigurationUpdateErrorCode
from .....tax.models import TaxConfiguration
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -387,3 +390,30 @@ def test_tax_configuration_update_tax_app_id_with_non_existent_app(
assert errors
assert errors[0]["message"] == "Did not found Tax App with provided taxAppId."
assert errors[0]["code"] == TaxConfigurationUpdateErrorCode.NOT_FOUND.name
+
+
+@override_settings(PLUGINS=["saleor.plugins.tests.sample_plugins.PluginSample"])
+def test_tax_configuration_update_tax_app_id_with_plugin(
+ example_tax_configuration, staff_api_client, permission_manage_taxes
+):
+ """Make sure that we are able to still use legacy plugin."""
+ # given
+ id = graphene.Node.to_global_id("TaxConfiguration", example_tax_configuration.pk)
+ plugin_id = PLUGIN_IDENTIFIER_PREFIX + PluginSample.PLUGIN_ID
+ variables = {
+ "id": id,
+ "input": {
+ "taxAppId": plugin_id,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION, variables, permissions=[permission_manage_taxes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["taxConfigurationUpdate"]["taxConfiguration"]
+ assert not content["data"]["taxConfigurationUpdate"]["errors"]
+ assert data["taxAppId"] == plugin_id
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index 77be66c371..fffc936b7d 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -2,15 +2,15 @@ from collections.abc import Iterable
from decimal import Decimal
from typing import Optional
-from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import prefetch_related_objects
from prices import Money, TaxedMoney
from ..core.prices import quantize_price
-from ..core.taxes import EmptyTaxData, TaxData, TaxError, zero_taxed_money
+from ..core.taxes import TaxData, TaxEmptyData, TaxError, zero_taxed_money
from ..discount import DiscountType
from ..payment.model_helpers import get_subtotal
+from ..plugins import PLUGIN_IDENTIFIER_PREFIX
from ..plugins.manager import PluginsManager
from ..tax import TaxCalculationStrategy
from ..tax.calculations import get_taxed_undiscounted_price
@@ -23,7 +23,6 @@ from ..tax.utils import (
)
from . import ORDER_EDITABLE_STATUS
from .base_calculations import apply_order_discounts, base_order_line_total
-from .error_codes import OrderErrorCode
from .interface import OrderTaxedPricesData
from .models import Order, OrderLine
@@ -33,7 +32,6 @@ def fetch_order_prices_if_expired(
manager: PluginsManager,
lines: Optional[Iterable[OrderLine]] = None,
force_update: bool = False,
- need_tax_calculation: bool = False,
) -> tuple[Order, Optional[Iterable[OrderLine]]]:
"""Fetch order prices with taxes.
@@ -56,7 +54,7 @@ def fetch_order_prices_if_expired(
order.should_refresh_prices = False
_update_order_discount_for_voucher(order)
- _recalculate_prices(order, manager, lines, need_tax_calculation)
+ _recalculate_prices(order, manager, lines)
order.subtotal = get_subtotal(lines, order.currency)
with transaction.atomic(savepoint=False):
@@ -72,6 +70,7 @@ def fetch_order_prices_if_expired(
"shipping_price_gross_amount",
"shipping_tax_rate",
"should_refresh_prices",
+ "tax_error",
]
)
order.lines.bulk_update(
@@ -129,7 +128,6 @@ def _recalculate_prices(
order: Order,
manager: PluginsManager,
lines: Iterable[OrderLine],
- need_tax_calculation: bool = False,
):
"""Calculate prices after handling order level discounts and taxes."""
tax_configuration = order.channel.tax_configuration
@@ -155,7 +153,7 @@ def _recalculate_prices(
manager,
prices_entered_with_tax,
)
- except EmptyTaxData as e:
+ except TaxEmptyData as e:
order.tax_error = str(e)
if not should_charge_tax:
@@ -177,19 +175,11 @@ def _recalculate_prices(
manager,
prices_entered_with_tax,
)
- except EmptyTaxData as e:
+ except TaxEmptyData as e:
order.tax_error = str(e)
else:
_remove_tax(order, lines)
- order.save(update_fields=["tax_error"])
- # raise an error if recorded tax_error and taxes are needed for process completion
- if order.tax_error and need_tax_calculation:
- raise ValidationError(
- "Configured Tax App didn't responded.",
- code=OrderErrorCode.TAX_ERROR.value,
- )
-
def _calculate_and_add_tax(
tax_calculation_strategy: str,
@@ -200,25 +190,64 @@ def _calculate_and_add_tax(
prices_entered_with_tax: bool,
):
if tax_calculation_strategy == TaxCalculationStrategy.TAX_APP:
- # Get the taxes calculated with plugins.
- _recalculate_with_plugins(manager, order, lines, prices_entered_with_tax)
- # Get the taxes calculated with apps and apply to order.
- tax_data = manager.get_taxes_for_order(order, tax_app_identifier)
- # If taxAppId is not configured we will for now allow to finalize process for
- # backward compatibility.
- if tax_data is None and tax_app_identifier is not None:
- raise EmptyTaxData("Empty tax data.")
- _apply_tax_data(order, lines, tax_data)
+ # 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:
+ # Get the taxes calculated with plugins.
+ _recalculate_with_plugins(manager, order, lines, prices_entered_with_tax)
+ # Get the taxes calculated with apps and apply to order.
+ tax_data = manager.get_taxes_for_order(order, tax_app_identifier)
+ _apply_tax_data(order, lines, tax_data)
+ else:
+ _call_plugin_or_tax_app(
+ tax_app_identifier,
+ order,
+ lines,
+ manager,
+ prices_entered_with_tax,
+ )
else:
# Get taxes calculated with flat rates and apply to order.
update_order_prices_with_flat_rates(order, lines, prices_entered_with_tax)
+def _call_plugin_or_tax_app(
+ tax_app_identifier: str,
+ order: "Order",
+ lines: Iterable["OrderLine"],
+ manager: "PluginsManager",
+ prices_entered_with_tax: bool,
+):
+ if tax_app_identifier.startswith(PLUGIN_IDENTIFIER_PREFIX):
+ plugin_ids = [tax_app_identifier.replace(PLUGIN_IDENTIFIER_PREFIX, "")]
+ plugins = manager.get_plugins(
+ order.channel.slug, active_only=True, plugin_ids=plugin_ids
+ )
+ if not plugins:
+ raise TaxEmptyData("Empty tax data.")
+ _recalculate_with_plugins(
+ manager,
+ order,
+ lines,
+ prices_entered_with_tax,
+ plugin_ids=plugin_ids,
+ )
+ if order.tax_error:
+ raise TaxEmptyData("Empty tax data.")
+ else:
+ tax_data = manager.get_taxes_for_order(order, tax_app_identifier)
+ if tax_data is None:
+ raise TaxEmptyData("Empty tax data.")
+ _apply_tax_data(order, lines, tax_data)
+
+
def _recalculate_with_plugins(
manager: PluginsManager,
order: Order,
lines: Iterable[OrderLine],
prices_entered_with_tax: bool,
+ plugin_ids: Optional[list[str]] = None,
) -> None:
"""Fetch taxes from plugins and recalculate order/lines prices.
@@ -233,18 +262,23 @@ def _recalculate_with_plugins(
try:
line_unit = manager.calculate_order_line_unit(
- order, line, variant, product, lines
+ order, line, variant, product, lines, plugin_ids=plugin_ids
)
line.unit_price = line_unit.price_with_discounts
line_total = manager.calculate_order_line_total(
- order, line, variant, product, lines
+ order, line, variant, product, lines, plugin_ids=plugin_ids
)
undiscounted_subtotal += line_total.undiscounted_price
line.total_price = line_total.price_with_discounts
line.tax_rate = manager.get_order_line_tax_rate(
- order, product, variant, None, line_unit.undiscounted_price
+ order,
+ product,
+ variant,
+ None,
+ line_unit.undiscounted_price,
+ plugin_ids=plugin_ids,
)
line.undiscounted_unit_price = _get_undiscounted_price(
line_unit,
@@ -264,9 +298,11 @@ def _recalculate_with_plugins(
pass
try:
- order.shipping_price = manager.calculate_order_shipping(order, lines)
+ order.shipping_price = manager.calculate_order_shipping(
+ order, lines, plugin_ids=plugin_ids
+ )
order.shipping_tax_rate = manager.get_order_shipping_tax_rate(
- order, order.shipping_price
+ order, order.shipping_price, plugin_ids=plugin_ids
)
except TaxError:
pass
@@ -274,7 +310,7 @@ def _recalculate_with_plugins(
order.undiscounted_total = undiscounted_subtotal + TaxedMoney(
net=order.base_shipping_price, gross=order.base_shipping_price
)
- order.total = manager.calculate_order_total(order, lines)
+ order.total = manager.calculate_order_total(order, lines, plugin_ids=plugin_ids)
def _get_undiscounted_price(
diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.py
index 48b73e4cb8..117268c864 100644
--- a/saleor/order/tests/test_calculations.py
+++ b/saleor/order/tests/test_calculations.py
@@ -3,12 +3,15 @@ from typing import Literal, Union
from unittest.mock import Mock, patch, sentinel
import pytest
+from django.test import override_settings
from prices import Money, TaxedMoney
from ...core.prices import quantize_price
from ...core.taxes import TaxData, TaxError, TaxLineData, zero_taxed_money
from ...discount import DiscountValueType
+from ...plugins import PLUGIN_IDENTIFIER_PREFIX
from ...plugins.manager import get_plugins_manager
+from ...plugins.tests.sample_plugins import PluginSample
from ...tax import TaxCalculationStrategy
from ...tax.calculations.order import update_order_prices_with_flat_rates
from .. import OrderStatus, calculations
@@ -1141,3 +1144,95 @@ def test_order_undiscounted_total(mocked_fetch_order_prices_if_expired):
assert undiscounted_total == quantize_price(
expected_undiscounted_total, order.currency
)
+
+
+@patch("saleor.plugins.manager.PluginsManager.calculate_order_line_total")
+@patch("saleor.plugins.manager.PluginsManager.get_taxes_for_order")
+@override_settings(PLUGINS=["saleor.plugins.tests.sample_plugins.PluginSample"])
+def test_fetch_order_data_calls_plugin(
+ mock_get_taxes,
+ mock_calculate_order_line_total,
+ order_with_lines,
+ order_lines,
+):
+ # given
+ order = order_with_lines
+ order.channel.tax_configuration.tax_app_id = (
+ PLUGIN_IDENTIFIER_PREFIX + PluginSample.PLUGIN_ID
+ )
+ order.channel.tax_configuration.save()
+
+ price = Money("10.0", currency=order.currency)
+ mock_calculate_order_line_total.return_value = OrderTaxedPricesData(
+ undiscounted_price=TaxedMoney(price, price),
+ price_with_discounts=TaxedMoney(price, price),
+ )
+
+ fetch_kwargs = {
+ "order": order,
+ "manager": get_plugins_manager(allow_replica=False),
+ "lines": order_lines,
+ "force_update": True,
+ }
+
+ # when
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+
+ # then
+ assert mock_calculate_order_line_total.call_count == 2
+ mock_get_taxes.assert_not_called()
+
+
+@patch("saleor.plugins.manager.PluginsManager.calculate_order_total")
+@patch("saleor.plugins.manager.PluginsManager.get_taxes_for_order")
+@patch("saleor.order.calculations._apply_tax_data")
+@override_settings(PLUGINS=["saleor.plugins.tests.sample_plugins.PluginSample"])
+def test_fetch_order_data_calls_tax_app(
+ mock_apply_tax_data,
+ mock_get_taxes,
+ mock_calculate_order_total,
+ order_with_lines,
+ order_lines,
+):
+ # given
+ order = order_with_lines
+ order.channel.tax_configuration.tax_app_id = "test.app"
+ order.channel.tax_configuration.save()
+
+ fetch_kwargs = {
+ "order": order,
+ "manager": get_plugins_manager(allow_replica=False),
+ "lines": order_lines,
+ "force_update": True,
+ }
+
+ # when
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+
+ # then
+ mock_apply_tax_data.assert_called_once()
+ mock_get_taxes.assert_called_once()
+ mock_calculate_order_total.assert_not_called()
+
+
+def test_fetch_order_data_calls_inactive_plugin(
+ order_with_lines,
+ order_lines,
+):
+ # given
+ order = order_with_lines
+ order.channel.tax_configuration.tax_app_id = "plugin:test"
+ order.channel.tax_configuration.save()
+
+ fetch_kwargs = {
+ "order": order,
+ "manager": get_plugins_manager(allow_replica=False),
+ "lines": order_lines,
+ "force_update": True,
+ }
+
+ # when
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+
+ # then
+ assert order_with_lines.tax_error == "Empty tax data."
diff --git a/saleor/plugins/__init__.py b/saleor/plugins/__init__.py
index 6826345c28..9bcefc170a 100644
--- a/saleor/plugins/__init__.py
+++ b/saleor/plugins/__init__.py
@@ -1,6 +1,7 @@
import importlib
default_app_config = "saleor.plugins.apps.PluginConfig"
+PLUGIN_IDENTIFIER_PREFIX = "plugin:"
def discover_plugins_modules(plugins: list[str]):
diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.py
index bfe69adb07..31c067f12b 100644
--- a/saleor/plugins/avatax/plugin.py
+++ b/saleor/plugins/avatax/plugin.py
@@ -23,9 +23,12 @@ from ...tax import TaxCalculationStrategy
from ...tax.utils import (
get_charge_taxes_for_checkout,
get_charge_taxes_for_order,
+ get_tax_app_identifier_for_checkout,
+ get_tax_app_identifier_for_order,
get_tax_calculation_strategy_for_checkout,
get_tax_calculation_strategy_for_order,
)
+from .. import PLUGIN_IDENTIFIER_PREFIX
from ..base_plugin import BasePlugin, ConfigurationTypeField
from ..error_codes import PluginErrorCode
from . import (
@@ -74,6 +77,8 @@ def _get_prices_entered_with_tax_for_order(order: "Order"):
class AvataxPlugin(BasePlugin):
PLUGIN_NAME = "Avalara"
PLUGIN_ID = "mirumee.taxes.avalara"
+ # identifier used in tax configuration
+ PLUGIN_IDENTIFIER = PLUGIN_IDENTIFIER_PREFIX + PLUGIN_ID
DEFAULT_CONFIGURATION = [
{"name": "Username or account", "value": None},
@@ -319,7 +324,12 @@ class AvataxPlugin(BasePlugin):
return previous_value
tax_strategy = get_tax_calculation_strategy_for_checkout(checkout_info, lines)
- if tax_strategy == TaxCalculationStrategy.FLAT_RATES:
+ tax_app_identifier = get_tax_app_identifier_for_checkout(checkout_info, lines)
+ if (
+ tax_strategy == TaxCalculationStrategy.FLAT_RATES
+ or tax_app_identifier is not None
+ and tax_app_identifier != self.PLUGIN_IDENTIFIER
+ ):
return previous_value
data = generate_request_data_from_checkout(
@@ -359,7 +369,12 @@ class AvataxPlugin(BasePlugin):
if not self.active:
return previous_value
tax_strategy = get_tax_calculation_strategy_for_order(order)
- if tax_strategy == TaxCalculationStrategy.FLAT_RATES:
+ tax_app_identifier = get_tax_app_identifier_for_order(order)
+ if (
+ tax_strategy == TaxCalculationStrategy.FLAT_RATES
+ or tax_app_identifier is not None
+ and tax_app_identifier != self.PLUGIN_IDENTIFIER
+ ):
return previous_value
request_data = get_order_request_data(order, self.config)
@@ -719,35 +734,55 @@ class AvataxPlugin(BasePlugin):
base_value: Union[TaxedMoney, Decimal],
):
if self._skip_plugin(base_value):
+ self._set_checkout_tax_error(checkout_info, lines_info)
return None
valid = _validate_checkout(checkout_info, lines_info)
if not valid:
+ self._set_checkout_tax_error(checkout_info, lines_info)
return None
response = get_checkout_tax_data(checkout_info, lines_info, self.config)
if not response or "error" in response:
+ self._set_checkout_tax_error(checkout_info, lines_info)
return None
return response
+ def _set_checkout_tax_error(
+ self,
+ checkout_info: "CheckoutInfo",
+ lines_info: Iterable["CheckoutLineInfo"],
+ ) -> None:
+ app_identifier = get_tax_app_identifier_for_checkout(checkout_info, lines_info)
+ if app_identifier == self.PLUGIN_IDENTIFIER:
+ checkout_info.checkout.tax_error = "Empty tax data."
+
def _get_order_tax_data(
self, order: "Order", base_value: Union[Decimal, OrderTaxedPricesData]
):
if self._skip_plugin(base_value):
+ self._set_order_tax_error(order)
return None
valid = _validate_order(order)
if not valid:
+ self._set_order_tax_error(order)
return None
response = get_order_tax_data(order, self.config, False)
if not response or "error" in response:
+ self._set_order_tax_error(order)
return None
return response
+ def _set_order_tax_error(self, order: "Order") -> None:
+ app_identifier = get_tax_app_identifier_for_order(order)
+ if app_identifier == self.PLUGIN_IDENTIFIER:
+ order.tax_error = "Empty tax data."
+
@staticmethod
def _get_unit_tax_rate(
response: dict[str, Any],
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index e7f45fca4f..d81b293880 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -6122,3 +6122,241 @@ def test_calculate_checkout_line_unit_price_validates_checkout(
# then
assert not mocked_func.called
+
+
+@patch("saleor.plugins.avatax.plugin.api_post_request_task.delay")
+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+def test_preprocess_order_creation_with_tax_app_id_as_plugin(
+ api_post_request_task_mock,
+ checkout_with_item,
+ address,
+ ship_to_pl_address,
+ site_settings,
+ shipping_zone,
+ plugin_configuration,
+):
+ # given
+ channel = checkout_with_item.channel
+ tax_configuration = channel.tax_configuration
+ tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
+ tax_configuration.tax_app_id = "test_app"
+ tax_configuration.save()
+ tax_configuration.country_exceptions.all().delete()
+
+ plugin_configuration(
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_postal_code="53-603",
+ from_country="PL",
+ shipping_tax_code="FR00001",
+ )
+
+ manager = get_plugins_manager(allow_replica=True)
+ site_settings.company_address = address
+ site_settings.save()
+
+ checkout_with_item.shipping_address = ship_to_pl_address
+ checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.save()
+ lines, _ = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
+
+ # when
+ manager.preprocess_order_creation(checkout_info, lines)
+
+ # then
+ api_post_request_task_mock.assert_not_called()
+
+
+@patch("saleor.plugins.avatax.plugin.api_post_request_task.delay")
+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+def test_preprocess_order_creation_with_country_exception_tax_app_id_plugin(
+ api_post_request_task_mock,
+ checkout_with_item,
+ address,
+ ship_to_pl_address,
+ site_settings,
+ shipping_zone,
+ plugin_configuration,
+):
+ # given
+ channel = checkout_with_item.channel
+ tax_configuration = channel.tax_configuration
+ tax_configuration.tax_app_id = None
+ tax_configuration.save()
+ tax_configuration.country_exceptions.all().delete()
+
+ tax_configuration.country_exceptions.create(
+ country="PL",
+ tax_calculation_strategy=TaxCalculationStrategy.TAX_APP,
+ tax_app_id="test_app",
+ )
+
+ plugin_configuration(
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_postal_code="53-603",
+ from_country="PL",
+ shipping_tax_code="FR00001",
+ )
+
+ manager = get_plugins_manager(allow_replica=True)
+ site_settings.company_address = address
+ site_settings.save()
+
+ checkout_with_item.shipping_address = ship_to_pl_address
+ checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.save()
+ lines, _ = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
+
+ # when
+ manager.preprocess_order_creation(checkout_info, lines)
+
+ # then
+ api_post_request_task_mock.assert_not_called()
+
+
+@patch("saleor.plugins.avatax.plugin.api_post_request_task.delay")
+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+def test_order_confirmed_skip_with_tax_app_id_as_plugin(
+ api_post_request_task_mock, order, plugin_configuration
+):
+ # given
+ channel = order.channel
+ tax_configuration = channel.tax_configuration
+ tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
+ tax_configuration.tax_app_id = "test_app"
+ tax_configuration.save()
+ tax_configuration.country_exceptions.all().delete()
+
+ plugin_configuration(
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_postal_code="53-603",
+ from_country="PL",
+ shipping_tax_code="FR00001",
+ )
+
+ manager = get_plugins_manager(allow_replica=True)
+
+ # when
+ manager.order_confirmed(order)
+
+ # then
+ api_post_request_task_mock.assert_not_called()
+
+
+@patch("saleor.plugins.avatax.plugin.api_post_request_task.delay")
+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+def test_order_confirmed_skip_with_country_exception_tax_app_id_plugin(
+ api_post_request_task_mock, order, order_line, plugin_configuration
+):
+ # given
+ channel = order.channel
+ tax_configuration = channel.tax_configuration
+ tax_configuration.tax_app_id = None
+ tax_configuration.save()
+ tax_configuration.country_exceptions.all().delete()
+
+ tax_configuration.country_exceptions.create(
+ country="PL",
+ tax_calculation_strategy=TaxCalculationStrategy.TAX_APP,
+ tax_app_id="test_app",
+ )
+
+ plugin_configuration(
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_postal_code="53-603",
+ from_country="PL",
+ shipping_tax_code="FR00001",
+ )
+
+ manager = get_plugins_manager(allow_replica=True)
+
+ # when
+ manager.order_confirmed(order)
+
+ # then
+ api_post_request_task_mock.assert_not_called()
+
+
+@patch("saleor.plugins.avatax.plugin.get_order_tax_data")
+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+def test_get_order_tax_data_set_tax_error(
+ mock_get_order_tax_data, order, order_line, plugin_configuration
+):
+ # given
+ mock_get_order_tax_data.return_value = None
+
+ channel = order.channel
+ tax_configuration = channel.tax_configuration
+ tax_configuration.tax_app_id = AvataxPlugin.PLUGIN_IDENTIFIER
+ tax_configuration.save()
+ tax_configuration.country_exceptions.all().delete()
+
+ plugin_configuration(
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_postal_code="53-603",
+ from_country="PL",
+ shipping_tax_code="FR00001",
+ )
+
+ manager = get_plugins_manager(allow_replica=True)
+
+ # when
+ manager.calculate_order_total(order, order.lines.all())
+
+ # then
+ assert order.tax_error == "Empty tax data."
+
+
+@patch("saleor.plugins.avatax.plugin.get_checkout_tax_data")
+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+def test_get_checkout_tax_data_set_tax_error(
+ mock_get_checkout_tax_data,
+ checkout_with_item,
+ address,
+ ship_to_pl_address,
+ site_settings,
+ shipping_zone,
+ plugin_configuration,
+):
+ # given
+ mock_get_checkout_tax_data.return_value = None
+
+ channel = checkout_with_item.channel
+ tax_configuration = channel.tax_configuration
+ tax_configuration.tax_app_id = AvataxPlugin.PLUGIN_IDENTIFIER
+ tax_configuration.save()
+ tax_configuration.country_exceptions.all().delete()
+
+ plugin_configuration(
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_postal_code="53-603",
+ from_country="PL",
+ shipping_tax_code="FR00001",
+ )
+
+ manager = get_plugins_manager(allow_replica=True)
+ site_settings.company_address = address
+ site_settings.save()
+
+ checkout_with_item.shipping_address = ship_to_pl_address
+ checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.save()
+ lines, _ = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
+
+ # when
+ manager.calculate_checkout_total(
+ checkout_info=checkout_info,
+ lines=lines,
+ address=address,
+ )
+
+ # then
+ assert checkout_with_item.tax_error == "Empty tax data."
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 3341a85123..5ae9ee9721 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -196,11 +196,16 @@ class PluginsManager(PaymentInterface):
default_value: Any,
*args,
channel_slug: Optional[str] = None,
+ plugin_ids: Optional[list[str]] = None,
**kwargs,
):
"""Try to run a method with the given name on each declared active plugin."""
value = default_value
- plugins = self.get_plugins(channel_slug=channel_slug, active_only=True)
+ plugins = self.get_plugins(
+ channel_slug=channel_slug,
+ active_only=True,
+ plugin_ids=plugin_ids,
+ )
for plugin in plugins:
value = self.__run_method_on_single_plugin(
plugin, method_name, value, *args, **kwargs
@@ -251,6 +256,7 @@ class PluginsManager(PaymentInterface):
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
+ plugin_ids: Optional[list[str]] = None,
) -> TaxedMoney:
currency = checkout_info.checkout.currency
@@ -274,6 +280,7 @@ class PluginsManager(PaymentInterface):
lines,
address,
channel_slug=checkout_info.channel.slug,
+ plugin_ids=plugin_ids,
),
currency,
)
@@ -283,6 +290,7 @@ class PluginsManager(PaymentInterface):
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
+ plugin_ids: Optional[list[str]] = None,
) -> TaxedMoney:
line_totals = [
self.calculate_checkout_line_total(
@@ -290,6 +298,7 @@ class PluginsManager(PaymentInterface):
lines,
line_info,
address,
+ plugin_ids=plugin_ids,
)
for line_info in lines
]
@@ -305,6 +314,7 @@ class PluginsManager(PaymentInterface):
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
+ plugin_ids: Optional[list[str]] = None,
) -> TaxedMoney:
price = base_calculations.base_checkout_delivery_price(checkout_info, lines)
default_value = TaxedMoney(price, price)
@@ -316,6 +326,7 @@ class PluginsManager(PaymentInterface):
lines,
address,
channel_slug=checkout_info.channel.slug,
+ plugin_ids=plugin_ids,
),
checkout_info.checkout.currency,
)
@@ -324,6 +335,7 @@ class PluginsManager(PaymentInterface):
self,
order: "Order",
lines: Iterable["OrderLine"],
+ plugin_ids: Optional[list[str]] = None,
) -> TaxedMoney:
currency = order.currency
default_value = base_order_calculations.base_order_total(order, lines)
@@ -341,12 +353,16 @@ class PluginsManager(PaymentInterface):
order,
lines,
channel_slug=order.channel.slug,
+ plugin_ids=plugin_ids,
),
currency,
)
def calculate_order_shipping(
- self, order: "Order", lines: Iterable["OrderLine"]
+ self,
+ order: "Order",
+ lines: Iterable["OrderLine"],
+ plugin_ids: Optional[list[str]] = None,
) -> TaxedMoney:
subtotal, shipping_price = propagate_order_discount_on_order_prices(
order, lines
@@ -358,6 +374,7 @@ class PluginsManager(PaymentInterface):
default_value,
order,
channel_slug=order.channel.slug,
+ plugin_ids=plugin_ids,
),
order.currency,
)
@@ -368,6 +385,7 @@ class PluginsManager(PaymentInterface):
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
shipping_price: TaxedMoney,
+ plugin_ids: Optional[list[str]] = None,
):
default_value = calculate_tax_rate(shipping_price)
return self.__run_method_on_plugins(
@@ -377,15 +395,22 @@ class PluginsManager(PaymentInterface):
lines,
address,
channel_slug=checkout_info.channel.slug,
+ plugin_ids=plugin_ids,
).quantize(Decimal(".0001"))
- def get_order_shipping_tax_rate(self, order: "Order", shipping_price: TaxedMoney):
+ def get_order_shipping_tax_rate(
+ self,
+ order: "Order",
+ shipping_price: TaxedMoney,
+ plugin_ids: Optional[list[str]] = None,
+ ):
default_value = calculate_tax_rate(shipping_price)
return self.__run_method_on_plugins(
"get_order_shipping_tax_rate",
default_value,
order,
channel_slug=order.channel.slug,
+ plugin_ids=plugin_ids,
).quantize(Decimal(".0001"))
def calculate_checkout_line_total(
@@ -394,6 +419,7 @@ class PluginsManager(PaymentInterface):
lines: Iterable["CheckoutLineInfo"],
checkout_line_info: "CheckoutLineInfo",
address: Optional["Address"],
+ plugin_ids: Optional[list[str]] = None,
) -> TaxedMoney:
default_value = base_calculations.calculate_base_line_total_price(
checkout_line_info,
@@ -416,6 +442,7 @@ class PluginsManager(PaymentInterface):
checkout_line_info,
address,
channel_slug=checkout_info.channel.slug,
+ plugin_ids=plugin_ids,
)
return quantize_price(line_total, checkout_info.checkout.currency)
@@ -427,6 +454,7 @@ class PluginsManager(PaymentInterface):
variant: "ProductVariant",
product: "Product",
lines: Iterable["OrderLine"],
+ plugin_ids: Optional[list[str]] = None,
) -> OrderTaxedPricesData:
base_subtotal = base_order_subtotal(order, lines)
subtotal, shipping_price = propagate_order_discount_on_order_prices(
@@ -451,6 +479,7 @@ class PluginsManager(PaymentInterface):
variant,
product,
channel_slug=order.channel.slug,
+ plugin_ids=plugin_ids,
)
line_total.price_with_discounts = quantize_price(
@@ -467,6 +496,7 @@ class PluginsManager(PaymentInterface):
lines: Iterable["CheckoutLineInfo"],
checkout_line_info: "CheckoutLineInfo",
address: Optional["Address"],
+ plugin_ids: Optional[list[str]] = None,
) -> TaxedMoney:
quantity = checkout_line_info.line.quantity
default_value = base_calculations.calculate_base_line_unit_price(
@@ -490,6 +520,7 @@ class PluginsManager(PaymentInterface):
checkout_line_info,
address,
channel_slug=checkout_info.channel.slug,
+ plugin_ids=plugin_ids,
)
return quantize_price(unit_price, checkout_info.checkout.currency)
@@ -500,6 +531,7 @@ class PluginsManager(PaymentInterface):
variant: "ProductVariant",
product: "Product",
lines: Iterable["OrderLine"],
+ plugin_ids: Optional[list[str]] = None,
) -> OrderTaxedPricesData:
base_subtotal = base_order_subtotal(order, lines)
subtotal, shipping_price = propagate_order_discount_on_order_prices(
@@ -528,6 +560,7 @@ class PluginsManager(PaymentInterface):
variant,
product,
channel_slug=order.channel.slug,
+ plugin_ids=plugin_ids,
)
line_unit.price_with_discounts = quantize_price(
line_unit.price_with_discounts, currency
@@ -544,6 +577,7 @@ class PluginsManager(PaymentInterface):
checkout_line_info: "CheckoutLineInfo",
address: Optional["Address"],
price: TaxedMoney,
+ plugin_ids: Optional[list[str]] = None,
) -> Decimal:
default_value = calculate_tax_rate(price)
return self.__run_method_on_plugins(
@@ -554,6 +588,7 @@ class PluginsManager(PaymentInterface):
checkout_line_info,
address,
channel_slug=checkout_info.channel.slug,
+ plugin_ids=plugin_ids,
).quantize(Decimal(".0001"))
def get_order_line_tax_rate(
@@ -563,6 +598,7 @@ class PluginsManager(PaymentInterface):
variant: "ProductVariant",
address: Optional["Address"],
unit_price: TaxedMoney,
+ plugin_ids: Optional[list[str]] = None,
) -> Decimal:
default_value = calculate_tax_rate(unit_price)
return self.__run_method_on_plugins(
@@ -573,6 +609,7 @@ class PluginsManager(PaymentInterface):
variant,
address,
channel_slug=order.channel.slug,
+ plugin_ids=plugin_ids,
).quantize(Decimal(".0001"))
def get_tax_rate_type_choices(self) -> list[TaxType]:
@@ -1778,7 +1815,10 @@ class PluginsManager(PaymentInterface):
)
def get_plugins(
- self, channel_slug: Optional[str] = None, active_only=False
+ self,
+ channel_slug: Optional[str] = None,
+ active_only=False,
+ plugin_ids: Optional[list[str]] = None,
) -> list["BasePlugin"]:
"""Return list of plugins for a given channel."""
if channel_slug:
@@ -1788,6 +1828,10 @@ class PluginsManager(PaymentInterface):
if active_only:
plugins = [plugin for plugin in plugins if plugin.active]
+
+ if plugin_ids:
+ plugins = [plugin for plugin in plugins if plugin.PLUGIN_ID in plugin_ids]
+
return plugins
def list_payment_gateways(