Skip to content

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

Fix rounding issue when propagating order/checkout level discount on lines (#17024)

Iga Karbowiakcf6cfe735a57
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index c670509eef..7da5159c23 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -15,8 +15,6 @@ from ..core.taxes import zero_money
from ..discount import VoucherType
if TYPE_CHECKING:
- from decimal import Decimal
-
from ..channel.models import Channel
from .fetch import CheckoutInfo, CheckoutLineInfo, ShippingMethodInfo
@@ -225,12 +223,11 @@ def checkout_total(
return subtotal + shipping_price
-def apply_checkout_discount_on_checkout_line(
+def get_line_total_price_with_propagated_checkout_discount(
checkout_info: "CheckoutInfo",
lines: list["CheckoutLineInfo"],
checkout_line_info: "CheckoutLineInfo",
- line_total_price: Money,
-):
+) -> Money:
"""Calculate the checkout line price with discounts.
Include the entire order voucher discount or discount from order
@@ -239,87 +236,91 @@ def apply_checkout_discount_on_checkout_line(
the rate of total line price to checkout total price.
"""
voucher = checkout_info.voucher
+ base_total_price = calculate_base_line_total_price(
+ checkout_line_info,
+ )
if voucher and (
voucher.apply_once_per_order
or voucher.type in [VoucherType.SHIPPING, VoucherType.SPECIFIC_PRODUCT]
):
- return line_total_price
+ return base_total_price
if not voucher and not checkout_info.discounts:
- return line_total_price
-
- total_discount_amount = checkout_info.checkout.discount_amount
- return _get_discounted_checkout_line_price(
- checkout_line_info,
- lines,
- line_total_price,
- total_discount_amount,
- checkout_info.channel,
- )
+ return base_total_price
+
+ total_discount = checkout_info.checkout.discount
+ for (
+ checkout_line,
+ total_price,
+ ) in _propagate_checkout_discount_on_checkout_lines_prices(
+ lines, total_discount, checkout_info.channel.currency_code
+ ):
+ if checkout_line_info.line.id == checkout_line.id:
+ return total_price
+ return base_total_price
-def _get_discounted_checkout_line_price(
- checkout_line_info: "CheckoutLineInfo",
+def _propagate_checkout_discount_on_checkout_lines_prices(
lines: list["CheckoutLineInfo"],
- line_total_price: Money,
- total_discount_amount: "Decimal",
- channel: "Channel",
+ total_discount: Money,
+ currency: str,
):
"""Apply checkout discount on checkout line price.
Propagate the discount amount proportionally to total prices of items.
Ensure that the sum of discounts is equal to the discount amount.
"""
- currency = channel.currency_code
-
lines = list(lines)
+ lines_count = len(lines)
# if the checkout has a single line, the whole discount amount will be applied
# to this line
- if len(lines) == 1:
- return max(
- (line_total_price - Money(total_discount_amount, currency)),
- zero_money(currency),
- )
-
- # if the checkout has more lines we need to propagate the discount amount
- # proportionally to total prices of items
- lines_total_prices = [
- calculate_base_line_total_price(
- line_info,
- ).amount
- for line_info in lines
- if line_info.line.id != checkout_line_info.line.id
- ]
-
- total_price = sum(lines_total_prices) + line_total_price.amount
-
- last_element = lines[-1].line.id == checkout_line_info.line.id
- if last_element:
- discount_amount = _calculate_discount_for_last_element(
- lines_total_prices, total_price, total_discount_amount
+ if lines_count == 1:
+ line_info = lines[0]
+ line_total_price = calculate_base_line_total_price(line_info)
+ yield (
+ line_info.line,
+ max(
+ (line_total_price - total_discount),
+ zero_money(currency),
+ ),
)
- else:
- discount_amount = line_total_price.amount / total_price * total_discount_amount
- return max(
- (line_total_price - Money(discount_amount, currency)),
- zero_money(currency),
- )
-
-
-def _calculate_discount_for_last_element(
- lines_total_prices, total_price, total_discount_amount
-):
- """Calculate the discount for last element.
-
- If the given line is last on the list we should calculate the discount by difference
- between total discount amount and sum of discounts applied to rest of the lines,
- otherwise the sum of discounts won't be equal to the discount amount.
- """
- sum_of_discounts_other_elements = sum(
- [
- line_total_price / total_price * total_discount_amount
- for line_total_price in lines_total_prices
+ elif lines_count > 1:
+ # if the checkout has more lines we need to propagate the discount amount
+ # proportionally to total prices of items
+ lines_total_prices = [
+ calculate_base_line_total_price(
+ line_info,
+ )
+ for line_info in lines
]
- )
- return total_discount_amount - sum_of_discounts_other_elements
+
+ total_price = sum(lines_total_prices, start=Money(0, currency))
+ remaining_discount = total_discount
+ for idx, line_info in enumerate(lines):
+ line = line_info.line
+ if not total_price:
+ yield line, zero_money(currency)
+ elif idx < lines_count - 1:
+ line_total_price = lines_total_prices[idx]
+ share = line_total_price / total_price
+ discount = quantize_price(
+ min(share * total_discount, line_total_price), currency
+ )
+ yield (
+ line,
+ max(
+ (line_total_price - discount),
+ zero_money(currency),
+ ),
+ )
+ remaining_discount -= discount
+ else:
+ line_total_price = lines_total_prices[idx]
+ yield (
+ line,
+ max(
+ (line_total_price - remaining_discount),
+ zero_money(currency),
+ ),
+ )
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index d52bb7efa9..0c73061105 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -635,11 +635,10 @@ def _set_checkout_base_prices(
for line_info in lines:
line = line_info.line
- quantity = line.quantity
-
- unit_price = base_calculations.calculate_base_line_unit_price(line_info)
- total_price = base_calculations.apply_checkout_discount_on_checkout_line(
- checkout_info, lines, line_info, unit_price * quantity
+ total_price = (
+ base_calculations.get_line_total_price_with_propagated_checkout_discount(
+ checkout_info, lines, line_info
+ )
)
line_total_price = quantize_price(total_price, currency)
subtotal += line_total_price
diff --git a/saleor/order/base_calculations.py b/saleor/order/base_calculations.py
index 8a5c720604..42b8a70856 100644
--- a/saleor/order/base_calculations.py
+++ b/saleor/order/base_calculations.py
@@ -245,7 +245,10 @@ def propagate_order_discount_on_order_lines_prices(
share = (
line.base_unit_price_amount * line.quantity / base_subtotal.amount
)
- discount = min(share * subtotal_discount, base_subtotal)
+ discount = quantize_price(
+ min(share * subtotal_discount, base_subtotal),
+ base_subtotal.currency,
+ )
yield (
line,
_get_total_price_with_subtotal_discount_for_order_line(
@@ -290,8 +293,7 @@ def apply_subtotal_discount_to_order_lines(
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_net = total_price
line.total_price_gross = line.total_price_net
line.undiscounted_total_price_gross_amount = (
line.undiscounted_total_price_net_amount
diff --git a/saleor/order/tests/fixtures/order.py b/saleor/order/tests/fixtures/order.py
index 00df0e736a..79ee5fb594 100644
--- a/saleor/order/tests/fixtures/order.py
+++ b/saleor/order/tests/fixtures/order.py
@@ -259,6 +259,73 @@ def order_list_with_cc_orders(orders, warehouse_for_cc):
return orders
+def order_lines_generator():
+ def create_order_line(
+ order, variants, unit_prices, quantities, create_allocations=True
+ ):
+ channel = order.channel
+ order_lines = []
+ allocations = []
+ stocks_to_update = []
+ variant_channel_listings_map = {
+ cl.variant_id: cl
+ for cl in ProductVariantChannelListing.objects.filter(
+ variant__in=variants, channel=channel
+ )
+ }
+ for variant, price, quantity in zip(variants, unit_prices, quantities):
+ product = variant.product
+ variant_channel_listing = variant_channel_listings_map[variant.id]
+ currency = channel.currency_code
+ base_price = Money(price, currency)
+ net = Money(price, channel.currency_code)
+ gross = Money(amount=net.amount * Decimal(1.23), currency=currency)
+ unit_price = TaxedMoney(net=net, gross=gross)
+ order_line = OrderLine(
+ order=order,
+ product_name=str(product),
+ variant_name=str(variant),
+ product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
+ is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
+ quantity=quantity,
+ variant=variant,
+ unit_price=unit_price,
+ total_price=unit_price * quantity,
+ undiscounted_unit_price=unit_price,
+ undiscounted_total_price=unit_price * quantity,
+ base_unit_price=base_price,
+ undiscounted_base_unit_price=base_price,
+ tax_rate=Decimal("0.23"),
+ **get_tax_class_kwargs_for_order_line(product.product_type.tax_class),
+ )
+ order_lines.append(order_line)
+ variant_channel_listing.price_amount = price
+ variant_channel_listing.discounted_price_amount = price
+ if create_allocations:
+ stock = variant.stocks.first()
+ allocation = Allocation(
+ order_line=order_line, stock=stock, quantity_allocated=quantity
+ )
+ allocations.append(allocation)
+ stock.quantity_allocated += quantity
+ stocks_to_update.append(stock)
+
+ OrderLine.objects.bulk_create(order_lines)
+ if allocations:
+ Allocation.objects.bulk_create(allocations)
+ Stock.objects.bulk_update(stocks_to_update, ["quantity_allocated"])
+ ProductVariantChannelListing.objects.bulk_update(
+ variant_channel_listings_map.values(),
+ ["price_amount", "discounted_price_amount"],
+ )
+ return order_lines
+
+ return create_order_line
+
+
@pytest.fixture
def order_with_lines(
order,
@@ -268,6 +335,7 @@ def order_with_lines(
warehouse,
channel_USD,
default_tax_class,
+ order_lines_generator,
):
product = Product.objects.create(
name="Test product",
@@ -283,47 +351,17 @@ def order_with_lines(
visible_in_listings=True,
available_for_purchase_at=datetime.datetime.now(tz=datetime.UTC),
)
- variant = ProductVariant.objects.create(product=product, sku="SKU_AA")
- channel_listing = ProductVariantChannelListing.objects.create(
- variant=variant,
+ variant_1_quantity = 3
+ variant_1 = ProductVariant.objects.create(product=product, sku="SKU_AA")
+ ProductVariantChannelListing.objects.create(
+ variant=variant_1,
channel=channel_USD,
price_amount=Decimal(10),
discounted_price_amount=Decimal(10),
cost_price_amount=Decimal(1),
currency=channel_USD.currency_code,
)
- quantity = 3
- stock = Stock.objects.create(
- warehouse=warehouse,
- product_variant=variant,
- quantity=5,
- quantity_allocated=quantity,
- )
- base_price = variant.get_price(channel_listing)
- currency = base_price.currency
- gross = Money(amount=base_price.amount * Decimal(1.23), currency=currency)
- unit_price = TaxedMoney(net=base_price, gross=gross)
- line = order.lines.create(
- product_name=str(variant.product),
- variant_name=str(variant),
- product_sku=variant.sku,
- product_variant_id=variant.get_global_id(),
- is_shipping_required=variant.is_shipping_required(),
- is_gift_card=variant.is_gift_card(),
- quantity=quantity,
- variant=variant,
- unit_price=unit_price,
- total_price=unit_price * quantity,
- undiscounted_unit_price=unit_price,
- undiscounted_total_price=unit_price * quantity,
- base_unit_price=base_price,
- undiscounted_base_unit_price=base_price,
- tax_rate=Decimal("0.23"),
- **get_tax_class_kwargs_for_order_line(product_type.tax_class),
- )
- Allocation.objects.create(
- order_line=line, stock=stock, quantity_allocated=line.quantity
- )
+ Stock.objects.create(warehouse=warehouse, product_variant=variant_1, quantity=5)
product = Product.objects.create(
name="Test product 2",
@@ -339,48 +377,23 @@ def order_with_lines(
visible_in_listings=True,
available_for_purchase_at=timezone.now(),
)
- variant = ProductVariant.objects.create(product=product, sku="SKU_B")
- channel_listing = ProductVariantChannelListing.objects.create(
- variant=variant,
+ variant_2 = ProductVariant.objects.create(product=product, sku="SKU_B")
+ variant_2_quantity = 2
+ ProductVariantChannelListing.objects.create(
+ variant=variant_2,
channel=channel_USD,
price_amount=Decimal(20),
discounted_price_amount=Decimal(20),
cost_price_amount=Decimal(2),
currency=channel_USD.currency_code,
)
- quantity = 2
- stock = Stock.objects.create(
- product_variant=variant,
- warehouse=warehouse,
- quantity=2,
- quantity_allocated=quantity,
- )
- stock.refresh_from_db()
+ Stock.objects.create(warehouse=warehouse, product_variant=variant_2, quantity=2)
- base_price = variant.get_price(channel_listing)
- currency = base_price.currency
- gross = Money(amount=base_price.amount * Decimal(1.23), currency=currency)
- unit_price = TaxedMoney(net=base_price, gross=gross)
- line = order.lines.create(
- product_name=str(variant.product),
- variant_name=str(variant),
- product_sku=variant.sku,
- product_variant_id=variant.get_global_id(),
- is_shipping_required=variant.is_shipping_required(),
- is_gift_card=variant.is_gift_card(),
- quantity=quantity,
- variant=variant,
- unit_price=unit_price,
- total_price=unit_price * quantity,
- undiscounted_unit_price=unit_price,
- undiscounted_total_price=unit_price * quantity,
- base_unit_price=base_price,
- undiscounted_base_unit_price=base_price,
- tax_rate=Decimal("0.23"),
- **get_tax_class_kwargs_for_order_line(product_type.tax_class),
- )
- Allocation.objects.create(
- order_line=line, stock=stock, quantity_allocated=line.quantity
+ order_lines_generator(
+ order,
+ [variant_1, variant_2],
+ [10, 20],
+ [variant_1_quantity, variant_2_quantity],
)
order.shipping_address = order.billing_address.get_copy()
diff --git a/saleor/order/tests/test_fetch_order_prices.py b/saleor/order/tests/test_fetch_order_prices.py
index 0a4f29b815..7fba6362d5 100644
--- a/saleor/order/tests/test_fetch_order_prices.py
+++ b/saleor/order/tests/test_fetch_order_prices.py
@@ -4,7 +4,7 @@ import before_after
import graphene
import pytest
-from ...core.prices import quantize_price
+from ...core.prices import Money, quantize_price
from ...core.taxes import zero_money
from ...discount import DiscountType, DiscountValueType, VoucherType
from ...discount.models import (
@@ -173,7 +173,9 @@ def test_fetch_order_prices_order_discount_flat_rates(
line_1_base_total = line_1.quantity * line_1.base_unit_price_amount
line_2_base_total = line_2.quantity * line_2.base_unit_price_amount
base_total = line_1_base_total + line_2_base_total
- line_1_order_discount_portion = reward_amount * line_1_base_total / base_total
+ line_1_order_discount_portion = quantize_price(
+ reward_amount * line_1_base_total / base_total, currency
+ )
line_2_order_discount_portion = reward_amount - line_1_order_discount_portion
assert discount.order == order
@@ -206,8 +208,8 @@ def test_fetch_order_prices_order_discount_flat_rates(
== variant_1_undiscounted_unit_price * tax_rate
)
assert line_1.total_price_net_amount == line_1_total_net_amount
- assert line_1.total_price_gross_amount == round_down(
- line_1_total_net_amount * tax_rate
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1_total_net_amount * tax_rate, currency
)
assert line_1.base_unit_price_amount == variant_1_undiscounted_unit_price
assert line_1.unit_price_net_amount == line_1_total_net_amount / line_1.quantity
@@ -238,8 +240,8 @@ def test_fetch_order_prices_order_discount_flat_rates(
== variant_2_undiscounted_unit_price * tax_rate
)
assert line_2.total_price_net_amount == line_2_total_net_amount
- assert line_2.total_price_gross_amount == round_up(
- line_2_total_net_amount * tax_rate
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2_total_net_amount * tax_rate, currency
)
assert line_2.base_unit_price_amount == variant_2_undiscounted_unit_price
assert line_2.unit_price_net_amount == quantize_price(
@@ -469,14 +471,14 @@ def test_fetch_order_prices_catalogue_and_order_discounts_flat_rates(
)
assert line_1.base_unit_price_amount == variant_1_undiscounted_unit_price
assert line_1.total_price_net_amount == line_1_total_net_amount
- assert line_1.total_price_gross_amount == round_up(
- line_1_total_net_amount * tax_rate
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1_total_net_amount * tax_rate, currency
)
assert line_1.unit_price_net_amount == quantize_price(
line_1_total_net_amount / line_1.quantity, currency
)
- assert line_1.unit_price_gross_amount == round_up(
- line_1.unit_price_net_amount * tax_rate
+ assert line_1.unit_price_gross_amount == quantize_price(
+ line_1.unit_price_net_amount * tax_rate, currency
)
assert catalogue_discount.line == line_2
@@ -515,8 +517,8 @@ def test_fetch_order_prices_catalogue_and_order_discounts_flat_rates(
== variant_2_undiscounted_unit_price - rule_catalogue_reward
)
assert line_2.total_price_net_amount == line_2_total_net_amount
- assert line_2.total_price_gross_amount == round_down(
- line_2_total_net_amount * tax_rate
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2_total_net_amount * tax_rate, currency
)
assert line_2.unit_price_net_amount == quantize_price(
line_2_total_net_amount / line_2.quantity, currency
@@ -1991,26 +1993,24 @@ def test_fetch_order_prices_manual_order_discount_and_voucher_apply_once_per_ord
discounted_line, line_1 = lines
voucher_discount_amount = discount_amount
order.refresh_from_db()
- assert order.total_gross_amount == quantize_price(
+ assert order.total_net_amount == quantize_price(
(
subtotal.amount
+ shipping_price.amount
- voucher_discount_amount
- order_discount_amount
- )
- * tax_rate,
+ ),
currency,
)
- shipping_discount = shipping_price - order.shipping_price_net
- subtotal_order_discount = order_discount_amount - shipping_discount.amount
- assert order.subtotal_gross_amount == quantize_price(
- (subtotal.amount - subtotal_order_discount - voucher_discount_amount)
- * tax_rate,
- currency,
+ assert order.total_gross_amount == (
+ discounted_line.total_price_gross_amount
+ + line_1.total_price_gross_amount
+ + order.shipping_price_gross_amount
)
assert order.undiscounted_total_gross == quantize_price(
(subtotal + shipping_price) * tax_rate, currency
)
+ shipping_discount = shipping_price - order.shipping_price_net
assert order.shipping_price_gross == quantize_price(
(shipping_price - shipping_discount) * tax_rate, currency
)
@@ -2023,8 +2023,11 @@ def test_fetch_order_prices_manual_order_discount_and_voucher_apply_once_per_ord
== discounted_line.undiscounted_base_unit_price_amount - unit_discount_amount
)
assert (
- discounted_line.total_price_gross_amount
- == discounted_line.unit_price_gross_amount * discounted_line.quantity
+ quantize_price(
+ discounted_line.total_price_gross_amount / discounted_line.quantity,
+ currency,
+ )
+ == discounted_line.unit_price_gross_amount
)
assert (
discounted_line.undiscounted_total_price_gross_amount
@@ -2458,6 +2461,102 @@ def test_fetch_order_prices_voucher_entire_order_fixed(
assert line_2.unit_price_net_amount == line_2_total_net_amount / line_2.quantity
+def test_fetch_order_prices_voucher_entire_order_multiple_lines(
+ order,
+ voucher,
+ plugins_manager,
+ order_lines_generator,
+ product_list,
+ tax_configuration_flat_rates,
+):
+ # given
+ assert voucher.type == VoucherType.ENTIRE_ORDER
+ assert voucher.discount_value_type == DiscountValueType.FIXED
+
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ discount_amount = Decimal("3")
+ voucher_listing.discount_value = discount_amount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.name = "Voucher name"
+ voucher.save(update_fields=["name"])
+
+ code = voucher.codes.first().code
+ order.voucher = voucher
+ order.voucher_code = code
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+
+ variant_list = [product.variants.first() for product in product_list[:3]]
+ unit_prices = [7, 33, 25]
+ quantities = [1, 1, 1]
+ lines = order_lines_generator(order, variant_list, unit_prices, quantities)
+
+ subtotal = Money(sum(unit_prices), currency)
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ assert OrderDiscount.objects.count() == 1
+ discount = order.discounts.first()
+ assert discount.voucher == voucher
+ assert discount.value_type == voucher.discount_value_type
+ assert discount.value == discount_amount
+ assert discount.amount_value == discount_amount
+ assert discount.reason == f"Voucher code: {code}"
+ assert discount.name == voucher.name
+ assert discount.type == DiscountType.VOUCHER
+ assert discount.voucher_code == code
+ # TODO (SHOPX-914): set translated voucher name
+ assert discount.translated_name == ""
+
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price * tax_rate
+ assert order.subtotal_net_amount == subtotal.amount - discount_amount
+ assert order.subtotal_gross_amount == (subtotal.amount - discount_amount) * tax_rate
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ )
+ assert order.undiscounted_total_net == subtotal + shipping_price
+ assert order.undiscounted_total_gross == (subtotal + shipping_price) * tax_rate
+
+ remaining_discount = discount_amount
+ for idx, line in enumerate(lines):
+ line.refresh_from_db()
+ idx = variant_list.index(line.variant)
+ base_price = unit_prices[idx]
+ line_base_total = base_price
+ if idx < len(lines) - 1:
+ line_order_discount_portion = quantize_price(
+ discount_amount * line_base_total / subtotal.amount, currency
+ )
+ remaining_discount -= line_order_discount_portion
+ else:
+ line_order_discount_portion = remaining_discount
+
+ line_total_net_amount = (
+ line.undiscounted_total_price_net_amount - line_order_discount_portion
+ )
+ assert line.undiscounted_total_price_net_amount == base_price
+ assert line.undiscounted_unit_price_net_amount == base_price
+ assert line.total_price_net_amount == line_total_net_amount
+ assert line.base_unit_price_amount == base_price
+ assert line.unit_price_net_amount == line_total_net_amount
+
+
def test_fetch_order_prices_voucher_entire_order_percentage(
order_with_lines,
voucher,
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 1e5e3d5516..b8c1c96a80 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -448,15 +448,13 @@ class PluginsManager(PaymentInterface):
address: Optional["Address"],
plugin_ids: Optional[list[str]] = None,
) -> TaxedMoney:
- default_value = base_calculations.calculate_base_line_total_price(
- checkout_line_info,
- )
# apply entire order discount or discount from order promotion
- default_value = base_calculations.apply_checkout_discount_on_checkout_line(
- checkout_info,
- lines,
- checkout_line_info,
- default_value,
+ default_value = (
+ base_calculations.get_line_total_price_with_propagated_checkout_discount(
+ checkout_info,
+ lines,
+ checkout_line_info,
+ )
)
default_value = quantize_price(default_value, checkout_info.checkout.currency)
default_taxed_value = TaxedMoney(net=default_value, gross=default_value)
@@ -525,15 +523,13 @@ class PluginsManager(PaymentInterface):
plugin_ids: Optional[list[str]] = None,
) -> TaxedMoney:
quantity = checkout_line_info.line.quantity
- default_value = base_calculations.calculate_base_line_unit_price(
- checkout_line_info
- )
# apply entire order discount
- total_value = base_calculations.apply_checkout_discount_on_checkout_line(
- checkout_info,
- lines,
- checkout_line_info,
- default_value * quantity,
+ total_value = (
+ base_calculations.get_line_total_price_with_propagated_checkout_discount(
+ checkout_info,
+ lines,
+ checkout_line_info,
+ )
)
default_taxed_value = TaxedMoney(
net=total_value / quantity, gross=total_value / quantity
diff --git a/saleor/tax/calculations/checkout.py b/saleor/tax/calculations/checkout.py
index 8c5f0a8eda..4da3e0defb 100644
--- a/saleor/tax/calculations/checkout.py
+++ b/saleor/tax/calculations/checkout.py
@@ -102,14 +102,12 @@ def calculate_checkout_line_total(
tax_rate: Decimal,
prices_entered_with_tax: bool,
) -> TaxedMoney:
- base_total_price = base_calculations.calculate_base_line_total_price(
- checkout_line_info,
- )
- total_price = base_calculations.apply_checkout_discount_on_checkout_line(
- checkout_info,
- lines,
- checkout_line_info,
- base_total_price,
+ total_price = (
+ base_calculations.get_line_total_price_with_propagated_checkout_discount(
+ checkout_info,
+ lines,
+ checkout_line_info,
+ )
)
total_price = calculate_flat_rate_tax(
total_price, tax_rate, prices_entered_with_tax
diff --git a/saleor/tax/tests/test_checkout_calculations.py b/saleor/tax/tests/test_checkout_calculations.py
index d9f1028d92..f96ea88ae1 100644
--- a/saleor/tax/tests/test_checkout_calculations.py
+++ b/saleor/tax/tests/test_checkout_calculations.py
@@ -11,6 +11,7 @@ from ...discount.utils.checkout import (
create_checkout_discount_objects_for_order_promotions,
)
from ...plugins.manager import get_plugins_manager
+from ...product.models import ProductVariantChannelListing
from ...tax.models import TaxClassCountryRate
from .. import TaxCalculationStrategy
from ..calculations.checkout import (
@@ -801,6 +802,106 @@ def test_calculate_checkout_line_total_with_voucher_multiple_lines_last_line(
)
+def test_calculate_checkout_line_total_with_voucher_for_multiple_lines(
+ checkout, shipping_zone, address, voucher, product_list
+):
+ # given
+ manager = get_plugins_manager(allow_replica=False)
+
+ rate = Decimal(23)
+ prices_entered_with_tax = True
+ _enable_flat_rates(checkout, prices_entered_with_tax)
+
+ currency = checkout.currency
+
+ # prepare the checkout with line prices and discount value that might
+ # result in rounding issues
+ checkout_info = fetch_checkout_info(checkout, [], manager)
+ variant_1 = product_list[0].variants.last()
+ variant_2 = product_list[1].variants.last()
+ variant_3 = product_list[2].variants.last()
+
+ variant_ids = [variant_1.id, variant_2.id, variant_3.id]
+ channel_listings = list(
+ ProductVariantChannelListing.objects.filter(
+ variant_id__in=variant_ids, channel_id=checkout.channel_id
+ )
+ )
+
+ line_prices = [7, 33, 25]
+ for listing in channel_listings:
+ price = line_prices[variant_ids.index(listing.variant_id)]
+ listing.price_amount = price
+ listing.discounted_price_amount = price
+
+ ProductVariantChannelListing.objects.bulk_update(
+ channel_listings, ["price_amount", "discounted_price_amount"]
+ )
+
+ qty = 1
+ add_variant_to_checkout(checkout_info, variant_1, qty)
+ add_variant_to_checkout(checkout_info, variant_2, qty)
+ add_variant_to_checkout(checkout_info, variant_3, qty)
+
+ method = shipping_zone.shipping_methods.get()
+ checkout.shipping_address = address
+ checkout.shipping_method_name = method.name
+ checkout.shipping_method = method
+ discount_amount = Decimal("3")
+ checkout.discount_amount = discount_amount
+ checkout.voucher_code = voucher.code
+ checkout.save()
+
+ line = checkout.lines.last()
+ variant = line.variant
+ product = variant.product
+ product.tax_class.country_rates.update_or_create(country=address.country, rate=rate)
+
+ total_price = Money(sum(line_prices), currency)
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
+ result_total_prices = []
+ for line_info in lines:
+ result_total_prices.append(
+ calculate_checkout_line_total(
+ checkout_info,
+ lines,
+ line_info,
+ rate,
+ prices_entered_with_tax,
+ )
+ )
+
+ # then
+ remaining_discount = discount_amount
+ assert (
+ sum(line_prices)
+ - sum([total_price.gross.amount for total_price in result_total_prices])
+ == discount_amount
+ )
+ for idx, line_total_price in enumerate(result_total_prices):
+ base_price = line_prices[idx]
+ line_base_total = Money(base_price, currency)
+ if idx < len(lines) - 1:
+ line_discount_amount = quantize_price(
+ discount_amount * line_base_total / total_price, currency
+ )
+ remaining_discount -= line_discount_amount
+ else:
+ line_discount_amount = remaining_discount
+
+ expected_total_line_price = line_base_total - Money(
+ line_discount_amount, currency
+ )
+ assert line_total_price == TaxedMoney(
+ net=quantize_price(expected_total_line_price / Decimal("1.23"), currency),
+ gross=quantize_price(expected_total_line_price, currency),
+ )
+
+
def test_calculate_checkout_line_total_with_shipping_voucher(
checkout_with_item,
shipping_zone,
diff --git a/saleor/tax/tests/test_order_calculations.py b/saleor/tax/tests/test_order_calculations.py
index d32084f7ba..43771b332c 100644
--- a/saleor/tax/tests/test_order_calculations.py
+++ b/saleor/tax/tests/test_order_calculations.py
@@ -250,7 +250,7 @@ def test_calculations_calculate_order_total_with_discount_for_subtotal_and_shipp
# then
assert order.total == TaxedMoney(
- net=Money("4.06", "USD"), gross=Money("5.01", "USD")
+ net=Money("4.07", "USD"), gross=Money("5.01", "USD")
)
@@ -315,7 +315,7 @@ def test_calculations_calculate_order_total_with_manual_discount_and_voucher(
# then
assert order.total == TaxedMoney(
- net=Money("48.78", "USD"), gross=Money("60.00", "USD")
+ net=Money("48.77", "USD"), gross=Money("60.00", "USD")
)
diff --git a/saleor/tests/e2e/orders/discounts/test_order_products_on_catalog_promotion_and_voucher_entire.py b/saleor/tests/e2e/orders/discounts/test_order_products_on_catalog_promotion_and_voucher_entire.py
index 4484b7f79a..83488672da 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_products_on_catalog_promotion_and_voucher_entire.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_products_on_catalog_promotion_and_voucher_entire.py
@@ -1,3 +1,5 @@
+from decimal import Decimal
+
import pytest
from .....product.tasks import recalculate_discounted_price_for_products_task
@@ -278,16 +280,17 @@ def test_order_products_on_catalog_promotion_and_voucher_entire_order_CORE_2131(
assert order_id is not None
# Step 2 - Add order lines to the order
+ quantity = 2
lines = [
- {"variantId": product_variant_id_1, "quantity": 2},
- {"variantId": product_variant_id_2, "quantity": 2},
+ {"variantId": product_variant_id_1, "quantity": quantity},
+ {"variantId": product_variant_id_2, "quantity": quantity},
]
order = order_lines_create(e2e_staff_api_client, order_id, lines)
order_product1_variant_id = order["order"]["lines"][0]
order_product2_variant_id = order["order"]["lines"][1]
# Assert lines:
- expected_product1_unit_price = round(
+ expected_product1_unit_price_after_catalogue_promotion = round(
product1_variant_price
- (product1_variant_price * (catalog_promotion_value / 100)),
2,
@@ -303,18 +306,32 @@ def test_order_products_on_catalog_promotion_and_voucher_entire_order_CORE_2131(
)
assert (
order_product1_variant_id["unitPrice"]["gross"]["amount"]
- == expected_product1_unit_price
+ == expected_product1_unit_price_after_catalogue_promotion
)
assert (
order_product1_variant_id["unitPrice"]["gross"]["amount"]
!= order_product1_variant_id["undiscountedUnitPrice"]["gross"]["amount"]
)
-
- expected_product2_unit_price = round(
- product2_variant_price
- - (product2_variant_price * (catalog_promotion_value / 100)),
+ expected_product1_total_price_after_catalogue_promotion = round(
+ expected_product1_unit_price_after_catalogue_promotion * quantity, 2
+ )
+ assert (
+ order_product1_variant_id["totalPrice"]["gross"]["amount"]
+ == expected_product1_total_price_after_catalogue_promotion
+ )
+ expected_product1_tax = round(
+ (expected_product1_total_price_after_catalogue_promotion * country_tax_rate)
+ / (100 + country_tax_rate),
2,
)
+ assert (
+ order_product1_variant_id["totalPrice"]["tax"]["amount"]
+ == expected_product1_tax
+ )
+
+ expected_product2_unit_price_after_catalogue_promotion = product2_variant_price - (
+ product2_variant_price * (catalog_promotion_value / 100)
+ )
assert order_product2_variant_id["variant"]["id"] == product_variant_id_2
assert (
order_product2_variant_id["unitDiscountReason"] == f"Promotion: {promotion_id}"
@@ -324,18 +341,34 @@ def test_order_products_on_catalog_promotion_and_voucher_entire_order_CORE_2131(
assert order_product2_variant_id["unitDiscount"]["amount"] == round(
product2_variant_price * (catalog_promotion_value / 100), 2
)
- assert (
- order_product2_variant_id["unitPrice"]["gross"]["amount"]
- == expected_product2_unit_price
+ assert order_product2_variant_id["unitPrice"]["gross"]["amount"] == round(
+ expected_product2_unit_price_after_catalogue_promotion, 2
)
assert (
order_product2_variant_id["unitPrice"]["gross"]["amount"]
!= order_product2_variant_id["undiscountedUnitPrice"]["gross"]["amount"]
)
+ expected_product2_total_price_after_catalogue_promotion = (
+ expected_product2_unit_price_after_catalogue_promotion * quantity
+ )
+ assert order_product2_variant_id["totalPrice"]["gross"]["amount"] == round(
+ expected_product2_total_price_after_catalogue_promotion, 2
+ )
+ expected_product2_tax = round(
+ (expected_product2_total_price_after_catalogue_promotion * country_tax_rate)
+ / (100 + country_tax_rate),
+ 2,
+ )
+ assert (
+ order_product2_variant_id["totalPrice"]["tax"]["amount"]
+ == expected_product2_tax
+ )
# Assert subtotal:
expected_subtotal_gross = round(
- (expected_product1_unit_price * 2 + expected_product2_unit_price * 2), 2
+ expected_product1_total_price_after_catalogue_promotion
+ + expected_product2_total_price_after_catalogue_promotion,
+ 2,
)
assert order["order"]["subtotal"]["gross"]["amount"] == expected_subtotal_gross
expected_subtotal_tax = round(
@@ -388,28 +421,94 @@ def test_order_products_on_catalog_promotion_and_voucher_entire_order_CORE_2131(
order = draft_order_update(
e2e_staff_api_client, order_id, {"voucherCode": voucher_code}
)
+
# Assert voucher
assert order["order"]["voucherCode"] == voucher_code
assert order["order"]["discounts"][0]["type"] == "VOUCHER"
assert order["order"]["discounts"][0]["value"] == voucher_discount_value
- assert order["order"]["discounts"][0]["amount"]["amount"] == round(
+ voucher_discount_amount = round(
expected_subtotal_gross * (voucher_discount_value / 100), 2
)
+ assert order["order"]["discounts"][0]["amount"]["amount"] == voucher_discount_amount
+
+ # Assert line prices
+ order_product1_variant_id = order["order"]["lines"][0]
+ order_product2_variant_id = order["order"]["lines"][1]
+
+ product1_voucher_discount_share = round(
+ voucher_discount_amount
+ * expected_product1_total_price_after_catalogue_promotion
+ / expected_subtotal_gross,
+ 2,
+ )
+ expected_product1_total_price = round(
+ expected_product1_total_price_after_catalogue_promotion
+ - product1_voucher_discount_share,
+ 2,
+ )
+ assert (
+ order_product1_variant_id["totalPrice"]["gross"]["amount"]
+ == expected_product1_total_price
+ )
+ expected_product1_tax = round(
+ (expected_product1_total_price * country_tax_rate) / (100 + country_tax_rate), 2
+ )
+ assert (
+ order_product1_variant_id["totalPrice"]["tax"]["amount"]
+ == expected_product1_tax
+ )
+ expected_product1_net = round(
+ expected_product1_total_price - expected_product1_tax, 2
+ )
+ assert (
+ order_product1_variant_id["totalPrice"]["net"]["amount"]
+ == expected_product1_net
+ )
+ assert order_product1_variant_id["unitPrice"]["gross"]["amount"] == round(
+ expected_product1_total_price / quantity, 2
+ )
+
+ product2_voucher_discount_share = (
+ voucher_discount_amount - product1_voucher_discount_share
+ )
+ expected_product2_total_price = (
+ expected_product2_total_price_after_catalogue_promotion
+ - product2_voucher_discount_share
+ )
+ assert order_product2_variant_id["totalPrice"]["gross"]["amount"] == round(
+ expected_product2_total_price, 2
+ )
+ expected_product2_tax = round(
+ (expected_product2_total_price * country_tax_rate) / (100 + country_tax_rate), 2
+ )
+ assert (
+ order_product2_variant_id["totalPrice"]["tax"]["amount"]
+ == expected_product2_tax
+ )
+ expected_product2_net = round(
+ expected_product2_total_price - expected_product2_tax, 2
+ )
+ assert (
+ order_product2_variant_id["totalPrice"]["net"]["amount"]
+ == expected_product2_net
+ )
+ assert order_product2_variant_id["unitPrice"]["gross"]["amount"] == float(
+ round(Decimal(str(expected_product2_total_price / quantity)), 2)
+ )
# Assert subtotal with voucher
subtotal_gross_with_voucher = round(
- expected_subtotal_gross * (1 - (voucher_discount_value / 100)), 2
+ expected_subtotal_gross - voucher_discount_amount, 2
)
assert order["order"]["subtotal"]["gross"]["amount"] == subtotal_gross_with_voucher
- subtotal_tax_with_voucher = round(
- (subtotal_gross_with_voucher * country_tax_rate) / (100 + country_tax_rate),
- 2,
- )
- assert order["order"]["subtotal"]["tax"]["amount"] == subtotal_tax_with_voucher
+ subtotal_net_with_voucher = expected_product1_net + expected_product2_net
+ assert order["order"]["subtotal"]["net"]["amount"] == subtotal_net_with_voucher
# Assert shipping price is the same
assert order["order"]["shippingPrice"]["gross"]["amount"] == shipping_price
assert order["order"]["shippingPrice"]["tax"]["amount"] == expected_shipping_tax
+ expected_shipping_net = shipping_price - expected_shipping_tax
+ assert order["order"]["shippingPrice"]["net"]["amount"] == expected_shipping_net
assert order["order"]["undiscountedShippingPrice"]["amount"] == shipping_price
# Assert total with voucher
@@ -418,20 +517,20 @@ def test_order_products_on_catalog_promotion_and_voucher_entire_order_CORE_2131(
2,
)
assert order["order"]["total"]["gross"]["amount"] == total_gross_with_voucher
- total_tax_with_voucher = round(
- (total_gross_with_voucher * country_tax_rate) / (100 + country_tax_rate),
+ total_net_with_voucher = round(
+ expected_shipping_net + subtotal_net_with_voucher,
2,
)
- assert order["order"]["total"]["tax"]["amount"] == total_tax_with_voucher
+ assert order["order"]["total"]["net"]["amount"] == total_net_with_voucher
# Step 5 - Complete the draft order
order = draft_order_complete(e2e_staff_api_client, order_id)
completed_order = order["order"]
assert completed_order["status"] == "UNFULFILLED"
assert completed_order["total"]["gross"]["amount"] == total_gross_with_voucher
- assert completed_order["total"]["tax"]["amount"] == total_tax_with_voucher
+ assert completed_order["total"]["net"]["amount"] == total_net_with_voucher
assert completed_order["subtotal"]["gross"]["amount"] == subtotal_gross_with_voucher
- assert completed_order["subtotal"]["tax"]["amount"] == subtotal_tax_with_voucher
+ assert completed_order["subtotal"]["net"]["amount"] == subtotal_net_with_voucher
assert completed_order["shippingPrice"]["gross"]["amount"] == shipping_price
assert completed_order["shippingPrice"]["tax"]["amount"] == expected_shipping_tax
assert (
diff --git a/saleor/tests/e2e/orders/utils/draft_order_update.py b/saleor/tests/e2e/orders/utils/draft_order_update.py
index 8c691731bb..9e0f522908 100644
--- a/saleor/tests/e2e/orders/utils/draft_order_update.py
+++ b/saleor/tests/e2e/orders/utils/draft_order_update.py
@@ -29,6 +29,9 @@ mutation DraftOrderUpdate($input: DraftOrderInput!, $id: ID!) {
total {
...BaseTaxedMoney
}
+ undiscountedTotal {
+ ...BaseTaxedMoney
+ }
voucherCode
voucher {
id