Skip to content

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

Unify checkout and order calculations (#16214) (#16237)

Iga Karbowiak04e23f05cc83
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index 137489cd8a..34e2c2c39a 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -13,7 +13,7 @@ from prices import Money
from ..core.prices import quantize_price
from ..core.taxes import zero_money
-from ..discount import DiscountValueType, VoucherType
+from ..discount import VoucherType
if TYPE_CHECKING:
from decimal import Decimal
@@ -24,7 +24,6 @@ if TYPE_CHECKING:
def calculate_base_line_unit_price(
line_info: "CheckoutLineInfo",
- channel: "Channel",
) -> Money:
"""Calculate line unit price including discounts and vouchers.
@@ -32,9 +31,7 @@ def calculate_base_line_unit_price(
voucher discounts.
The price does not include the entire order discount.
"""
- total_line_price = calculate_base_line_total_price(
- line_info=line_info, channel=channel
- )
+ total_line_price = calculate_base_line_total_price(line_info=line_info)
quantity = line_info.line.quantity
currency = total_line_price.currency
return quantize_price(total_line_price / quantity, currency)
@@ -42,7 +39,6 @@ def calculate_base_line_unit_price(
def calculate_base_line_total_price(
line_info: "CheckoutLineInfo",
- channel: "Channel",
include_voucher: bool = True,
) -> Money:
"""Calculate line total price including discounts and vouchers.
@@ -52,10 +48,9 @@ def calculate_base_line_total_price(
The price does not include order promotions and the entire order vouchers.
When the line is gift reward, the price is zero.
"""
- variant = line_info.variant
- currency = line_info.channel_listing.currency
- quantity = line_info.line.quantity
+ from ..discount.utils import calculate_line_discount_amount_from_voucher
+ variant = line_info.variant
variant_price = variant.get_base_price(
line_info.channel_listing, line_info.line.price_override
)
@@ -67,39 +62,10 @@ def calculate_base_line_total_price(
total_price -= discount_amount
if include_voucher and line_info.voucher:
- if not line_info.voucher.apply_once_per_order:
- if line_info.voucher.discount_value_type == DiscountValueType.PERCENTAGE:
- voucher_discount_amount = line_info.voucher.get_discount_amount_for(
- total_price, channel=channel
- )
- total_price = max(
- total_price - voucher_discount_amount, zero_money(currency)
- )
- else:
- unit_price = total_price / quantity
- voucher_unit_discount_amount = (
- line_info.voucher.get_discount_amount_for(
- unit_price, channel=channel
- )
- )
- total_price = max(
- total_price - (voucher_unit_discount_amount * quantity),
- zero_money(currency),
- )
- else:
- unit_price = total_price / quantity
- voucher_unit_discount_amount = line_info.voucher.get_discount_amount_for(
- unit_price, channel=channel
- )
- variant_price_with_discounts = max(
- unit_price - voucher_unit_discount_amount, zero_money(currency)
- )
- # we add -1 as we handle a case when voucher is applied only to single line
- # of the cheapest item
- quantity_without_voucher = line_info.line.quantity - 1
- total_price = (
- unit_price * quantity_without_voucher + variant_price_with_discounts
- )
+ discount_amount = calculate_line_discount_amount_from_voucher(
+ line_info, total_price
+ )
+ total_price -= discount_amount
return quantize_price(total_price, total_price.currency)
@@ -230,7 +196,6 @@ def base_checkout_subtotal(
line_totals = [
calculate_base_line_total_price(
line,
- channel,
include_voucher=include_voucher,
)
for line in checkout_lines
@@ -329,7 +294,6 @@ def _get_discounted_checkout_line_price(
lines_total_prices = [
calculate_base_line_total_price(
line_info,
- channel,
).amount
for line_info in lines
if line_info.line.id != checkout_line_info.line.id
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index 327b5ec819..f541aa78cd 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -556,9 +556,7 @@ def _set_checkout_base_prices(
line = line_info.line
quantity = line.quantity
- unit_price = base_calculations.calculate_base_line_unit_price(
- line_info, checkout_info.channel
- )
+ 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
)
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index c96a6073d2..c97a82df54 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -259,9 +259,7 @@ def _create_line_for_order(
# the price with sale and discounts applied - base price that is used for
# total price calculation
- base_unit_price = calculate_base_line_unit_price(
- line_info=checkout_line_info, channel=checkout_info.channel
- )
+ base_unit_price = calculate_base_line_unit_price(line_info=checkout_line_info)
# the unit price before applying any discount (sale or voucher)
undiscounted_base_unit_price = calculate_undiscounted_base_line_unit_price(
line_info=checkout_line_info,
diff --git a/saleor/checkout/tests/test_base_calculations.py b/saleor/checkout/tests/test_base_calculations.py
index 33527b72bf..57f21357d7 100644
--- a/saleor/checkout/tests/test_base_calculations.py
+++ b/saleor/checkout/tests/test_base_calculations.py
@@ -23,9 +23,7 @@ def test_calculate_base_line_unit_price(checkout_with_single_item):
variant = checkout_line_info.variant
# when
- unit_price = calculate_base_line_unit_price(
- checkout_line_info, checkout_with_single_item.channel
- )
+ unit_price = calculate_base_line_unit_price(checkout_line_info)
# then
expected_price = variant.get_price(
@@ -46,9 +44,7 @@ def test_calculate_base_line_unit_price_with_custom_price(checkout_with_single_i
assert not checkout_line_info.voucher
# when
- unit_price = calculate_base_line_unit_price(
- checkout_line_info, checkout_with_single_item.channel
- )
+ unit_price = calculate_base_line_unit_price(checkout_line_info)
# then
currency = checkout_line_info.channel_listing.currency
@@ -60,7 +56,6 @@ def test_calculate_base_line_unit_price_with_variant_on_sale(
checkout_with_item_on_sale,
):
# given
- checkout = checkout_with_item_on_sale
checkout_lines_info, _ = fetch_checkout_lines(checkout_with_item_on_sale)
checkout_line_info = checkout_lines_info[0]
@@ -69,7 +64,7 @@ def test_calculate_base_line_unit_price_with_variant_on_sale(
checkout_line_info.product = variant.product
# when
- unit_price = calculate_base_line_unit_price(checkout_line_info, checkout.channel)
+ unit_price = calculate_base_line_unit_price(checkout_line_info)
# then
assert unit_price == checkout_line_info.channel_listing.discounted_price
@@ -79,7 +74,6 @@ def test_calculate_base_line_unit_price_with_variant_on_sale_custom_price(
checkout_with_item_on_sale,
):
# given
- checkout = checkout_with_item_on_sale
line = checkout_with_item_on_sale.lines.first()
price_override = Decimal("20.00")
line.price_override = price_override
@@ -89,7 +83,7 @@ def test_calculate_base_line_unit_price_with_variant_on_sale_custom_price(
checkout_line_info = checkout_lines_info[0]
# when
- unit_price = calculate_base_line_unit_price(checkout_line_info, checkout.channel)
+ unit_price = calculate_base_line_unit_price(checkout_line_info)
# then
discount = line.discounts.first()
@@ -106,7 +100,7 @@ def test_calculate_base_line_unit_price_with_variant_on_promotion(
checkout_line_info = checkout_lines_info[0]
# when
- unit_price = calculate_base_line_unit_price(checkout_line_info, checkout.channel)
+ unit_price = calculate_base_line_unit_price(checkout_line_info)
# then
assert unit_price == checkout_line_info.channel_listing.discounted_price
@@ -126,7 +120,7 @@ def test_calculate_base_line_unit_price_with_variant_on_promotion_custom_price(
checkout_line_info = checkout_lines_info[0]
# when
- unit_price = calculate_base_line_unit_price(checkout_line_info, checkout.channel)
+ unit_price = calculate_base_line_unit_price(checkout_line_info)
# then
discount = line.discounts.first()
@@ -156,9 +150,7 @@ def test_calculate_base_line_unit_price_with_fixed_voucher(
variant = checkout_line_info.variant
# when
- unit_price = calculate_base_line_unit_price(
- checkout_line_info, checkout_with_single_item.channel
- )
+ unit_price = calculate_base_line_unit_price(checkout_line_info)
# then
expected_price = variant.get_price(
@@ -191,9 +183,7 @@ def test_calculate_base_line_unit_price_with_fixed_voucher_custom_prices(
assert checkout_line_info.voucher
# when
- unit_price = calculate_base_line_unit_price(
- checkout_line_info, checkout_with_single_item.channel
- )
+ unit_price = calculate_base_line_unit_price(checkout_line_info)
# then
currency = checkout_line_info.channel_listing.currency
@@ -224,9 +214,7 @@ def test_calculate_base_line_unit_price_with_percentage_voucher(
variant = checkout_line_info.variant
# when
- unit_price = calculate_base_line_unit_price(
- checkout_line_info, checkout_with_single_item.channel
- )
+ unit_price = calculate_base_line_unit_price(checkout_line_info)
# then
expected_voucher_amount = Money(Decimal("1"), checkout_with_single_item.currency)
@@ -261,9 +249,7 @@ def test_calculate_base_line_unit_price_with_percentage_voucher_custom_prices(
assert checkout_line_info.voucher
# when
- unit_price = calculate_base_line_unit_price(
- checkout_line_info, checkout_with_single_item.channel
- )
+ unit_price = calculate_base_line_unit_price(checkout_line_info)
# then
currency = checkout_line_info.channel_listing.currency
@@ -298,9 +284,7 @@ def test_calculate_base_line_unit_price_with_discounts_apply_once_per_order(
variant = checkout_line_info.variant
# when
- unit_price = calculate_base_line_unit_price(
- checkout_line_info, checkout_with_single_item.channel
- )
+ unit_price = calculate_base_line_unit_price(checkout_line_info)
# then
expected_price = variant.get_price(
@@ -336,9 +320,7 @@ def test_calculate_base_line_unit_price_with_discounts_once_per_order_custom_pri
assert checkout_line_info.voucher
# when
- unit_price = calculate_base_line_unit_price(
- checkout_line_info, checkout_with_single_item.channel
- )
+ unit_price = calculate_base_line_unit_price(checkout_line_info)
# then
currency = checkout_line_info.channel_listing.currency
@@ -367,9 +349,7 @@ def test_calculate_base_line_unit_price_with_variant_on_sale_and_voucher(
checkout_line_info = checkout_lines_info[0]
# when
- unit_price = calculate_base_line_unit_price(
- checkout_line_info, checkout_with_single_item.channel
- )
+ unit_price = calculate_base_line_unit_price(checkout_line_info)
# then
expected_unit_price = checkout_line_info.channel_listing.discounted_price
@@ -400,7 +380,7 @@ def test_calculate_base_line_unit_price_with_variant_on_promotion_and_voucher(
assert checkout_line_info.voucher
# when
- unit_price = calculate_base_line_unit_price(checkout_line_info, checkout.channel)
+ unit_price = calculate_base_line_unit_price(checkout_line_info)
# then
expected_price = checkout_line_info.channel_listing.discounted_price
@@ -421,9 +401,7 @@ def test_calculate_base_line_total_price(checkout_with_single_item):
variant = checkout_line_info.variant
# when
- total_price = calculate_base_line_total_price(
- checkout_line_info, checkout_with_single_item.channel
- )
+ total_price = calculate_base_line_total_price(checkout_line_info)
# then
expected_price = variant.get_price(
@@ -446,7 +424,7 @@ def test_calculate_base_line_total_price_with_variant_on_sale(
checkout_line_info = checkout_lines_info[0]
# when
- total_price = calculate_base_line_total_price(checkout_line_info, checkout.channel)
+ total_price = calculate_base_line_total_price(checkout_line_info)
# then
expected_unit_price = checkout_line_info.channel_listing.discounted_price
@@ -468,7 +446,7 @@ def test_calculate_base_line_total_price_with_variant_on_promotion(
assert not checkout_line_info.voucher
# when
- total_price = calculate_base_line_total_price(checkout_line_info, checkout.channel)
+ total_price = calculate_base_line_total_price(checkout_line_info)
# then
assert total_price == checkout_line_info.channel_listing.discounted_price * quantity
@@ -509,7 +487,7 @@ def test_calculate_base_line_total_price_with_1_cent_variant_on_10_percentage_di
checkout_line_info = checkout_lines_info[0]
# when
- total_price = calculate_base_line_total_price(checkout_line_info, checkout.channel)
+ total_price = calculate_base_line_total_price(checkout_line_info)
# then
variant_channel_listing.refresh_from_db()
@@ -544,9 +522,7 @@ def test_calculate_base_line_total_price_with_fixed_voucher(
variant = checkout_line_info.variant
# when
- total_price = calculate_base_line_total_price(
- checkout_line_info, checkout_with_single_item.channel
- )
+ total_price = calculate_base_line_total_price(checkout_line_info)
# then
expected_unit_price = variant.get_price(
@@ -583,9 +559,7 @@ def test_calculate_base_line_total_price_with_percentage_voucher(
variant = checkout_line_info.variant
# when
- total_price = calculate_base_line_total_price(
- checkout_line_info, checkout_with_single_item.channel
- )
+ total_price = calculate_base_line_total_price(checkout_line_info)
# then
expected_voucher_amount = Money(Decimal("1"), checkout_with_single_item.currency)
@@ -624,9 +598,7 @@ def test_calculate_base_line_total_price_with_discounts_apply_once_per_order(
variant = checkout_line_info.variant
# when
- total_price = calculate_base_line_total_price(
- checkout_line_info, checkout_with_single_item.channel
- )
+ total_price = calculate_base_line_total_price(checkout_line_info)
# then
expected_voucher_amount = Money(Decimal("1"), checkout_with_single_item.currency)
@@ -664,7 +636,7 @@ def test_calculate_base_line_total_price_with_variant_on_sale_and_voucher(
checkout_line_info = checkout_lines_info[0]
# when
- total_price = calculate_base_line_total_price(checkout_line_info, checkout.channel)
+ total_price = calculate_base_line_total_price(checkout_line_info)
# then
expected_unit_price = checkout_line_info.channel_listing.discounted_price
@@ -698,7 +670,7 @@ def test_calculate_base_line_total_price_with_variant_on_sale_and_voucher_applie
checkout_line_info = checkout_lines_info[0]
# when
- total_price = calculate_base_line_total_price(checkout_line_info, checkout.channel)
+ total_price = calculate_base_line_total_price(checkout_line_info)
# then
expected_unit_price = checkout_line_info.channel_listing.discounted_price
@@ -732,7 +704,7 @@ def test_calculate_base_line_total_price_with_variant_on_promotion_and_voucher(
assert checkout_line_info.voucher
# when
- total_price = calculate_base_line_total_price(checkout_line_info, checkout.channel)
+ total_price = calculate_base_line_total_price(checkout_line_info)
# then
expected_unit_price = checkout_line_info.channel_listing.discounted_price
@@ -774,7 +746,7 @@ def test_calculate_base_line_total_price_variant_on_promotion_and_voucher_applie
checkout_line_info.product = variant.product
# when
- total_price = calculate_base_line_total_price(checkout_line_info, checkout.channel)
+ total_price = calculate_base_line_total_price(checkout_line_info)
# then
expected_unit_price = checkout_line_info.channel_listing.discounted_price
diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.py
index b16005eaad..34607390eb 100644
--- a/saleor/checkout/tests/test_calculations.py
+++ b/saleor/checkout/tests/test_calculations.py
@@ -509,8 +509,7 @@ def test_fetch_checkout_prices_when_tax_exemption_and_not_include_taxes_in_price
# then
one_line_total_prices = [
- calculate_base_line_total_price(line_info, checkout_info.channel)
- for line_info in lines_info
+ calculate_base_line_total_price(line_info) for line_info in lines_info
]
all_lines_total_price = sum(one_line_total_prices, zero_taxed_money(currency))
shipping_price = base_checkout_delivery_price(checkout_info, lines_info)
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index e4aeadf089..0b35eecc1c 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -25,7 +25,7 @@ from ..core.utils.promo_code import (
from ..core.utils.translations import get_translation
from ..core.weight import zero_weight
from ..discount import DiscountType, VoucherType
-from ..discount.interface import VoucherInfo, fetch_voucher_info
+from ..discount.interface import fetch_voucher_info
from ..discount.models import (
CheckoutDiscount,
NotApplicable,
@@ -36,6 +36,7 @@ from ..discount.utils import (
create_checkout_discount_objects_for_order_promotions,
create_checkout_line_discount_objects_for_catalogue_promotions,
delete_gift_line,
+ get_discounted_lines,
get_products_voucher_discount,
get_voucher_code_instance,
validate_voucher_for_checkout,
@@ -60,6 +61,7 @@ if TYPE_CHECKING:
from measurement.measures import Weight
from ..account.models import Address
+ from ..core.pricing.interface import LineInfo
from ..order.models import Order
from .fetch import CheckoutInfo, CheckoutLineInfo
@@ -447,42 +449,8 @@ def _get_shipping_voucher_discount_for_checkout(
return voucher.get_discount_amount_for(shipping_price, checkout_info.channel)
-def get_discounted_lines(
- lines: Iterable["CheckoutLineInfo"], voucher_info: "VoucherInfo"
-) -> Iterable["CheckoutLineInfo"]:
- discounted_lines = []
- if (
- voucher_info.product_pks
- or voucher_info.collection_pks
- or voucher_info.category_pks
- or voucher_info.variant_pks
- ):
- for line_info in lines:
- if line_info.line.is_gift:
- continue
- line_variant = line_info.variant
- line_product = line_info.product
- line_category = line_info.product.category
- line_collections = set(
- [collection.pk for collection in line_info.collections]
- )
- if line_info.variant and (
- line_variant.pk in voucher_info.variant_pks
- or line_product.pk in voucher_info.product_pks
- or line_category
- and line_category.pk in voucher_info.category_pks
- or line_collections.intersection(voucher_info.collection_pks)
- ):
- discounted_lines.append(line_info)
- else:
- # If there's no discounted products, collections or categories,
- # it means that all products are discounted
- discounted_lines.extend(lines)
- return discounted_lines
-
-
def get_prices_of_discounted_specific_product(
- lines: Iterable["CheckoutLineInfo"],
+ lines: Iterable["LineInfo"],
voucher: Voucher,
) -> list[Money]:
"""Get prices of variants belonging to the discounted specific products.
@@ -492,16 +460,14 @@ def get_prices_of_discounted_specific_product(
product to child category won't work.
"""
voucher_info = fetch_voucher_info(voucher)
- discounted_lines: Iterable[CheckoutLineInfo] = get_discounted_lines(
- lines, voucher_info
- )
+ discounted_lines: Iterable[LineInfo] = get_discounted_lines(lines, voucher_info)
line_prices = get_base_lines_prices(discounted_lines)
return line_prices
def get_base_lines_prices(
- lines: Iterable["CheckoutLineInfo"],
+ lines: Iterable["LineInfo"],
):
"""Get base total price of checkout lines without voucher discount applied."""
return [
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index a97a87071a..ee1ce54583 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -164,7 +164,7 @@ class Voucher(ModelWithMetadata):
)
raise NotImplementedError("Unknown discount type")
- def get_discount_amount_for(self, price: Money, channel: Channel):
+ def get_discount_amount_for(self, price: Money, channel: Channel) -> Money:
discount = self.get_discount(channel)
after_discount = discount(price)
if after_discount.amount < 0:
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 69ed4b885f..66d9081f3b 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -59,7 +59,7 @@ if TYPE_CHECKING:
from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ..core.pricing.interface import LineInfo
from ..discount.models import Voucher
- from ..order.fetch import DraftOrderLineInfo
+ from ..order.fetch import EditableOrderLineInfo
from ..order.models import OrderLine
from ..plugins.manager import PluginsManager
from ..product.managers import ProductVariantQueryset
@@ -527,7 +527,7 @@ def prepare_line_discount_objects_for_catalogue_promotions(
@overload
def prepare_line_discount_objects_for_catalogue_promotions(
- lines_info: Iterable["DraftOrderLineInfo"],
+ lines_info: Iterable["EditableOrderLineInfo"],
) -> tuple[
list[dict], list["OrderLineDiscount"], list["OrderLineDiscount"], list[str]
]: ...
@@ -1115,7 +1115,7 @@ def _handle_order_promotion_for_checkout(
@allow_writer()
def delete_gift_line(
order_or_checkout: Union[Checkout, Order],
- lines_info: Iterable[Union["CheckoutLineInfo", "DraftOrderLineInfo"]],
+ lines_info: Iterable[Union["CheckoutLineInfo", "EditableOrderLineInfo"]],
):
if gift_line_infos := [line for line in lines_info if line.line.is_gift]:
order_or_checkout.lines.filter(is_gift=True).delete() # type: ignore[misc]
@@ -1406,7 +1406,7 @@ def update_rule_variant_relation(
def create_or_update_discount_objects_for_order(
order: "Order",
- lines_info: Iterable["DraftOrderLineInfo"],
+ lines_info: Iterable["EditableOrderLineInfo"],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
create_or_update_discount_objects_from_promotion_for_order(
@@ -1419,7 +1419,7 @@ def create_or_update_discount_objects_for_order(
def create_or_update_discount_objects_from_promotion_for_order(
order: "Order",
- lines_info: Iterable["DraftOrderLineInfo"],
+ lines_info: Iterable["EditableOrderLineInfo"],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
create_order_line_discount_objects_for_catalogue_promotions(lines_info)
@@ -1431,14 +1431,14 @@ def create_or_update_discount_objects_from_promotion_for_order(
def create_order_line_discount_objects_for_catalogue_promotions(
- lines_info: Iterable["DraftOrderLineInfo"],
+ lines_info: Iterable["EditableOrderLineInfo"],
):
discount_data = prepare_line_discount_objects_for_catalogue_promotions(lines_info)
create_order_line_discount_objects(lines_info, discount_data)
def create_order_line_discount_objects(
- lines_info: Iterable["DraftOrderLineInfo"],
+ lines_info: Iterable["EditableOrderLineInfo"],
discount_data: tuple[
list[dict],
list["OrderLineDiscount"],
@@ -1498,7 +1498,9 @@ def create_order_line_discount_objects(
return modified_lines_info
-def _copy_unit_discount_data_to_order_line(lines_info: Iterable["DraftOrderLineInfo"]):
+def _copy_unit_discount_data_to_order_line(
+ lines_info: Iterable["EditableOrderLineInfo"],
+):
for line_info in lines_info:
if discounts := line_info.discounts:
line = line_info.line
@@ -1523,7 +1525,7 @@ def _copy_unit_discount_data_to_order_line(lines_info: Iterable["DraftOrderLineI
def _update_base_unit_price_amount_for_catalogue_promotion(
- lines_info: Iterable["DraftOrderLineInfo"],
+ lines_info: Iterable["EditableOrderLineInfo"],
):
for line_info in lines_info:
line = line_info.line
@@ -1536,7 +1538,7 @@ def _update_base_unit_price_amount_for_catalogue_promotion(
def create_order_discount_objects_for_order_promotions(
order: "Order",
- lines_info: Iterable["DraftOrderLineInfo"],
+ lines_info: Iterable["EditableOrderLineInfo"],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
from ..order.base_calculations import base_order_subtotal
@@ -1616,14 +1618,14 @@ def create_order_discount_objects_for_order_promotions(
@allow_writer()
def _clear_order_discount(
order_or_checkout: Union[Checkout, Order],
- lines_info: Iterable["DraftOrderLineInfo"],
+ lines_info: Iterable["EditableOrderLineInfo"],
):
with transaction.atomic():
delete_gift_line(order_or_checkout, lines_info)
order_or_checkout.discounts.filter(type=DiscountType.ORDER_PROMOTION).delete()
-def _set_order_base_prices(order: Order, lines_info: Iterable["DraftOrderLineInfo"]):
+def _set_order_base_prices(order: Order, lines_info: Iterable["EditableOrderLineInfo"]):
"""Set base order prices that includes only catalogue discounts."""
from ..order.base_calculations import base_order_subtotal
@@ -1647,7 +1649,7 @@ def _set_order_base_prices(order: Order, lines_info: Iterable["DraftOrderLineInf
def _handle_order_promotion_for_order(
order: Order,
- lines_info: Iterable["DraftOrderLineInfo"],
+ lines_info: Iterable["EditableOrderLineInfo"],
discount_object_defaults: dict,
rule_info: VariantPromotionRuleInfo,
):
@@ -1675,12 +1677,12 @@ def _handle_order_promotion_for_order(
@allow_writer()
def _handle_gift_reward_for_order(
order: Order,
- lines_info: Iterable["DraftOrderLineInfo"],
+ lines_info: Iterable["EditableOrderLineInfo"],
gift_listing: ProductVariantChannelListing,
discount_object_defaults: dict,
rule_info: VariantPromotionRuleInfo,
):
- from ..order.fetch import DraftOrderLineInfo
+ from ..order.fetch import EditableOrderLineInfo
with transaction.atomic():
line, line_created = create_gift_line(order, gift_listing.variant_id)
@@ -1722,7 +1724,7 @@ def _handle_gift_reward_for_order(
"voucher": None,
"voucher_code": None,
}
- gift_line_info = DraftOrderLineInfo(**init_values)
+ gift_line_info = EditableOrderLineInfo(**init_values)
lines_info.append(gift_line_info) # type: ignore[attr-defined]
else:
line_info = next(
@@ -1775,7 +1777,7 @@ def create_or_update_line_discount_objects_from_voucher(order, lines_info):
# TODO (SHOPX-912): share the method with checkout
def prepare_line_discount_objects_for_voucher(
- lines_info: Iterable["DraftOrderLineInfo"],
+ lines_info: Iterable["EditableOrderLineInfo"],
):
line_discounts_to_create_inputs: list[dict] = []
line_discounts_to_update: list[OrderLineDiscount] = []
@@ -1849,7 +1851,7 @@ def prepare_line_discount_objects_for_voucher(
def calculate_line_discount_amount_from_voucher(
line_info: "LineInfo", total_price: Money
-):
+) -> Money:
"""Calculate discount amount for voucher applied on line.
Included vouchers: `SPECIFIC_PRODUCT` and `apply_once_per_order`.
@@ -1890,7 +1892,7 @@ def calculate_line_discount_amount_from_voucher(
def _reduce_base_unit_price_for_voucher_discount(
- lines_info: Iterable["DraftOrderLineInfo"],
+ lines_info: Iterable["EditableOrderLineInfo"],
):
for line_info in lines_info:
line = line_info.line
diff --git a/saleor/graphql/core/types/taxes.py b/saleor/graphql/core/types/taxes.py
index ee8d2f7202..97306790d0 100644
--- a/saleor/graphql/core/types/taxes.py
+++ b/saleor/graphql/core/types/taxes.py
@@ -213,32 +213,19 @@ class TaxableObjectLine(BaseObjectType):
if isinstance(root, CheckoutLine):
def with_checkout(checkout):
- checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(
- checkout.token
- )
lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(
checkout.token
)
- def calculate_line_unit_price(data):
- (
- checkout_info,
- lines,
- ) = data
+ def calculate_line_unit_price(lines):
for line_info in lines:
if line_info.line.pk == root.pk:
return base_calculations.calculate_base_line_unit_price(
line_info=line_info,
- channel=checkout_info.channel,
)
return None
- return Promise.all(
- [
- checkout_info,
- lines,
- ]
- ).then(calculate_line_unit_price)
+ return lines.then(calculate_line_unit_price)
return (
CheckoutByTokenLoader(info.context)
@@ -252,32 +239,19 @@ class TaxableObjectLine(BaseObjectType):
if isinstance(root, CheckoutLine):
def with_checkout(checkout):
- checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(
- checkout.token
- )
lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(
checkout.token
)
- def calculate_line_total_price(data):
- (
- checkout_info,
- lines,
- ) = data
+ def calculate_line_total_price(lines):
for line_info in lines:
if line_info.line.pk == root.pk:
return base_calculations.calculate_base_line_total_price(
- line_info=line_info,
- channel=checkout_info.channel,
+ line_info=line_info
)
return None
- return Promise.all(
- [
- checkout_info,
- lines,
- ]
- ).then(calculate_line_total_price)
+ return lines.then(calculate_line_total_price)
return (
CheckoutByTokenLoader(info.context)
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index b87126fdab..1f788009b8 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -27,7 +27,7 @@ from ..tax.utils import (
)
from . import ORDER_EDITABLE_STATUS
from .base_calculations import apply_order_discounts, base_order_line_total
-from .fetch import DraftOrderLineInfo, fetch_draft_order_lines_info
+from .fetch import EditableOrderLineInfo, fetch_draft_order_lines_info
from .interface import OrderTaxedPricesData
from .models import Order, OrderLine
from .utils import log_address_if_validation_skipped_for_order
@@ -56,7 +56,7 @@ def fetch_order_prices_if_expired(
return order, lines
# handle promotions
- lines_info: list[DraftOrderLineInfo] = fetch_draft_order_lines_info(order, lines)
+ lines_info: list[EditableOrderLineInfo] = fetch_draft_order_lines_info(order, lines)
create_or_update_discount_objects_for_order(
order, lines_info, database_connection_name
)
diff --git a/saleor/order/fetch.py b/saleor/order/fetch.py
index 7324b28648..0e1edb329a 100644
--- a/saleor/order/fetch.py
+++ b/saleor/order/fetch.py
@@ -69,9 +69,9 @@ def fetch_order_lines(order: "Order") -> list[OrderLineInfo]:
quantity=line.quantity,
is_digital=is_digital,
variant=variant,
- digital_content=variant.digital_content
- if is_digital and variant
- else None,
+ digital_content=(
+ variant.digital_content if is_digital and variant else None
+ ),
)
)
@@ -79,7 +79,7 @@ def fetch_order_lines(order: "Order") -> list[OrderLineInfo]:
@dataclass
-class DraftOrderLineInfo(LineInfo):
+class EditableOrderLineInfo(LineInfo):
line: "OrderLine"
discounts: list["OrderLineDiscount"]
@@ -93,9 +93,8 @@ class DraftOrderLineInfo(LineInfo):
def fetch_draft_order_lines_info(
- order: "Order",
- lines: Optional[Iterable["OrderLine"]] = None,
-) -> list[DraftOrderLineInfo]:
+ order: "Order", lines: Optional[Iterable["OrderLine"]] = None
+) -> list[EditableOrderLineInfo]:
prefetch_related_fields = [
"discounts__promotion_rule__promotion",
"variant__channel_listings__variantlistingpromotionrule__promotion_rule__promotion__translations",
@@ -130,7 +129,7 @@ def fetch_draft_order_lines_info(
else []
)
lines_info.append(
- DraftOrderLineInfo(
+ EditableOrderLineInfo(
line=line,
variant=variant,
product=product,
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index 820b01a7c6..134b4c4d9d 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -1,5 +1,5 @@
from decimal import Decimal
-from unittest.mock import Mock, patch
+from unittest.mock import patch
import graphene
import pytest
@@ -11,11 +11,6 @@ from ...discount import DiscountType, RewardValueType
from ...discount.interface import VariantPromotionRuleInfo
from ...discount.models import (
DiscountValueType,
- NotApplicable,
- Voucher,
- VoucherChannelListing,
- VoucherCode,
- VoucherType,
)
from ...discount.utils import validate_voucher_in_order
from ...graphql.core.utils import to_global_id_or_none
@@ -24,7 +19,6 @@ from ...graphql.tests.utils import get_graphql_content
from ...payment import ChargeStatus
from ...payment.models import Payment
from ...plugins.manager import get_plugins_manager
-from ...product.models import Collection
from ...tests.fixtures import recalculate_order
from ...warehouse import WarehouseClickAndCollectOption
from ...warehouse.models import Stock, Warehouse
@@ -49,7 +43,6 @@ from ..utils import (
add_variant_to_order,
change_order_line_quantity,
delete_order_line,
- get_voucher_discount_for_order,
restock_fulfillment_lines,
update_order_authorize_data,
update_order_charge_data,
@@ -707,236 +700,6 @@ def test_validate_voucher_in_order_without_voucher(
mock_validate_voucher.assert_not_called()
- (
- "subtotal",
- "discount_value",
- "discount_type",
- "min_spent_amount",
- "expected_value",
- ),
- [
- ("100", 10, DiscountValueType.FIXED, None, 10),
- ("100.05", 10, DiscountValueType.PERCENTAGE, 100, Decimal("10.01")),
- ],
-)
-def test_value_voucher_order_discount(
- subtotal,
- discount_value,
- discount_type,
- min_spent_amount,
- expected_value,
- channel_USD,
- address_usa,
-):
- voucher = Voucher.objects.create(
- type=VoucherType.ENTIRE_ORDER,
- discount_value_type=discount_type,
- )
- VoucherCode.objects.create(code="unique", voucher=voucher)
- VoucherChannelListing.objects.create(
- voucher=voucher,
- channel=channel_USD,
- discount=Money(discount_value, channel_USD.currency_code),
- min_spent_amount=(min_spent_amount if min_spent_amount is not None else None),
- )
- subtotal = Money(subtotal, "USD")
- subtotal = TaxedMoney(net=subtotal, gross=subtotal)
- order = Mock(
- subtotal=subtotal,
- voucher=voucher,
- shipping_address=address_usa,
- billing_address=address_usa,
- channel=channel_USD,
- )
- order.lines = Mock(all=Mock(return_value=[]))
- discount = get_voucher_discount_for_order(order)
- assert discount == Money(expected_value, "USD")
-
-
- ("shipping_cost", "discount_value", "discount_type", "expected_value"),
- [(10, 50, DiscountValueType.PERCENTAGE, 5), (10, 20, DiscountValueType.FIXED, 10)],
-)
-def test_shipping_voucher_order_discount(
- shipping_cost,
- discount_value,
- discount_type,
- expected_value,
- channel_USD,
- address_usa,
-):
- voucher = Voucher.objects.create(
- type=VoucherType.SHIPPING,
- discount_value_type=discount_type,
- )
- VoucherCode.objects.create(code="unique", voucher=voucher)
- VoucherChannelListing.objects.create(
- voucher=voucher,
- channel=channel_USD,
- discount=Money(discount_value, channel_USD.currency_code),
- )
- subtotal = Money(100, "USD")
- subtotal = TaxedMoney(net=subtotal, gross=subtotal)
- shipping_total = TaxedMoney(
- gross=Money(shipping_cost, "USD"), net=Money(shipping_cost, "USD")
- )
- order = Mock(
- get_subtotal=Mock(return_value=subtotal),
- shipping_price=shipping_total,
- shipping_address=address_usa,
- billing_address=address_usa,
- voucher=voucher,
- channel=channel_USD,
- )
- order.lines = Mock(all=Mock(return_value=[]))
- discount = get_voucher_discount_for_order(order)
- assert discount == Money(expected_value, "USD")
-
-
- (
- "total",
- "total_quantity",
- "min_spent_amount",
- "min_checkout_items_quantity",
- "voucher_type",
- ),
- [
- (99, 10, 100, 10, VoucherType.SHIPPING),
- (100, 9, 100, 10, VoucherType.SHIPPING),
- (99, 9, 100, 10, VoucherType.SHIPPING),
- (99, 10, 100, 10, VoucherType.ENTIRE_ORDER),
- (100, 9, 100, 10, VoucherType.ENTIRE_ORDER),
- (99, 9, 100, 10, VoucherType.ENTIRE_ORDER),
- (99, 10, 100, 10, VoucherType.SPECIFIC_PRODUCT),
- (100, 9, 100, 10, VoucherType.SPECIFIC_PRODUCT),
- (99, 9, 100, 10, VoucherType.SPECIFIC_PRODUCT),
- ],
-)
-def test_shipping_voucher_checkout_discount_not_applicable_returns_zero(
- total,
- total_quantity,
- min_spent_amount,
- min_checkout_items_quantity,
- voucher_type,
- channel_USD,
- address_usa,
-):
- voucher = Voucher.objects.create(
- type=voucher_type,
- discount_value_type=DiscountValueType.FIXED,
- min_checkout_items_quantity=min_checkout_items_quantity,
- )
- VoucherCode.objects.create(code="unique", voucher=voucher)
- VoucherChannelListing.objects.create(
- voucher=voucher,
- channel=channel_USD,
- discount=Money(10, channel_USD.currency_code),
- min_spent_amount=(min_spent_amount if min_spent_amount is not None else None),
- )
- price = Money(total, "USD")
- price = TaxedMoney(net=price, gross=price)
- order = Mock(
- subtotal=price,
- get_total_quantity=Mock(return_value=total_quantity),
- shipping_address=address_usa,
- billing_address=address_usa,
- shipping_price=price,
- voucher=voucher,
- channel=channel_USD,
- )
- order.lines = Mock(all=Mock(return_value=[]))
- with pytest.raises(NotApplicable):
- get_voucher_discount_for_order(order)
-
-
- ("discount_value", "discount_type", "apply_once_per_order", "discount_amount"),
- [
- (5, DiscountValueType.FIXED, True, "5"),
- (5, DiscountValueType.FIXED, False, "25"),
- (10000, DiscountValueType.FIXED, True, "12.3"),
- (10000, DiscountValueType.FIXED, False, "86.1"),
- (10, DiscountValueType.PERCENTAGE, True, "1.23"),
- (10, DiscountValueType.PERCENTAGE, False, "8.61"),
- ],
-)
-def test_get_discount_for_order_specific_products_voucher(
- order_with_lines,
- discount_value,
- discount_type,
- apply_once_per_order,
- discount_amount,
- channel_USD,
-):
- voucher = Voucher.objects.create(
- type=VoucherType.SPECIFIC_PRODUCT,
- discount_value_type=discount_type,
- apply_once_per_order=apply_once_per_order,
- )
- VoucherCode.objects.create(code="unique", voucher=voucher)
- VoucherChannelListing.objects.create(
- voucher=voucher,
- channel=channel_USD,
- discount=Money(discount_value, channel_USD.currency_code),
- )
- voucher.products.add(order_with_lines.lines.first().variant.product)
- voucher.products.add(order_with_lines.lines.last().variant.product)
- order_with_lines.voucher = voucher
- order_with_lines.save()
- discount = get_voucher_discount_for_order(order_with_lines)
- assert discount == Money(discount_amount, "USD")
-
-
-def test_product_voucher_checkout_discount_raises_not_applicable(
- order_with_lines, product_with_images, channel_USD
-):
- discounted_product = product_with_images
- voucher = Voucher.objects.create(
- type=VoucherType.SPECIFIC_PRODUCT,
- discount_value_type=DiscountValueType.FIXED,
- )
- VoucherCode.objects.create(code="unique", voucher=voucher)
- VoucherChannelListing.objects.create(
- voucher=voucher,
- channel=channel_USD,
- discount=Money(10, channel_USD.currency_code),
- )
- voucher.save()
- voucher.products.add(discounted_product)
- order_with_lines.voucher = voucher
- order_with_lines.save()
- # Offer is valid only for products listed in voucher
- with pytest.raises(NotApplicable):
- get_voucher_discount_for_order(order_with_lines)
-
-
-def test_category_voucher_checkout_discount_raises_not_applicable(
- order_with_lines, channel_USD
-):
- discounted_collection = Collection.objects.create(
- name="Discounted", slug="discount"
- )
- voucher = Voucher.objects.create(
- type=VoucherType.SPECIFIC_PRODUCT,
- discount_value_type=DiscountValueType.FIXED,
- )
- VoucherCode.objects.create(code="unique", voucher=voucher)
- VoucherChannelListing.objects.create(
- voucher=voucher,
- channel=channel_USD,
- discount=Money(10, channel_USD.currency_code),
- )
- voucher.save()
- voucher.collections.add(discounted_collection)
- order_with_lines.voucher = voucher
- order_with_lines.save()
- # Discount should be valid only for items in the discounted collections
- with pytest.raises(NotApplicable):
- get_voucher_discount_for_order(order_with_lines)
-
-
def test_ordered_item_change_quantity(staff_user, transactional_db, lines_info):
app = None
order = lines_info[0].line.order
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 7476f391af..ea26d74892 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -1,6 +1,5 @@
from collections.abc import Iterable
from decimal import Decimal
-from functools import wraps
from typing import TYPE_CHECKING, Optional, cast
from django.conf import settings
@@ -17,20 +16,16 @@ from ..core.utils.translations import get_translation
from ..core.weight import zero_weight
from ..discount import DiscountType, DiscountValueType
from ..discount.models import (
- NotApplicable,
OrderDiscount,
OrderLineDiscount,
- Voucher,
VoucherType,
)
from ..discount.utils import (
apply_discount_to_value,
get_discount_name,
get_discount_translated_name,
- get_products_voucher_discount,
get_sale_id,
prepare_promotion_discount_reason,
- validate_voucher_in_order,
)
from ..giftcard import events as gift_card_events
from ..giftcard.models import GiftCard
@@ -102,22 +97,6 @@ def order_needs_automatic_fulfillment(lines_data: Iterable["OrderLineInfo"]) ->
return False
-def update_voucher_discount(func):
- """Recalculate order discount amount based on order voucher."""
-
- @wraps(func)
- def decorator(*args, **kwargs):
- if kwargs.pop("update_voucher_discount", True):
- order = args[0]
- try:
- discount = get_voucher_discount_for_order(order)
- except NotApplicable:
- discount = zero_money(order.currency)
- return func(*args, **kwargs, discount=discount)
-
- return decorator
-
-
def get_voucher_discount_assigned_to_order(order: Order):
return order.discounts.filter(type=DiscountType.VOUCHER).first()
@@ -758,56 +737,6 @@ def get_discounted_lines(lines, voucher):
return discounted_lines
-def get_prices_of_discounted_specific_product(
- lines: Iterable[OrderLine],
- voucher: Voucher,
-) -> list[Money]:
- """Get prices of variants belonging to the discounted specific products.
-
- Specific products are products, collections and categories.
- Product must be assigned directly to the discounted category, assigning
- product to child category won't work.
- """
- line_prices = []
- discounted_lines = get_discounted_lines(lines, voucher)
-
- for line in discounted_lines:
- line_prices.extend([line.unit_price_gross] * line.quantity)
-
- return line_prices
-
-
-def get_products_voucher_discount_for_order(order: Order, voucher: Voucher) -> Money:
- """Calculate products discount value for a voucher, depending on its type."""
- prices = None
- if voucher and voucher.type == VoucherType.SPECIFIC_PRODUCT:
- prices = get_prices_of_discounted_specific_product(order.lines.all(), voucher)
- if not prices:
- msg = "This offer is only valid for selected items."
- raise NotApplicable(msg)
- return get_products_voucher_discount(voucher, prices, order.channel)
-
-
-def get_voucher_discount_for_order(order: Order) -> Money:
- """Calculate discount value depending on voucher and discount types.
-
- Raise NotApplicable if voucher of given type cannot be applied.
- """
- if not order.voucher:
- return zero_money(order.currency)
- validate_voucher_in_order(order, order.lines.all(), order.channel)
- subtotal = order.subtotal
- if order.voucher.type == VoucherType.ENTIRE_ORDER:
- return order.voucher.get_discount_amount_for(subtotal.gross, order.channel)
- if order.voucher.type == VoucherType.SHIPPING:
- return order.voucher.get_discount_amount_for(
- order.shipping_price.gross, order.channel
- )
- if order.voucher.type == VoucherType.SPECIFIC_PRODUCT:
- return get_products_voucher_discount_for_order(order, order.voucher)
- raise NotImplementedError("Unknown discount type")
-
-
def match_orders_with_new_user(user: User) -> None:
Order.objects.confirmed().filter(user_email=user.email, user=None).update(user=user)
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index 27fbc1e30c..443c69d616 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -288,7 +288,6 @@ def generate_request_data_from_checkout_lines(
config: AvataxConfiguration,
) -> list[dict[str, Union[str, int, bool, None]]]:
data: list[dict[str, Union[str, int, bool, None]]] = []
- channel = checkout_info.channel
charge_taxes = get_charge_taxes_for_checkout(checkout_info, lines_info)
prices_entered_with_tax = checkout_info.tax_configuration.prices_entered_with_tax
@@ -318,7 +317,6 @@ def generate_request_data_from_checkout_lines(
checkout_line_total = base_calculations.calculate_base_line_total_price(
line_info,
- channel,
)
# This is a workaround for Avatax and sending a lines with amount 0. Like
diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.py
index 4c86fd879b..1989a939d1 100644
--- a/saleor/plugins/avatax/plugin.py
+++ b/saleor/plugins/avatax/plugin.py
@@ -228,9 +228,7 @@ class AvataxPlugin(BasePlugin):
# for some cases we will need a base_value but no need to call it for
# each line
base_value=SimpleLazyObject(
- lambda: base_calculations.calculate_base_line_total_price(
- line, checkout_info.channel
- )
+ lambda: base_calculations.calculate_base_line_total_price(line)
),
)
taxed_total += taxed_line_total_data
@@ -419,7 +417,7 @@ class AvataxPlugin(BasePlugin):
prices_entered_with_tax,
base_value=SimpleLazyObject(
lambda: base_calculations.calculate_base_line_total_price(
- checkout_line_info, checkout_info.channel
+ checkout_line_info
)
),
)
@@ -562,7 +560,7 @@ class AvataxPlugin(BasePlugin):
prices_entered_with_tax,
base_value=SimpleLazyObject(
lambda: base_calculations.calculate_base_line_total_price(
- checkout_line_info, checkout_info.channel
+ checkout_line_info
)
),
)
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 82f256d59b..f1c2bffc19 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -451,7 +451,6 @@ class PluginsManager(PaymentInterface):
) -> TaxedMoney:
default_value = base_calculations.calculate_base_line_total_price(
checkout_line_info,
- checkout_info.channel,
)
# apply entire order discount or discount from order promotion
default_value = base_calculations.apply_checkout_discount_on_checkout_line(
@@ -528,7 +527,7 @@ class PluginsManager(PaymentInterface):
) -> TaxedMoney:
quantity = checkout_line_info.line.quantity
default_value = base_calculations.calculate_base_line_unit_price(
- checkout_line_info, checkout_info.channel
+ checkout_line_info
)
# apply entire order discount
total_value = base_calculations.apply_checkout_discount_on_checkout_line(
diff --git a/saleor/tax/calculations/checkout.py b/saleor/tax/calculations/checkout.py
index 266b8d1c26..4b2a012c25 100644
--- a/saleor/tax/calculations/checkout.py
+++ b/saleor/tax/calculations/checkout.py
@@ -105,7 +105,6 @@ def calculate_checkout_line_total(
) -> TaxedMoney:
base_total_price = base_calculations.calculate_base_line_total_price(
checkout_line_info,
- checkout_info.channel,
)
total_price = base_calculations.apply_checkout_discount_on_checkout_line(
checkout_info,
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index ac69c47a57..b06d60e476 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -41,7 +41,11 @@ from ..attribute.utils import associate_attribute_values_to_instance
from ..checkout import base_calculations
from ..checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ..checkout.models import Checkout, CheckoutLine, CheckoutMetadata
-from ..checkout.utils import add_variant_to_checkout, add_voucher_to_checkout
+from ..checkout.utils import (
+ add_variant_to_checkout,
+ add_voucher_to_checkout,
+ get_prices_of_discounted_specific_product,
+)
from ..core import EventDeliveryStatus, JobStatus
from ..core.models import EventDelivery, EventDeliveryAttempt, EventPayload
from ..core.payments import PaymentInterface
@@ -76,6 +80,10 @@ from ..discount.models import (
VoucherCustomer,
VoucherTranslation,
)
+from ..discount.utils import (
+ get_products_voucher_discount,
+ validate_voucher_in_order,
+)
from ..giftcard import GiftCardEvents
from ..giftcard.models import GiftCard, GiftCardEvent, GiftCardTag
from ..menu.models import Menu, MenuItem, MenuItemTranslation
@@ -98,7 +106,6 @@ from ..order.models import (
from ..order.search import prepare_order_search_vector_value
from ..order.utils import (
get_voucher_discount_assigned_to_order,
- get_voucher_discount_for_order,
)
from ..page.models import Page, PageTranslation, PageType
from ..payment import ChargeStatus, TransactionKind
@@ -4911,6 +4918,37 @@ def recalculate_order(order):
order.save()
+def get_voucher_discount_for_order(order: Order) -> Money:
+ """Calculate discount value depending on voucher and discount types.
+
+ Raise NotApplicable if voucher of given type cannot be applied.
+ """
+ if not order.voucher:
+ return zero_money(order.currency)
+ validate_voucher_in_order(order)
+ subtotal = order.subtotal
+ if order.voucher.type == VoucherType.ENTIRE_ORDER:
+ return order.voucher.get_discount_amount_for(subtotal.gross, order.channel)
+ if order.voucher.type == VoucherType.SHIPPING:
+ return order.voucher.get_discount_amount_for(
+ order.shipping_price.gross, order.channel
+ )
+ if order.voucher.type == VoucherType.SPECIFIC_PRODUCT:
+ return get_products_voucher_discount_for_order(order, order.voucher)
+ raise NotImplementedError("Unknown discount type")
+
+
+def get_products_voucher_discount_for_order(order: Order, voucher: Voucher) -> Money:
+ """Calculate products discount value for a voucher, depending on its type."""
+ prices = None
+ if voucher and voucher.type == VoucherType.SPECIFIC_PRODUCT:
+ prices = get_prices_of_discounted_specific_product(order.lines.all(), voucher)
+ if not prices:
+ msg = "This offer is only valid for selected items."
+ raise NotApplicable(msg)
+ return get_products_voucher_discount(voucher, prices, order.channel)
+
+
@pytest.fixture
def order_with_lines(
order,
@@ -8107,14 +8145,13 @@ def checkout_with_prices(
checkout_with_items.save(update_fields=["shipping_method"])
manager = get_plugins_manager(allow_replica=False)
- channel = checkout_with_items.channel
lines = checkout_with_items.lines.all()
lines_info, _ = fetch_checkout_lines(checkout_with_items)
checkout_info = fetch_checkout_info(checkout_with_items, lines_info, manager)
for line, line_info in zip(lines, lines_info):
line.total_price_net_amount = base_calculations.calculate_base_line_total_price(
- line_info, channel
+ line_info
).amount
line.total_price_gross_amount = line.total_price_net_amount * Decimal("1.230")
diff --git a/saleor/webhook/serializers.py b/saleor/webhook/serializers.py
index 67a710d946..baf02095b5 100644
--- a/saleor/webhook/serializers.py
+++ b/saleor/webhook/serializers.py
@@ -82,22 +82,17 @@ def serialize_checkout_lines_for_tax_calculation(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
) -> list[dict]:
- channel = checkout_info.channel
charge_taxes = get_charge_taxes_for_checkout(checkout_info, lines)
return [
{
**_get_checkout_line_payload_data(line_info),
"charge_taxes": charge_taxes,
"unit_amount": quantize_price(
- base_calculations.calculate_base_line_unit_price(
- line_info, channel
- ).amount,
+ base_calculations.calculate_base_line_unit_price(line_info).amount,
checkout_info.checkout.currency,
),
"total_amount": quantize_price(
- base_calculations.calculate_base_line_total_price(
- line_info, channel
- ).amount,
+ base_calculations.calculate_base_line_total_price(line_info).amount,
checkout_info.checkout.currency,
),
}
diff --git a/saleor/webhook/tests/test_webhook_serializers.py b/saleor/webhook/tests/test_webhook_serializers.py
index 372ca739d2..a8f06308c9 100644
--- a/saleor/webhook/tests/test_webhook_serializers.py
+++ b/saleor/webhook/tests/test_webhook_serializers.py
@@ -312,11 +312,9 @@ def test_serialize_checkout_lines_for_tax_calculation(
product = variant.product
total_price = base_calculations.calculate_base_line_total_price(
- line_info, checkout_info.channel
- ).amount
- unit_price = base_calculations.calculate_base_line_unit_price(
- line_info, checkout_info.channel
+ line_info
).amount
+ unit_price = base_calculations.calculate_base_line_unit_price(line_info).amount
assert data == {
"id": graphene.Node.to_global_id("CheckoutLine", line.pk),
@@ -374,11 +372,9 @@ def test_serialize_checkout_lines_for_tax_calculation_with_promotion(
product = variant.product
total_price = base_calculations.calculate_base_line_total_price(
- line_info, checkout_info.channel
- ).amount
- unit_price = base_calculations.calculate_base_line_unit_price(
- line_info, checkout_info.channel
+ line_info
).amount
+ unit_price = base_calculations.calculate_base_line_unit_price(line_info).amount
assert data == {
"id": graphene.Node.to_global_id("CheckoutLine", line.pk),