Skip to content

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

Refactor order price calculation. (#14846)

Piotr Zabieglik6c0186e7c73a
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
index a0c2b9c180..f961ffc2f5 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
@@ -147,11 +147,11 @@ def test_checkout_complete_with_inactive_channel(
@pytest.mark.integration
-@patch("saleor.order.calculations._recalculate_order_prices")
+@patch("saleor.order.calculations._recalculate_with_plugins")
@patch("saleor.plugins.manager.PluginsManager.order_confirmed")
def test_checkout_complete(
order_confirmed_mock,
- _recalculate_order_prices_mock,
+ recalculate_with_plugins_mock,
user_api_client,
checkout_with_gift_card,
gift_card,
@@ -256,7 +256,7 @@ def test_checkout_complete(
pk=checkout.pk
).exists(), "Checkout should have been deleted"
order_confirmed_mock.assert_called_once_with(order)
- _recalculate_order_prices_mock.assert_not_called()
+ recalculate_with_plugins_mock.assert_not_called()
assert not len(Reservation.objects.all())
@@ -775,11 +775,11 @@ def test_checkout_complete_with_variant_without_price(
assert errors[0]["variants"] == [variant_id]
-@patch("saleor.order.calculations._recalculate_order_prices")
+@patch("saleor.order.calculations._recalculate_with_plugins")
@patch("saleor.plugins.manager.PluginsManager.order_confirmed")
def test_checkout_complete_requires_confirmation(
order_confirmed_mock,
- _recalculate_order_prices_mock,
+ recalculate_with_plugins_mock,
user_api_client,
site_settings,
payment_dummy,
@@ -806,7 +806,7 @@ def test_checkout_complete_requires_confirmation(
order = Order.objects.get(pk=order_id)
assert order.is_unconfirmed()
order_confirmed_mock.assert_not_called()
- _recalculate_order_prices_mock.assert_not_called()
+ recalculate_with_plugins_mock.assert_not_called()
@pytest.mark.integration
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
index 58da05489a..85442da38f 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
@@ -1055,11 +1055,11 @@ def test_checkout_complete_with_inactive_channel(
@pytest.mark.integration
-@patch("saleor.order.calculations._recalculate_order_prices")
+@patch("saleor.order.calculations._recalculate_with_plugins")
@patch("saleor.plugins.manager.PluginsManager.order_confirmed")
def test_checkout_complete(
order_confirmed_mock,
- _recalculate_order_prices_mock,
+ recalculate_with_plugins_mock,
user_api_client,
checkout_with_gift_card,
gift_card,
@@ -1163,7 +1163,7 @@ def test_checkout_complete(
pk=checkout.pk
).exists(), "Checkout should have been deleted"
order_confirmed_mock.assert_called_once_with(order)
- _recalculate_order_prices_mock.assert_not_called()
+ recalculate_with_plugins_mock.assert_not_called()
assert not len(Reservation.objects.all())
diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
index 277f4806d5..471da32c67 100644
--- a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
@@ -100,11 +100,11 @@ def test_order_from_checkout_with_inactive_channel(
@pytest.mark.integration
-@patch("saleor.order.calculations._recalculate_order_prices")
+@patch("saleor.order.calculations._recalculate_with_plugins")
@patch("saleor.plugins.manager.PluginsManager.order_confirmed")
def test_order_from_checkout(
order_confirmed_mock,
- _recalculate_order_prices_mock,
+ recalculate_with_plugins_mock,
app_api_client,
permission_handle_checkouts,
site_settings,
@@ -205,7 +205,7 @@ def test_order_from_checkout(
)
order_confirmed_mock.assert_called_once_with(order)
- _recalculate_order_prices_mock.assert_not_called()
+ recalculate_with_plugins_mock.assert_not_called()
def test_order_from_checkout_with_transaction(
@@ -677,11 +677,11 @@ def test_order_from_checkout_with_variant_without_price(
assert errors[0]["variants"] == [variant_id]
-@patch("saleor.order.calculations._recalculate_order_prices")
+@patch("saleor.order.calculations._recalculate_with_plugins")
@patch("saleor.plugins.manager.PluginsManager.order_confirmed")
def test_order_from_checkout_requires_confirmation(
order_confirmed_mock,
- _recalculate_order_prices_mock,
+ recalculate_with_plugins_mock,
app_api_client,
permission_handle_checkouts,
site_settings,
@@ -707,7 +707,7 @@ def test_order_from_checkout_requires_confirmation(
order = Order.objects.get(pk=order_id)
assert order.is_unconfirmed()
order_confirmed_mock.assert_not_called()
- _recalculate_order_prices_mock.assert_not_called()
+ recalculate_with_plugins_mock.assert_not_called()
@pytest.mark.integration
diff --git a/saleor/graphql/order/mutations/order_line_discount_update.py b/saleor/graphql/order/mutations/order_line_discount_update.py
index c9173f1035..7c0897cfe1 100644
--- a/saleor/graphql/order/mutations/order_line_discount_update.py
+++ b/saleor/graphql/order/mutations/order_line_discount_update.py
@@ -62,6 +62,8 @@ class OrderLineDiscountUpdate(OrderDiscountCommon):
order_line_before_update = copy.deepcopy(order_line)
app = get_app_promise(info.context).get()
with traced_atomic_transaction():
+ # TODO: Apply fixed order line discount to its total instead of unit price.
+ # https://github.com/saleor/saleor/issues/14879
update_discount_for_order_line(
order_line,
order=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 d8e6e2ced4..86986098b0 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
@@ -183,6 +183,7 @@ def test_draft_order_complete_with_voucher(
order.save(update_fields=["voucher", "voucher_code", "should_refresh_prices"])
voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ discount_value = voucher_listing.discount_value
order_total = order.total_net_amount
order_id = graphene.Node.to_global_id("Order", order.id)
@@ -200,15 +201,22 @@ def test_draft_order_complete_with_voucher(
assert data["voucherCode"] == code_instance.code
assert data["voucher"]["code"] == voucher.code
assert data["undiscountedTotal"]["net"]["amount"] == order_total
- assert (
- data["total"]["net"]["amount"] == order_total - voucher_listing.discount_value
- )
+ assert data["total"]["net"]["amount"] == order_total - discount_value
assert order.search_vector
- for line in order.lines.all():
+ lines = order.lines.all()
+ for line in lines:
allocation = line.allocations.get()
assert allocation.quantity_allocated == line.quantity_unfulfilled
+ # TODO: ensure entire order discount is propagated to order lines:
+ # https://github.com/saleor/saleor/issues/14880
+ # lines_undiscounted_total = sum(
+ # line.undiscounted_total_price_net_amount for line in lines
+ # )
+ # lines_total = sum(line.total_price_net_amount for line in lines)
+ # assert lines_undiscounted_total == lines_total + discount_value
+
# ensure there are only 2 events with correct types
event_params = {
"user": staff_user,
diff --git a/saleor/graphql/order/tests/mutations/test_order_discount.py b/saleor/graphql/order/tests/mutations/test_order_discount.py
index 889bfc585e..e35056b270 100644
--- a/saleor/graphql/order/tests/mutations/test_order_discount.py
+++ b/saleor/graphql/order/tests/mutations/test_order_discount.py
@@ -50,34 +50,41 @@ mutation OrderDiscountAdd($orderId: ID!, $input: OrderDiscountCommonInput!){
def test_add_order_discount_incorrect_values(
value, value_type, draft_order, staff_api_client, permission_group_manage_orders
):
+ # given
variables = {
"orderId": graphene.Node.to_global_id("Order", draft_order.pk),
"input": {"valueType": value_type, "value": value},
}
permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
response = staff_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["orderDiscountAdd"]
-
errors = data["errors"]
-
error = data["errors"][0]
assert error["field"] == "value"
assert error["code"] == OrderErrorCode.INVALID.name
-
assert len(errors) == 1
def test_add_fixed_order_discount_order_is_not_draft(
order_with_lines, staff_api_client, permission_group_manage_orders
):
+ # given
value = Decimal("10")
variables = {
"orderId": graphene.Node.to_global_id("Order", order_with_lines.pk),
"input": {"valueType": DiscountValueTypeEnum.FIXED.name, "value": value},
}
permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
response = staff_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["orderDiscountAdd"]
@@ -92,6 +99,7 @@ def test_add_fixed_order_discount_order_is_not_draft(
def test_add_fixed_order_discount_to_order(
status, draft_order, staff_api_client, permission_group_manage_orders
):
+ # given
order = draft_order
order.status = status
order.save(update_fields=["status"])
@@ -102,13 +110,16 @@ def test_add_fixed_order_discount_to_order(
"input": {"valueType": DiscountValueTypeEnum.FIXED.name, "value": value},
}
permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
response = staff_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)
content = get_graphql_content(response)
+
+ # then
data = content["data"]["orderDiscountAdd"]
order.refresh_from_db()
expected_net = total_before_order_discount.net.amount - value
-
errors = data["errors"]
assert len(errors) == 0
@@ -484,7 +495,7 @@ def test_update_order_discount_incorrect_values(
assert error["code"] == OrderErrorCode.INVALID.name
-def test_update_order_discount__by_user_no_channel_access(
+def test_update_order_discount_by_user_no_channel_access(
draft_order_with_fixed_discount_order,
staff_api_client,
permission_group_all_perms_channel_USD_only,
diff --git a/saleor/order/base_calculations.py b/saleor/order/base_calculations.py
index 321f43bcc0..2425110aa4 100644
--- a/saleor/order/base_calculations.py
+++ b/saleor/order/base_calculations.py
@@ -3,10 +3,12 @@ from typing import TYPE_CHECKING
from prices import Money, TaxedMoney
+from ..core.prices import quantize_price
from ..core.taxes import zero_money
-from ..discount import DiscountType, DiscountValueType
+from ..discount import DiscountType, DiscountValueType, VoucherType
from ..discount.models import OrderDiscount
from ..discount.utils import apply_discount_to_value
+from ..shipping.models import ShippingMethodChannelListing
from .interface import OrderTaxedPricesData
if TYPE_CHECKING:
@@ -19,95 +21,245 @@ def base_order_shipping(order: "Order") -> Money:
def base_order_subtotal(order: "Order", lines: Iterable["OrderLine"]) -> Money:
+ """Return order subtotal.
+
+ May include order line level discounts, like promotions, specific product vouchers
+ and manual line discounts.
+ Does not include order level discounts, like entire order vouchers and manual
+ order discounts.
+ """
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
- return subtotal
+ base_line_total = line.base_unit_price * quantity
+ subtotal += base_line_total
+ return quantize_price(subtotal, currency)
def base_order_total(order: "Order", lines: Iterable["OrderLine"]) -> Money:
"""Return order total, recalculate, and update order discounts.
- This function returns the order total. All discounts are included in this price.
- Shipping vouchers are included in the shipping price.
+ All discounts are included in this price.
+ """
+ subtotal, shipping_price = apply_order_discounts(order, lines, assign_prices=False)
+ return subtotal + shipping_price
+
+
+def base_order_line_total(order_line: "OrderLine") -> OrderTaxedPricesData:
+ """Return order line base total.
+
+ May include order line level discounts, like promotions, specific product vouchers
+ and manual line discounts.
+ Does not include order level discounts, like entire order vouchers and manual
+ order discounts.
+ """
+ quantity = order_line.quantity
+ price_with_line_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_line_discounts,
+ )
+
+
+def apply_order_discounts(
+ order: "Order",
+ lines: Iterable["OrderLine"],
+ assign_prices=True,
+) -> tuple[Money, Money]:
+ """Calculate prices after applying order level discounts.
+
+ Handles manual discounts and ENTIRE_ORDER vouchers.
+ Shipping vouchers are included in the base shipping price.
Specific product vouchers are included in line base prices.
Entire order vouchers are recalculated and updated in this function
(OrderDiscounts with type `order_discount.type == DiscountType.VOUCHER`).
Staff order discounts are recalculated and updated in this function
(OrderDiscounts with type `order_discount.type == DiscountType.MANUAL`).
"""
+ base_subtotal = base_order_subtotal(order, lines)
+ base_shipping_price = order.base_shipping_price
+ subtotal = base_subtotal
+ shipping_price = base_shipping_price
currency = order.currency
- subtotal = base_order_subtotal(order, lines)
- shipping_price = order.base_shipping_price
- order_discounts = order.discounts.all()
order_discounts_to_update = []
- for order_discount in order_discounts:
+ for order_discount in order.discounts.all():
subtotal_before_discount = subtotal
shipping_price_before_discount = shipping_price
if order_discount.type == DiscountType.VOUCHER:
- subtotal = apply_discount_to_value(
- value=order_discount.value,
- value_type=order_discount.value_type,
- currency=currency,
- price_to_discount=subtotal,
- )
- elif order_discount.value_type == DiscountValueType.PERCENTAGE:
- subtotal = apply_discount_to_value(
- value=order_discount.value,
- value_type=order_discount.value_type,
- currency=currency,
- price_to_discount=subtotal,
- )
- shipping_price = apply_discount_to_value(
- value=order_discount.value,
- value_type=order_discount.value_type,
- currency=currency,
- price_to_discount=shipping_price,
- )
- else:
- temporary_undiscounted_total = subtotal + shipping_price
- if temporary_undiscounted_total.amount > 0:
- temporary_total = apply_discount_to_value(
+ voucher = order_discount.voucher
+ if voucher and voucher.type == VoucherType.ENTIRE_ORDER:
+ subtotal = apply_discount_to_value(
+ value=order_discount.value,
+ value_type=order_discount.value_type,
+ currency=currency,
+ price_to_discount=subtotal,
+ )
+ elif order_discount.type == DiscountType.MANUAL:
+ if order_discount.value_type == DiscountValueType.PERCENTAGE:
+ subtotal = apply_discount_to_value(
+ value=order_discount.value,
+ value_type=order_discount.value_type,
+ currency=currency,
+ price_to_discount=subtotal,
+ )
+ shipping_price = apply_discount_to_value(
value=order_discount.value,
value_type=order_discount.value_type,
currency=currency,
- price_to_discount=temporary_undiscounted_total,
+ price_to_discount=shipping_price,
)
- total_discount = temporary_undiscounted_total - temporary_total
- subtotal_discount = (
- subtotal / temporary_undiscounted_total
- ) * total_discount
- shipping_discount = total_discount - subtotal_discount
-
- subtotal -= subtotal_discount
- shipping_price -= shipping_discount
+ else:
+ temporary_undiscounted_total = subtotal + shipping_price
+ if temporary_undiscounted_total.amount > 0:
+ temporary_total = apply_discount_to_value(
+ value=order_discount.value,
+ value_type=order_discount.value_type,
+ currency=currency,
+ price_to_discount=temporary_undiscounted_total,
+ )
+ total_discount = temporary_undiscounted_total - temporary_total
+ subtotal_discount = (
+ subtotal / temporary_undiscounted_total
+ ) * total_discount
+ shipping_discount = total_discount - subtotal_discount
+
+ subtotal -= subtotal_discount
+ shipping_price -= shipping_discount
shipping_discount_amount = shipping_price_before_discount - shipping_price
subtotal_discount_amount = subtotal_before_discount - subtotal
total_discount_amount = shipping_discount_amount + subtotal_discount_amount
if order_discount.amount != total_discount_amount:
order_discount.amount = total_discount_amount
order_discounts_to_update.append(order_discount)
+
if order_discounts_to_update:
OrderDiscount.objects.bulk_update(order_discounts_to_update, ["amount_value"])
- return max(subtotal + shipping_price, 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,
+ if assign_prices:
+ assign_order_prices(
+ order,
+ lines,
+ subtotal,
+ shipping_price,
)
- * quantity
- )
- return OrderTaxedPricesData(
- undiscounted_price=undiscounted_price,
- price_with_discounts=price_with_discounts,
+ subtotal_discount = base_subtotal - subtotal
+ apply_subtotal_discount_to_order_lines(lines, base_subtotal, subtotal_discount)
+
+ return subtotal, shipping_price
+
+
+def apply_subtotal_discount_to_order_lines(
+ lines: Iterable["OrderLine"],
+ base_subtotal: Money,
+ subtotal_discount: Money,
+):
+ """Calculate order lines prices after applying discounts to entire subtotal."""
+ # Handle order with single line - propagate the whole discount to the single line.
+ lines = list(lines)
+ lines_count = len(lines)
+ if lines_count == 1:
+ line = lines[0]
+ apply_subtotal_discount_to_order_line(line, subtotal_discount)
+
+ # Handle order with multiple lines - propagate the order discount proportionally
+ # to the lines.
+ elif lines_count > 1:
+ remaining_discount = subtotal_discount
+ for idx, line in enumerate(lines):
+ if idx < lines_count - 1:
+ share = (
+ line.base_unit_price_amount * line.quantity / base_subtotal.amount
+ )
+ discount = min(share * remaining_discount, base_subtotal)
+ apply_subtotal_discount_to_order_line(line, discount)
+ remaining_discount -= discount
+ else:
+ apply_subtotal_discount_to_order_line(line, remaining_discount)
+
+
+def apply_subtotal_discount_to_order_line(line: "OrderLine", discount: Money):
+ """Calculate order line prices after applying order level discount."""
+ currency = discount.currency
+ # This price includes line level discounts, but not entire order ones.
+ base_line_total = base_order_line_total(line).price_with_discounts.net
+ total_price = max(base_line_total - discount, zero_money(currency))
+ assign_order_line_prices(line, total_price)
+
+
+def assign_order_line_prices(line: "OrderLine", total_price: Money):
+ currency = total_price.currency
+ line.total_price_net = quantize_price(total_price, currency)
+ line.total_price_gross = line.total_price_net
+ line.undiscounted_total_price_gross_amount = (
+ line.undiscounted_total_price_net_amount
)
+
+ quantity = line.quantity
+ if quantity > 0:
+ unit_price = total_price / quantity
+ line.unit_price_net = unit_price
+ line.unit_price_gross = unit_price
+
+ undiscounted_unit_price = line.undiscounted_total_price_net_amount / quantity
+ line.undiscounted_unit_price_net_amount = undiscounted_unit_price
+ line.undiscounted_unit_price_gross_amount = undiscounted_unit_price
+
+
+def assign_order_prices(
+ order: "Order",
+ lines: Iterable["OrderLine"],
+ subtotal: Money,
+ shipping_price: Money,
+):
+ order.shipping_price_net_amount = shipping_price.amount
+ order.shipping_price_gross_amount = shipping_price.amount
+ order.total_net_amount = subtotal.amount + shipping_price.amount
+ order.total_gross_amount = subtotal.amount + shipping_price.amount
+
+ undiscounted_total = undiscounted_order_total(order, lines)
+ order.undiscounted_total_net_amount = undiscounted_total.amount
+ order.undiscounted_total_gross_amount = undiscounted_total.amount
+
+
+def update_order_discount_amounts(order, lines):
+ """Update order level discount amount."""
+ apply_order_discounts(order, lines, assign_prices=False)
+
+
+def undiscounted_order_shipping(order: "Order") -> Money:
+ """Return shipping price without any discounts."""
+ # TODO: add undiscounted_shipping_price field to order model.
+ # https://github.com/saleor/saleor/issues/14915
+ if shipping_method := order.shipping_method:
+ if listing := ShippingMethodChannelListing.objects.filter(
+ channel=order.channel, shipping_method=shipping_method
+ ).first():
+ return Money(listing.price_amount, order.currency)
+ return zero_money(order.currency)
+
+
+def undiscounted_order_subtotal(order: "Order", lines: Iterable["OrderLine"]) -> Money:
+ """Return order subtotal without any discounts."""
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_line_total = line.undiscounted_unit_price.net * line.quantity
+ subtotal += undiscounted_line_total
+ return quantize_price(subtotal, currency)
+
+
+def undiscounted_order_total(order: "Order", lines: Iterable["OrderLine"]) -> Money:
+ """Return order total without any discounts."""
+ subtotal = undiscounted_order_subtotal(order, lines)
+ shipping_price = undiscounted_order_shipping(order)
+ return quantize_price(subtotal + shipping_price, order.currency)
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index 4b34b2e381..f519a53b05 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -9,214 +9,27 @@ from prices import Money, TaxedMoney
from ..core.prices import quantize_price
from ..core.taxes import TaxData, TaxError, zero_taxed_money
from ..discount import DiscountType
-from ..order import base_calculations
from ..payment.model_helpers import get_subtotal
from ..plugins.manager import PluginsManager
from ..tax import TaxCalculationStrategy
from ..tax.calculations import get_taxed_undiscounted_price
from ..tax.calculations.order import update_order_prices_with_flat_rates
from ..tax.utils import (
- calculate_tax_rate,
get_charge_taxes_for_order,
get_tax_calculation_strategy_for_order,
normalize_tax_rate_for_db,
)
from . import ORDER_EDITABLE_STATUS
from .base_calculations import (
+ apply_order_discounts,
base_order_line_total,
- base_order_subtotal,
- base_order_total,
+ undiscounted_order_total,
+ update_order_discount_amounts,
)
from .interface import OrderTaxedPricesData
from .models import Order, OrderLine
-def _recalculate_order_prices(
- manager: PluginsManager,
- order: Order,
- lines: Iterable[OrderLine],
- prices_entered_with_tax: bool,
-) -> None:
- """Fetch taxes from plugins and recalculate order/lines prices.
-
- Does not throw TaxError.
- """
- undiscounted_subtotal = zero_taxed_money(order.currency)
-
- _update_order_discounts_and_base_undiscounted_total(order, lines)
-
- for line in lines:
- variant = line.variant
- if variant:
- product = variant.product
-
- try:
- line_unit = manager.calculate_order_line_unit(
- order, line, variant, product
- )
- line.unit_price = line_unit.price_with_discounts
-
- line_total = manager.calculate_order_line_total(
- order, line, variant, product
- )
- 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
- )
- line.undiscounted_unit_price = get_undiscounted_price(
- line_unit,
- line.undiscounted_base_unit_price,
- line.tax_rate,
- prices_entered_with_tax,
- )
-
- line.undiscounted_total_price = get_undiscounted_price(
- line_total,
- # base_order_line_total returns equal gross and net
- base_order_line_total(line).undiscounted_price.net,
- line.tax_rate,
- prices_entered_with_tax,
- )
- except TaxError:
- pass
-
- try:
- order.shipping_price = manager.calculate_order_shipping(order)
- order.shipping_tax_rate = manager.get_order_shipping_tax_rate(
- order, order.shipping_price
- )
- except TaxError:
- pass
- order.undiscounted_total = undiscounted_subtotal + TaxedMoney(
- net=order.base_shipping_price, gross=order.base_shipping_price
- )
- order.total = manager.calculate_order_total(order, lines)
-
-
-def get_undiscounted_price(
- line_price: OrderTaxedPricesData,
- line_base_price: Money,
- tax_rate,
- prices_entered_with_tax,
-):
- if (
- tax_rate > 0
- and line_price.undiscounted_price.net == line_price.undiscounted_price.gross
- ):
- get_taxed_undiscounted_price(
- line_base_price,
- line_price.undiscounted_price,
- tax_rate,
- prices_entered_with_tax,
- )
- return line_price.undiscounted_price
-
-
-def _update_order_discounts_and_base_undiscounted_total(
- order: Order, lines: Iterable[OrderLine]
-):
- """Update order discounts and order undiscounted_total price.
-
- Entire order vouchers and staff order discounts are recalculated and updated.
- """
- base_order_total(order, lines)
- subtotal = base_order_subtotal(order, lines)
- undiscounted_total = subtotal + order.base_shipping_price
- order.undiscounted_total = TaxedMoney(
- net=undiscounted_total, gross=undiscounted_total
- )
-
-
-def _get_order_base_prices(order, lines):
- currency = order.currency
- undiscounted_subtotal = zero_taxed_money(currency)
-
- # Calculate order lines prices.
- for line in lines:
- variant = line.variant
- if not variant:
- continue
-
- line_unit_default = OrderTaxedPricesData(
- undiscounted_price=TaxedMoney(
- line.undiscounted_base_unit_price,
- line.undiscounted_base_unit_price,
- ),
- price_with_discounts=TaxedMoney(
- line.base_unit_price,
- line.base_unit_price,
- ),
- )
- line_unit_default.price_with_discounts = quantize_price(
- line_unit_default.price_with_discounts, currency
- )
- line_unit_default.undiscounted_price = quantize_price(
- line_unit_default.undiscounted_price, currency
- )
-
- line.undiscounted_unit_price = line_unit_default.undiscounted_price
- line.unit_price = line_unit_default.price_with_discounts
-
- line_total = base_calculations.base_order_line_total(line)
- line_total.price_with_discounts = quantize_price(
- line_total.price_with_discounts, currency
- )
- line_total.undiscounted_price = quantize_price(
- line_total.undiscounted_price, currency
- )
-
- 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 = calculate_tax_rate(line.unit_price)
-
- # Calculate shipping price.
- shipping_price = order.base_shipping_price
- order.shipping_price = quantize_price(
- TaxedMoney(net=shipping_price, gross=shipping_price),
- shipping_price.currency,
- )
- order.shipping_tax_rate = calculate_tax_rate(order.shipping_price)
-
- # Calculate order total.
- order.undiscounted_total = undiscounted_subtotal + order.shipping_price
- total = base_calculations.base_order_total(order, lines)
- order.total = quantize_price(TaxedMoney(total, total), currency)
-
-
-def _apply_tax_data(
- order: Order, lines: Iterable[OrderLine], tax_data: Optional[TaxData]
-) -> None:
- """Apply all prices from tax data to order and order lines."""
- if not tax_data:
- return
-
- currency = order.currency
- shipping_price = TaxedMoney(
- net=Money(tax_data.shipping_price_net_amount, currency),
- gross=Money(tax_data.shipping_price_gross_amount, currency),
- )
-
- order.shipping_price = shipping_price
- order.shipping_tax_rate = normalize_tax_rate_for_db(tax_data.shipping_tax_rate)
-
- subtotal = zero_taxed_money(order.currency)
- for order_line, tax_line in zip(lines, tax_data.lines):
- line_total_price = TaxedMoney(
- net=Money(tax_line.total_net_amount, currency),
- gross=Money(tax_line.total_gross_amount, currency),
- )
- order_line.total_price = line_total_price
- order_line.unit_price = line_total_price / order_line.quantity
- order_line.tax_rate = normalize_tax_rate_for_db(tax_line.tax_rate)
- subtotal += line_total_price
-
- order.total = shipping_price + subtotal
-
-
def fetch_order_prices_if_expired(
order: Order,
manager: PluginsManager,
@@ -225,10 +38,9 @@ def fetch_order_prices_if_expired(
) -> tuple[Order, Optional[Iterable[OrderLine]]]:
"""Fetch order prices with taxes.
- First calculate and apply all order prices with taxes separately,
- then apply tax data as well if we receive one.
+ First applies order level discounts, then calculates taxes.
- Prices will be updated if force_update is True,
+ Prices will be updated if force_update is True
or if order.should_refresh_prices is True.
"""
if order.status not in ORDER_EDITABLE_STATUS:
@@ -237,14 +49,6 @@ def fetch_order_prices_if_expired(
if not force_update and not order.should_refresh_prices:
return order, lines
- tax_configuration = order.channel.tax_configuration
- tax_calculation_strategy = get_tax_calculation_strategy_for_order(order)
- prices_entered_with_tax = tax_configuration.prices_entered_with_tax
- charge_taxes = get_charge_taxes_for_order(order)
- should_charge_tax = charge_taxes and not order.tax_exemption
-
- _update_order_discount_for_voucher(order)
-
if lines is None:
lines = list(order.lines.select_related("variant__product__product_type"))
else:
@@ -252,29 +56,8 @@ def fetch_order_prices_if_expired(
order.should_refresh_prices = False
- if prices_entered_with_tax:
- # If prices are entered with tax, we need to always calculate it anyway, to
- # display the tax rate to the user.
- _calculate_and_add_tax(
- tax_calculation_strategy, order, lines, manager, prices_entered_with_tax
- )
-
- if not should_charge_tax:
- # If charge_taxes is disabled or order is exempt from taxes, remove the
- # tax from the original gross prices.
- _remove_tax(order, lines)
-
- else:
- # Prices are entered without taxes.
- if should_charge_tax:
- # Calculate taxes if charge_taxes is enabled and order is not exempt
- # from taxes.
- _calculate_and_add_tax(
- tax_calculation_strategy, order, lines, manager, prices_entered_with_tax
- )
- else:
- # Calculate net prices without taxes.
- _get_order_base_prices(order, lines)
+ _update_order_discount_for_voucher(order)
+ _recalculate_prices(order, manager, lines)
with transaction.atomic(savepoint=False):
order.save(
@@ -303,12 +86,12 @@ def fetch_order_prices_if_expired(
"tax_rate",
],
)
+
return order, lines
def _update_order_discount_for_voucher(order: Order):
"""Create or delete OrderDiscount instances."""
-
if not order.voucher_id:
order.discounts.filter(type=DiscountType.VOUCHER).delete()
@@ -340,6 +123,41 @@ def _update_order_discount_for_voucher(order: Order):
prefetch_related_objects([order], "discounts")
+def _recalculate_prices(
+ order: Order,
+ manager: PluginsManager,
+ lines: Iterable[OrderLine],
+):
+ """Calculate prices after handling order level discounts and taxes."""
+ tax_configuration = order.channel.tax_configuration
+ tax_calculation_strategy = get_tax_calculation_strategy_for_order(order)
+ prices_entered_with_tax = tax_configuration.prices_entered_with_tax
+ charge_taxes = get_charge_taxes_for_order(order)
+ should_charge_tax = charge_taxes and not order.tax_exemption
+ if prices_entered_with_tax:
+ # If prices are entered with tax, we need to always calculate it anyway, to
+ # display the tax rate to the user.
+ _calculate_and_add_tax(
+ tax_calculation_strategy, order, lines, manager, prices_entered_with_tax
+ )
+ if not should_charge_tax:
+ # If charge_taxes is disabled or order is exempt from taxes, remove the
+ # tax from the original gross prices.
+ _remove_tax(order, lines)
+
+ else:
+ # Prices are entered without taxes.
+ if should_charge_tax:
+ # Calculate taxes if charge_taxes is enabled and order is not exempt
+ # from taxes.
+ _calculate_and_add_tax(
+ tax_calculation_strategy, order, lines, manager, prices_entered_with_tax
+ )
+ else:
+ apply_order_discounts(order, lines, assign_prices=True)
+ _remove_tax(order, lines)
+
+
def _calculate_and_add_tax(
tax_calculation_strategy: str,
order: "Order",
@@ -348,13 +166,144 @@ def _calculate_and_add_tax(
prices_entered_with_tax: bool,
):
if tax_calculation_strategy == TaxCalculationStrategy.TAX_APP:
- _recalculate_order_prices(manager, order, lines, prices_entered_with_tax)
+ # 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)
_apply_tax_data(order, lines, tax_data)
+ # TODO: If tax data is empty, order level discounts are not propagated
+ # to its lines and not reflected in line total prices.
+ # https://github.com/saleor/saleor/issues/14880
else:
+ # Get taxes calculated with flat rates and apply to order.
update_order_prices_with_flat_rates(order, lines, prices_entered_with_tax)
+def _recalculate_with_plugins(
+ manager: PluginsManager,
+ order: Order,
+ lines: Iterable[OrderLine],
+ prices_entered_with_tax: bool,
+) -> None:
+ """Fetch taxes from plugins and recalculate order/lines prices.
+
+ Does not throw TaxError.
+ """
+ _update_order_discounts_and_base_undiscounted_total(order, lines)
+ undiscounted_subtotal = zero_taxed_money(order.currency)
+ for line in lines:
+ variant = line.variant
+ if not variant:
+ continue
+ product = variant.product
+
+ try:
+ line_unit = manager.calculate_order_line_unit(order, line, variant, product)
+ line.unit_price = line_unit.price_with_discounts
+
+ line_total = manager.calculate_order_line_total(
+ order, line, variant, product
+ )
+ 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
+ )
+ line.undiscounted_unit_price = _get_undiscounted_price(
+ line_unit,
+ line.undiscounted_base_unit_price,
+ line.tax_rate,
+ prices_entered_with_tax,
+ )
+
+ line.undiscounted_total_price = _get_undiscounted_price(
+ line_total,
+ # base_order_line_total returns equal gross and net
+ base_order_line_total(line).undiscounted_price.net,
+ line.tax_rate,
+ prices_entered_with_tax,
+ )
+ except TaxError:
+ pass
+
+ try:
+ order.shipping_price = manager.calculate_order_shipping(order)
+ order.shipping_tax_rate = manager.get_order_shipping_tax_rate(
+ order, order.shipping_price
+ )
+ except TaxError:
+ pass
+
+ order.undiscounted_total = undiscounted_subtotal + TaxedMoney(
+ net=order.base_shipping_price, gross=order.base_shipping_price
+ )
+ order.total = manager.calculate_order_total(order, lines)
+
+
+def _get_undiscounted_price(
+ line_price: OrderTaxedPricesData,
+ line_base_price: Money,
+ tax_rate,
+ prices_entered_with_tax,
+):
+ if (
+ tax_rate > 0
+ and line_price.undiscounted_price.net == line_price.undiscounted_price.gross
+ ):
+ get_taxed_undiscounted_price(
+ line_base_price,
+ line_price.undiscounted_price,
+ tax_rate,
+ prices_entered_with_tax,
+ )
+ return line_price.undiscounted_price
+
+
+def _update_order_discounts_and_base_undiscounted_total(
+ order: Order, lines: Iterable[OrderLine]
+):
+ """Update order discounts and order undiscounted_total price.
+
+ Entire order vouchers and staff order discounts are recalculated and updated.
+ """
+ update_order_discount_amounts(order, lines)
+ undiscounted_total = undiscounted_order_total(order, lines)
+ order.undiscounted_total = TaxedMoney(
+ net=undiscounted_total, gross=undiscounted_total
+ )
+
+
+def _apply_tax_data(
+ order: Order, lines: Iterable[OrderLine], tax_data: Optional[TaxData]
+) -> None:
+ """Apply all prices from tax data to order and order lines."""
+ if not tax_data:
+ return
+
+ currency = order.currency
+ shipping_price = TaxedMoney(
+ net=Money(tax_data.shipping_price_net_amount, currency),
+ gross=Money(tax_data.shipping_price_gross_amount, currency),
+ )
+
+ order.shipping_price = shipping_price
+ order.shipping_tax_rate = normalize_tax_rate_for_db(tax_data.shipping_tax_rate)
+
+ subtotal = zero_taxed_money(order.currency)
+ for order_line, tax_line in zip(lines, tax_data.lines):
+ line_total_price = TaxedMoney(
+ net=Money(tax_line.total_net_amount, currency),
+ gross=Money(tax_line.total_gross_amount, currency),
+ )
+ order_line.total_price = line_total_price
+ order_line.unit_price = line_total_price / order_line.quantity
+ order_line.tax_rate = normalize_tax_rate_for_db(tax_line.tax_rate)
+ subtotal += line_total_price
+
+ order.total = shipping_price + subtotal
+
+
def _remove_tax(order, lines):
order.total_gross_amount = order.total_net_amount
order.undiscounted_total_gross_amount = order.undiscounted_total_net_amount
diff --git a/saleor/order/tests/test_base_calculations/__init__.py b/saleor/order/tests/test_base_calculations/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/saleor/order/tests/test_base_calculations/test_base_order_line_total.py b/saleor/order/tests/test_base_order_line_total.py
similarity index 91%
rename from saleor/order/tests/test_base_calculations/test_base_order_line_total.py
rename to saleor/order/tests/test_base_order_line_total.py
index 0b5dd2588a..e18f0a279e 100644
--- a/saleor/order/tests/test_base_calculations/test_base_order_line_total.py
+++ b/saleor/order/tests/test_base_order_line_total.py
@@ -1,7 +1,7 @@
from prices import TaxedMoney
-from ... import base_calculations
-from ...interface import OrderTaxedPricesData
+from .. import base_calculations
+from ..interface import OrderTaxedPricesData
def test_base_order_line_total(order_with_lines):
diff --git a/saleor/order/tests/test_base_calculations/test_base_order_total.py b/saleor/order/tests/test_base_order_total.py
similarity index 95%
rename from saleor/order/tests/test_base_calculations/test_base_order_total.py
rename to saleor/order/tests/test_base_order_total.py
index 8221e6f4dd..b280159e63 100644
--- a/saleor/order/tests/test_base_calculations/test_base_order_total.py
+++ b/saleor/order/tests/test_base_order_total.py
@@ -2,9 +2,9 @@ from decimal import ROUND_HALF_UP, Decimal
from prices import Money
-from ....core.taxes import zero_money
-from ....discount import DiscountType, DiscountValueType
-from ... import base_calculations
+from ...core.taxes import zero_money
+from ...discount import DiscountType, DiscountValueType
+from .. import base_calculations
def test_base_order_total(order_with_lines):
@@ -24,7 +24,7 @@ def test_base_order_total(order_with_lines):
assert order_total == undiscounted_total
-def test_base_order_total_with_fixed_voucher(order_with_lines):
+def test_base_order_total_with_fixed_voucher(order_with_lines, voucher):
# given
order = order_with_lines
lines = order.lines.all()
@@ -43,6 +43,7 @@ def test_base_order_total_with_fixed_voucher(order_with_lines):
translated_name="VoucherPL",
currency=order.currency,
amount_value=0,
+ voucher=voucher,
)
# when
@@ -54,7 +55,7 @@ def test_base_order_total_with_fixed_voucher(order_with_lines):
assert order_discount.amount_value == discount_amount
-def test_base_order_total_with_fixed_voucher_more_then_total(order_with_lines):
+def test_base_order_total_with_fixed_voucher_more_then_total(order_with_lines, voucher):
# given
order = order_with_lines
lines = order.lines.all()
@@ -71,6 +72,7 @@ def test_base_order_total_with_fixed_voucher_more_then_total(order_with_lines):
translated_name="VoucherPL",
currency=order.currency,
amount_value=0,
+ voucher=voucher,
)
# when
@@ -83,7 +85,7 @@ def test_base_order_total_with_fixed_voucher_more_then_total(order_with_lines):
assert order_discount.amount == subtotal
-def test_base_order_total_with_percentage_voucher(order_with_lines):
+def test_base_order_total_with_percentage_voucher(order_with_lines, voucher_percentage):
# given
order = order_with_lines
lines = order.lines.all()
@@ -102,6 +104,7 @@ def test_base_order_total_with_percentage_voucher(order_with_lines):
translated_name="VoucherPL",
currency=order.currency,
amount_value=0,
+ voucher=voucher_percentage,
)
# when
@@ -224,7 +227,7 @@ def test_base_order_total_with_percentage_manual_discount(order_with_lines):
def test_base_order_total_with_fixed_voucher_and_fixed_manual_discount(
- order_with_lines,
+ order_with_lines, voucher
):
# given
order = order_with_lines
@@ -244,6 +247,7 @@ def test_base_order_total_with_fixed_voucher_and_fixed_manual_discount(
translated_name="StaffDiscountPL",
currency=order.currency,
amount_value=0,
+ voucher=voucher,
)
manual_discount_amount = 10
manual_order_discount = order.discounts.create(
@@ -270,7 +274,7 @@ def test_base_order_total_with_fixed_voucher_and_fixed_manual_discount(
def test_base_order_total_with_percentage_voucher_and_fixed_manual_discount(
- order_with_lines,
+ order_with_lines, voucher_percentage
):
# given
order = order_with_lines
@@ -290,6 +294,7 @@ def test_base_order_total_with_percentage_voucher_and_fixed_manual_discount(
translated_name="StaffDiscountPL",
currency=order.currency,
amount_value=0,
+ voucher=voucher_percentage,
)
manual_discount_amount = 10
manual_order_discount = order.discounts.create(
@@ -316,7 +321,7 @@ def test_base_order_total_with_percentage_voucher_and_fixed_manual_discount(
def test_base_order_total_with_fixed_voucher_and_percentage_manual_discount(
- order_with_lines,
+ order_with_lines, voucher
):
# given
order = order_with_lines
@@ -336,6 +341,7 @@ def test_base_order_total_with_fixed_voucher_and_percentage_manual_discount(
translated_name="StaffDiscountPL",
currency=order.currency,
amount_value=0,
+ voucher=voucher,
)
temporary_total = undiscounted_total - Money(
voucher_discount_amount, order.currency
@@ -365,7 +371,7 @@ def test_base_order_total_with_fixed_voucher_and_percentage_manual_discount(
def test_base_order_total_with_percentage_voucher_and_percentage_manual_discount(
- order_with_lines,
+ order_with_lines, voucher_percentage
):
# given
order = order_with_lines
@@ -385,6 +391,7 @@ def test_base_order_total_with_percentage_voucher_and_percentage_manual_discount
translated_name="StaffDiscountPL",
currency=order.currency,
amount_value=0,
+ voucher=voucher_percentage,
)
temporary_total = undiscounted_total - Money(
@@ -415,7 +422,7 @@ def test_base_order_total_with_percentage_voucher_and_percentage_manual_discount
def test_base_order_total_with_fixed_manual_discount_and_fixed_voucher(
- order_with_lines,
+ order_with_lines, voucher
):
# given
order = order_with_lines
@@ -446,6 +453,7 @@ def test_base_order_total_with_fixed_manual_discount_and_fixed_voucher(
translated_name="StaffDiscountPL",
currency=order.currency,
amount_value=0,
+ voucher=voucher,
)
# when
@@ -462,7 +470,7 @@ def test_base_order_total_with_fixed_manual_discount_and_fixed_voucher(
def test_base_order_total_with_fixed_manual_discount_and_percentage_voucher(
- order_with_lines,
+ order_with_lines, voucher_percentage
):
# given
order = order_with_lines
@@ -499,6 +507,7 @@ def test_base_order_total_with_fixed_manual_discount_and_percentage_voucher(
translated_name="StaffDiscountPL",
currency=order.currency,
amount_value=voucher_discount_amount,
+ voucher=voucher_percentage,
)
# when
@@ -519,7 +528,7 @@ def test_base_order_total_with_fixed_manual_discount_and_percentage_voucher(
def test_base_order_total_with_percentage_manual_discount_and_fixed_voucher(
- order_with_lines,
+ order_with_lines, voucher
):
# given
order = order_with_lines
@@ -550,6 +559,7 @@ def test_base_order_total_with_percentage_manual_discount_and_fixed_voucher(
translated_name="StaffDiscountPL",
currency=order.currency,
amount_value=0,
+ voucher=voucher,
)
# when
@@ -566,7 +576,7 @@ def test_base_order_total_with_percentage_manual_discount_and_fixed_voucher(
def test_base_order_total_with_percentage_manual_discount_and_percentage_voucher(
- order_with_lines,
+ order_with_lines, voucher_percentage
):
# given
order = order_with_lines
@@ -598,6 +608,7 @@ def test_base_order_total_with_percentage_manual_discount_and_percentage_voucher
translated_name="StaffDiscountPL",
currency=order.currency,
amount_value=0,
+ voucher=voucher_percentage,
)
# when
diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.py
index 209c470b3f..b0f93d1126 100644
--- a/saleor/order/tests/test_calculations.py
+++ b/saleor/order/tests/test_calculations.py
@@ -68,7 +68,7 @@ def create_order_taxed_prices_data(
)
-def test_recalculate_order_prices(order_with_lines, order_lines, tax_data):
+def test_recalculate_with_plugins(order_with_lines, order_lines, tax_data):
# given
order = order_with_lines
currency = order.currency
@@ -104,7 +104,7 @@ def test_recalculate_order_prices(order_with_lines, order_lines, tax_data):
)
# when
- calculations._recalculate_order_prices(manager, order, lines, False)
+ calculations._recalculate_with_plugins(manager, order, lines, False)
# then
assert order.total == total
@@ -141,7 +141,7 @@ def test_recalculate_order_prices(order_with_lines, order_lines, tax_data):
"get_order_shipping_tax_rate",
],
)
-def test_recalculate_order_prices_tax_error(
+def test_recalculate_with_plugins_tax_error(
order_with_lines, order_lines, mocked_method_name
):
# given
@@ -163,13 +163,13 @@ def test_recalculate_order_prices_tax_error(
manager = Mock(**manager_methods)
# when
- calculations._recalculate_order_prices(manager, order, lines, False)
+ calculations._recalculate_with_plugins(manager, order, lines, False)
# then
# no exception is raised
-def test_recalculate_order_prices_tax_error_line_prices(
+def test_recalculate_with_plugins_tax_error_line_prices(
order_with_lines, order_lines, tax_data
):
# given
@@ -214,7 +214,7 @@ def test_recalculate_order_prices_tax_error_line_prices(
)
# when
- calculations._recalculate_order_prices(manager, order, lines, False)
+ calculations._recalculate_with_plugins(manager, order, lines, False)
# then
assert order.total == total
@@ -247,7 +247,7 @@ def test_recalculate_order_prices_tax_error_line_prices(
assert tax_rate == line.tax_rate
-def test_recalculate_order_prices_tax_error_shipping_price(
+def test_recalculate_with_plugins_tax_error_shipping_price(
order_with_lines, order_lines, tax_data
):
# given
@@ -287,7 +287,7 @@ def test_recalculate_order_prices_tax_error_shipping_price(
)
# when
- calculations._recalculate_order_prices(manager, order, lines, False)
+ calculations._recalculate_with_plugins(manager, order, lines, False)
# then
assert order.total == subtotal + old_shipping_price
@@ -314,7 +314,7 @@ def test_recalculate_order_prices_tax_error_shipping_price(
assert tax_rate == line.tax_rate
-def test_recalculate_order_prices_order_discounts_and_total_undiscounted_price_changed(
+def test_recalculate_with_plugins_order_discounts_and_total_undiscounted_price_changed(
draft_order, order_lines, shipping_method_weight_based, tax_data
):
# given
@@ -375,7 +375,7 @@ def test_recalculate_order_prices_order_discounts_and_total_undiscounted_price_c
)
# when
- calculations._recalculate_order_prices(manager, order, lines, False)
+ calculations._recalculate_with_plugins(manager, order, lines, False)
# then
order_discount.refresh_from_db()
@@ -794,20 +794,20 @@ def test_fetch_order_prices_when_tax_exemption_and_not_include_taxes_in_prices(
tax plugins should be ignored and only net prices should be calculated and returned.
"""
# given
-
tc = order_with_lines.channel.tax_configuration
tc.prices_entered_with_tax = False
tc.save(update_fields=["prices_entered_with_tax"])
tc.country_exceptions.all().delete()
currency = order_with_lines.currency
- discount_amount = Decimal("3.00")
- discount_as_money = Money(discount_amount, currency)
+ discount = Decimal("50")
order_with_lines.discounts.create(
- value=discount_amount,
- amount_value=discount_amount,
+ value=discount,
+ value_type=DiscountValueType.PERCENTAGE,
currency=order_with_lines.currency,
)
+ expected_discount_amount = order_with_lines.total_net_amount * discount / 100
+
order_with_lines.total_net_amount = Decimal("0.00")
order_with_lines.total_gross_amount = Decimal("0.00")
order_with_lines.undiscounted_total_net_amount = Decimal("0.00")
@@ -822,19 +822,13 @@ def test_fetch_order_prices_when_tax_exemption_and_not_include_taxes_in_prices(
# then
order_with_lines.refresh_from_db()
-
+ assert order_with_lines.discounts.first().amount_value == expected_discount_amount
subtotal = zero_taxed_money(currency)
undiscounted_subtotal = zero_taxed_money(currency)
- shipping_price = order_with_lines.base_shipping_price
- shipping_price = quantize_price(
- TaxedMoney(
- shipping_price,
- shipping_price,
- ),
- currency,
- )
-
- assert order_with_lines.shipping_price == shipping_price
+ undiscounted_shipping = order_with_lines.base_shipping_price
+ shipping_price = order_with_lines.shipping_price
+ assert shipping_price.net == undiscounted_shipping * discount / 100
+ assert shipping_price.net == shipping_price.gross
assert order_with_lines.shipping_tax_rate == Decimal("0.00")
for order_line in order_with_lines.lines.all():
@@ -853,7 +847,7 @@ def test_fetch_order_prices_when_tax_exemption_and_not_include_taxes_in_prices(
currency,
)
- line_total = line_price_with_discounts * order_line.quantity
+ line_total = line_price_with_discounts * order_line.quantity * discount / 100
undiscounted_total_price = undiscounted_line_price * order_line.quantity
subtotal += line_total
@@ -866,19 +860,9 @@ def test_fetch_order_prices_when_tax_exemption_and_not_include_taxes_in_prices(
assert (
order_with_lines.undiscounted_total
- == undiscounted_subtotal + shipping_price.net
- )
- assert order_with_lines.total == (
- subtotal
- + shipping_price
- - quantize_price(
- TaxedMoney(
- discount_as_money,
- discount_as_money,
- ),
- currency,
- )
+ == undiscounted_subtotal + undiscounted_shipping
)
+ 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/tests/test_discount_calculations.py b/saleor/order/tests/test_discount_calculations.py
new file mode 100644
index 0000000000..84e6b6a122
--- /dev/null
+++ b/saleor/order/tests/test_discount_calculations.py
@@ -0,0 +1,685 @@
+from decimal import Decimal
+
+import pytest
+from prices import Money, TaxedMoney
+
+from ...core.prices import quantize_price
+from ...core.taxes import zero_money
+from ...discount import DiscountType, DiscountValueType
+from ...order.base_calculations import (
+ apply_order_discounts,
+ apply_subtotal_discount_to_order_lines,
+ base_order_line_total,
+ base_order_total,
+)
+from ...order.interface import OrderTaxedPricesData
+
+
+def test_base_order_total(order_with_lines):
+ # given
+ order = order_with_lines
+ lines = order.lines.all()
+ shipping_price = order.shipping_price.net
+ subtotal = zero_money(order.currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+ undiscounted_total = subtotal + shipping_price
+
+ # when
+ order_total = base_order_total(order, lines)
+
+ # then
+ assert order_total == undiscounted_total
+
+
+def test_base_order_line_total(order_with_lines):
+ # given
+ line = order_with_lines.lines.all().first()
+
+ # when
+ order_total = base_order_line_total(line)
+
+ # then
+ base_line_unit_price = line.base_unit_price
+ quantity = line.quantity
+ expected_price_with_discount = (
+ TaxedMoney(base_line_unit_price, base_line_unit_price) * quantity
+ )
+ base_line_undiscounted_unit_price = line.undiscounted_base_unit_price
+ expected_undiscounted_price = (
+ TaxedMoney(base_line_undiscounted_unit_price, base_line_undiscounted_unit_price)
+ * quantity
+ )
+ assert order_total == OrderTaxedPricesData(
+ price_with_discounts=expected_price_with_discount,
+ undiscounted_price=expected_undiscounted_price,
+ )
+
+
+def test_apply_order_discounts_voucher_entire_order(order_with_lines, voucher):
+ # given
+ order = order_with_lines
+ lines = order.lines.all()
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ discount_amount = 10
+ order_discount = order.discounts.create(
+ type=DiscountType.VOUCHER,
+ value_type=DiscountValueType.FIXED,
+ value=discount_amount,
+ name="Voucher",
+ translated_name="VoucherPL",
+ currency=currency,
+ amount_value=0,
+ voucher=voucher,
+ )
+
+ # when
+ discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+
+ # then
+ assert discounted_shipping_price == shipping_price
+ assert discounted_subtotal == subtotal - Money(discount_amount, currency)
+ assert order.total_net == discounted_subtotal + discounted_shipping_price
+ assert order.total_gross == discounted_subtotal + discounted_shipping_price
+ assert order.shipping_price_net == discounted_shipping_price
+ assert order.shipping_price_gross == discounted_shipping_price
+ assert order.undiscounted_total_net == subtotal + shipping_price
+ assert order.undiscounted_total_gross == subtotal + shipping_price
+ order_discount.refresh_from_db()
+ assert order_discount.amount_value == discount_amount
+
+
+def test_apply_order_discounts_voucher_entire_order_exceed_subtotal(
+ order_with_lines, voucher
+):
+ # given
+ order = order_with_lines
+ lines = order.lines.all()
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ discount_amount = 100
+ assert Money(discount_amount, currency) > subtotal
+
+ order_discount = order.discounts.create(
+ type=DiscountType.VOUCHER,
+ value_type=DiscountValueType.FIXED,
+ value=discount_amount,
+ name="Voucher",
+ translated_name="VoucherPL",
+ currency=currency,
+ amount_value=0,
+ voucher=voucher,
+ )
+
+ # when
+ discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+
+ # then
+ assert discounted_shipping_price == shipping_price
+ assert discounted_subtotal == zero_money(currency)
+ assert order.total_net == discounted_shipping_price
+ assert order.total_gross == discounted_shipping_price
+ assert order.shipping_price_net == discounted_shipping_price
+ assert order.shipping_price_gross == discounted_shipping_price
+ assert order.undiscounted_total_net == subtotal + shipping_price
+ assert order.undiscounted_total_gross == subtotal + shipping_price
+ order_discount.refresh_from_db()
+ assert order_discount.amount_value == subtotal.amount
+
+
+def test_apply_order_discounts_voucher_entire_order_percentage(
+ order_with_lines, voucher_percentage
+):
+ # given
+ order = order_with_lines
+ lines = order.lines.all()
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ discount_amount = 50
+ order_discount = order.discounts.create(
+ type=DiscountType.VOUCHER,
+ value_type=DiscountValueType.PERCENTAGE,
+ value=discount_amount,
+ name="Voucher",
+ translated_name="VoucherPL",
+ currency=currency,
+ amount_value=0,
+ voucher=voucher_percentage,
+ )
+
+ # when
+ discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+
+ # then
+ assert discounted_shipping_price == shipping_price
+ assert discounted_subtotal == Money(subtotal.amount / 2, currency)
+ assert order.total_net == discounted_subtotal + discounted_shipping_price
+ assert order.total_gross == discounted_subtotal + discounted_shipping_price
+ assert order.shipping_price_net == discounted_shipping_price
+ assert order.shipping_price_gross == discounted_shipping_price
+ assert order.undiscounted_total_net == subtotal + shipping_price
+ assert order.undiscounted_total_gross == subtotal + shipping_price
+ order_discount.refresh_from_db()
+ assert order_discount.amount_value == quantize_price(subtotal.amount / 2, currency)
+
+
+def test_apply_order_discounts_manual_discount(order_with_lines):
+ # given
+ order = order_with_lines
+ lines = order.lines.all()
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ discount_amount = 8
+ order_discount = order.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.FIXED,
+ value=discount_amount,
+ name="StaffDiscount",
+ translated_name="StaffDiscountPL",
+ currency=currency,
+ amount_value=0,
+ )
+ undiscounted_total = subtotal + shipping_price
+ shipping_share = shipping_price / undiscounted_total
+ subtotal_share = 1 - shipping_share
+
+ # when
+ discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+
+ # then
+ assert discounted_shipping_price == shipping_price - shipping_share * Money(
+ discount_amount, currency
+ )
+ assert discounted_subtotal == subtotal - subtotal_share * Money(
+ discount_amount, currency
+ )
+ assert order.total_net == discounted_subtotal + discounted_shipping_price
+ assert order.total_gross == discounted_subtotal + discounted_shipping_price
+ assert order.shipping_price_net == discounted_shipping_price
+ assert order.shipping_price_gross == discounted_shipping_price
+ assert order.undiscounted_total_net == subtotal + shipping_price
+ assert order.undiscounted_total_gross == subtotal + shipping_price
+ order_discount.refresh_from_db()
+ assert order_discount.amount_value == discount_amount
+
+
+def test_apply_order_discounts_manual_discount_and_zero_order_total(order):
+ # given
+ lines = order.lines.all()
+ assert not lines
+
+ currency = order.currency
+ order.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.FIXED,
+ value=0,
+ name="StaffDiscount",
+ translated_name="StaffDiscountPL",
+ currency=currency,
+ amount_value=0,
+ )
+
+ # when
+ discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+
+ # then
+ assert discounted_subtotal + discounted_shipping_price == zero_money(currency)
+
+
+def test_apply_order_discounts_manual_discount_exceed_total(order_with_lines):
+ # given
+ order = order_with_lines
+ lines = order.lines.all()
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+ undiscounted_total = subtotal + shipping_price
+
+ discount_amount = 160
+ assert Money(discount_amount, currency) > undiscounted_total
+ order_discount = order.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.FIXED,
+ value=discount_amount,
+ name="StaffDiscount",
+ translated_name="StaffDiscountPL",
+ currency=currency,
+ amount_value=0,
+ )
+
+ # when
+ discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+
+ # then
+ assert discounted_shipping_price == zero_money(currency)
+ assert discounted_subtotal == zero_money(currency)
+ assert order.total_net == zero_money(currency)
+ assert order.total_gross == zero_money(currency)
+ assert order.shipping_price_net == zero_money(currency)
+ assert order.shipping_price_gross == zero_money(currency)
+ assert order.undiscounted_total_net == undiscounted_total
+ assert order.undiscounted_total_gross == undiscounted_total
+ order_discount.refresh_from_db()
+ assert order_discount.amount_value == undiscounted_total.amount
+
+
+def test_apply_order_discounts_manual_discount_percentage(order_with_lines):
+ # given
+ order = order_with_lines
+ lines = order.lines.all()
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+ undiscounted_total = subtotal + shipping_price
+
+ discount_amount = undiscounted_total.amount * Decimal(0.5)
+ order_discount = order.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.PERCENTAGE,
+ value=50,
+ name="StaffDiscount",
+ translated_name="StaffDiscountPL",
+ currency=currency,
+ amount_value=0,
+ )
+
+ # when
+ discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+
+ # then
+ discounted_total = discounted_subtotal + discounted_shipping_price
+ assert discounted_shipping_price == shipping_price / 2
+ assert discounted_subtotal == subtotal / 2
+ assert order.total_net == discounted_total
+ assert order.total_gross == discounted_total
+ assert order.shipping_price_net == discounted_shipping_price
+ assert order.shipping_price_gross == discounted_shipping_price
+ assert order.undiscounted_total_net == undiscounted_total
+ assert order.undiscounted_total_gross == undiscounted_total
+ order_discount.refresh_from_db()
+ assert order_discount.amount_value == discount_amount
+
+
+def test_apply_order_discounts_voucher_entire_order_and_manual_discount_fixed(
+ order_with_lines, voucher
+):
+ # given
+ order = order_with_lines
+ lines = order.lines.all()
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+ undiscounted_total = subtotal + shipping_price
+ expected_subtotal = subtotal
+ expected_shipping = shipping_price
+
+ voucher_discount_amount = 10
+ voucher_order_discount = order.discounts.create(
+ type=DiscountType.VOUCHER,
+ value_type=DiscountValueType.FIXED,
+ value=voucher_discount_amount,
+ name="Voucher",
+ translated_name="VoucherPL",
+ currency=currency,
+ amount_value=0,
+ voucher=voucher,
+ )
+ # entire order voucher is applied to subtotal only
+ expected_subtotal -= Money(voucher_discount_amount, currency)
+
+ manual_discount_amount = 8
+ manual_order_discount = order.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.FIXED,
+ value=manual_discount_amount,
+ name="StaffDiscount",
+ translated_name="StaffDiscountPL",
+ currency=currency,
+ amount_value=0,
+ )
+ # manual discount is applied to both subtotal and shipping price
+ subtotal_share = expected_subtotal / (expected_subtotal + expected_shipping)
+ subtotal_discount = subtotal_share * manual_discount_amount
+ shipping_discount = manual_discount_amount - subtotal_discount
+ expected_subtotal -= Money(subtotal_discount, currency)
+ expected_shipping -= Money(shipping_discount, currency)
+
+ # when
+ discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+
+ # then
+ assert discounted_shipping_price == expected_shipping
+ assert discounted_subtotal == expected_subtotal
+ assert order.total_net == expected_shipping + expected_subtotal
+ assert order.total_gross == expected_shipping + expected_subtotal
+ assert order.shipping_price_net == discounted_shipping_price
+ assert order.shipping_price_gross == discounted_shipping_price
+ assert order.undiscounted_total_net == undiscounted_total
+ assert order.undiscounted_total_gross == undiscounted_total
+ voucher_order_discount.refresh_from_db()
+ assert voucher_order_discount.amount_value == voucher_discount_amount
+ manual_order_discount.refresh_from_db()
+ assert manual_order_discount.amount_value == manual_discount_amount
+
+
+def test_apply_order_discounts_manual_discount_fixed_and_voucher_entire_order(
+ order_with_lines, voucher
+):
+ # given
+ order = order_with_lines
+ lines = order.lines.all()
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+ undiscounted_total = subtotal + shipping_price
+ expected_subtotal = subtotal
+ expected_shipping = shipping_price
+ subtotal_share = subtotal / undiscounted_total
+
+ manual_discount_amount = 8
+ manual_order_discount = order.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.FIXED,
+ value=manual_discount_amount,
+ name="StaffDiscount",
+ translated_name="StaffDiscountPL",
+ currency=currency,
+ amount_value=0,
+ )
+ # manual discount is applied to both subtotal and shipping price
+ subtotal_discount = subtotal_share * manual_discount_amount
+ shipping_discount = manual_discount_amount - subtotal_discount
+ expected_subtotal -= Money(subtotal_discount, currency)
+ expected_shipping -= Money(shipping_discount, currency)
+
+ voucher_discount_amount = 10
+ voucher_order_discount = order.discounts.create(
+ type=DiscountType.VOUCHER,
+ value_type=DiscountValueType.FIXED,
+ value=voucher_discount_amount,
+ name="Voucher",
+ translated_name="VoucherPL",
+ currency=currency,
+ amount_value=0,
+ voucher=voucher,
+ )
+ # entire order voucher is applied to subtotal only
+ expected_subtotal -= Money(voucher_discount_amount, currency)
+
+ # when
+ discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+
+ # then
+ assert discounted_shipping_price == expected_shipping
+ assert discounted_subtotal == expected_subtotal
+ assert order.total_net == expected_shipping + expected_subtotal
+ assert order.total_gross == expected_shipping + expected_subtotal
+ assert order.shipping_price_net == discounted_shipping_price
+ assert order.shipping_price_gross == discounted_shipping_price
+ assert order.undiscounted_total_net == undiscounted_total
+ assert order.undiscounted_total_gross == undiscounted_total
+ voucher_order_discount.refresh_from_db()
+ assert voucher_order_discount.amount_value == voucher_discount_amount
+ manual_order_discount.refresh_from_db()
+ assert manual_order_discount.amount_value == manual_discount_amount
+
+
+def test_apply_order_discounts_voucher_entire_order_and_manual_discount_percentage(
+ order_with_lines,
+ voucher_percentage,
+):
+ # given
+ order = order_with_lines
+ lines = order.lines.all()
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+ undiscounted_total = subtotal + shipping_price
+ expected_subtotal = subtotal
+ expected_shipping = shipping_price
+
+ voucher_value = 50
+ voucher_order_discount = order.discounts.create(
+ type=DiscountType.VOUCHER,
+ value_type=DiscountValueType.PERCENTAGE,
+ value=voucher_value,
+ name="Voucher",
+ translated_name="VoucherPL",
+ currency=currency,
+ amount_value=0,
+ voucher=voucher_percentage,
+ )
+ # entire order voucher is applied to subtotal only
+ voucher_discount = Decimal(voucher_value / 100) * expected_subtotal
+ expected_subtotal -= voucher_discount
+
+ manual_discount_value = 50
+ manual_order_discount = order.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.PERCENTAGE,
+ value=manual_discount_value,
+ name="StaffDiscount",
+ translated_name="StaffDiscountPL",
+ currency=currency,
+ amount_value=0,
+ )
+ # manual discount is applied to both subtotal and shipping price
+ manual_discount_subtotal = Decimal(manual_discount_value / 100) * expected_subtotal
+ expected_subtotal -= manual_discount_subtotal
+ manual_discount_shipping = Decimal(manual_discount_value / 100) * expected_shipping
+ expected_shipping -= manual_discount_shipping
+ manual_discount = manual_discount_subtotal + manual_discount_shipping
+
+ # when
+ discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+
+ # then
+ assert discounted_shipping_price == expected_shipping
+ assert discounted_subtotal == expected_subtotal
+ assert order.total_net == expected_shipping + expected_subtotal
+ assert order.total_gross == expected_shipping + expected_subtotal
+ assert order.shipping_price_net == discounted_shipping_price
+ assert order.shipping_price_gross == discounted_shipping_price
+ assert order.undiscounted_total_net == undiscounted_total
+ assert order.undiscounted_total_gross == undiscounted_total
+ voucher_order_discount.refresh_from_db()
+ assert voucher_order_discount.amount_value == voucher_discount.amount
+ manual_order_discount.refresh_from_db()
+ assert manual_order_discount.amount_value == manual_discount.amount
+
+
+def test_apply_order_discounts_manual_discount_percentage_and_voucher_entire_order(
+ order_with_lines,
+ voucher_percentage,
+):
+ # given
+ order = order_with_lines
+ lines = order.lines.all()
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+ undiscounted_total = subtotal + shipping_price
+ expected_subtotal = subtotal
+ expected_shipping = shipping_price
+
+ manual_discount_value = 50
+ manual_order_discount = order.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.PERCENTAGE,
+ value=manual_discount_value,
+ name="StaffDiscount",
+ translated_name="StaffDiscountPL",
+ currency=currency,
+ amount_value=0,
+ )
+ # manual discount is applied to both subtotal and shipping price
+ manual_discount_subtotal = Decimal(manual_discount_value / 100) * expected_subtotal
+ expected_subtotal -= manual_discount_subtotal
+ manual_discount_shipping = Decimal(manual_discount_value / 100) * expected_shipping
+ expected_shipping -= manual_discount_shipping
+ manual_discount = manual_discount_subtotal + manual_discount_shipping
+
+ voucher_value = 50
+ voucher_order_discount = order.discounts.create(
+ type=DiscountType.VOUCHER,
+ value_type=DiscountValueType.PERCENTAGE,
+ value=voucher_value,
+ name="Voucher",
+ translated_name="VoucherPL",
+ currency=currency,
+ amount_value=0,
+ voucher=voucher_percentage,
+ )
+ # entire order voucher is applied to subtotal only
+ voucher_discount = Decimal(voucher_value / 100) * expected_subtotal
+ expected_subtotal -= voucher_discount
+
+ # when
+ discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+
+ # then
+ assert discounted_shipping_price == expected_shipping
+ assert discounted_subtotal == expected_subtotal
+ assert order.total_net == expected_shipping + expected_subtotal
+ assert order.total_gross == expected_shipping + expected_subtotal
+ assert order.shipping_price_net == discounted_shipping_price
+ assert order.shipping_price_gross == discounted_shipping_price
+ assert order.undiscounted_total_net == undiscounted_total
+ assert order.undiscounted_total_gross == undiscounted_total
+ voucher_order_discount.refresh_from_db()
+ assert voucher_order_discount.amount_value == voucher_discount.amount
+ manual_order_discount.refresh_from_db()
+ assert manual_order_discount.amount_value == manual_discount.amount
+
+
[email protected]("discount", ["10", "1", "17.3", "10000", "0"])
+def test_apply_subtotal_discount_to_order_lines(
+ discount,
+ order_with_lines,
+ voucher,
+):
+ # given
+ order = order_with_lines
+ currency = order.currency
+
+ def _quantize(price):
+ return quantize_price(price, currency)
+
+ lines = order.lines.all()
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+ subtotal_discount = Money(Decimal(discount), currency)
+ expected_subtotal = max(subtotal - subtotal_discount, zero_money(currency))
+
+ # when
+ apply_subtotal_discount_to_order_lines(lines, subtotal, subtotal_discount)
+
+ # then
+ discounted_subtotal = zero_money(currency)
+ for line in lines:
+ discounted_subtotal += line.total_price_net
+ assert discounted_subtotal == expected_subtotal
+
+ assert (
+ discounted_subtotal.amount
+ == lines[0].total_price_net_amount + lines[1].total_price_net_amount
+ )
+ assert (
+ discounted_subtotal.amount
+ == lines[0].total_price_gross_amount + lines[1].total_price_gross_amount
+ )
+
+ assert lines[0].total_price_net_amount == _quantize(
+ lines[0].unit_price_net_amount * lines[0].quantity
+ )
+ assert lines[0].total_price_gross_amount == _quantize(
+ lines[0].unit_price_gross_amount * lines[0].quantity
+ )
+ assert lines[1].total_price_net_amount == _quantize(
+ lines[1].unit_price_net_amount * lines[1].quantity
+ )
+ assert lines[1].total_price_gross_amount == _quantize(
+ lines[1].unit_price_gross_amount * lines[1].quantity
+ )
+ assert (
+ max(
+ lines[0].base_unit_price * lines[0].quantity
+ + lines[1].base_unit_price * lines[1].quantity
+ - subtotal_discount,
+ zero_money(currency),
+ )
+ == expected_subtotal
+ )
+
+
[email protected]("discount", ["10", "1", "17.3", "10000", "0"])
+def test_apply_subtotal_discount_to_order_lines_order_with_single_line(
+ discount,
+ order_with_lines,
+ voucher,
+):
+ # given
+ order = order_with_lines
+ currency = order.currency
+
+ def _quantize(price):
+ return quantize_price(price, currency)
+
+ order.lines.all()[1].delete()
+ line = order.lines.first()
+ subtotal = line.base_unit_price * line.quantity
+ subtotal_discount = Money(Decimal(discount), currency)
+ expected_subtotal = max(subtotal - subtotal_discount, zero_money(currency))
+
+ # when
+ apply_subtotal_discount_to_order_lines([line], subtotal, subtotal_discount)
+
+ # then
+ discounted_subtotal = line.total_price_net
+ assert discounted_subtotal == expected_subtotal
+ assert discounted_subtotal.amount == line.total_price_net_amount
+ assert discounted_subtotal.amount == line.total_price_gross_amount
+
+ assert line.total_price_net_amount == _quantize(
+ line.unit_price_net_amount * line.quantity
+ )
+ assert line.total_price_gross_amount == _quantize(
+ line.unit_price_gross_amount * line.quantity
+ )
+ assert (
+ max(
+ line.base_unit_price * line.quantity - subtotal_discount,
+ zero_money(currency),
+ )
+ == line.total_price_net
+ )
diff --git a/saleor/tax/calculations/order.py b/saleor/tax/calculations/order.py
index 1050680775..6b44ef80a8 100644
--- a/saleor/tax/calculations/order.py
+++ b/saleor/tax/calculations/order.py
@@ -2,16 +2,12 @@ from collections.abc import Iterable
from decimal import Decimal
from typing import TYPE_CHECKING
-from prices import Money, TaxedMoney
+from prices import TaxedMoney
from ...core.prices import quantize_price
-from ...core.taxes import zero_money, zero_taxed_money
-from ...discount import DiscountType
+from ...core.taxes import zero_taxed_money
from ...order import base_calculations
-from ...order.utils import (
- get_order_country,
- get_total_order_discount_excluding_shipping,
-)
+from ...order.utils import get_order_country
from ..models import TaxClassCountryRate
from ..utils import (
denormalize_tax_rate_from_db,
@@ -37,7 +33,10 @@ def update_order_prices_with_flat_rates(
default_country_rate_obj.rate if default_country_rate_obj else Decimal(0)
)
- # Calculate order line totals.
+ # Apply order level discounts
+ base_calculations.apply_order_discounts(order, lines)
+
+ # Calculate order line taxes.
_, undiscounted_subtotal = update_taxes_for_order_lines(
order, lines, country_code, default_tax_rate, prices_entered_with_tax
)
@@ -91,17 +90,13 @@ def _calculate_order_total(
undiscounted_subtotal += line.undiscounted_total_price
total += order.shipping_price
- order_discount = order.discounts.filter(type=DiscountType.MANUAL).first()
- if order_discount and order_discount.amount > undiscounted_subtotal.gross:
- remaining_amount = order_discount.amount - undiscounted_subtotal.gross
- total -= remaining_amount
return quantize_price(max(total, zero_taxed_money(currency)), currency)
def _calculate_order_shipping(
order: "Order", tax_rate: Decimal, prices_entered_with_tax: bool
) -> TaxedMoney:
- shipping_price = order.base_shipping_price
+ shipping_price = order.shipping_price.net
taxed_shipping_price = calculate_flat_rate_tax(
shipping_price, tax_rate, prices_entered_with_tax
)
@@ -118,12 +113,6 @@ def update_taxes_for_order_lines(
currency = order.currency
lines = list(lines)
- total_discount_amount = get_total_order_discount_excluding_shipping(order).amount
- order_total_price = sum(
- [line.base_unit_price.amount * line.quantity for line in lines]
- )
- total_line_discounts = 0
-
undiscounted_subtotal = zero_taxed_money(order.currency)
for line in lines:
@@ -148,32 +137,8 @@ def update_taxes_for_order_lines(
else:
tax_rate = default_tax_rate
- line_total_price = line.base_unit_price * line.quantity
undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
-
- price_with_discounts = line.base_unit_price
- if total_discount_amount:
- if line is lines[-1]:
- # for the last line applied remaining discount
- discount_amount = total_discount_amount - total_line_discounts
- else:
- # calculate discount proportionally to the rate of total line price
- # to order total price.
- discount_amount = quantize_price(
- line_total_price.amount / order_total_price * total_discount_amount,
- currency,
- )
- price_with_discounts = max(
- quantize_price(
- (line_total_price - Money(discount_amount, currency))
- / line.quantity,
- currency,
- ),
- zero_money(currency),
- )
- # sum already applied discounts
- total_line_discounts += discount_amount
-
+ price_with_discounts = line.unit_price.net
unit_price = calculate_flat_rate_tax(
price_with_discounts, tax_rate, prices_entered_with_tax
)
diff --git a/saleor/tax/tests/test_order_calculations.py b/saleor/tax/tests/test_order_calculations.py
index c9a694bbd5..d4a9af81c9 100644
--- a/saleor/tax/tests/test_order_calculations.py
+++ b/saleor/tax/tests/test_order_calculations.py
@@ -8,6 +8,7 @@ from ...core.prices import quantize_price
from ...core.taxes import zero_money, zero_taxed_money
from ...discount import DiscountType, DiscountValueType
from ...order import OrderStatus
+from ...order.base_calculations import apply_order_discounts
from ...order.calculations import fetch_order_prices_if_expired
from ...order.utils import get_order_country
from ...plugins.manager import get_plugins_manager
@@ -67,6 +68,7 @@ def test_calculations_calculate_order_undiscounted_total(
name=voucher_shipping_type.code,
currency=order.currency,
amount_value=Decimal(5.0),
+ voucher=voucher_shipping_type,
)
# when
@@ -140,7 +142,7 @@ def test_calculations_calculate_order_total_default_country_rate(order_with_line
)
-def test_calculations_calculate_order_total_voucher(order_with_lines):
+def test_calculations_calculate_order_total_voucher(order_with_lines, voucher):
# given
order = order_with_lines
prices_entered_with_tax = True
@@ -156,6 +158,7 @@ def test_calculations_calculate_order_total_voucher(order_with_lines):
translated_name="VoucherPL",
currency=order.currency,
amount_value=10,
+ voucher=voucher,
)
# when
@@ -163,7 +166,7 @@ def test_calculations_calculate_order_total_voucher(order_with_lines):
# then
assert order.total == TaxedMoney(
- net=Money("56.92", "USD"), gross=Money("70.01", "USD")
+ net=Money("56.91", "USD"), gross=Money("70.00", "USD")
)
@@ -189,7 +192,7 @@ def test_calculations_calculate_order_total_with_manual_discount(order_with_line
# then
assert order.total == TaxedMoney(
- net=Money("56.92", "USD"), gross=Money("70.01", "USD")
+ net=Money("56.91", "USD"), gross=Money("70.00", "USD")
)
@@ -243,7 +246,7 @@ def test_calculations_calculate_order_total_with_discount_for_subtotal_and_shipp
# then
assert order.total == TaxedMoney(
- net=Money("3.13", "USD"), gross=Money("5.00", "USD")
+ net=Money("4.06", "USD"), gross=Money("5.01", "USD")
)
@@ -274,7 +277,7 @@ def test_calculations_calculate_order_total_with_discount_for_more_than_order_to
def test_calculations_calculate_order_total_with_manual_discount_and_voucher(
- order_with_lines,
+ order_with_lines, voucher
):
# given
order = order_with_lines
@@ -299,6 +302,7 @@ def test_calculations_calculate_order_total_with_manual_discount_and_voucher(
translated_name="VoucherPL",
currency=order.currency,
amount_value=10,
+ voucher=voucher,
)
# when
@@ -379,6 +383,7 @@ def test_calculate_order_shipping_voucher_on_shipping(
name=voucher_shipping_type.code,
currency=currency,
amount_value=discount_amount,
+ voucher=voucher_shipping_type,
)
channel = order.channel
shipping_channel_listings = method.channel_listings.get(channel=channel)
@@ -428,6 +433,7 @@ def test_calculate_order_shipping_free_shipping_voucher(
name=voucher_shipping_type.code,
currency=currency,
amount_value=shipping_price.amount,
+ voucher=voucher_shipping_type,
)
# when
@@ -454,7 +460,6 @@ def test_update_taxes_for_order_lines(order_with_lines):
)
# then
-
for line in lines:
assert line.unit_price == TaxedMoney(
net=quantize_price(line.base_unit_price / Decimal("1.23"), currency),
@@ -479,21 +484,12 @@ def test_update_taxes_for_order_lines_voucher_on_entire_order(
currency = order.currency
prices_entered_with_tax = True
_enable_flat_rates(order, prices_entered_with_tax)
- lines = order.lines.all()
country_code = get_order_country(order)
order.voucher = voucher
lines = list(order.lines.all())
total_amount = sum([line.base_unit_price.amount * line.quantity for line in lines])
- order.undiscounted_total_gross_amount = total_amount
- order.undiscounted_total_net_amount = total_amount
- order.save(
- update_fields=[
- "voucher",
- "undiscounted_total_gross_amount",
- "undiscounted_total_net_amount",
- ]
- )
+ order.save(update_fields=["voucher"])
order_discount_amount = Decimal("5.0")
order.discounts.create(
@@ -503,9 +499,11 @@ def test_update_taxes_for_order_lines_voucher_on_entire_order(
name=voucher.code,
currency=currency,
amount_value=order_discount_amount,
+ voucher=voucher,
)
# when
+ apply_order_discounts(order, lines)
lines, _ = update_taxes_for_order_lines(
order, lines, country_code, Decimal(23), prices_entered_with_tax
)
@@ -516,10 +514,9 @@ def test_update_taxes_for_order_lines_voucher_on_entire_order(
discount_amount = quantize_price(
total_line_price.amount / total_amount * order_discount_amount, currency
)
- unit_gross = quantize_price(
- (total_line_price - Money(discount_amount, currency)) / line.quantity,
- currency,
- )
+ unit_gross = (
+ total_line_price - Money(discount_amount, currency)
+ ) / line.quantity
assert line.unit_price == TaxedMoney(
net=quantize_price(unit_gross / Decimal("1.23"), currency),
gross=quantize_price(unit_gross, currency),
@@ -575,6 +572,7 @@ def test_update_taxes_for_order_lines_voucher_on_shipping(
name=voucher_shipping_type.code,
currency=currency,
amount_value=order_discount_amount,
+ voucher=voucher_shipping_type,
)
# when
diff --git a/saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py b/saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py
index a3b01a0ec2..1c40e8844f 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py
@@ -1,5 +1,8 @@
+from decimal import Decimal
+
import pytest
+from .....core.prices import quantize_price
from ... import DEFAULT_ADDRESS
from ...product.utils.preparing_product import prepare_product
from ...promotions.utils import create_promotion, create_promotion_rule
@@ -53,7 +56,7 @@ def test_order_products_on_promotion_and_manual_order_discount_CORE_2108(
)
promotion_name = "Percentage promotion"
- discount_value = 10
+ promotion_discount_value = Decimal(10)
discount_type = "PERCENTAGE"
promotion_rule_name = "rule for product"
@@ -67,13 +70,14 @@ def test_order_products_on_promotion_and_manual_order_discount_CORE_2108(
promotion_id,
catalogue_predicate,
discount_type,
- discount_value,
+ promotion_discount_value,
promotion_rule_name,
result_channel_id,
)
product_predicate = promotion_rule["cataloguePredicate"]["productPredicate"]["ids"]
assert promotion_rule["channels"][0]["id"] == result_channel_id
assert product_predicate[0] == product_id
+ currency = "USD"
# Step 1 - Create a draft order for a product with fixed promotion
input = {
@@ -93,25 +97,29 @@ def test_order_products_on_promotion_and_manual_order_discount_CORE_2108(
lines = [{"variantId": product_variant_id, "quantity": quantity}]
order_lines = order_lines_create(e2e_staff_api_client, order_id, lines)
order_product_variant_id = order_lines["order"]["lines"][0]["variant"]["id"]
- promotion_value = round(float(product_variant_price) * discount_value / 100, 2)
+ product_variant_price = Decimal(product_variant_price)
+ promotion_value = quantize_price(
+ product_variant_price * promotion_discount_value / 100, currency
+ )
assert order_product_variant_id == product_variant_id
- unit_price = float(product_variant_price) - promotion_value
+ unit_price = product_variant_price - promotion_value
undiscounted_unit_price = order_lines["order"]["lines"][0]["undiscountedUnitPrice"][
"gross"
]["amount"]
- assert undiscounted_unit_price == float(product_variant_price)
+ assert undiscounted_unit_price == product_variant_price
assert (
order_lines["order"]["lines"][0]["unitPrice"]["gross"]["amount"] == unit_price
)
promotion_reason = order_lines["order"]["lines"][0]["unitDiscountReason"]
assert promotion_reason == f"Promotion: {promotion_id}"
+ subtotal = unit_price * quantity
# Step 3 - Add manual discount to the order
+ manual_discount_value = 2
manual_discount_input = {
"valueType": "FIXED",
- "value": 2,
+ "value": manual_discount_value,
}
-
discount_data = order_discount_add(
e2e_staff_api_client,
order_id,
@@ -121,10 +129,10 @@ def test_order_products_on_promotion_and_manual_order_discount_CORE_2108(
assert discount is not None
assert discount["type"] == "MANUAL"
assert discount["valueType"] == "FIXED"
- discount_value = discount["value"]
- assert discount_value == 2
+ assert discount["value"] == manual_discount_value
# Step 4 - Add a shipping method to the order
+ base_shipping_price = 10
input = {"shippingMethod": result_shipping_method_id}
draft_update = draft_order_update(e2e_staff_api_client, order_id, input)
order_shipping_id = draft_update["order"]["deliveryMethod"]["id"]
@@ -139,18 +147,33 @@ def test_order_products_on_promotion_and_manual_order_discount_CORE_2108(
assert order_complete_id == order_id
order_line = order["order"]["lines"][0]
assert order_line["productVariantId"] == product_variant_id
- product_price = order_line["undiscountedUnitPrice"]["gross"]["amount"]
- assert product_price == float(product_variant_price)
- assert promotion_value == order_line["unitDiscount"]["amount"]
+ product_price = quantize_price(
+ Decimal(order_line["undiscountedUnitPrice"]["gross"]["amount"]), currency
+ )
+ manual_discount_subtotal_share = (
+ subtotal / (base_shipping_price + subtotal) * manual_discount_value
+ )
+ manual_discount_shipping_share = (
+ manual_discount_value - manual_discount_subtotal_share
+ )
+ assert product_price == product_variant_price
+ assert order_line["unitDiscount"]["amount"] == promotion_value
assert order_line["unitDiscountType"] == "FIXED"
assert order_line["unitDiscountValue"] == promotion_value
assert order_line["unitDiscountReason"] == promotion_reason
product_discounted_price = product_price - promotion_value
- shipping_amount = order["order"]["shippingPrice"]["gross"]["amount"]
- assert shipping_amount == shipping_price
- subtotal = quantity * product_discounted_price - discount_value
- assert subtotal == order["order"]["subtotal"]["gross"]["amount"]
- assert subtotal == subtotal_gross_amount
+ shipping_amount = quantize_price(
+ Decimal(order["order"]["shippingPrice"]["gross"]["amount"]), currency
+ )
+ assert shipping_amount == quantize_price(
+ base_shipping_price - manual_discount_shipping_share, currency
+ )
+ assert float(shipping_amount) == shipping_price
+ subtotal = quantize_price(
+ quantity * product_discounted_price - manual_discount_subtotal_share, currency
+ )
+ assert float(subtotal) == order["order"]["subtotal"]["gross"]["amount"]
+ assert float(subtotal) == subtotal_gross_amount
total = shipping_amount + subtotal
assert total == order["order"]["total"]["gross"]["amount"]
assert total == total_gross_amount