Skip to content

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

Fix applying `SPECIFIC_PRODUCT` and `apply_once_per_order` voucher on draft orders (#16153) (#16209)

Iga Karbowiak873bc25652d3
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index 1708c3bd7e..b40453a8b5 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -13,7 +13,8 @@ from uuid import UUID
from django.conf import settings
-from ..discount import DiscountType, VoucherType
+from ..core.pricing.interface import LineInfo
+from ..discount import VoucherType
from ..discount.interface import fetch_variant_rules_info, fetch_voucher_info
from ..shipping.interface import ShippingMethodData
from ..shipping.models import ShippingMethod, ShippingMethodChannelListing
@@ -27,7 +28,7 @@ from ..warehouse.models import Warehouse
if TYPE_CHECKING:
from ..account.models import Address, User
from ..channel.models import Channel
- from ..discount.interface import VariantPromotionRuleInfo, VoucherInfo
+ from ..checkout.models import CheckoutLine
from ..discount.models import (
CheckoutDiscount,
CheckoutLineDiscount,
@@ -36,7 +37,6 @@ if TYPE_CHECKING:
)
from ..plugins.manager import PluginsManager
from ..product.models import (
- Collection,
Product,
ProductChannelListing,
ProductType,
@@ -44,36 +44,17 @@ if TYPE_CHECKING:
ProductVariantChannelListing,
)
from ..tax.models import TaxClass, TaxConfiguration
- from .models import Checkout, CheckoutLine
+ from .models import Checkout
@dataclass
-class CheckoutLineInfo:
+class CheckoutLineInfo(LineInfo):
line: "CheckoutLine"
variant: "ProductVariant"
- channel_listing: "ProductVariantChannelListing"
product: "Product"
product_type: "ProductType"
- collections: list["Collection"]
discounts: list["CheckoutLineDiscount"]
- rules_info: list["VariantPromotionRuleInfo"]
- channel: "Channel"
tax_class: Optional["TaxClass"] = None
- voucher: Optional["Voucher"] = None
-
- def get_promotion_discounts(self) -> list["CheckoutLineDiscount"]:
- return [
- discount
- for discount in self.discounts
- if discount.type in [DiscountType.PROMOTION, DiscountType.ORDER_PROMOTION]
- ]
-
- def get_catalogue_discounts(self) -> list["CheckoutLineDiscount"]:
- return [
- discount
- for discount in self.discounts
- if discount.type == DiscountType.PROMOTION
- ]
@dataclass
@@ -314,6 +295,7 @@ def fetch_checkout_lines(
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
) -> tuple[Iterable[CheckoutLineInfo], Iterable[int]]:
"""Fetch checkout lines as CheckoutLineInfo objects."""
+ from ..discount.utils import apply_voucher_to_line
from .utils import get_voucher_for_checkout
select_related_fields = ["variant__product__product_type__tax_class"]
@@ -376,6 +358,8 @@ def fetch_checkout_lines(
discounts=discounts,
rules_info=rules_info,
channel=channel,
+ voucher=None,
+ voucher_code=None,
)
)
continue
@@ -392,6 +376,8 @@ def fetch_checkout_lines(
discounts=discounts,
rules_info=rules_info,
channel=channel,
+ voucher=None,
+ voucher_code=None,
)
)
@@ -408,8 +394,8 @@ def fetch_checkout_lines(
# discount from voucher
return lines_info, unavailable_variant_pks
if voucher.type == VoucherType.SPECIFIC_PRODUCT or voucher.apply_once_per_order:
- voucher_info = fetch_voucher_info(voucher)
- apply_voucher_to_checkout_line(voucher_info, lines_info)
+ voucher_info = fetch_voucher_info(voucher, checkout.voucher_code)
+ apply_voucher_to_line(voucher_info, lines_info)
return lines_info, unavailable_variant_pks
@@ -456,44 +442,6 @@ def _get_product_channel_listing(
return product_channel_listing
-def apply_voucher_to_checkout_line(
- voucher_info: "VoucherInfo",
- lines_info: Iterable[CheckoutLineInfo],
-):
- """Attach voucher to valid checkout lines info.
-
- Apply a voucher to checkout line info when the voucher has the type
- SPECIFIC_PRODUCTS or is applied only to the cheapest item.
- """
- from .utils import get_discounted_lines
-
- voucher = voucher_info.voucher
- discounted_lines_by_voucher: list[CheckoutLineInfo] = []
- lines_included_in_discount = lines_info
- if voucher.type == VoucherType.SPECIFIC_PRODUCT:
- discounted_lines_by_voucher.extend(
- get_discounted_lines(lines_info, voucher_info)
- )
- lines_included_in_discount = discounted_lines_by_voucher
- if voucher.apply_once_per_order:
- cheapest_line = _get_the_cheapest_line(lines_included_in_discount)
- if cheapest_line:
- discounted_lines_by_voucher = [cheapest_line]
- for line_info in lines_info:
- if line_info in discounted_lines_by_voucher:
- line_info.voucher = voucher
-
-
-def _get_the_cheapest_line(
- lines_info: Optional[Iterable[CheckoutLineInfo]],
-) -> Optional[CheckoutLineInfo]:
- if not lines_info:
- return None
- return min(
- lines_info, key=lambda line_info: line_info.channel_listing.discounted_price
- )
-
-
def fetch_checkout_info(
checkout: "Checkout",
lines: Iterable[CheckoutLineInfo],
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index 2f8f165b7e..b3236ce7a5 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -445,6 +445,8 @@ def test_get_discount_for_checkout_value_entire_order_voucher(
rules_info=[],
product_type=line.variant.product.product_type,
channel=channel_USD,
+ voucher=None,
+ voucher_code=None,
)
for line in checkout_with_items.lines.all()
]
@@ -609,6 +611,8 @@ def test_get_discount_for_checkout_value_specific_product_voucher(
product=line.variant.product,
variant=line.variant,
product_type=line.variant.product.product_type,
+ voucher=None,
+ voucher_code=None,
)
for line in checkout_with_items.lines.all()
]
diff --git a/saleor/core/pricing/__init__.py b/saleor/core/pricing/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/core/pricing/interface.py b/saleor/core/pricing/interface.py
new file mode 100644
index 0000000000..d4e6925f46
--- /dev/null
+++ b/saleor/core/pricing/interface.py
@@ -0,0 +1,59 @@
+from collections.abc import Iterable
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Optional, Union
+
+from ...discount import DiscountType
+
+if TYPE_CHECKING:
+ from ...channel.models import Channel
+ from ...checkout.models import CheckoutLine
+ from ...discount.interface import VariantPromotionRuleInfo
+ from ...discount.models import CheckoutLineDiscount, OrderLineDiscount, Voucher
+ from ...order.models import OrderLine
+ from ...product.models import (
+ Collection,
+ Product,
+ ProductVariant,
+ ProductVariantChannelListing,
+ )
+
+
+@dataclass
+class LineInfo:
+ line: Union["OrderLine", "CheckoutLine"]
+ variant: Optional["ProductVariant"]
+ product: Optional["Product"]
+ collections: list["Collection"]
+ channel_listing: "ProductVariantChannelListing"
+ channel: "Channel"
+ discounts: Iterable[Union["OrderLineDiscount", "CheckoutLineDiscount"]]
+ rules_info: list["VariantPromotionRuleInfo"]
+ voucher: Optional["Voucher"]
+ voucher_code: Optional[str]
+
+ def get_promotion_discounts(
+ self,
+ ):
+ return [
+ discount
+ for discount in self.discounts
+ if discount.type in [DiscountType.PROMOTION, DiscountType.ORDER_PROMOTION]
+ ]
+
+ def get_catalogue_discounts(
+ self,
+ ):
+ return [
+ discount
+ for discount in self.discounts
+ if discount.type == DiscountType.PROMOTION
+ ]
+
+ def get_voucher_discounts(
+ self,
+ ):
+ return [
+ discount
+ for discount in self.discounts
+ if discount.type == DiscountType.VOUCHER
+ ]
diff --git a/saleor/discount/interface.py b/saleor/discount/interface.py
index d835c58b2f..e470511f81 100644
--- a/saleor/discount/interface.py
+++ b/saleor/discount/interface.py
@@ -21,13 +21,16 @@ class VoucherInfo:
"""It contains the voucher's details and PKs of all applicable objects."""
voucher: Voucher
+ voucher_code: Optional[str]
product_pks: list[int]
variant_pks: list[int]
collection_pks: list[int]
category_pks: list[int]
-def fetch_voucher_info(voucher: Voucher) -> VoucherInfo:
+def fetch_voucher_info(
+ voucher: Voucher, voucher_code: Optional[str] = None
+) -> VoucherInfo:
variant_pks = list(variant.id for variant in voucher.variants.all())
product_pks = list(product.id for product in voucher.products.all())
category_pks = list(category.id for category in voucher.categories.all())
@@ -35,6 +38,7 @@ def fetch_voucher_info(voucher: Voucher) -> VoucherInfo:
return VoucherInfo(
voucher=voucher,
+ voucher_code=voucher_code,
product_pks=product_pks,
variant_pks=variant_pks,
collection_pks=collection_pks,
diff --git a/saleor/discount/tests/test_discounts.py b/saleor/discount/tests/test_discounts.py
index 53906b28ab..38c9f88c2f 100644
--- a/saleor/discount/tests/test_discounts.py
+++ b/saleor/discount/tests/test_discounts.py
@@ -6,6 +6,7 @@ import pytest
from django.utils import timezone
from prices import Money, TaxedMoney
+from ...checkout.fetch import CheckoutLineInfo
from ...discount.interface import VariantPromotionRuleInfo
from .. import DiscountValueType, RewardValueType, VoucherType
from ..models import (
@@ -16,6 +17,7 @@ from ..models import (
VoucherCustomer,
)
from ..utils import (
+ _get_the_cheapest_line,
activate_voucher_code,
add_voucher_usage_by_customer,
deactivate_voucher_code,
@@ -637,3 +639,34 @@ def test_is_order_level_voucher_another_type(voucher_type, voucher):
# then
assert result is False
+
+
+def test_get_the_cheapest_line_no_lines_provided():
+ # when
+ line_info = _get_the_cheapest_line(None)
+ # then
+ assert line_info is None
+
+
+def test_get_the_cheapest_line(checkout_with_items, channel_USD):
+ # given
+ lines = [
+ CheckoutLineInfo(
+ line=line,
+ channel_listing=line.variant.channel_listings.first(),
+ collections=[],
+ product=line.variant.product,
+ variant=line.variant,
+ discounts=list(line.discounts.all()),
+ rules_info=[],
+ product_type=line.variant.product.product_type,
+ channel=channel_USD,
+ voucher=None,
+ voucher_code=None,
+ )
+ for line in checkout_with_items.lines.all()
+ ]
+ # when
+ line_info = _get_the_cheapest_line(lines)
+ # then
+ assert line_info == lines[0]
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index b893b1c5bd..351e48693a 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -3,7 +3,7 @@ from collections import defaultdict, namedtuple
from collections.abc import Iterable, Iterator
from decimal import ROUND_HALF_UP, Decimal
from functools import partial
-from typing import TYPE_CHECKING, Callable, Optional, Union, cast
+from typing import TYPE_CHECKING, Callable, Optional, Union, cast, overload
from uuid import UUID
import graphene
@@ -19,14 +19,11 @@ from ..checkout.base_calculations import (
base_checkout_delivery_price,
base_checkout_subtotal,
)
-from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ..checkout.models import Checkout
from ..core.db.connection import allow_writer
from ..core.exceptions import InsufficientStock
from ..core.taxes import zero_money
from ..core.utils.promo_code import InvalidPromoCode
-from ..discount.models import VoucherType
-from ..order.fetch import DraftOrderLineInfo
from ..order.models import Order, OrderLine
from ..product.models import (
Product,
@@ -40,6 +37,7 @@ from . import (
PromotionType,
RewardType,
RewardValueType,
+ VoucherType,
)
from .interface import VariantPromotionRuleInfo, get_rule_translations
from .models import (
@@ -58,10 +56,13 @@ from .models import (
if TYPE_CHECKING:
from ..account.models import User
- from ..discount.models import Voucher
+ from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
+ from ..core.pricing.interface import LineInfo
+ from ..order.fetch import DraftOrderLineInfo
from ..plugins.manager import PluginsManager
from ..product.managers import ProductVariantQueryset
from ..product.models import VariantChannelListingPromotionRule
+ from .interface import VoucherInfo
CatalogueInfo = defaultdict[str, set[Union[int, str]]]
CATALOGUE_FIELDS = ["categories", "collections", "products", "variants"]
@@ -187,6 +188,78 @@ def get_voucher_code_instance(
return code_instance
+def apply_voucher_to_line(
+ voucher_info: "VoucherInfo",
+ lines_info: Iterable["LineInfo"],
+):
+ """Attach voucher to valid checkout or order lines info.
+
+ Apply a voucher to checkout/order line info when the voucher has the type
+ SPECIFIC_PRODUCTS or is applied only to the cheapest item.
+ """
+ voucher = voucher_info.voucher
+ discounted_lines_by_voucher: list[LineInfo] = []
+ lines_included_in_discount = lines_info
+ if voucher.type == VoucherType.SPECIFIC_PRODUCT:
+ discounted_lines_by_voucher.extend(
+ get_discounted_lines(lines_info, voucher_info)
+ )
+ lines_included_in_discount = discounted_lines_by_voucher
+ if voucher.apply_once_per_order:
+ if cheapest_line := _get_the_cheapest_line(lines_included_in_discount):
+ discounted_lines_by_voucher = [cheapest_line]
+ for line_info in lines_info:
+ if line_info in discounted_lines_by_voucher:
+ line_info.voucher = voucher
+ line_info.voucher_code = voucher_info.voucher_code
+
+
+def get_discounted_lines(
+ lines: Iterable["LineInfo"], voucher_info: "VoucherInfo"
+) -> Iterable["LineInfo"]:
+ 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
+ if not line_variant or not line_product:
+ continue
+ line_category = line_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_the_cheapest_line(
+ lines_info: Optional[Iterable["LineInfo"]],
+) -> Optional["LineInfo"]:
+ if not lines_info:
+ return None
+ return min(
+ lines_info, key=lambda line_info: line_info.channel_listing.discounted_price
+ )
+
+
def calculate_discounted_price_for_rules(
*, price: Money, rules: Iterable["PromotionRule"], currency: str
):
@@ -379,7 +452,7 @@ def create_or_update_discount_objects_from_promotion_for_checkout(
def create_checkout_line_discount_objects_for_catalogue_promotions(
- lines_info: Iterable[CheckoutLineInfo],
+ lines_info: Iterable["CheckoutLineInfo"],
):
discount_data = prepare_line_discount_objects_for_catalogue_promotions(lines_info)
if not discount_data or not lines_info:
@@ -428,9 +501,23 @@ def create_checkout_line_discount_objects_for_catalogue_promotions(
)
+@overload
def prepare_line_discount_objects_for_catalogue_promotions(
- lines_info: Union[Iterable["CheckoutLineInfo"], Iterable["DraftOrderLineInfo"]],
-):
+ lines_info: Iterable["CheckoutLineInfo"],
+) -> tuple[
+ list[dict], list["CheckoutLineDiscount"], list["CheckoutLineDiscount"], list[str]
+]: ...
+
+
+@overload
+def prepare_line_discount_objects_for_catalogue_promotions(
+ lines_info: Iterable["DraftOrderLineInfo"],
+) -> tuple[
+ list[dict], list["OrderLineDiscount"], list["OrderLineDiscount"], list[str]
+]: ...
+
+
+def prepare_line_discount_objects_for_catalogue_promotions(lines_info):
line_discounts_to_create_inputs: list[dict] = []
line_discounts_to_update: list[Union[CheckoutLineDiscount, OrderLineDiscount]] = []
line_discounts_to_remove: list[Union[CheckoutLineDiscount, OrderLineDiscount]] = []
@@ -492,7 +579,7 @@ def prepare_line_discount_objects_for_catalogue_promotions(
}
line_discounts_to_create_inputs.append(line_discount_input)
else:
- _update_discount(
+ _update_promotion_discount(
rule,
rule_info,
rule_discount_amount,
@@ -564,7 +651,7 @@ def get_discount_translated_name(rule_info: "VariantPromotionRuleInfo"):
return None
-def _update_discount(
+def _update_promotion_discount(
rule: "PromotionRule",
rule_info: "VariantPromotionRuleInfo",
rule_discount_amount: Decimal,
@@ -573,39 +660,73 @@ def _update_discount(
],
updated_fields: list[str],
):
- if discount_to_update.promotion_rule_id != rule.id:
- discount_to_update.promotion_rule_id = rule.id
- updated_fields.append("promotion_rule_id")
+ discount_name = get_discount_name(rule, rule_info.promotion)
+ translated_name = get_discount_translated_name(rule_info)
+ reason = prepare_promotion_discount_reason(
+ rule_info.promotion, get_sale_id(rule_info.promotion)
+ )
# gift rule has empty reward_value_type
value_type = rule.reward_value_type or RewardValueType.FIXED
+ # gift rule has empty reward_value
+ value = rule.reward_value or rule_discount_amount
+ _update_discount(
+ rule,
+ None,
+ discount_name,
+ translated_name,
+ reason,
+ rule_discount_amount,
+ value,
+ value_type,
+ DiscountType.PROMOTION,
+ discount_to_update,
+ updated_fields,
+ )
+
+
+def _update_discount(
+ rule: Optional["PromotionRule"],
+ voucher: Optional["Voucher"],
+ discount_name: str,
+ translated_name: str,
+ discount_reason: str,
+ discount_amount: Decimal,
+ value: Decimal,
+ value_type: str,
+ unique_type: str,
+ discount_to_update: Union[
+ "CheckoutLineDiscount", "CheckoutDiscount", "OrderLineDiscount", "OrderDiscount"
+ ],
+ updated_fields: list[str],
+):
+ if voucher and discount_to_update.voucher_id != voucher.id:
+ discount_to_update.voucher_id = voucher.id
+ updated_fields.append("voucher_id")
+ if rule and discount_to_update.promotion_rule_id != rule.id:
+ discount_to_update.promotion_rule_id = rule.id
+ updated_fields.append("promotion_rule_id")
if discount_to_update.value_type != value_type:
discount_to_update.value_type = value_type
updated_fields.append("value_type")
- # gift rule has empty reward_value
- value = rule.reward_value or rule_discount_amount
if discount_to_update.value != value:
discount_to_update.value = value
updated_fields.append("value")
- if discount_to_update.amount_value != rule_discount_amount:
- discount_to_update.amount_value = rule_discount_amount
+ if discount_to_update.amount_value != discount_amount:
+ discount_to_update.amount_value = discount_amount
updated_fields.append("amount_value")
- discount_name = get_discount_name(rule, rule_info.promotion)
if discount_to_update.name != discount_name:
discount_to_update.name = discount_name
updated_fields.append("name")
- translated_name = get_discount_translated_name(rule_info)
if discount_to_update.translated_name != translated_name:
discount_to_update.translated_name = translated_name
updated_fields.append("translated_name")
- reason = prepare_promotion_discount_reason(
- rule_info.promotion, get_sale_id(rule_info.promotion)
- )
- if discount_to_update.reason != reason:
- discount_to_update.reason = reason
+
+ if discount_to_update.reason != discount_reason:
+ discount_to_update.reason = discount_reason
updated_fields.append("reason")
if hasattr(discount_to_update, "unique_type"):
if discount_to_update.unique_type is None:
- discount_to_update.unique_type = DiscountType.PROMOTION
+ discount_to_update.unique_type = unique_type
updated_fields.append("unique_type")
@@ -906,8 +1027,8 @@ def _get_available_for_purchase_variant_ids(
@allow_writer()
def _handle_order_promotion_for_checkout(
- checkout_info: CheckoutInfo,
- lines_info: Iterable[CheckoutLineInfo],
+ checkout_info: "CheckoutInfo",
+ lines_info: Iterable["CheckoutLineInfo"],
discount_object_defaults: dict,
rule_info: VariantPromotionRuleInfo,
save: bool = False,
@@ -921,7 +1042,7 @@ def _handle_order_promotion_for_checkout(
if not created:
fields_to_update: list[str] = []
- _update_discount(
+ _update_promotion_discount(
discount_object_defaults["promotion_rule"],
rule_info,
discount_amount,
@@ -961,13 +1082,15 @@ def delete_gift_line(
@allow_writer()
def _handle_gift_reward_for_checkout(
- checkout_info: CheckoutInfo,
- lines_info: Iterable[CheckoutLineInfo],
+ checkout_info: "CheckoutInfo",
+ lines_info: Iterable["CheckoutLineInfo"],
gift_listing: ProductVariantChannelListing,
discount_object_defaults: dict,
rule_info: VariantPromotionRuleInfo,
save: bool = False,
):
+ from ..checkout.fetch import CheckoutLineInfo
+
with transaction.atomic():
line, line_created = create_gift_line(
checkout_info.checkout, gift_listing.variant_id
@@ -986,7 +1109,7 @@ def _handle_gift_reward_for_checkout(
if line_discount.line_id != line.id:
line_discount.line = line
fields_to_update.append("line_id")
- _update_discount(
+ _update_promotion_discount(
discount_object_defaults["promotion_rule"],
rule_info,
discount_object_defaults["amount_value"],
@@ -1013,6 +1136,8 @@ def _handle_gift_reward_for_checkout(
"product": variant.product,
"product_type": variant.product.product_type,
"collections": [],
+ "voucher": None,
+ "voucher_code": None,
}
gift_line_info = CheckoutLineInfo(**init_values)
@@ -1236,22 +1361,48 @@ def update_rule_variant_relation(
)
+def create_or_update_discount_objects_for_order(
+ order: "Order",
+ lines_info: Iterable["DraftOrderLineInfo"],
+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
+):
+ create_or_update_discount_objects_from_promotion_for_order(
+ order, lines_info, database_connection_name
+ )
+ create_or_update_line_discount_objects_for_manual_discounts(lines_info)
+ create_or_update_line_discount_objects_from_voucher(order, lines_info)
+ _copy_unit_discount_data_to_order_line(lines_info)
+
+
def create_or_update_discount_objects_from_promotion_for_order(
order: "Order",
lines_info: Iterable["DraftOrderLineInfo"],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
create_order_line_discount_objects_for_catalogue_promotions(lines_info)
+ # base unit price must reflect all actual catalogue discounts
+ _update_base_unit_price_amount_for_catalogue_promotion(lines_info)
create_order_discount_objects_for_order_promotions(
order, lines_info, database_connection_name=database_connection_name
)
- _copy_unit_discount_data_to_order_line(lines_info)
def create_order_line_discount_objects_for_catalogue_promotions(
- lines_info: Iterable[DraftOrderLineInfo],
+ lines_info: Iterable["DraftOrderLineInfo"],
):
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"],
+ discount_data: tuple[
+ list[dict],
+ list["OrderLineDiscount"],
+ list["OrderLineDiscount"],
+ list[str],
+ ],
+):
if not discount_data or not lines_info:
return
@@ -1262,7 +1413,7 @@ def create_order_line_discount_objects_for_catalogue_promotions(
updated_fields,
) = discount_data
- new_line_discounts = []
+ new_line_discounts: list[OrderLineDiscount] = []
with allow_writer():
with transaction.atomic():
# Protect against potential thread race. OrderLine object can have only
@@ -1293,21 +1444,18 @@ def create_order_line_discount_objects_for_catalogue_promotions(
_update_line_info_cached_discounts(
lines_info, new_line_discounts, discounts_to_update, discount_ids_to_remove
)
-
affected_line_ids = [
- discount_line.line.id
- for discount_line in new_line_discounts
- + discounts_to_update
- + discount_to_remove
+ discount_line.line_id
+ for discount_line in (new_line_discounts + discounts_to_update)
]
+ affected_line_ids.extend(discount_ids_to_remove)
modified_lines_info = [
line_info for line_info in lines_info if line_info.line.id in affected_line_ids
]
- # base unit price must reflect all actual catalogue discounts
- _update_base_unit_price_amount(modified_lines_info)
+ 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["DraftOrderLineInfo"]):
for line_info in lines_info:
if discounts := line_info.discounts:
line = line_info.line
@@ -1331,11 +1479,13 @@ def _copy_unit_discount_data_to_order_line(lines_info: Iterable[DraftOrderLineIn
line.unit_discount_value = discount_value
-def _update_base_unit_price_amount(lines_info: Iterable[DraftOrderLineInfo]):
+def _update_base_unit_price_amount_for_catalogue_promotion(
+ lines_info: Iterable["DraftOrderLineInfo"],
+):
for line_info in lines_info:
line = line_info.line
base_unit_price = line.undiscounted_base_unit_price_amount
- for discount in line_info.discounts:
+ for discount in line_info.get_catalogue_discounts():
unit_discount = discount.amount_value / line.quantity
base_unit_price -= unit_discount
line.base_unit_price_amount = max(base_unit_price, Decimal(0))
@@ -1423,14 +1573,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["DraftOrderLineInfo"],
):
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["DraftOrderLineInfo"]):
"""Set base order prices that includes only catalogue discounts."""
from ..order.base_calculations import base_order_subtotal
@@ -1454,7 +1604,7 @@ def _set_order_base_prices(order: Order, lines_info: Iterable[DraftOrderLineInfo
def _handle_order_promotion_for_order(
order: Order,
- lines_info: Iterable[DraftOrderLineInfo],
+ lines_info: Iterable["DraftOrderLineInfo"],
discount_object_defaults: dict,
rule_info: VariantPromotionRuleInfo,
):
@@ -1466,7 +1616,7 @@ def _handle_order_promotion_for_order(
if not created:
fields_to_update: list[str] = []
- _update_discount(
+ _update_promotion_discount(
discount_object_defaults["promotion_rule"],
rule_info,
discount_amount,
@@ -1482,11 +1632,13 @@ def _handle_order_promotion_for_order(
@allow_writer()
def _handle_gift_reward_for_order(
order: Order,
- lines_info: Iterable[DraftOrderLineInfo],
+ lines_info: Iterable["DraftOrderLineInfo"],
gift_listing: ProductVariantChannelListing,
discount_object_defaults: dict,
rule_info: VariantPromotionRuleInfo,
):
+ from ..order.fetch import DraftOrderLineInfo
+
with transaction.atomic():
line, line_created = create_gift_line(order, gift_listing.variant_id)
(
@@ -1503,7 +1655,7 @@ def _handle_gift_reward_for_order(
if line_discount.line_id != line.id:
line_discount.line = line
fields_to_update.append("line_id")
- _update_discount(
+ _update_promotion_discount(
discount_object_defaults["promotion_rule"],
rule_info,
discount_object_defaults["amount_value"],
@@ -1518,10 +1670,14 @@ def _handle_gift_reward_for_order(
init_values = {
"line": line,
"variant": variant,
+ "product": variant.product,
+ "collections": list(variant.product.collections.all()),
"channel_listing": gift_listing,
"discounts": [line_discount],
"rules_info": [rule_info],
"channel": order.channel_id,
+ "voucher": None,
+ "voucher_code": None,
}
gift_line_info = DraftOrderLineInfo(**init_values)
lines_info.append(gift_line_info) # type: ignore[attr-defined]
@@ -1533,6 +1689,174 @@ def _handle_gift_reward_for_order(
line_info.discounts = [line_discount]
+def create_or_update_line_discount_objects_for_manual_discounts(lines_info):
+ discount_to_update: list[OrderLineDiscount] = []
+ for line_info in lines_info:
+ manual_discount = line_info.get_manual_line_discount()
+ if not manual_discount:
+ continue
+ line = line_info.line
+ base_unit_price = line.undiscounted_base_unit_price
+ reduced_unit_price = apply_discount_to_value(
+ manual_discount.value,
+ manual_discount.value_type,
+ line.currency,
+ base_unit_price,
+ )
+ reduced_unit_price = max(reduced_unit_price, zero_money(line.currency))
+ line.base_unit_price_amount = reduced_unit_price.amount
+
+ discount_unit_amount = (base_unit_price - reduced_unit_price).amount
+ discount_amount = discount_unit_amount * line.quantity
+ if manual_discount.amount_value != discount_amount:
+ manual_discount.amount_value = discount_amount
+ discount_to_update.append(manual_discount)
+
+ if discount_to_update:
+ OrderLineDiscount.objects.bulk_update(discount_to_update, ["amount_value"])
+
+
+def create_or_update_line_discount_objects_from_voucher(order, lines_info):
+ """Create or update line discount object for voucher applied on lines.
+
+ The LineDiscount object is created for each line with voucher applied.
+ Only `SPECIFIC_PRODUCT` and `apply_once_per_order` voucher types are applied.
+
+ """
+ discount_data = prepare_line_discount_objects_for_voucher(lines_info)
+ modified_lines_info = create_order_line_discount_objects(lines_info, discount_data)
+ # base unit price must reflect all actual line voucher discounts
+ if modified_lines_info:
+ _reduce_base_unit_price_for_voucher_discount(modified_lines_info)
+
+
+# TODO (SHOPX-912): share the method with checkout
+def prepare_line_discount_objects_for_voucher(
+ lines_info: Iterable["DraftOrderLineInfo"],
+):
+ line_discounts_to_create_inputs: list[dict] = []
+ line_discounts_to_update: list[OrderLineDiscount] = []
+ line_discounts_to_remove: list[OrderLineDiscount] = []
+ updated_fields: list[str] = []
+
+ if not lines_info:
+ return
+
+ for line_info in lines_info:
+ line = line_info.line
+ total_price = line.base_unit_price * line.quantity
+ discount_amount = calculate_line_discount_amount_from_voucher(
+ line_info, total_price
+ )
+ # only one voucher can be applied
+ discount_to_update = None
+ if discounts_to_update := line_info.get_voucher_discounts():
+ discount_to_update = discounts_to_update[0]
+
+ if not discount_amount or line.is_gift:
+ if discount_to_update:
+ line_discounts_to_remove.append(discount_to_update)
+ continue
+
+ discount_amount = discount_amount.amount
+ discount_reason = f"Voucher code: {line_info.voucher_code}"
+ voucher = cast(Voucher, line_info.voucher)
+ discount_name = f"{voucher.name}"
+ if discount_to_update:
+ _update_discount(
+ None,
+ voucher,
+ discount_name,
+ # TODO (SHOPX-914): set translated voucher name
+ "",
+ discount_reason,
+ discount_amount,
+ # TODO (SHOPX-914): should be taken from voucher value_type and value
+ discount_amount,
+ DiscountValueType.FIXED,
+ DiscountType.VOUCHER,
+ discount_to_update,
+ updated_fields,
+ )
+ line_discounts_to_update.append(discount_to_update)
+ else:
+ line_discount_input = {
+ "line": line,
+ "type": DiscountType.VOUCHER,
+ # TODO (SHOPX-914): should be taken from voucher value_type and value
+ "value_type": DiscountValueType.FIXED,
+ "value": discount_amount,
+ "amount_value": discount_amount,
+ "currency": line.currency,
+ "name": discount_name,
+ "translated_name": None,
+ "reason": discount_reason,
+ "voucher": line_info.voucher,
+ "unique_type": DiscountType.VOUCHER,
+ }
+ line_discounts_to_create_inputs.append(line_discount_input)
+
+ return (
+ line_discounts_to_create_inputs,
+ line_discounts_to_update,
+ line_discounts_to_remove,
+ updated_fields,
+ )
+
+
+def calculate_line_discount_amount_from_voucher(
+ line_info: "LineInfo", total_price: Money
+):
+ """Calculate discount amount for voucher applied on line.
+
+ Included vouchers: `SPECIFIC_PRODUCT` and `apply_once_per_order`.
+
+ Args:
+ line_info: Order/Checkout line data.
+ total_price: Total price of the line, should be already reduced by
+ catalogue discounts if any applied.
+
+ """
+ if not line_info.voucher:
+ return zero_money(total_price.currency)
+
+ channel = line_info.channel
+ quantity = line_info.line.quantity
+ 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
+ )
+ discount_amount = min(voucher_discount_amount, total_price)
+ else:
+ unit_price = total_price / quantity
+ voucher_unit_discount_amount = line_info.voucher.get_discount_amount_for(
+ unit_price, channel=channel
+ )
+ discount_amount = min(
+ voucher_unit_discount_amount * quantity,
+ total_price,
+ )
+ else:
+ unit_price = total_price / quantity
+ voucher_unit_discount_amount = line_info.voucher.get_discount_amount_for(
+ unit_price, channel=channel
+ )
+ discount_amount = min(voucher_unit_discount_amount, unit_price)
+ return discount_amount
+
+
+def _reduce_base_unit_price_for_voucher_discount(
+ lines_info: Iterable["DraftOrderLineInfo"],
+):
+ for line_info in lines_info:
+ line = line_info.line
+ base_unit_price = line.base_unit_price_amount
+ for discount in line_info.get_voucher_discounts():
+ base_unit_price -= discount.amount_value / line.quantity
+ line.base_unit_price_amount = max(base_unit_price, Decimal(0))
+
+
def get_active_catalogue_promotion_rules(
allow_replica: bool = False,
) -> "QuerySet[PromotionRule]":
diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.py
index 92f3886be4..2c23aa7987 100644
--- a/saleor/graphql/checkout/dataloaders.py
+++ b/saleor/graphql/checkout/dataloaders.py
@@ -7,7 +7,6 @@ from promise import Promise
from ...checkout.fetch import (
CheckoutInfo,
CheckoutLineInfo,
- apply_voucher_to_checkout_line,
)
from ...checkout.models import Checkout, CheckoutLine, CheckoutMetadata
from ...checkout.problems import (
@@ -23,6 +22,7 @@ from ...checkout.problems import (
from ...core.db.connection import allow_writer_in_context
from ...discount import VoucherType
from ...discount.interface import VariantPromotionRuleInfo
+from ...discount.utils import apply_voucher_to_line
from ...payment.models import TransactionItem
from ...product.models import ProductChannelListing
from ...warehouse.models import Stock
@@ -143,6 +143,8 @@ class CheckoutLinesInfoByCheckoutTokenLoader(DataLoader[str, list[CheckoutLineIn
tax_class=tax_class_map[line.variant_id],
channel=channels[checkout.channel_id],
rules_info=rules_info_map[line.id],
+ voucher=None,
+ voucher_code=None,
)
for line in lines
]
@@ -159,7 +161,7 @@ class CheckoutLinesInfoByCheckoutTokenLoader(DataLoader[str, list[CheckoutLineIn
voucher.type == VoucherType.SPECIFIC_PRODUCT
or voucher.apply_once_per_order
):
- apply_voucher_to_checkout_line(
+ apply_voucher_to_line(
voucher_info=voucher_info,
lines_info=lines_info_map[checkout.pk],
)
diff --git a/saleor/graphql/checkout/tests/mutations/test_utils.py b/saleor/graphql/checkout/tests/mutations/test_utils.py
index 751bdb4876..3ca44f1354 100644
--- a/saleor/graphql/checkout/tests/mutations/test_utils.py
+++ b/saleor/graphql/checkout/tests/mutations/test_utils.py
@@ -1,8 +1,6 @@
import graphene
from .....checkout.fetch import (
- CheckoutLineInfo,
- _get_the_cheapest_line,
fetch_checkout_lines,
)
from ...mutations.utils import (
@@ -183,32 +181,3 @@ def test_group_on_update_when_one_line_and_mixed_parameters_provided(
assert expected == group_lines_input_data_on_update(
lines_data, existing_checkout_lines
)
-
-
-def test_get_the_cheapest_line_no_lines_provided():
- # when
- line_info = _get_the_cheapest_line(None)
- # then
- assert line_info is None
-
-
-def test_get_the_cheapest_line(checkout_with_items, channel_USD):
- # given
- lines = [
- CheckoutLineInfo(
- line=line,
- channel_listing=line.variant.channel_listings.first(),
- collections=[],
- product=line.variant.product,
- variant=line.variant,
- discounts=list(line.discounts.all()),
- rules_info=[],
- product_type=line.variant.product.product_type,
- channel=channel_USD,
- )
- for line in checkout_with_items.lines.all()
- ]
- # when
- line_info = _get_the_cheapest_line(lines)
- # then
- assert line_info == lines[0]
diff --git a/saleor/graphql/core/types/taxes.py b/saleor/graphql/core/types/taxes.py
index 23084fbc7e..ee8d2f7202 100644
--- a/saleor/graphql/core/types/taxes.py
+++ b/saleor/graphql/core/types/taxes.py
@@ -7,7 +7,7 @@ from promise import Promise
from ....checkout import base_calculations
from ....checkout.models import Checkout, CheckoutLine
from ....core.prices import quantize_price
-from ....discount import DiscountType, VoucherType
+from ....discount import DiscountType
from ....discount.utils import is_order_level_voucher
from ....order.models import Order, OrderLine
from ....order.utils import get_order_country
@@ -429,13 +429,7 @@ class TaxableObject(BaseObjectType):
for discount in discounts
if (
discount.type == DiscountType.MANUAL
- # TODO (SHOPX-873): apply_once_per_order voucher are included
- # for now, as the discount for such vouchers is currently not
- # propagated to the draft order lines
- or (
- discount.voucher
- and discount.voucher.type == VoucherType.ENTIRE_ORDER
- )
+ or is_order_level_voucher(discount.voucher)
)
]
diff --git a/saleor/graphql/discount/dataloaders.py b/saleor/graphql/discount/dataloaders.py
index 18b5e44439..8f3338a34d 100644
--- a/saleor/graphql/discount/dataloaders.py
+++ b/saleor/graphql/discount/dataloaders.py
@@ -210,6 +210,7 @@ class VoucherInfoByVoucherCodeLoader(DataLoader[str, Optional[VoucherInfo]]):
voucher_infos.append(
VoucherInfo(
voucher=voucher_code.voucher,
+ voucher_code=voucher_code.code,
product_pks=product_pks_map.get(voucher_code.voucher_id, []),
variant_pks=variant_pks_map.get(voucher_code.voucher_id, []),
category_pks=category_pks_map.get(voucher_code.voucher_id, []),
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index 5b5bf4a191..f602df889e 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -343,6 +343,7 @@ class DraftOrderCreate(
voucher = code_instance.voucher
cls.clean_voucher_listing(voucher, channel, "voucher_code")
cleaned_input["voucher"] = voucher
+ cleaned_input["voucher_code"] = voucher_code
cleaned_input["voucher_code_instance"] = code_instance
@classmethod
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
index 543c1e9782..5b068a10a1 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -134,7 +134,7 @@ DRAFT_ORDER_CREATE_MUTATION = """
"""
-def test_draft_order_create_with_voucher(
+def test_draft_order_create_with_voucher_entire_order(
staff_api_client,
permission_group_manage_orders,
staff_user,
@@ -696,6 +696,290 @@ def test_draft_order_create_percentage_voucher(
assert order_discount.amount_value == discount_amount
+def test_draft_order_create_with_voucher_specific_product(
+ staff_api_client,
+ permission_group_manage_orders,
+ customer_user,
+ product_without_shipping,
+ shipping_method,
+ variant,
+ voucher_specific_product_type,
+ channel_USD,
+ graphql_address_data,
+):
+ # given
+ discounted_variant = variant
+ voucher = voucher_specific_product_type
+ code = voucher.codes.first().code
+ query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_0_id = graphene.Node.to_global_id("ProductVariant", discounted_variant.id)
+ discounted_variant_listing = discounted_variant.channel_listings.get(
+ channel=channel_USD
+ )
+ variant_0_qty = 2
+
+ variant_1 = product_without_shipping.variants.first()
+ variant_1_qty = 1
+ channel_listing_1 = variant_1.channel_listings.get(channel=channel_USD)
+
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)
+ variant_list = [
+ {"variantId": variant_0_id, "quantity": variant_0_qty},
+ {"variantId": variant_1_id, "quantity": variant_1_qty},
+ ]
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+
+ voucher_listing = voucher.channel_listings.get(channel=channel_USD)
+ discount_value = voucher_listing.discount_value
+
+ shipping_address = graphql_address_data
+ redirect_url = "https://www.example.com"
+
+ variables = {
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ "billingAddress": shipping_address,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucherCode": code,
+ "channelId": channel_id,
+ "redirectUrl": redirect_url,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ assert not content["data"]["draftOrderCreate"]["errors"]
+ data = content["data"]["draftOrderCreate"]["order"]
+ assert data["status"] == OrderStatus.DRAFT.upper()
+ assert data["voucher"]["code"] == code
+ assert data["voucherCode"] == code
+ assert data["redirectUrl"] == redirect_url
+
+ shipping_total = shipping_method.channel_listings.get(
+ channel=channel_USD
+ ).get_total()
+ discount_amount = (
+ discounted_variant_listing.discounted_price_amount
+ * variant_0_qty
+ * discount_value
+ / 100
+ )
+ discounted_variant_total = (
+ discounted_variant_listing.discounted_price_amount * variant_0_qty
+ - discount_amount
+ )
+ variant_1_total = channel_listing_1.discounted_price_amount * variant_1_qty
+ order_total = discounted_variant_total + variant_1_total + shipping_total.amount
+ assert data["undiscountedTotal"]["gross"]["amount"] == order_total + discount_amount
+ assert data["total"]["gross"]["amount"] == order_total
+
+ order = Order.objects.first()
+ subtotal = get_subtotal(order.lines.all(), order.currency)
+ assert data["subtotal"]["gross"]["amount"] == subtotal.gross.amount
+
+ assert order.voucher_code == voucher.code
+ assert order.user == customer_user
+ assert order.shipping_method == shipping_method
+ assert order.shipping_method_name == shipping_method.name
+ assert order.search_vector
+ shipping_total = shipping_method.channel_listings.get(
+ channel_id=order.channel_id
+ ).get_total()
+ assert order.base_shipping_price == shipping_total
+
+ lines_data = data["lines"]
+ discounted_line_data, line_1_data = lines_data
+ assert discounted_line_data["productVariantId"] == variant_0_id
+ assert discounted_line_data["quantity"] == variant_0_qty
+ assert (
+ discounted_line_data["unitPrice"]["gross"]["amount"]
+ == discounted_variant_total / variant_0_qty
+ )
+ assert (
+ discounted_line_data["totalPrice"]["gross"]["amount"]
+ == discounted_variant_total
+ )
+ assert (
+ discounted_line_data["unitDiscount"]["amount"]
+ == discount_amount / variant_0_qty
+ )
+ assert discounted_line_data["unitDiscountType"] == DiscountValueType.FIXED.upper()
+ assert discounted_line_data["unitDiscountReason"] == f"Voucher code: {code}"
+
+ assert line_1_data["productVariantId"] == variant_1_id
+ assert line_1_data["quantity"] == variant_1_qty
+ assert (
+ line_1_data["unitPrice"]["gross"]["amount"] == variant_1_total / variant_1_qty
+ )
+ assert line_1_data["totalPrice"]["gross"]["amount"] == variant_1_total
+ assert line_1_data["unitDiscount"]["amount"] == 0
+ assert line_1_data["unitDiscountType"] is None
+ assert line_1_data["unitDiscountReason"] is None
+
+ # TODO (SHOPX-874): Order discount object shouldn't be created
+ assert order.discounts.count() == 1
+
+ discounted_line = order.lines.get(variant=discounted_variant)
+ assert discounted_line.discounts.count() == 1
+ order_line_discount = discounted_line.discounts.first()
+ assert order_line_discount.voucher == voucher
+ assert order_line_discount.type == DiscountType.VOUCHER
+ assert order_line_discount.value_type == DiscountValueType.FIXED
+ assert order_line_discount.value == discount_amount
+ assert order_line_discount.amount_value == discount_amount
+
+
+def test_draft_order_create_with_voucher_apply_once_per_order(
+ staff_api_client,
+ permission_group_manage_orders,
+ customer_user,
+ product_without_shipping,
+ shipping_method,
+ variant,
+ voucher_percentage,
+ channel_USD,
+ graphql_address_data,
+):
+ # given
+ discounted_variant = variant
+ voucher = voucher_percentage
+ voucher.apply_once_per_order = True
+ voucher.save(update_fields=["apply_once_per_order"])
+ code = voucher.codes.first().code
+
+ query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_0_id = graphene.Node.to_global_id("ProductVariant", discounted_variant.id)
+ discounted_variant_listing = discounted_variant.channel_listings.get(
+ channel=channel_USD
+ )
+ variant_0_qty = 2
+
+ variant_1 = product_without_shipping.variants.first()
+ variant_1_qty = 1
+ channel_listing_1 = variant_1.channel_listings.get(channel=channel_USD)
+
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)
+ variant_list = [
+ {"variantId": variant_0_id, "quantity": variant_0_qty},
+ {"variantId": variant_1_id, "quantity": variant_1_qty},
+ ]
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+
+ voucher_listing = voucher.channel_listings.get(channel=channel_USD)
+ discount_value = voucher_listing.discount_value
+
+ shipping_address = graphql_address_data
+ redirect_url = "https://www.example.com"
+
+ variables = {
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ "billingAddress": shipping_address,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucherCode": code,
+ "channelId": channel_id,
+ "redirectUrl": redirect_url,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ assert not content["data"]["draftOrderCreate"]["errors"]
+ data = content["data"]["draftOrderCreate"]["order"]
+ assert data["status"] == OrderStatus.DRAFT.upper()
+ assert data["voucher"]["code"] == code
+ assert data["voucherCode"] == code
+ assert data["redirectUrl"] == redirect_url
+
+ shipping_total = shipping_method.channel_listings.get(
+ channel=channel_USD
+ ).get_total()
+ discount_amount = (
+ discounted_variant_listing.discounted_price_amount * discount_value / 100
+ )
+ discounted_variant_total = (
+ discounted_variant_listing.discounted_price_amount * variant_0_qty
+ - discount_amount
+ )
+ variant_1_total = channel_listing_1.discounted_price_amount * variant_1_qty
+ order_total = discounted_variant_total + variant_1_total + shipping_total.amount
+ assert data["undiscountedTotal"]["gross"]["amount"] == order_total + discount_amount
+ assert data["total"]["gross"]["amount"] == order_total
+
+ order = Order.objects.first()
+ subtotal = get_subtotal(order.lines.all(), order.currency)
+ assert data["subtotal"]["gross"]["amount"] == subtotal.gross.amount
+
+ assert order.voucher_code == voucher.code
+ assert order.user == customer_user
+ assert order.shipping_method == shipping_method
+ assert order.shipping_method_name == shipping_method.name
+ assert order.search_vector
+ shipping_total = shipping_method.channel_listings.get(
+ channel_id=order.channel_id
+ ).get_total()
+ assert order.base_shipping_price == shipping_total
+
+ lines_data = data["lines"]
+ discounted_line_data, line_1_data = lines_data
+ assert discounted_line_data["productVariantId"] == variant_0_id
+ assert discounted_line_data["quantity"] == variant_0_qty
+ assert (
+ discounted_line_data["unitPrice"]["gross"]["amount"]
+ == discounted_variant_total / variant_0_qty
+ )
+ assert (
+ discounted_line_data["totalPrice"]["gross"]["amount"]
+ == discounted_variant_total
+ )
+ assert (
+ discounted_line_data["unitDiscount"]["amount"]
+ == discount_amount / variant_0_qty
+ )
+ assert discounted_line_data["unitDiscountType"] == DiscountValueType.FIXED.upper()
+ assert discounted_line_data["unitDiscountReason"] == f"Voucher code: {code}"
+
+ assert line_1_data["productVariantId"] == variant_1_id
+ assert line_1_data["quantity"] == variant_1_qty
+ assert (
+ line_1_data["unitPrice"]["gross"]["amount"] == variant_1_total / variant_1_qty
+ )
+ assert line_1_data["totalPrice"]["gross"]["amount"] == variant_1_total
+ assert line_1_data["unitDiscount"]["amount"] == 0
+ assert line_1_data["unitDiscountType"] is None
+ assert line_1_data["unitDiscountReason"] is None
+
+ # TODO (SHOPX-874): Order discount object shouldn't be created
+ assert order.discounts.count() == 1
+
+ discounted_line = order.lines.get(variant=discounted_variant)
+ assert discounted_line.discounts.count() == 1
+ order_line_discount = discounted_line.discounts.first()
+ assert order_line_discount.voucher == voucher
+ assert order_line_discount.type == DiscountType.VOUCHER
+ assert order_line_discount.value_type == DiscountValueType.FIXED
+ assert order_line_discount.value == discount_amount
+ assert order_line_discount.amount_value == discount_amount
+
+
def test_draft_order_create_by_user_no_channel_access(
staff_api_client,
permission_group_all_perms_channel_USD_only,
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_update.py b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
index 25e96ca74a..f3b63de7f5 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
@@ -178,7 +178,7 @@ def test_draft_order_update_voucher_not_available(
assert error["field"] == "voucher"
-def test_draft_order_update_with_voucher(
+def test_draft_order_update_with_voucher_entire_order(
staff_api_client,
permission_group_manage_orders,
draft_order,
@@ -259,6 +259,195 @@ def test_draft_order_update_with_voucher(
assert order_discount.amount_value == voucher_listing.discount_value
+def test_draft_order_update_with_voucher_specific_product(
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ voucher_specific_product_type,
+ graphql_address_data,
+):
+ # given
+ voucher = voucher_specific_product_type
+ code = voucher.codes.first().code
+
+ order = draft_order
+ assert not order.voucher
+ assert not order.voucher_code
+ assert not order.customer_note
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ query = DRAFT_ORDER_UPDATE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ order_total = order.total_net_amount
+
+ discounted_line, line_1 = order.lines.all()
+ voucher.variants.add(discounted_line.variant)
+ discount_amount = (
+ discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ * voucher_listing.discount_value
+ / 100
+ )
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "voucherCode": code,
+ "shippingAddress": graphql_address_data,
+ "billingAddress": graphql_address_data,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderUpdate"]
+ assert not data["errors"]
+ assert data["order"]["voucher"]["code"] == voucher.code
+ assert data["order"]["voucherCode"] == voucher.code
+
+ assert data["order"]["undiscountedTotal"]["net"]["amount"] == order_total
+ assert data["order"]["total"]["net"]["amount"] == order_total - discount_amount
+
+ discounted_variant_total = (
+ discounted_line.undiscounted_base_unit_price_amount * discounted_line.quantity
+ - discount_amount
+ )
+ lines_data = data["order"]["lines"]
+ discounted_line_data, line_1_data = lines_data
+ assert (
+ discounted_line_data["unitPrice"]["net"]["amount"]
+ == discounted_variant_total / discounted_line.quantity
+ )
+ assert (
+ discounted_line_data["totalPrice"]["net"]["amount"] == discounted_variant_total
+ )
+ assert (
+ discounted_line_data["unitDiscount"]["amount"]
+ == discount_amount / discounted_line.quantity
+ )
+ assert discounted_line_data["unitDiscountType"] == DiscountValueType.FIXED.upper()
+ assert discounted_line_data["unitDiscountReason"] == f"Voucher code: {code}"
+
+ line_1_total = line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ assert line_1_data["unitPrice"]["net"]["amount"] == line_1_total / line_1.quantity
+ assert line_1_data["totalPrice"]["net"]["amount"] == line_1_total
+ assert line_1_data["unitDiscount"]["amount"] == 0
+ assert line_1_data["unitDiscountType"] is None
+ assert line_1_data["unitDiscountReason"] is None
+
+ order.refresh_from_db()
+ assert order.voucher_code == voucher.code
+ assert order.search_vector
+
+ # TODO (SHOPX-874): Order discount object shouldn't be created
+ assert order.discounts.count() == 1
+
+ assert discounted_line.discounts.count() == 1
+ order_line_discount = discounted_line.discounts.first()
+ assert order_line_discount.voucher == voucher
+ assert order_line_discount.type == DiscountType.VOUCHER
+ assert order_line_discount.value_type == DiscountValueType.FIXED
+ assert order_line_discount.value == discount_amount
+ assert order_line_discount.amount_value == discount_amount
+
+
+def test_draft_order_update_with_voucher_apply_once_per_order(
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ voucher_percentage,
+ graphql_address_data,
+):
+ # given
+ order = draft_order
+ assert not order.voucher
+ assert not order.voucher_code
+
+ voucher = voucher_percentage
+ voucher.apply_once_per_order = True
+ voucher.save(update_fields=["apply_once_per_order"])
+ code = voucher.codes.first().code
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ query = DRAFT_ORDER_UPDATE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ order_total = order.total_net_amount
+
+ discounted_line, line_1 = order.lines.all()
+ voucher.variants.add(discounted_line.variant)
+ discount_amount = (
+ discounted_line.undiscounted_base_unit_price_amount
+ * voucher_listing.discount_value
+ / 100
+ )
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "voucher": voucher_id,
+ "shippingAddress": graphql_address_data,
+ "billingAddress": graphql_address_data,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderUpdate"]
+ assert not data["errors"]
+ assert data["order"]["voucher"]["code"] == voucher.code
+ assert data["order"]["voucherCode"] == voucher.code
+ assert data["order"]["undiscountedTotal"]["net"]["amount"] == order_total
+ assert data["order"]["total"]["net"]["amount"] == order_total - discount_amount
+
+ discounted_variant_total = (
+ discounted_line.undiscounted_base_unit_price_amount * discounted_line.quantity
+ - discount_amount
+ )
+ lines_data = data["order"]["lines"]
+ discounted_line_data, line_1_data = lines_data
+ assert discounted_line_data["unitPrice"]["net"]["amount"] == float(
+ round(discounted_variant_total / discounted_line.quantity, 2)
+ )
+ assert (
+ discounted_line_data["totalPrice"]["net"]["amount"] == discounted_variant_total
+ )
+ assert discounted_line_data["unitDiscount"]["amount"] == float(
+ round(discount_amount / discounted_line.quantity, 2)
+ )
+ assert discounted_line_data["unitDiscountType"] == DiscountValueType.FIXED.upper()
+ assert discounted_line_data["unitDiscountReason"] == f"Voucher code: {code}"
+
+ line_1_total = line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ assert line_1_data["unitPrice"]["net"]["amount"] == line_1_total / line_1.quantity
+ assert line_1_data["totalPrice"]["net"]["amount"] == line_1_total
+ assert line_1_data["unitDiscount"]["amount"] == 0
+ assert line_1_data["unitDiscountType"] is None
+ assert line_1_data["unitDiscountReason"] is None
+
+ order.refresh_from_db()
+ assert order.voucher_code == voucher.code
+ assert order.search_vector
+
+ # TODO (SHOPX-874): Order discount object shouldn't be created
+ assert order.discounts.count() == 1
+
+ assert discounted_line.discounts.count() == 1
+ order_line_discount = discounted_line.discounts.first()
+ assert order_line_discount.voucher == voucher
+ assert order_line_discount.type == DiscountType.VOUCHER
+ assert order_line_discount.value_type == DiscountValueType.FIXED
+ assert order_line_discount.value == discount_amount
+ assert order_line_discount.amount_value == discount_amount
+
+
def test_draft_order_update_clear_voucher(
staff_api_client,
permission_group_manage_orders,
diff --git a/saleor/graphql/order/tests/mutations/test_order_discount.py b/saleor/graphql/order/tests/mutations/test_order_discount.py
index 4950e1b440..d8a1ec0a2e 100644
--- a/saleor/graphql/order/tests/mutations/test_order_discount.py
+++ b/saleor/graphql/order/tests/mutations/test_order_discount.py
@@ -1045,10 +1045,10 @@ def test_update_order_line_discount(
- (second_line.base_unit_price - second_line.unit_price.gross)
* second_line.quantity
)
- assert (
- discount_applied_to_discounted_line
- == (line_to_discount.base_unit_price - line_to_discount.unit_price.gross)
- * line_to_discount.quantity
+ assert discount_applied_to_discounted_line == quantize_price(
+ (line_to_discount.base_unit_price - line_to_discount.unit_price.gross)
+ * line_to_discount.quantity,
+ order.currency,
)
errors = data["errors"]
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index f6a388a9d8..acb92b0842 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -1593,7 +1593,9 @@ class Order(ModelObjectType[models.Order]):
return None
for discount in discounts:
if discount.type == DiscountType.VOUCHER:
- return Money(amount=discount.value, currency=discount.currency)
+ return Money(
+ amount=discount.amount_value, currency=discount.currency
+ )
return None
return (
diff --git a/saleor/order/base_calculations.py b/saleor/order/base_calculations.py
index 91bb48f51d..b1df2d7dad 100644
--- a/saleor/order/base_calculations.py
+++ b/saleor/order/base_calculations.py
@@ -9,7 +9,7 @@ from ..core.prices import quantize_price
from ..core.taxes import zero_money
from ..discount import DiscountType, DiscountValueType, VoucherType
from ..discount.models import OrderDiscount
-from ..discount.utils import apply_discount_to_value
+from ..discount.utils import apply_discount_to_value, is_order_level_voucher
from ..shipping.models import ShippingMethodChannelListing
from .interface import OrderTaxedPricesData
@@ -36,6 +36,7 @@ def base_order_subtotal(order: "Order", lines: Iterable["OrderLine"]) -> Money:
quantity = line.quantity
base_line_total = line.base_unit_price * quantity
subtotal += base_line_total
+
return quantize_price(subtotal, currency)
@@ -106,7 +107,7 @@ def propagate_order_discount_on_order_prices(
shipping_price_before_discount = shipping_price
if order_discount.type == DiscountType.VOUCHER:
voucher = order_discount.voucher
- if voucher and voucher.type == VoucherType.ENTIRE_ORDER:
+ if is_order_level_voucher(voucher):
subtotal = apply_discount_to_value(
value=order_discount.value,
value_type=order_discount.value_type,
@@ -160,9 +161,6 @@ def propagate_order_discount_on_order_prices(
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"])
-
# Apply shipping voucher discount
if shipping_voucher_discount:
shipping_price = apply_discount_to_value(
@@ -171,6 +169,13 @@ def propagate_order_discount_on_order_prices(
currency=currency,
price_to_discount=shipping_price,
)
+ discount_amount = shipping_price_before_discount - shipping_price
+ if shipping_voucher_discount.amount != discount_amount:
+ shipping_voucher_discount.amount = discount_amount
+ order_discounts_to_update.append(shipping_voucher_discount)
+
+ if order_discounts_to_update:
+ OrderDiscount.objects.bulk_update(order_discounts_to_update, ["amount_value"])
return subtotal, shipping_price
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index fe882fe613..10d568b2ef 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -12,7 +12,7 @@ from ..core.db.connection import allow_writer
from ..core.prices import quantize_price
from ..core.taxes import TaxData, TaxEmptyData, TaxError, zero_taxed_money
from ..discount import DiscountType
-from ..discount.utils import create_or_update_discount_objects_from_promotion_for_order
+from ..discount.utils import create_or_update_discount_objects_for_order
from ..payment.model_helpers import get_subtotal
from ..plugins import PLUGIN_IDENTIFIER_PREFIX
from ..plugins.manager import PluginsManager
@@ -57,7 +57,7 @@ def fetch_order_prices_if_expired(
# handle promotions
lines_info: list[DraftOrderLineInfo] = fetch_draft_order_lines_info(order, lines)
- create_or_update_discount_objects_from_promotion_for_order(
+ create_or_update_discount_objects_for_order(
order, lines_info, database_connection_name
)
lines = [line_info.line for line_info in lines_info]
diff --git a/saleor/order/fetch.py b/saleor/order/fetch.py
index eab485ca52..7324b28648 100644
--- a/saleor/order/fetch.py
+++ b/saleor/order/fetch.py
@@ -1,15 +1,20 @@
from collections.abc import Iterable
from dataclasses import dataclass
-from typing import Optional, cast
+from typing import Optional
from uuid import UUID
from django.db.models import prefetch_related_objects
from ..channel.models import Channel
from ..core.db.connection import allow_writer
-from ..discount import DiscountType
-from ..discount.interface import VariantPromotionRuleInfo, fetch_variant_rules_info
-from ..discount.models import OrderLineDiscount, Voucher
+from ..core.pricing.interface import LineInfo
+from ..discount import DiscountType, VoucherType
+from ..discount.interface import (
+ fetch_variant_rules_info,
+ fetch_voucher_info,
+)
+from ..discount.models import OrderLineDiscount
+from ..discount.utils import apply_voucher_to_line
from ..payment.models import Payment
from ..product.models import (
DigitalContent,
@@ -74,28 +79,17 @@ def fetch_order_lines(order: "Order") -> list[OrderLineInfo]:
@dataclass
-class DraftOrderLineInfo:
+class DraftOrderLineInfo(LineInfo):
line: "OrderLine"
- variant: "ProductVariant"
- channel_listing: "ProductVariantChannelListing"
discounts: list["OrderLineDiscount"]
- rules_info: list["VariantPromotionRuleInfo"]
- channel: "Channel"
- voucher: Optional["Voucher"] = None
-
- def get_promotion_discounts(self) -> list["OrderLineDiscount"]:
- return [
- discount
- for discount in self.discounts
- if discount.type in [DiscountType.PROMOTION, DiscountType.ORDER_PROMOTION]
- ]
- def get_catalogue_discounts(self) -> list["OrderLineDiscount"]:
- return [
- discount
- for discount in self.discounts
- if discount.type == DiscountType.PROMOTION
- ]
+ def get_manual_line_discount(
+ self,
+ ) -> Optional["OrderLineDiscount"]:
+ for discount in self.discounts:
+ if discount.type == DiscountType.MANUAL:
+ return discount
+ return None
def fetch_draft_order_lines_info(
@@ -106,6 +100,7 @@ def fetch_draft_order_lines_info(
"discounts__promotion_rule__promotion",
"variant__channel_listings__variantlistingpromotionrule__promotion_rule__promotion__translations",
"variant__channel_listings__variantlistingpromotionrule__promotion_rule__translations",
+ "variant__product__collections",
]
if lines is None:
with allow_writer():
@@ -121,7 +116,10 @@ def fetch_draft_order_lines_info(
channel = order.channel
for line in lines:
- variant = cast(ProductVariant, line.variant)
+ variant = line.variant
+ if not variant:
+ continue
+ product = variant.product
variant_channel_listing = get_prefetched_variant_listing(variant, channel.id)
if not variant_channel_listing:
continue
@@ -135,12 +133,22 @@ def fetch_draft_order_lines_info(
DraftOrderLineInfo(
line=line,
variant=variant,
+ product=product,
+ collections=list(product.collections.all()) if product else [],
channel_listing=variant_channel_listing,
discounts=list(line.discounts.all()),
rules_info=rules_info,
channel=channel,
+ voucher=None,
+ voucher_code=None,
)
)
+ voucher = order.voucher
+ if voucher and (
+ voucher.type == VoucherType.SPECIFIC_PRODUCT or voucher.apply_once_per_order
+ ):
+ voucher_info = fetch_voucher_info(voucher, order.voucher_code)
+ apply_voucher_to_line(voucher_info, lines_info)
return lines_info
diff --git a/saleor/order/tests/benchmark/test_fetch_order_prices.py b/saleor/order/tests/benchmark/test_fetch_order_prices.py
index 3a2a866ad8..5a1a17e4c6 100644
--- a/saleor/order/tests/benchmark/test_fetch_order_prices.py
+++ b/saleor/order/tests/benchmark/test_fetch_order_prices.py
@@ -41,7 +41,7 @@ def test_fetch_order_prices_catalogue_discount(
tc.save()
# when
- with django_assert_num_queries(38):
+ with django_assert_num_queries(43):
fetch_order_prices_if_expired(order, plugins_manager, None, True)
# then
@@ -136,7 +136,7 @@ def test_fetch_order_prices_multiple_catalogue_discounts(
tc.save()
# when
- with django_assert_num_queries(38):
+ with django_assert_num_queries(43):
fetch_order_prices_if_expired(order, plugins_manager, None, True)
# then
diff --git a/saleor/order/tests/test_apply_order_discount.py b/saleor/order/tests/test_apply_order_discount.py
index 6c05367456..7b05dd9abf 100644
--- a/saleor/order/tests/test_apply_order_discount.py
+++ b/saleor/order/tests/test_apply_order_discount.py
@@ -218,8 +218,7 @@ def test_apply_order_discounts_shipping_voucher(
assert order.undiscounted_total_net == subtotal + shipping_price
assert order.undiscounted_total_gross == subtotal + shipping_price
order_discount.refresh_from_db()
- # OrderDiscount has amount value only from not applied discounts
- assert order_discount.amount_value == 0
+ assert order_discount.amount_value == shipping_price.amount
def test_apply_order_discounts_zero_discount(order_with_lines):
diff --git a/saleor/order/tests/test_fetch.py b/saleor/order/tests/test_fetch.py
index 684d97115d..dd2f9cde09 100644
--- a/saleor/order/tests/test_fetch.py
+++ b/saleor/order/tests/test_fetch.py
@@ -34,7 +34,7 @@ def test_fetch_draft_order_lines_info(
)
# when
- with django_assert_num_queries(9):
+ with django_assert_num_queries(11):
lines_info = fetch_draft_order_lines_info(order)
# then
diff --git a/saleor/order/tests/test_fetch_order_prices.py b/saleor/order/tests/test_fetch_order_prices.py
index 5ccf22d535..544e59a207 100644
--- a/saleor/order/tests/test_fetch_order_prices.py
+++ b/saleor/order/tests/test_fetch_order_prices.py
@@ -5,6 +5,7 @@ import graphene
import pytest
from ...core.prices import quantize_price
+from ...core.taxes import zero_money
from ...discount import DiscountType, DiscountValueType
from ...discount.models import (
OrderDiscount,
@@ -1357,19 +1358,916 @@ def test_fetch_order_prices_manual_line_discount_and_catalogue_discount_flat_rat
line_1 = [line for line in lines if line.quantity == 3][0]
- assert line_1.base_unit_price_amount == variant_1_listing.price_amount
+ assert (
+ line_1.base_unit_price_amount
+ == variant_1_listing.price_amount - manual_discount_value
+ )
assert manual_discount.line == line_1
assert manual_discount.value == manual_discount_value
assert manual_discount.value_type == manual_discount_value_type
assert manual_discount.type == DiscountType.MANUAL
assert manual_discount.reason == manual_discount_reason
- # TODO https://github.com/saleor/saleor/issues/15517
- # line_1_total_net_amount = quantize_price(
- # (variant_1_listing.price_amount - manual_discount_value) * line_1.quantity,
- # order.currency
- # )
- # assert line_1.total_price_net_amount == line_1_total_net_amount
+ line_1_total_net_amount = quantize_price(
+ (variant_1_listing.price_amount - manual_discount_value) * line_1.quantity,
+ order.currency,
+ )
+ assert line_1.total_price_net_amount == line_1_total_net_amount
+
+
+def test_fetch_order_prices_voucher_specific_product_fixed(
+ order_with_lines, voucher_specific_product_type, plugins_manager
+):
+ # given
+ order = order_with_lines
+ voucher = voucher_specific_product_type
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ unit_discount_amount = Decimal("5")
+ voucher_listing.discount_value = unit_discount_amount
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.save(update_fields=["discount_value_type"])
+
+ lines = order.lines.all()
+ discounted_line, line_1 = lines
+ voucher.variants.add(discounted_line.variant)
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ discounted_line, line_1 = lines
+ discount_amount = unit_discount_amount * discounted_line.quantity
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price
+ assert order.subtotal_net_amount == subtotal.amount - discount_amount
+ assert order.subtotal_gross_amount == subtotal.amount - discount_amount
+ 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
+ )
+ assert order.undiscounted_total_net == subtotal + shipping_price
+ assert order.undiscounted_total_gross == subtotal + shipping_price
+
+ assert (
+ discounted_line.base_unit_price_amount
+ == discounted_line.undiscounted_base_unit_price_amount - unit_discount_amount
+ )
+ assert (
+ discounted_line.total_price_gross_amount
+ == discounted_line.base_unit_price_amount * discounted_line.quantity
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ )
+ assert discounted_line.unit_discount_amount == unit_discount_amount
+ assert discounted_line.unit_discount_type == DiscountValueType.FIXED
+ assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ assert discounted_line.discounts.count() == 1
+ line_discount = discounted_line.discounts.first()
+ assert line_discount.amount_value == discount_amount
+ assert line_discount.value_type == DiscountValueType.FIXED
+ assert line_discount.type == DiscountType.VOUCHER
+ assert line_discount.reason == f"Voucher code: {order.voucher_code}"
+ assert line_discount.value == discount_amount
+
+
+def test_fetch_order_prices_voucher_specific_product_discount_line_object_updated(
+ order_with_lines, voucher_specific_product_type, plugins_manager
+):
+ # given
+ order = order_with_lines
+ voucher = voucher_specific_product_type
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ unit_discount_amount = Decimal("5")
+ voucher_listing.discount_value = unit_discount_amount
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.save(update_fields=["discount_value_type"])
+
+ lines = order.lines.all()
+ discounted_line, line_1 = lines
+ voucher.variants.add(discounted_line.variant)
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+
+ line_discount = discounted_line.discounts.create(
+ value_type=DiscountValueType.FIXED,
+ value=Decimal("0"),
+ name="Manual line discount",
+ type=DiscountType.VOUCHER,
+ )
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ discounted_line, line_1 = lines
+ discount_amount = unit_discount_amount * discounted_line.quantity
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price
+ assert order.subtotal_net_amount == subtotal.amount - discount_amount
+ assert order.subtotal_gross_amount == subtotal.amount - discount_amount
+ 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
+ )
+ assert order.undiscounted_total_net == subtotal + shipping_price
+ assert order.undiscounted_total_gross == subtotal + shipping_price
+
+ assert (
+ discounted_line.base_unit_price_amount
+ == discounted_line.undiscounted_base_unit_price_amount - unit_discount_amount
+ )
+ assert (
+ discounted_line.total_price_gross_amount
+ == discounted_line.base_unit_price_amount * discounted_line.quantity
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ )
+ assert discounted_line.unit_discount_amount == unit_discount_amount
+ assert discounted_line.unit_discount_type == DiscountValueType.FIXED
+ assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ assert discounted_line.discounts.count() == 1
+ line_discount.refresh_from_db()
+ assert line_discount.amount_value == discount_amount
+ assert line_discount.value_type == DiscountValueType.FIXED
+ assert line_discount.type == DiscountType.VOUCHER
+ assert line_discount.reason == f"Voucher code: {order.voucher_code}"
+ assert line_discount.value == discount_amount
+
+
+def test_fetch_order_prices_voucher_specific_product_percentage(
+ order_with_lines, voucher_specific_product_type, plugins_manager
+):
+ # given
+ order = order_with_lines
+ voucher = voucher_specific_product_type
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ discount_value = Decimal("10")
+ voucher_listing.discount_value = discount_value
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["discount_value_type"])
+
+ lines = order.lines.all()
+ discounted_line, line_1 = lines
+ voucher.variants.add(discounted_line.variant)
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ discounted_line, line_1 = lines
+ discount_amount = (
+ discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ * discount_value
+ / 100
+ )
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price
+ assert order.subtotal_net_amount == subtotal.amount - discount_amount
+ assert order.subtotal_gross_amount == subtotal.amount - discount_amount
+ 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
+ )
+ assert order.undiscounted_total_net == subtotal + shipping_price
+ assert order.undiscounted_total_gross == subtotal + shipping_price
+
+ unit_discount_amount = discount_amount / discounted_line.quantity
+ assert (
+ discounted_line.base_unit_price_amount
+ == discounted_line.undiscounted_base_unit_price_amount - unit_discount_amount
+ )
+ assert (
+ discounted_line.total_price_gross_amount
+ == discounted_line.base_unit_price_amount * discounted_line.quantity
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ )
+ assert discounted_line.unit_discount_amount == unit_discount_amount
+ assert discounted_line.unit_discount_type == DiscountValueType.FIXED
+ assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ assert discounted_line.discounts.count() == 1
+ line_discount = discounted_line.discounts.first()
+ assert line_discount.amount_value == discount_amount
+ # TODO: should be from voucher probably
+ assert line_discount.value_type == DiscountValueType.FIXED
+ assert line_discount.type == DiscountType.VOUCHER
+ assert line_discount.reason == f"Voucher code: {order.voucher_code}"
+ assert line_discount.value == discount_amount
+
+
+def test_fetch_order_prices_voucher_apply_once_per_order_fixed(
+ order_with_lines, voucher, plugins_manager
+):
+ # given
+ order = order_with_lines
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ discount_amount = Decimal("5")
+ voucher_listing.discount_value = discount_amount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.apply_once_per_order = True
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.save(update_fields=["discount_value_type", "apply_once_per_order"])
+
+ lines = order.lines.all()
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ discounted_line, line_1 = lines
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price
+ assert order.subtotal_net_amount == subtotal.amount - discount_amount
+ assert order.subtotal_gross_amount == subtotal.amount - discount_amount
+ 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
+ )
+ assert order.undiscounted_total_net == subtotal + shipping_price
+ assert order.undiscounted_total_gross == subtotal + shipping_price
+
+ unit_discount_amount = discount_amount / discounted_line.quantity
+ assert (
+ discounted_line.base_unit_price_amount
+ == discounted_line.undiscounted_base_unit_price_amount - unit_discount_amount
+ )
+ assert (
+ discounted_line.total_price_gross_amount
+ == discounted_line.base_unit_price_amount * discounted_line.quantity
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ )
+ assert discounted_line.unit_discount_amount == unit_discount_amount
+ assert discounted_line.unit_discount_type == DiscountValueType.FIXED
+ assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ assert discounted_line.discounts.count() == 1
+ line_discount = discounted_line.discounts.first()
+ assert line_discount.amount_value == discount_amount
+ assert line_discount.value_type == DiscountValueType.FIXED
+ assert line_discount.type == DiscountType.VOUCHER
+ assert line_discount.reason == f"Voucher code: {order.voucher_code}"
+ assert line_discount.value == discount_amount
+
+
+def test_fetch_order_prices_voucher_apply_once_per_order_percentage(
+ order_with_lines, voucher, plugins_manager
+):
+ # given
+ order = order_with_lines
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ discount_value = Decimal("10")
+ voucher_listing.discount_value = discount_value
+ voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.apply_once_per_order = True
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["discount_value_type", "apply_once_per_order"])
+
+ lines = order.lines.all()
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ discounted_line, line_1 = lines
+ discount_amount = (
+ discounted_line.undiscounted_base_unit_price_amount * discount_value / 100
+ )
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price
+ assert order.subtotal_net_amount == subtotal.amount - discount_amount
+ assert order.subtotal_gross_amount == subtotal.amount - discount_amount
+ 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
+ )
+ assert order.undiscounted_total_net == subtotal + shipping_price
+ assert order.undiscounted_total_gross == subtotal + shipping_price
+
+ unit_discount_amount = discount_amount / discounted_line.quantity
+ assert (
+ discounted_line.base_unit_price_amount
+ == discounted_line.undiscounted_base_unit_price_amount - unit_discount_amount
+ )
+ assert (
+ discounted_line.total_price_gross_amount
+ == discounted_line.base_unit_price_amount * discounted_line.quantity
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ )
+ assert discounted_line.unit_discount_amount == unit_discount_amount
+ assert discounted_line.unit_discount_type == DiscountValueType.FIXED
+ assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ assert discounted_line.discounts.count() == 1
+ line_discount = discounted_line.discounts.first()
+ assert line_discount.amount_value == discount_amount
+ assert line_discount.value_type == DiscountValueType.FIXED
+ assert line_discount.type == DiscountType.VOUCHER
+ assert line_discount.reason == f"Voucher code: {order.voucher_code}"
+ assert line_discount.value == discount_amount
+
+
+def test_fetch_order_prices_manual_order_discount_voucher_specific_product(
+ order_with_lines, voucher_specific_product_type, plugins_manager
+):
+ # given
+ order = order_with_lines
+ voucher = voucher_specific_product_type
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ unit_discount_amount = Decimal("2")
+ voucher_listing.discount_value = unit_discount_amount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.save(update_fields=["discount_value_type"])
+
+ lines = order.lines.all()
+ discounted_line, line_1 = lines
+ voucher.variants.add(discounted_line.variant)
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+
+ # create manual order discount
+ order_discount_amount = Decimal("10")
+ order_discount = order.discounts.create(
+ value_type=DiscountValueType.FIXED,
+ value=order_discount_amount,
+ name="Manual order discount",
+ type=DiscountType.MANUAL,
+ )
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ discounted_line, line_1 = lines
+ voucher_discount_amount = unit_discount_amount * discounted_line.quantity
+ assert (
+ order.total_gross_amount
+ == subtotal.amount
+ + shipping_price.amount
+ - voucher_discount_amount
+ - order_discount_amount
+ )
+ shipping_discount = shipping_price - order.shipping_price_gross
+ subtotal_order_discount = order_discount_amount - shipping_discount.amount
+ assert (
+ order.subtotal_gross_amount
+ == subtotal.amount - subtotal_order_discount - voucher_discount_amount
+ )
+ assert order.undiscounted_total_gross == subtotal + shipping_price
+ assert order.shipping_price_gross == shipping_price - shipping_discount
+ assert order.base_shipping_price == shipping_price
+
+ assert (
+ discounted_line.base_unit_price_amount
+ == 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
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ )
+ assert discounted_line.unit_discount_amount == unit_discount_amount
+ assert discounted_line.unit_discount_type == DiscountValueType.FIXED
+ assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == order.subtotal_gross_amount - discounted_line.total_price_gross_amount
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ order_discount.refresh_from_db()
+ assert order_discount.amount_value == order_discount_amount
+
+ assert discounted_line.discounts.count() == 1
+ line_discount = discounted_line.discounts.first()
+ assert line_discount.amount_value == voucher_discount_amount
+ assert line_discount.value_type == DiscountValueType.FIXED
+ assert line_discount.type == DiscountType.VOUCHER
+ assert line_discount.reason == f"Voucher code: {order.voucher_code}"
+ assert line_discount.value == voucher_discount_amount
+
+
+def test_fetch_order_prices_manual_order_discount_and_voucher_apply_once_per_order(
+ order_with_lines, voucher, plugins_manager
+):
+ # given
+ order = order_with_lines
+
+ 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.apply_once_per_order = True
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.save(update_fields=["discount_value_type", "apply_once_per_order"])
+
+ lines = order.lines.all()
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+
+ # create manual order discount
+ order_discount_amount = Decimal("10")
+ order_discount = order.discounts.create(
+ value_type=DiscountValueType.FIXED,
+ value=order_discount_amount,
+ name="Manual order discount",
+ type=DiscountType.MANUAL,
+ )
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ discounted_line, line_1 = lines
+ voucher_discount_amount = discount_amount
+ assert (
+ order.total_gross_amount
+ == subtotal.amount
+ + shipping_price.amount
+ - voucher_discount_amount
+ - order_discount_amount
+ )
+ shipping_discount = shipping_price - order.shipping_price_gross
+ subtotal_order_discount = order_discount_amount - shipping_discount.amount
+ assert (
+ order.subtotal_gross_amount
+ == subtotal.amount - subtotal_order_discount - voucher_discount_amount
+ )
+ assert order.undiscounted_total_gross == subtotal + shipping_price
+ assert order.shipping_price_gross == shipping_price - shipping_discount
+ assert order.base_shipping_price == shipping_price
+
+ unit_discount_amount = discount_amount / discounted_line.quantity
+ assert (
+ discounted_line.base_unit_price_amount
+ == 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
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ )
+ assert discounted_line.unit_discount_amount == unit_discount_amount
+ assert discounted_line.unit_discount_type == DiscountValueType.FIXED
+ assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == order.subtotal_gross_amount - discounted_line.total_price_gross_amount
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ order_discount.refresh_from_db()
+ assert order_discount.amount_value == order_discount_amount
+
+ assert discounted_line.discounts.count() == 1
+ line_discount = discounted_line.discounts.first()
+ assert line_discount.amount_value == voucher_discount_amount
+ assert line_discount.value_type == DiscountValueType.FIXED
+ assert line_discount.type == DiscountType.VOUCHER
+ assert line_discount.reason == f"Voucher code: {order.voucher_code}"
+ assert line_discount.value == voucher_discount_amount
+
+
+def test_fetch_order_prices_manual_line_discount_voucher_specific_product(
+ order_with_lines, voucher_specific_product_type, plugins_manager
+):
+ # given
+ order = order_with_lines
+ voucher = voucher_specific_product_type
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ unit_discount_amount = Decimal("2")
+ voucher_listing.discount_value = unit_discount_amount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.save(update_fields=["discount_value_type"])
+
+ lines = order.lines.all()
+ discounted_line, line_1 = lines
+ voucher.variants.add(discounted_line.variant)
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+
+ # create manual order line discount
+ manual_line_discount_amount = Decimal("3")
+ manual_line_discount = discounted_line.discounts.create(
+ value_type=DiscountValueType.FIXED,
+ value=manual_line_discount_amount,
+ name="Manual line discount",
+ type=DiscountType.MANUAL,
+ )
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ discounted_line.refresh_from_db()
+ line_1.refresh_from_db()
+ voucher_discount_amount = unit_discount_amount * discounted_line.quantity
+ manual_discount_amount = manual_line_discount_amount * discounted_line.quantity
+ assert (
+ order.total_gross_amount
+ == subtotal.amount
+ + shipping_price.amount
+ - voucher_discount_amount
+ - manual_discount_amount
+ )
+ assert (
+ order.subtotal_gross_amount
+ == subtotal.amount - manual_discount_amount - voucher_discount_amount
+ )
+ assert order.undiscounted_total_gross == subtotal + shipping_price
+ assert order.shipping_price_gross == shipping_price
+ assert order.base_shipping_price == shipping_price
+
+ assert (
+ discounted_line.base_unit_price_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ - unit_discount_amount
+ - manual_line_discount_amount
+ )
+ assert (
+ discounted_line.total_price_gross_amount
+ == discounted_line.unit_price_gross_amount * discounted_line.quantity
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ )
+ assert (
+ discounted_line.unit_discount_amount
+ == unit_discount_amount + manual_line_discount_amount
+ )
+ assert discounted_line.unit_discount_type == DiscountValueType.FIXED
+ assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == order.subtotal_gross_amount - discounted_line.total_price_gross_amount
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ assert discounted_line.discounts.count() == 2
+ voucher_line_discount = discounted_line.discounts.get(type=DiscountType.VOUCHER)
+ assert voucher_line_discount.amount_value == voucher_discount_amount
+ assert voucher_line_discount.value_type == DiscountValueType.FIXED
+ assert voucher_line_discount.type == DiscountType.VOUCHER
+ assert voucher_line_discount.reason == f"Voucher code: {order.voucher_code}"
+ assert voucher_line_discount.value == voucher_discount_amount
+
+ manual_line_discount.refresh_from_db()
+ assert manual_line_discount.amount_value == manual_discount_amount
+ assert manual_line_discount.type == DiscountType.MANUAL
+
+
+def test_fetch_order_prices_manual_line_discount_and_voucher_apply_once_per_order(
+ order_with_lines, voucher, plugins_manager
+):
+ # given
+ order = order_with_lines
+
+ 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.apply_once_per_order = True
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.save(update_fields=["discount_value_type", "apply_once_per_order"])
+
+ lines = order.lines.all()
+ discounted_line, line_1 = lines
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+
+ # create manual order line discount
+ manual_line_discount_amount = Decimal("3")
+ manual_line_discount = discounted_line.discounts.create(
+ value_type=DiscountValueType.FIXED,
+ value=manual_line_discount_amount,
+ name="Manual line discount",
+ type=DiscountType.MANUAL,
+ reason="Manual line discount",
+ )
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ discounted_line.refresh_from_db()
+ line_1.refresh_from_db()
+ voucher_discount_amount = discount_amount
+ manual_discount_amount = manual_line_discount_amount * discounted_line.quantity
+ assert (
+ order.total_gross_amount
+ == subtotal.amount
+ + shipping_price.amount
+ - voucher_discount_amount
+ - manual_discount_amount
+ )
+ shipping_discount = shipping_price - order.shipping_price_gross
+ subtotal_order_discount = manual_discount_amount - shipping_discount.amount
+ assert (
+ order.subtotal_gross_amount
+ == subtotal.amount - subtotal_order_discount - voucher_discount_amount
+ )
+ assert order.undiscounted_total_gross == subtotal + shipping_price
+ assert order.shipping_price_gross == shipping_price - shipping_discount
+ assert order.base_shipping_price == shipping_price
+
+ unit_discount_amount = discount_amount / discounted_line.quantity
+ assert (
+ discounted_line.base_unit_price_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ - unit_discount_amount
+ - manual_line_discount_amount
+ )
+ assert (
+ discounted_line.total_price_gross_amount
+ == discounted_line.unit_price_gross_amount * discounted_line.quantity
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ )
+ assert (
+ discounted_line.unit_discount_amount
+ == manual_line_discount_amount + unit_discount_amount
+ )
+ assert discounted_line.unit_discount_type == DiscountValueType.FIXED
+ assert (
+ discounted_line.unit_discount_reason
+ == f"{manual_line_discount.reason}; Voucher code: {order.voucher_code}"
+ )
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == order.subtotal_gross_amount - discounted_line.total_price_gross_amount
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ assert discounted_line.discounts.count() == 2
+ voucher_line_discount = discounted_line.discounts.get(type=DiscountType.VOUCHER)
+ assert voucher_line_discount.amount_value == voucher_discount_amount
+ assert voucher_line_discount.value_type == DiscountValueType.FIXED
+ assert voucher_line_discount.type == DiscountType.VOUCHER
+ assert voucher_line_discount.reason == f"Voucher code: {order.voucher_code}"
+ assert voucher_line_discount.value == voucher_discount_amount
+
+ manual_line_discount.refresh_from_db()
+ assert manual_line_discount.amount_value == manual_discount_amount
+ assert manual_line_discount.type == DiscountType.MANUAL
def test_fetch_order_prices_catalogue_discount_race_condition(
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 86c52f1ea7..764828838e 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -857,6 +857,7 @@ def update_discount_for_order_line(
if reason is not None:
order_line.unit_discount_reason = reason
fields_to_update.append("unit_discount_reason")
+
if current_value != value or current_value_type != value_type:
undiscounted_base_unit_price = order_line.undiscounted_base_unit_price
currency = undiscounted_base_unit_price.currency
@@ -871,6 +872,7 @@ def update_discount_for_order_line(
order_line.unit_discount_type = value_type
order_line.unit_discount_value = value
+ # TODO: should we save those values?
order_line.total_price = order_line.unit_price * order_line.quantity
order_line.undiscounted_unit_price = (
order_line.unit_price + order_line.unit_discount
@@ -915,7 +917,7 @@ def _update_manual_order_line_discount_object(
for discount in discounts:
if discount.type == DiscountType.MANUAL and not discount_to_update:
discount_to_update = discount
- else:
+ elif discount.type != DiscountType.VOUCHER:
discount_to_delete_ids.append(discount.pk)
if discount_to_delete_ids:
@@ -932,6 +934,7 @@ def _update_manual_order_line_discount_object(
amount_value=amount_value,
currency=currency,
reason=reason,
+ unique_type=DiscountType.MANUAL,
)
else:
update_fields = []
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
index adfe3a2a30..9be5f01e01 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
@@ -701,7 +701,7 @@ def test_draft_order_calculate_taxes_apply_once_per_order_voucher(
"taxBase": {
"address": {"id": to_global_id_or_none(order.shipping_address)},
"currency": "USD",
- "discounts": [{"amount": {"amount": float(discount_amount)}}],
+ "discounts": [],
"channel": {"id": to_global_id_or_none(order.channel)},
"lines": [
{
@@ -714,9 +714,13 @@ def test_draft_order_calculate_taxes_apply_once_per_order_voucher(
"id": to_global_id_or_none(line),
},
"totalPrice": {
- "amount": float(line.base_unit_price_amount * line.quantity)
+ "amount": float(
+ round(line.base_unit_price_amount * line.quantity, 2)
+ )
+ },
+ "unitPrice": {
+ "amount": float(round(line.base_unit_price_amount, 2))
},
- "unitPrice": {"amount": float(line.base_unit_price_amount)},
"variantName": line.variant_name,
}
for line in order.lines.all()
@@ -731,6 +735,100 @@ def test_draft_order_calculate_taxes_apply_once_per_order_voucher(
}
+@freeze_time("2020-03-18 12:00:00")
+def test_order_calculate_taxes_specific_product_voucher(
+ order_line,
+ subscription_calculate_taxes_for_order,
+ shipping_zone,
+ voucher_specific_product_type,
+):
+ # given
+ order = order_line.order
+ webhook = subscription_calculate_taxes_for_order
+ expected_shipping_price = Money("2.00", order.currency)
+ order.base_shipping_price = expected_shipping_price
+ order.shipping_price = TaxedMoney(
+ net=expected_shipping_price, gross=expected_shipping_price
+ )
+ order.status = OrderStatus.DRAFT
+ order.voucher = voucher_specific_product_type
+ order.voucher_code = voucher_specific_product_type.codes.first().code
+ order.save(
+ update_fields=[
+ "base_shipping_price_amount",
+ "shipping_price_net_amount",
+ "shipping_price_gross_amount",
+ "voucher_code",
+ "voucher",
+ "status",
+ ]
+ )
+
+ voucher_specific_product_type.discount_value_type = DiscountValueType.FIXED
+ voucher_specific_product_type.save(update_fields=["discount_value_type"])
+
+ voucher_listing = voucher_specific_product_type.channel_listings.get(
+ channel=order.channel
+ )
+ unit_discount_amount = Decimal("2")
+ voucher_listing.discount_value = unit_discount_amount
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher_specific_product_type.variants.add(order_line.variant)
+
+ manager = get_plugins_manager(allow_replica=False)
+ fetch_order_prices_if_expired(order, manager, order.lines.all(), True)
+
+ shipping_method = shipping_zone.shipping_methods.first()
+ order.shipping_method = shipping_method
+
+ webhook.subscription_query = TAXES_SUBSCRIPTION_QUERY
+ webhook.save(update_fields=["subscription_query"])
+
+ # when
+ deliveries = create_delivery_for_subscription_sync_event(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
+ )
+
+ # then
+ expected_total_price_amount = (
+ order_line.undiscounted_base_unit_price_amount - unit_discount_amount
+ ) * order_line.quantity
+ assert json.loads(deliveries.payload.payload) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": {"id": to_global_id_or_none(order.shipping_address)},
+ "currency": "USD",
+ "discounts": [],
+ "channel": {"id": to_global_id_or_none(order.channel)},
+ "lines": [
+ {
+ "chargeTaxes": True,
+ "productName": order_line.product_name,
+ "productSku": "SKU_A",
+ "quantity": order_line.quantity,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(order_line),
+ },
+ "totalPrice": {"amount": float(expected_total_price_amount)},
+ "unitPrice": {
+ "amount": float(
+ expected_total_price_amount / order_line.quantity
+ )
+ },
+ "variantName": order_line.variant_name,
+ }
+ ],
+ "pricesEnteredWithTax": True,
+ "shippingPrice": {"amount": float(expected_shipping_price.amount)},
+ "sourceObject": {
+ "__typename": "Order",
+ "id": to_global_id_or_none(order),
+ },
+ },
+ }
+
+
@freeze_time("2020-03-18 12:00:00")
@pytest.mark.parametrize("charge_taxes", [True, False])
def test_draft_order_calculate_taxes_free_shipping_voucher(
diff --git a/saleor/warehouse/tests/test_preorder_availability.py b/saleor/warehouse/tests/test_preorder_availability.py
index b6195000fb..ada54d60fd 100644
--- a/saleor/warehouse/tests/test_preorder_availability.py
+++ b/saleor/warehouse/tests/test_preorder_availability.py
@@ -164,6 +164,8 @@ def test_check_preorder_reserved_threshold_bulk_channel_threshold(
discounts=[],
rules_info=[],
channel=channel_USD,
+ voucher=None,
+ voucher_code=None,
)
],
check_reservations=True,
@@ -234,6 +236,8 @@ def test_check_preorder_reserved_threshold_bulk_global_threshold(
discounts=[],
rules_info=[],
channel=channel_USD,
+ voucher=None,
+ voucher_code=None,
)
],
check_reservations=True,