Skip to content

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

Order discount is applied 2 times when any tax app/plugin is active. (#10428)

Jakub6bc3e230dc96
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index 1ec1399912..e1a381a420 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -14,12 +14,10 @@ from prices import Money, TaxedMoney
from ..core.prices import quantize_price
from ..core.taxes import zero_money
from ..discount import DiscountInfo, VoucherType
-from ..order.interface import OrderTaxedPricesData
from .fetch import CheckoutInfo, CheckoutLineInfo
if TYPE_CHECKING:
from ..channel.models import Channel
- from ..order.models import OrderLine
from .fetch import ShippingMethodInfo
@@ -217,24 +215,6 @@ def base_checkout_subtotal(
return sum(line_totals, zero_money(currency))
-def base_order_line_total(order_line: "OrderLine") -> OrderTaxedPricesData:
- quantity = order_line.quantity
- price_with_discounts = (
- TaxedMoney(order_line.base_unit_price, order_line.base_unit_price) * quantity
- )
- undiscounted_price = (
- TaxedMoney(
- order_line.undiscounted_base_unit_price,
- order_line.undiscounted_base_unit_price,
- )
- * quantity
- )
- return OrderTaxedPricesData(
- undiscounted_price=undiscounted_price,
- price_with_discounts=price_with_discounts,
- )
-
-
def base_tax_rate(price: TaxedMoney):
tax_rate = Decimal("0.0")
# The condition will return False when unit_price.gross or unit_price.net is 0.0
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index da074ce8b6..ffca97ca0c 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -1,5 +1,7 @@
import datetime
from collections import defaultdict
+from decimal import Decimal
+from functools import partial
from typing import (
TYPE_CHECKING,
Callable,
@@ -11,17 +13,24 @@ from typing import (
Optional,
Set,
Tuple,
+ Union,
cast,
)
from django.db.models import F
from django.utils import timezone
-from prices import Money, TaxedMoney
+from prices import Money, TaxedMoney, fixed_discount, percentage_discount
from ..channel.models import Channel
from ..core.taxes import include_taxes_in_prices, zero_money
from . import DiscountInfo
-from .models import NotApplicable, Sale, SaleChannelListing, VoucherCustomer
+from .models import (
+ DiscountValueType,
+ NotApplicable,
+ Sale,
+ SaleChannelListing,
+ VoucherCustomer,
+)
if TYPE_CHECKING:
# flake8: noqa
@@ -360,3 +369,23 @@ def fetch_catalogue_info(instance: Sale) -> CatalogueInfo:
catalogue_info[field].add(id)
return catalogue_info
+
+
+def apply_discount_to_value(
+ value: Decimal,
+ value_type: str,
+ currency: str,
+ price_to_discount: Union[Money, TaxedMoney],
+):
+ """Calculate the price based on the provided values."""
+ if value_type == DiscountValueType.FIXED:
+ discount_method = fixed_discount
+ discount_kwargs = {"discount": Money(value, currency)}
+ else:
+ discount_method = percentage_discount
+ discount_kwargs = {"percentage": value}
+ discount = partial(
+ discount_method,
+ **discount_kwargs,
+ )
+ return discount(price_to_discount)
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index 36833f3098..d97c87278d 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -300,6 +300,8 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
@classmethod
def _commit_changes(cls, info, instance, cleaned_input, is_new_instance):
+ if shipping_method := cleaned_input["shipping_method"]:
+ instance.shipping_method_name = shipping_method.name
super().save(info, instance, cleaned_input)
# Create draft created event if the instance is from scratch
diff --git a/saleor/graphql/order/tests/test_discount_order.py b/saleor/graphql/order/tests/test_discount_order.py
index 9d63ef6fa7..e3cec138cd 100644
--- a/saleor/graphql/order/tests/test_discount_order.py
+++ b/saleor/graphql/order/tests/test_discount_order.py
@@ -256,7 +256,7 @@ def test_update_percentage_order_discount_to_order(
errors = data["errors"]
assert len(errors) == 0
- # Use `net` values in comparison due to that fixture have taxes incluted in
+ # Use `net` values in comparison due to that fixture have taxes included in
# prices but after recalculation taxes are removed because in tests we
# don't use any tax app.
assert order.undiscounted_total.net == current_undiscounted_total.net
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 60a5c3e9cb..89e3fe5eac 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -3527,44 +3527,9 @@ def test_draft_order_create_invalid_shipping_address(
assert errors[0]["addressType"] == AddressType.SHIPPING.upper()
-TAX_RATE_1 = Decimal("1.23")
-TAX_RATE_2 = Decimal("1.18")
-
-
-def calculate_order_line_price_side_effect(price_name):
- tax_rates = iter([TAX_RATE_1, TAX_RATE_2])
-
- def inner(
- order,
- order_line,
- variant,
- product,
- ):
- tax_rate = next(tax_rates)
- undiscounted_price = getattr(order_line, f"undiscounted_{price_name}")
- undiscounted_price.gross *= tax_rate
- price_with_discounts = getattr(order_line, price_name)
- price_with_discounts.gross *= tax_rate
-
- return OrderTaxedPricesData(
- undiscounted_price=undiscounted_price.quantize(),
- price_with_discounts=price_with_discounts.quantize(),
- )
-
- return inner
-
-
- PluginsManager,
- "calculate_order_line_unit",
- new=Mock(side_effect=calculate_order_line_price_side_effect("unit_price")),
-)
- PluginsManager,
- "calculate_order_line_total",
- new=Mock(side_effect=calculate_order_line_price_side_effect("total_price")),
-)
+@patch("saleor.order.calculations.fetch_order_prices_if_expired")
def test_draft_order_create_price_recalculation(
+ mock_fetch_order_prices_if_expired,
staff_api_client,
permission_manage_orders,
customer_user,
@@ -3575,6 +3540,10 @@ def test_draft_order_create_price_recalculation(
voucher,
):
# given
+ fake_order = Mock()
+ fake_order.total = zero_taxed_money(channel_PLN.currency_code)
+ response = Mock(return_value=(fake_order, None))
+ mock_fetch_order_prices_if_expired.side_effect = response
query = DRAFT_ORDER_CREATE_MUTATION
user_id = graphene.Node.to_global_id("User", customer_user.id)
discount = "10"
@@ -3617,17 +3586,8 @@ def test_draft_order_create_price_recalculation(
assert not content["data"]["draftOrderCreate"]["errors"]
assert Order.objects.count() == 1
order = Order.objects.first()
- line1, line2 = order.lines.all()
-
- assert line1.total_price == line1.unit_price * quantity_1
- assert line1.unit_price.gross == line1.unit_price.net * TAX_RATE_1
- assert line1.total_price.gross == line1.total_price.net * TAX_RATE_1
-
- assert line2.total_price == line2.unit_price * quantity_2
- assert line2.unit_price.gross == line2.unit_price.net * TAX_RATE_2
- assert line2.total_price.gross == line2.total_price.net * TAX_RATE_2
-
- assert order.total == line1.total_price + line2.total_price
+ lines = list(order.lines.all())
+ mock_fetch_order_prices_if_expired.assert_called_once_with(order, ANY, lines, False)
DRAFT_UPDATE_QUERY = """
diff --git a/saleor/order/base_calculations.py b/saleor/order/base_calculations.py
new file mode 100644
index 0000000000..4e985b68e4
--- /dev/null
+++ b/saleor/order/base_calculations.py
@@ -0,0 +1,67 @@
+from typing import TYPE_CHECKING, Iterable
+
+from prices import Money, TaxedMoney
+
+from ..core.taxes import zero_money
+from ..discount import OrderDiscountType
+from ..discount.utils import apply_discount_to_value
+from .interface import OrderTaxedPricesData
+
+if TYPE_CHECKING:
+ from .models import Order, OrderLine
+
+
+def base_order_shipping(order: "Order") -> Money:
+ if not order.shipping_method:
+ return zero_money(order.currency)
+ channel_listing = order.shipping_method.channel_listings.filter(
+ channel_id=order.channel_id
+ ).first()
+ if not channel_listing:
+ return zero_money(order.currency)
+ return channel_listing.price
+
+
+def base_order_total(order: "Order", lines: Iterable["OrderLine"]) -> Money:
+ currency = order.currency
+ total = base_order_total_without_order_discount(order, lines)
+ order_discount = order.discounts.filter(type=OrderDiscountType.MANUAL).first()
+ if order_discount:
+ total = apply_discount_to_value(
+ value=order_discount.value,
+ value_type=order_discount.value_type,
+ currency=currency,
+ price_to_discount=total,
+ )
+ return max(total, zero_money(currency))
+
+
+def base_order_total_without_order_discount(
+ order: "Order", lines: Iterable["OrderLine"]
+) -> Money:
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ quantity = line.quantity
+ price_with_discounts = line.base_unit_price * quantity
+ subtotal += price_with_discounts
+ base_shipping_price = base_order_shipping(order)
+ return subtotal + base_shipping_price
+
+
+def base_order_line_total(order_line: "OrderLine") -> OrderTaxedPricesData:
+ quantity = order_line.quantity
+ price_with_discounts = (
+ TaxedMoney(order_line.base_unit_price, order_line.base_unit_price) * quantity
+ )
+ undiscounted_price = (
+ TaxedMoney(
+ order_line.undiscounted_base_unit_price,
+ order_line.undiscounted_base_unit_price,
+ )
+ * quantity
+ )
+ return OrderTaxedPricesData(
+ undiscounted_price=undiscounted_price,
+ price_with_discounts=price_with_discounts,
+ )
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index c464ba63a9..1c43f09a7d 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -21,9 +21,7 @@ def _recalculate_order_prices(
Does not throw TaxError.
"""
- currency = order.currency
-
- subtotal = zero_taxed_money(currency)
+ undiscounted_subtotal = zero_taxed_money(order.currency)
for line in lines:
variant = line.variant
if variant:
@@ -40,6 +38,7 @@ def _recalculate_order_prices(
order, line, variant, product
)
line.undiscounted_total_price = line_total.undiscounted_price
+ undiscounted_subtotal += line_total.undiscounted_price
line.total_price = line_total.price_with_discounts
line.tax_rate = manager.get_order_line_tax_rate(
@@ -48,7 +47,6 @@ def _recalculate_order_prices(
except TaxError:
pass
- subtotal += line.total_price
try:
order.shipping_price = manager.calculate_order_shipping(order)
order.shipping_tax_rate = manager.get_order_shipping_tax_rate(
@@ -56,8 +54,8 @@ def _recalculate_order_prices(
)
except TaxError:
pass
-
- order.total = order.shipping_price + subtotal
+ order.undiscounted_total = undiscounted_subtotal + order.shipping_price
+ order.total = manager.calculate_order_total(order, lines)
def _apply_tax_data(
@@ -93,29 +91,6 @@ def _apply_tax_data(
order.total = shipping_price + subtotal
-def _recalculate_order_discounts(order: Order, lines: Iterable[OrderLine]) -> None:
- """Recalculate all order discounts and update order/lines prices."""
- undiscounted_subtotal = zero_taxed_money(order.currency)
- for line in lines:
- line.undiscounted_unit_price = line.unit_price + line.unit_discount
- undiscounted_total_price = (
- line.undiscounted_unit_price * line.quantity
- if line.unit_discount
- else line.total_price
- )
- line.undiscounted_total_price = undiscounted_total_price
- undiscounted_subtotal += undiscounted_total_price
-
- order.undiscounted_total = undiscounted_subtotal + order.shipping_price
-
- order_discounts = order.discounts.filter(type=OrderDiscountType.MANUAL)
- for order_discount in order_discounts:
- utils.update_order_discount_for_order(
- order,
- order_discount,
- )
-
-
def fetch_order_prices_if_expired(
order: Order,
manager: PluginsManager,
@@ -143,6 +118,14 @@ def fetch_order_prices_if_expired(
order.should_refresh_prices = False
+ order_discount = order.discounts.filter(type=OrderDiscountType.MANUAL).first()
+ if order_discount:
+ utils.update_order_discount_for_order(
+ order,
+ lines,
+ order_discount,
+ )
+
_recalculate_order_prices(manager, order, lines)
tax_data = manager.get_taxes_for_order(order)
@@ -151,8 +134,6 @@ def fetch_order_prices_if_expired(
if tax_data:
_apply_tax_data(order, lines, tax_data)
- _recalculate_order_discounts(order, lines)
-
order.save(
update_fields=[
"total_net_amount",
diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.py
index ee4584c27f..52c9e70b42 100644
--- a/saleor/order/tests/test_calculations.py
+++ b/saleor/order/tests/test_calculations.py
@@ -103,6 +103,7 @@ def test_recalculate_order_prices(order_with_lines, order_lines, tax_data):
get_order_shipping_tax_rate=Mock(return_value=shipping_tax_rate),
get_order_line_tax_rate=Mock(side_effect=tax_rates),
calculate_order_shipping=Mock(return_value=shipping),
+ calculate_order_total=Mock(return_value=total),
)
# when
@@ -216,6 +217,7 @@ def test_recalculate_order_prices_tax_error_line_prices(
get_order_shipping_tax_rate=Mock(return_value=shipping_tax_rate),
get_order_line_tax_rate=Mock(side_effect=tax_rates[1:]),
calculate_order_shipping=Mock(return_value=shipping),
+ calculate_order_total=Mock(return_value=total),
)
# when
@@ -287,6 +289,7 @@ def test_recalculate_order_prices_tax_error_shipping_price(
get_order_shipping_tax_rate=Mock(return_value=shipping_tax_rate),
get_order_line_tax_rate=Mock(side_effect=tax_rates),
calculate_order_shipping=Mock(side_effect=TaxError),
+ calculate_order_total=Mock(return_value=subtotal + order.shipping_price),
)
# when
@@ -437,6 +440,7 @@ def test_fetch_order_prices_if_expired_plugins(
plugins_manager.calculate_order_shipping = Mock(return_value=shipping)
plugins_manager.get_order_shipping_tax_rate = Mock(return_value=shipping_tax_rate)
plugins_manager.get_taxes_for_order = Mock(return_value=None)
+ plugins_manager.calculate_order_total = Mock(return_value=total)
# when
calculations.fetch_order_prices_if_expired(**fetch_kwargs)
@@ -513,17 +517,20 @@ def test_fetch_order_prices_if_expired_recalculate_all_prices(
assert order_with_lines.shipping_price == shipping_price
assert order_with_lines.shipping_tax_rate == tax_data.shipping_tax_rate / 100
subtotal = zero_taxed_money(currency)
+ undiscounted_subtotal = zero_taxed_money(currency)
for order_line, tax_line in zip(order_with_lines.lines.all(), tax_data.lines):
line_total = get_taxed_money(tax_line, "total", currency)
subtotal += line_total
+ undiscounted_subtotal += order_line.undiscounted_total_price
assert order_line.total_price == line_total
assert order_line.unit_price == line_total / order_line.quantity
assert order_line.tax_rate == tax_line.tax_rate / 100
- assert order_with_lines.undiscounted_total == subtotal + shipping_price
- assert order_with_lines.total == subtotal + shipping_price - create_taxed_money(
- discount_amount, discount_amount, order_with_lines.currency
+ assert (
+ order_with_lines.undiscounted_total
+ == undiscounted_subtotal + shipping_price.net
)
+ assert order_with_lines.total == subtotal + shipping_price
def test_fetch_order_prices_if_expired_prefetch(fetch_kwargs, order_lines):
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 139c2adfdc..5952d1b74a 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -1,20 +1,21 @@
from decimal import Decimal
-from functools import partial, wraps
-from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union, cast
+from functools import wraps
+from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, cast
import graphene
from django.conf import settings
from django.utils import timezone
-from prices import Money, TaxedMoney, fixed_discount, percentage_discount
+from prices import Money, TaxedMoney
from ..account.models import User
from ..core.prices import quantize_price
from ..core.taxes import zero_money
from ..core.tracing import traced_atomic_transaction
from ..core.weight import zero_weight
-from ..discount import DiscountValueType, OrderDiscountType
+from ..discount import OrderDiscountType
from ..discount.models import NotApplicable, OrderDiscount, Voucher, VoucherType
from ..discount.utils import (
+ apply_discount_to_value,
get_products_voucher_discount,
get_sale_id_applied_as_a_discount,
validate_voucher_in_order,
@@ -42,6 +43,7 @@ from . import (
OrderAuthorizeStatus,
OrderChargeStatus,
OrderStatus,
+ base_calculations,
events,
)
from .fetch import OrderLineInfo
@@ -727,40 +729,19 @@ def get_order_discounts(order: Order) -> List[OrderDiscount]:
return list(order.discounts.filter(type=OrderDiscountType.MANUAL))
-def apply_discount_to_value(
- value: Decimal,
- value_type: str,
- currency: str,
- price_to_discount: Union[Money, TaxedMoney],
-):
- """Calculate the price based on the provided values."""
- if value_type == DiscountValueType.FIXED:
- discount_method = fixed_discount
- discount_kwargs = {"discount": Money(value, currency)}
- else:
- discount_method = percentage_discount
- discount_kwargs = {"percentage": value}
- discount = partial(
- discount_method,
- **discount_kwargs,
- )
- return discount(price_to_discount)
-
-
def create_order_discount_for_order(
order: Order, reason: str, value_type: str, value: Decimal
):
"""Add new order discount and update the prices."""
- current_total = order.total
+ current_total = order.undiscounted_total
currency = order.currency
- net_total = apply_discount_to_value(value, value_type, currency, current_total.net)
gross_total = apply_discount_to_value(
value, value_type, currency, current_total.gross
)
- new_amount = (current_total - gross_total).gross
+ new_amount = quantize_price((current_total - gross_total).gross, currency)
order_discount = order.discounts.create(
value_type=value_type,
@@ -768,44 +749,40 @@ def create_order_discount_for_order(
reason=reason,
amount=new_amount, # type: ignore
)
- order.total = TaxedMoney(net_total, gross_total)
- order.save(update_fields=["total_net_amount", "total_gross_amount", "updated_at"])
return order_discount
def update_order_discount_for_order(
order: Order,
+ lines: Iterable[OrderLine],
order_discount_to_update: OrderDiscount,
reason: Optional[str] = None,
value_type: Optional[str] = None,
value: Optional[Decimal] = None,
):
- """Update the order_discount for an order and recalculate the order's prices."""
+ """Update the order_discount for an order."""
current_value = order_discount_to_update.value
value = value if value is not None else current_value
value_type = value_type or order_discount_to_update.value_type
- currency = order_discount_to_update.currency
fields_to_update = []
if reason is not None:
order_discount_to_update.reason = reason
fields_to_update.append("reason")
- current_total = order.total
-
- net_total = apply_discount_to_value(value, value_type, currency, current_total.net)
- gross_total = apply_discount_to_value(
- value, value_type, currency, current_total.gross
+ current_total = base_calculations.base_order_total_without_order_discount(
+ order, lines
)
- new_amount = (current_total - gross_total).gross
+ discounted_total = apply_discount_to_value(
+ value, value_type, order.currency, current_total
+ )
+ new_amount = quantize_price(current_total - discounted_total, order.currency)
order_discount_to_update.amount = new_amount
order_discount_to_update.value = value
order_discount_to_update.value_type = value_type
fields_to_update.extend(["value_type", "value", "amount_value"])
- order.total = TaxedMoney(net_total, gross_total)
-
order_discount_to_update.save(update_fields=fields_to_update)
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index 1ecd3b413c..f4c9546886 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -16,7 +16,8 @@ from requests.auth import HTTPBasicAuth
from ...checkout import base_calculations
from ...checkout.utils import is_shipping_required
from ...core.taxes import TaxError
-from ...discount import VoucherType
+from ...discount import OrderDiscountType, VoucherType
+from ...order import base_calculations as base_order_calculations
from ...order.utils import (
get_total_order_discount_excluding_shipping,
get_voucher_discount_assigned_to_order,
@@ -368,7 +369,7 @@ def get_order_lines_data(
product_type = line.variant.product.product_type
tax_code = retrieve_tax_code_from_meta(product, default=None)
tax_code = tax_code or retrieve_tax_code_from_meta(product_type)
- prices_data = base_calculations.base_order_line_total(line)
+ prices_data = base_order_calculations.base_order_line_total(line)
if tax_included:
undiscounted_amount = prices_data.undiscounted_price.gross.amount
@@ -412,8 +413,15 @@ def get_order_lines_data(
shipping_method_channel_listing.price.amount - shipping_discount_amount,
Decimal("0"),
)
+ shipping_discounted = order.discounts.filter(
+ type=OrderDiscountType.MANUAL
+ ).exists()
append_shipping_to_data(
- data, shipping_price, config.shipping_tax_code, tax_included
+ data,
+ shipping_price,
+ config.shipping_tax_code,
+ tax_included,
+ shipping_discounted,
)
return data
diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.py
index 0a7ea9194a..673ea688e9 100644
--- a/saleor/plugins/avatax/plugin.py
+++ b/saleor/plugins/avatax/plugin.py
@@ -16,6 +16,7 @@ from ...checkout import base_calculations
from ...checkout.fetch import fetch_checkout_lines
from ...core.taxes import TaxError, TaxType, charge_taxes_on_shipping, zero_taxed_money
from ...discount import DiscountInfo
+from ...order import base_calculations as base_order_calculations
from ...order.interface import OrderTaxedPricesData
from ...product.models import ProductType
from ..base_plugin import BasePlugin, ConfigurationTypeField
@@ -576,26 +577,15 @@ class AvataxPlugin(BasePlugin):
/ quantity,
)
- def calculate_order_shipping(
- self, order: "Order", previous_value: TaxedMoney
+ def _calculate_order_shipping(
+ self, order, taxes_data, previous_value
) -> TaxedMoney:
- if self._skip_plugin(previous_value):
- return previous_value
-
- if not charge_taxes_on_shipping():
- return previous_value
-
- if not _validate_order(order):
- return previous_value
- taxes_data = get_order_tax_data(
- order, self.config, self.config.tax_included, False
- )
-
currency = taxes_data.get("currencyCode")
for line in taxes_data.get("lines", []):
if line["itemCode"] == "Shipping":
tax = Decimal(line.get("tax", 0.0))
- net = Decimal(line.get("lineAmount", 0.0))
+ discount_amount = Decimal(line.get("discountAmount", 0.0))
+ net = Decimal(line.get("lineAmount", 0.0)) - discount_amount
if currency == "JPY" and self.config.tax_included:
gross = previous_value.gross
net = Money(amount=gross.amount - tax, currency=currency)
@@ -616,6 +606,72 @@ class AvataxPlugin(BasePlugin):
gross=price,
)
+ def calculate_order_shipping(
+ self, order: "Order", previous_value: TaxedMoney
+ ) -> TaxedMoney:
+ if self._skip_plugin(previous_value):
+ return previous_value
+
+ if not charge_taxes_on_shipping():
+ return previous_value
+
+ if not _validate_order(order):
+ return previous_value
+
+ taxes_data = get_order_tax_data(
+ order, self.config, self.config.tax_included, False
+ )
+
+ return self._calculate_order_shipping(order, taxes_data, previous_value)
+
+ def calculate_order_total(
+ self,
+ order: "Order",
+ lines: Iterable["OrderLine"],
+ previous_value: TaxedMoney,
+ ) -> TaxedMoney:
+ if self._skip_plugin(previous_value):
+ return previous_value
+ order_total = previous_value
+
+ if not _validate_order(order):
+ return order_total
+
+ taxes_data = get_order_tax_data(
+ order, self.config, self.config.tax_included, False
+ )
+
+ currency = order.currency
+ taxed_subtotal = zero_taxed_money(currency)
+
+ for line in lines:
+ base_line_price = OrderTaxedPricesData(
+ undiscounted_price=line.undiscounted_total_price,
+ price_with_discounts=TaxedMoney(
+ line.base_unit_price, line.base_unit_price
+ )
+ * line.quantity,
+ )
+ taxed_line_total_data = self._calculate_order_line_total_price(
+ taxes_data,
+ line.product_sku or line.variant_name,
+ self.config.tax_included,
+ base_line_price,
+ ).price_with_discounts
+ taxed_subtotal += taxed_line_total_data
+
+ base_shipping_price = base_order_calculations.base_order_shipping(order)
+ shipping_price = self._calculate_order_shipping(
+ order, taxes_data, base_shipping_price
+ )
+
+ taxed_total = taxed_subtotal + shipping_price
+
+ return max(
+ taxed_total,
+ zero_taxed_money(currency),
+ )
+
def get_tax_rate_type_choices(self, previous_value: Any) -> List[TaxType]:
if not self.active:
return previous_value
diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_order_total.yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_order_total.yaml
new file mode 100644
index 0000000000..c300d3597d
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_order_total.yaml
@@ -0,0 +1,72 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesInvoice",
+ "lines": [{"quantity": 3, "amount": "36.900", "taxCode": "O9999999", "taxIncluded":
+ true, "itemCode": "SKU_A", "discounted": false, "description": "Test product"},
+ {"quantity": 1, "amount": "10.000", "taxCode": "FR000000", "taxIncluded": true,
+ "itemCode": "Shipping", "discounted": false, "description": null}], "code":
+ "ef9ff645-e75b-4a77-9afd-67452e48a8f5", "date": "2022-08-26", "customerCode":
+ 0, "discount": null, "addresses": {"shipFrom": {"line1": "Teczowa 7", "line2":
+ null, "city": "Wroclaw", "region": "", "country": "PL", "postalCode": "53-601"},
+ "shipTo": {"line1": "T\u0119czowa 7", "line2": "", "city": "WROC\u0141AW", "region":
+ "", "country": "PL", "postalCode": "53-601"}}, "commit": false, "currencyCode":
+ "USD", "email": "[email protected]"}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '837'
+ User-Agent:
+ - python-requests/2.28.1
+ method: POST
+ uri: https://rest.avatax.com/api/v2/transactions/createoradjust
+ response:
+ body:
+ string: '{"id":85073099883332,"code":"ef9ff645-e75b-4a77-9afd-67452e48a8f5","companyId":242975,"date":"2022-08-26","status":"Saved","type":"SalesInvoice","batchCode":"","currencyCode":"USD","exchangeRateCurrencyCode":"USD","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","taxOverrideType":"None","taxOverrideAmount":0.0,"taxOverrideReason":"","totalAmount":38.13,"totalExempt":0.0,"totalDiscount":0.0,"totalTax":8.77,"totalTaxable":38.13,"totalTaxCalculated":8.77,"adjustmentReason":"NotAdjusted","adjustmentDescription":"","locked":false,"region":"","country":"PL","version":1,"softwareVersion":"22.7.2.0","originAddressId":85073099883334,"destinationAddressId":85073099883333,"exchangeRateEffectiveDate":"2022-08-26","exchangeRate":1.0,"description":"","email":"[email protected]","businessIdentificationNo":"","modifiedDate":"2022-08-26T09:09:52.3008941Z","modifiedUserId":283192,"taxDate":"2022-08-26","lines":[{"id":85073099883338,"transactionId":85073099883332,"lineNumber":"1","boundaryOverrideId":0,"customerUsageType":"","entityUseCode":"","description":"Test
+ product","destinationAddressId":85073099883333,"originAddressId":85073099883334,"discountAmount":0.0,"discountTypeId":0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"isSSTP":false,"itemCode":"SKU_A","lineAmount":30.0000,"quantity":3.0,"ref1":"","ref2":"","reportingDate":"2022-08-26","revAccount":"","sourcing":"Destination","tax":6.9,"taxableAmount":30.0,"taxCalculated":6.9,"taxCode":"O9999999","taxCodeId":5340,"taxDate":"2022-08-26","taxEngine":"","taxOverrideType":"None","businessIdentificationNo":"","taxOverrideAmount":0.0,"taxOverrideReason":"","taxIncluded":true,"details":[{"id":85073099883343,"transactionLineId":85073099883338,"transactionId":85073099883332,"addressId":85073099883333,"country":"PL","region":"PL","countyFIPS":"","stateFIPS":"","exemptAmount":0.0000,"exemptReasonId":4,"inState":true,"jurisCode":"PL","jurisName":"POLAND","jurisdictionId":200102,"signatureCode":"","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0000,"nonTaxableRuleId":0,"nonTaxableType":"RateRule","rate":0.230000,"rateRuleId":410972,"rateSourceId":0,"serCode":"","sourcing":"Destination","tax":6.9000,"taxableAmount":30.0000,"taxType":"Output","taxSubTypeId":"O","taxTypeGroupId":"InputAndOutput","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxRegionId":205102,"taxCalculated":6.9000,"taxOverride":0.0000,"rateType":"Standard","rateTypeCode":"S","taxableUnits":30.0000,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":30.0,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":6.9,"reportingTaxCalculated":6.9,"liabilityType":"Seller"}],"nonPassthroughDetails":[],"lineLocationTypes":[{"documentLineLocationTypeId":85073099883341,"documentLineId":85073099883338,"documentAddressId":85073099883334,"locationTypeCode":"ShipFrom"},{"documentLineLocationTypeId":85073099883342,"documentLineId":85073099883338,"documentAddressId":85073099883333,"locationTypeCode":"ShipTo"}],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230C","vatNumberTypeId":0},{"id":85073099883339,"transactionId":85073099883332,"lineNumber":"2","boundaryOverrideId":0,"customerUsageType":"","entityUseCode":"","description":"","destinationAddressId":85073099883333,"originAddressId":85073099883334,"discountAmount":0.0,"discountTypeId":0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"isSSTP":false,"itemCode":"Shipping","lineAmount":8.1300,"quantity":1.0,"ref1":"","ref2":"","reportingDate":"2022-08-26","revAccount":"","sourcing":"Destination","tax":1.87,"taxableAmount":8.13,"taxCalculated":1.87,"taxCode":"FR000000","taxCodeId":4779,"taxDate":"2022-08-26","taxEngine":"","taxOverrideType":"None","businessIdentificationNo":"","taxOverrideAmount":0.0,"taxOverrideReason":"","taxIncluded":true,"details":[{"id":85073099883347,"transactionLineId":85073099883339,"transactionId":85073099883332,"addressId":85073099883333,"country":"PL","region":"PL","countyFIPS":"","stateFIPS":"","exemptAmount":0.0000,"exemptReasonId":4,"inState":true,"jurisCode":"PL","jurisName":"POLAND","jurisdictionId":200102,"signatureCode":"","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0000,"nonTaxableRuleId":0,"nonTaxableType":"RateRule","rate":0.230000,"rateRuleId":410972,"rateSourceId":0,"serCode":"","sourcing":"Destination","tax":1.8700,"taxableAmount":8.1300,"taxType":"Output","taxSubTypeId":"O","taxTypeGroupId":"InputAndOutput","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxRegionId":205102,"taxCalculated":1.8700,"taxOverride":0.0000,"rateType":"Standard","rateTypeCode":"S","taxableUnits":8.1300,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":8.13,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":1.87,"reportingTaxCalculated":1.87,"liabilityType":"Seller"}],"nonPassthroughDetails":[],"lineLocationTypes":[{"documentLineLocationTypeId":85073099883345,"documentLineId":85073099883339,"documentAddressId":85073099883334,"locationTypeCode":"ShipFrom"},{"documentLineLocationTypeId":85073099883346,"documentLineId":85073099883339,"documentAddressId":85073099883333,"locationTypeCode":"ShipTo"}],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230D","vatNumberTypeId":0}],"addresses":[{"id":85073099883333,"transactionId":85073099883332,"boundaryLevel":"Zip5","line1":"Teczowa
+ 7","line2":"","line3":"","city":"WROCLAW","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102},{"id":85073099883334,"transactionId":85073099883332,"boundaryLevel":"Zip5","line1":"Teczowa
+ 7","line2":"","line3":"","city":"Wroclaw","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102}],"locationTypes":[{"documentLocationTypeId":85073099883336,"documentId":85073099883332,"documentAddressId":85073099883334,"locationTypeCode":"ShipFrom"},{"documentLocationTypeId":85073099883337,"documentId":85073099883332,"documentAddressId":85073099883333,"locationTypeCode":"ShipTo"}],"summary":[{"country":"PL","region":"PL","jurisType":"Country","jurisCode":"PL","jurisName":"POLAND","taxAuthorityType":45,"stateAssignedNo":"","taxType":"Output","taxSubType":"O","taxName":"Standard
+ Rate","rateType":"Standard","taxable":38.13,"rate":0.230000,"tax":8.77,"taxCalculated":8.77,"nonTaxable":0.00,"exemption":0.00}]}'
+ headers:
+ Connection:
+ - keep-alive
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Fri, 26 Aug 2022 09:09:52 GMT
+ Location:
+ - /api/v2/companies/242975/transactions/85073099883332
+ ServerDuration:
+ - '00:00:00.1137149'
+ Transfer-Encoding:
+ - chunked
+ X-Content-Type-Options:
+ - nosniff
+ cache-control:
+ - private, no-cache, no-store
+ referrer-policy:
+ - same-origin
+ strict-transport-security:
+ - max-age=31536000; includeSubdomains
+ x-avalara-uid:
+ - 8862b67b-c9f8-4add-9665-53a3e1ba11eb
+ x-correlation-id:
+ - 8862b67b-c9f8-4add-9665-53a3e1ba11eb
+ x-frame-options:
+ - sameorigin
+ x-permitted-cross-domain-policies:
+ - none
+ x-xss-protection:
+ - 1; mode=block
+ status:
+ code: 201
+ message: Created
+version: 1
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index a938807a83..31b458a65a 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -1701,6 +1701,28 @@ def test_calculate_order_shipping(
assert price == TaxedMoney(net=Money("8.13", "USD"), gross=Money("10.00", "USD"))
+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+def test_calculate_order_total(
+ order_line, shipping_zone, site_settings, address, plugin_configuration
+):
+ plugin_configuration()
+ manager = get_plugins_manager()
+ order = order_line.order
+ method = shipping_zone.shipping_methods.get()
+ order.shipping_address = order.billing_address.get_copy()
+ order.shipping_method_name = method.name
+ order.shipping_method = method
+ order.save()
+
+ site_settings.company_address = address
+ site_settings.save()
+
+ price = manager.calculate_order_total(order, order.lines.all())
+ price = quantize_price(price, price.currency)
+ assert price == TaxedMoney(net=Money("38.13", "USD"), gross=Money("46.90", "USD"))
+
+
@pytest.mark.vcr
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
def test_calculate_order_shipping_entire_order_voucher(
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 82eca299a6..27b2c2e079 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -334,6 +334,14 @@ class BasePlugin:
# changes in draft order. Return TaxedMoney.
calculate_order_shipping: Callable[["Order", TaxedMoney], TaxedMoney]
+ # Calculate order total.
+ #
+ # Overwrite this method if you need to apply specific logic for the calculation
+ # of a order total. Return TaxedMoney.
+ calculate_order_total: Callable[
+ ["Order", List["OrderLine"], TaxedMoney], TaxedMoney
+ ]
+
capture_payment: Callable[["PaymentData", Any], GatewayResponse]
# Trigger when category is created.
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 604e344824..95ece16318 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -31,6 +31,7 @@ from ..core.payments import PaymentInterface
from ..core.prices import quantize_price
from ..core.taxes import TaxData, TaxType, zero_money, zero_taxed_money
from ..discount import DiscountInfo
+from ..order import base_calculations as base_order_calculations
from ..order.interface import OrderTaxedPricesData
from .base_plugin import ExcludedShippingMethod, ExternalAccessTokens
from .models import PluginConfiguration
@@ -292,15 +293,32 @@ class PluginsManager(PaymentInterface):
checkout_info.checkout.currency,
)
+ def calculate_order_total(
+ self,
+ order: "Order",
+ lines: Iterable["OrderLine"],
+ ) -> TaxedMoney:
+ currency = order.currency
+ default_value = base_order_calculations.base_order_total(order, lines)
+ default_value = TaxedMoney(default_value, default_value)
+ if default_value <= zero_taxed_money(currency):
+ return quantize_price(
+ default_value,
+ currency,
+ )
+
+ return quantize_price(
+ self.__run_method_on_plugins(
+ "calculate_order_total",
+ default_value,
+ order,
+ lines,
+ ),
+ currency,
+ )
+
def calculate_order_shipping(self, order: "Order") -> TaxedMoney:
- if not order.shipping_method:
- return zero_taxed_money(order.currency)
- channel_listing = order.shipping_method.channel_listings.filter(
- channel_id=order.channel_id
- ).first()
- if not channel_listing:
- return zero_taxed_money(order.currency)
- shipping_price = channel_listing.price
+ shipping_price = base_order_calculations.base_order_shipping(order)
default_value = quantize_price(
TaxedMoney(net=shipping_price, gross=shipping_price),
shipping_price.currency,
@@ -390,7 +408,7 @@ class PluginsManager(PaymentInterface):
variant: "ProductVariant",
product: "Product",
) -> OrderTaxedPricesData:
- default_value = base_calculations.base_order_line_total(order_line)
+ default_value = base_order_calculations.base_order_line_total(order_line)
line_total = self.__run_method_on_plugins(
"calculate_order_line_total",
default_value,