Skip to content

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

Update denormalized discounts when adding a new line discount (#17612)

Maciej Korycinskid7b03a3eeec0
diff --git a/saleor/discount/interface.py b/saleor/discount/interface.py
index 5e9104bc62..9e7872189d 100644
--- a/saleor/discount/interface.py
+++ b/saleor/discount/interface.py
@@ -1,7 +1,9 @@
from dataclasses import dataclass
+from decimal import Decimal
from typing import TYPE_CHECKING, NamedTuple, Optional
-from .models import Voucher
+from . import DiscountType, DiscountValueType
+from .models import PromotionRule, Voucher
if TYPE_CHECKING:
from ..product.models import (
@@ -16,6 +18,26 @@ if TYPE_CHECKING:
)
+@dataclass
+class DiscountInfo:
+ """It stores the discount details.
+
+ The dataclass used to represent the discount before storing it on database side.
+ """
+
+ currency: str
+ type: str = DiscountType.MANUAL
+ value_type: str = DiscountValueType.FIXED
+ value: Decimal = Decimal("0.0")
+ amount_value: Decimal = Decimal("0.0")
+ name: str | None = None
+ translated_name: str | None = None
+ reason: str | None = None
+ promotion_rule: PromotionRule | None = None
+ voucher: Voucher | None = None
+ voucher_code: str | None = None
+
+
@dataclass
class VoucherInfo:
"""It contains the voucher's details and PKs of all applicable objects."""
diff --git a/saleor/discount/tests/test_utils/test_copy_unit_discount_data_to_order_line.py b/saleor/discount/tests/test_utils/test_copy_unit_discount_data_to_order_line.py
index 172ec7c8f6..f07a968d22 100644
--- a/saleor/discount/tests/test_utils/test_copy_unit_discount_data_to_order_line.py
+++ b/saleor/discount/tests/test_utils/test_copy_unit_discount_data_to_order_line.py
@@ -5,7 +5,7 @@ import graphene
from ....order.fetch import fetch_draft_order_lines_info
from ... import DiscountType, DiscountValueType
from ...models import PromotionRule
-from ...utils.order import update_unit_discount_data_on_order_line
+from ...utils.order import update_unit_discount_data_on_order_lines_info
def test_copy_unit_discount_data_to_order_line_multiple_discounts(
@@ -38,7 +38,7 @@ def test_copy_unit_discount_data_to_order_line_multiple_discounts(
lines_info = fetch_draft_order_lines_info(order)
# when
- update_unit_discount_data_on_order_line(lines_info)
+ update_unit_discount_data_on_order_lines_info(lines_info)
# then
line = lines_info[0].line
@@ -68,7 +68,7 @@ def test_copy_unit_discount_data_to_order_line_single_discount(
lines_info = fetch_draft_order_lines_info(order)
# when
- update_unit_discount_data_on_order_line(lines_info)
+ update_unit_discount_data_on_order_lines_info(lines_info)
# then
line = lines_info[0].line
@@ -86,7 +86,7 @@ def test_copy_unit_discount_data_to_order_line_no_discount(order_with_lines):
lines_info = fetch_draft_order_lines_info(order)
# when
- update_unit_discount_data_on_order_line(lines_info)
+ update_unit_discount_data_on_order_lines_info(lines_info)
# then
line = lines_info[0].line
diff --git a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_order.py b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_order.py
index 4b4e80dc55..76decd4f42 100644
--- a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_order.py
+++ b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_order.py
@@ -8,7 +8,7 @@ from ....product.models import (
VariantChannelListingPromotionRule,
)
from ....warehouse.models import Stock
-from ... import DiscountType, RewardType, RewardValueType
+from ... import DiscountType, DiscountValueType, RewardType, RewardValueType
from ...interface import VariantPromotionRuleInfo, fetch_variant_rules_info
from ...models import OrderDiscount, OrderLineDiscount
from ...utils.order import (
@@ -269,9 +269,9 @@ def test_create_order_discount_gift(
assert gift_line.unit_price_gross_amount == Decimal(0)
assert gift_line.unit_price_net_amount == Decimal(0)
assert gift_line.base_unit_price_amount == Decimal(0)
- assert gift_line.unit_discount_amount == Decimal(0)
- assert gift_line.unit_discount_type is None
- assert gift_line.unit_discount_value == Decimal(0)
+ assert gift_line.unit_discount_amount == listing.price_amount
+ assert gift_line.unit_discount_type == DiscountValueType.FIXED
+ assert gift_line.unit_discount_value == listing.price_amount
assert gift_line.product_name == product.name
assert gift_line.product_sku == variant.sku
diff --git a/saleor/discount/tests/test_utils/test_create_voucher_discount_object_for_order.py b/saleor/discount/tests/test_utils/test_create_voucher_discount_object_for_order.py
index 997038981a..8329bbf415 100644
--- a/saleor/discount/tests/test_utils/test_create_voucher_discount_object_for_order.py
+++ b/saleor/discount/tests/test_utils/test_create_voucher_discount_object_for_order.py
@@ -7,14 +7,8 @@ from ....core.taxes import zero_money
from ....order import OrderStatus
from ....order.calculations import fetch_order_prices_if_expired
from ... import DiscountType, DiscountValueType, VoucherType
-from ...models import (
- OrderDiscount,
- OrderLineDiscount,
- PromotionRule,
-)
-from ...utils.voucher import (
- create_or_update_voucher_discount_objects_for_order,
-)
+from ...models import OrderDiscount, OrderLineDiscount, PromotionRule
+from ...utils.voucher import create_or_update_voucher_discount_objects_for_order
def test_create_discount_for_voucher_specific_product_fixed(
@@ -300,7 +294,9 @@ def test_create_discount_for_voucher_apply_once_per_order_percentage(
* discounted_line.quantity
* tax_rate
)
- assert discounted_line.unit_discount_amount == unit_discount_amount
+ assert discounted_line.unit_discount_amount == quantize_price(
+ unit_discount_amount, currency
+ )
assert discounted_line.unit_discount_type == DiscountValueType.PERCENTAGE
assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
@@ -406,7 +402,9 @@ def test_create_discount_for_voucher_apply_once_per_order_fixed(
* discounted_line.quantity
* tax_rate
)
- assert discounted_line.unit_discount_amount == unit_discount_amount
+ assert discounted_line.unit_discount_amount == quantize_price(
+ unit_discount_amount, currency
+ )
assert discounted_line.unit_discount_type == DiscountValueType.FIXED
assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
diff --git a/saleor/discount/tests/test_utils/test_update_voucher_discount_object_for_order.py b/saleor/discount/tests/test_utils/test_update_voucher_discount_object_for_order.py
index 530b0ae320..2fd846f23a 100644
--- a/saleor/discount/tests/test_utils/test_update_voucher_discount_object_for_order.py
+++ b/saleor/discount/tests/test_utils/test_update_voucher_discount_object_for_order.py
@@ -224,7 +224,9 @@ def test_update_voucher_discount_specific_product_with_apply_once_per_order(
assert discount_2.reason == f"Voucher code: {order.voucher_code}"
assert discount_2.value == voucher_2_discount_amount
- unit_discount_amount_2 = discount_amount_2 / cheapest_line.quantity
+ unit_discount_amount_2 = quantize_price(
+ discount_amount_2 / cheapest_line.quantity, currency
+ )
assert quantize_price(
cheapest_line.base_unit_price_amount, currency
) == quantize_price(
diff --git a/saleor/discount/utils/order.py b/saleor/discount/utils/order.py
index 01632c268b..af4ca44776 100644
--- a/saleor/discount/utils/order.py
+++ b/saleor/discount/utils/order.py
@@ -16,10 +16,7 @@ from ...order.base_calculations import base_order_subtotal
from ...order.models import Order, OrderLine
from .. import DiscountType
from ..interface import VariantPromotionRuleInfo
-from ..models import (
- DiscountValueType,
- OrderLineDiscount,
-)
+from ..models import DiscountValueType, OrderLineDiscount
from .manual_discount import apply_discount_to_value
from .promotion import (
_get_rule_discount_amount,
@@ -40,7 +37,7 @@ if TYPE_CHECKING:
def create_order_line_discount_objects(
lines_info: list["EditableOrderLineInfo"],
discount_data: tuple[
- list[dict],
+ list[OrderLineDiscount],
list[OrderLineDiscount],
list[OrderLineDiscount],
list[str],
@@ -52,13 +49,12 @@ def create_order_line_discount_objects(
return None
(
- discounts_to_create_inputs,
+ discounts_to_create,
discounts_to_update,
discount_to_remove,
updated_fields,
) = discount_data
- new_line_discounts: list[OrderLineDiscount] = []
affected_line_ids: list[UUID] = []
with allow_writer():
with transaction.atomic():
@@ -77,12 +73,9 @@ def create_order_line_discount_objects(
)
OrderLineDiscount.objects.filter(id__in=discount_ids_to_remove).delete()
- if discounts_to_create_inputs:
- new_line_discounts = [
- OrderLineDiscount(**input) for input in discounts_to_create_inputs
- ]
+ if discounts_to_create:
OrderLineDiscount.objects.bulk_create(
- new_line_discounts, ignore_conflicts=True
+ discounts_to_create, ignore_conflicts=True
)
if discounts_to_update and updated_fields:
@@ -91,11 +84,11 @@ def create_order_line_discount_objects(
)
update_line_info_cached_discounts(
- lines_info, new_line_discounts, discounts_to_update, discount_ids_to_remove
+ lines_info, discounts_to_create, discounts_to_update, discount_ids_to_remove
)
affected_line_ids.extend(
discount_line.line_id
- for discount_line in (new_line_discounts + discounts_to_update)
+ for discount_line in (discounts_to_create + discounts_to_update)
if discount_line.line_id is not None
)
@@ -130,34 +123,45 @@ def update_catalogue_promotion_discount_amount_for_order(
def update_unit_discount_data_on_order_line(
+ line: OrderLine, discounts: list[OrderLineDiscount]
+):
+ unit_discount_reason = (
+ "; ".join([discount.reason for discount in discounts if discount.reason])
+ or None
+ )
+
+ unit_discount_amount = Decimal("0.0")
+ unit_discount_type = None
+ unit_discount_value = Decimal("0.0")
+ if discounts:
+ discount_amount = sum(
+ [discount.amount_value for discount in discounts], Decimal("0.0")
+ )
+ unit_discount_amount = quantize_price(
+ discount_amount / line.quantity, line.currency
+ )
+
+ more_than_one_discount = len(discounts) > 1
+ if more_than_one_discount:
+ unit_discount_type = DiscountValueType.FIXED
+ unit_discount_value = unit_discount_amount
+ else:
+ discount = discounts[0]
+ unit_discount_type = discount.value_type
+ unit_discount_value = discount.value
+
+ line.unit_discount_amount = unit_discount_amount
+ line.unit_discount_reason = unit_discount_reason
+ line.unit_discount_type = unit_discount_type
+ line.unit_discount_value = unit_discount_value
+
+
+def update_unit_discount_data_on_order_lines_info(
lines_info: list["EditableOrderLineInfo"],
):
for line_info in lines_info:
line = line_info.line
- if discounts := line_info.discounts:
- discount_amount = sum([discount.amount_value for discount in discounts])
- unit_discount_amount = discount_amount / line.quantity
- discount_reason = "; ".join(
- [discount.reason for discount in discounts if discount.reason]
- )
- discount_type = (
- discounts[0].value_type
- if len(discounts) == 1
- else DiscountValueType.FIXED
- )
- discount_value = (
- discounts[0].value if len(discounts) == 1 else unit_discount_amount
- )
-
- line.unit_discount_amount = unit_discount_amount
- line.unit_discount_reason = discount_reason
- line.unit_discount_type = discount_type
- line.unit_discount_value = discount_value
- else:
- line.unit_discount_amount = Decimal("0.0")
- line.unit_discount_reason = None
- line.unit_discount_type = None
- line.unit_discount_value = Decimal("0.0")
+ update_unit_discount_data_on_order_line(line, line_info.discounts)
def handle_order_promotion(
@@ -246,48 +250,50 @@ def _clear_order_discount(
order_or_checkout.discounts.filter(type=DiscountType.ORDER_PROMOTION).delete()
+def _create_order_line_discount_for_catalogue_promotion(
+ line: OrderLine, rule_info: VariantPromotionRuleInfo, channel: Channel
+):
+ rule = rule_info.rule
+ rule_discount_amount = _get_rule_discount_amount(line, rule_info, channel)
+ 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)
+ return OrderLineDiscount(
+ line=line,
+ type=DiscountType.PROMOTION,
+ value_type=rule.reward_value_type,
+ value=rule.reward_value,
+ amount_value=rule_discount_amount,
+ currency=line.currency,
+ name=discount_name,
+ translated_name=translated_name,
+ reason=reason,
+ promotion_rule=rule,
+ unique_type=DiscountType.PROMOTION,
+ )
+
+
def create_order_line_discount_objects_for_catalogue_promotions(
line: "OrderLine",
rules_info: Iterable[VariantPromotionRuleInfo],
channel: Channel,
-) -> Iterable["OrderLineDiscount"]:
+) -> list["OrderLineDiscount"]:
from ...order.utils import order_qs_select_for_update
- line_discounts_to_create_inputs: list[dict] = []
+ line_discounts_to_create: list[OrderLineDiscount] = []
for rule_info in rules_info:
- rule = rule_info.rule
- rule_discount_amount = _get_rule_discount_amount(line, rule_info, channel)
- 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)
-
- line_discount_input = {
- "line": line,
- "type": DiscountType.PROMOTION,
- "value_type": rule.reward_value_type,
- "value": rule.reward_value,
- "amount_value": rule_discount_amount,
- "currency": line.currency,
- "name": discount_name,
- "translated_name": translated_name,
- "reason": reason,
- "promotion_rule": rule,
- "unique_type": DiscountType.PROMOTION,
- }
- line_discounts_to_create_inputs.append(line_discount_input)
-
- if line_discounts_to_create_inputs:
+ line_discount = _create_order_line_discount_for_catalogue_promotion(
+ line, rule_info, channel
+ )
+ line_discounts_to_create.append(line_discount)
+
+ if line_discounts_to_create:
with allow_writer():
with transaction.atomic():
order_id = line.order_id
_order_lock = list(order_qs_select_for_update().filter(id=order_id))
- new_line_discounts = [
- OrderLineDiscount(**input)
- for input in line_discounts_to_create_inputs
- ]
-
return OrderLineDiscount.objects.bulk_create(
- new_line_discounts, ignore_conflicts=True
+ line_discounts_to_create, ignore_conflicts=True
)
return []
@@ -303,7 +309,7 @@ def refresh_order_line_discount_objects_for_catalogue_promotions(
def prepare_order_line_discount_objects_for_catalogue_promotions(lines_info):
- line_discounts_to_create_inputs: list[dict] = []
+ line_discounts_to_create: list[OrderLineDiscount] = []
line_discounts_to_update: list[OrderLineDiscount] = []
line_discounts_to_remove: list[OrderLineDiscount] = []
updated_fields: list[str] = []
@@ -344,28 +350,15 @@ def prepare_order_line_discount_objects_for_catalogue_promotions(lines_info):
if line_info.rules_info:
rule_info = line_info.rules_info[0]
rule = rule_info.rule
- rule_discount_amount = _get_rule_discount_amount(
- line, rule_info, line_info.channel
- )
- 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)
if not discount_to_update:
- line_discount_input = {
- "line": line,
- "type": DiscountType.PROMOTION,
- "value_type": rule.reward_value_type,
- "value": rule.reward_value,
- "amount_value": rule_discount_amount,
- "currency": line.currency,
- "name": discount_name,
- "translated_name": translated_name,
- "reason": reason,
- "promotion_rule": rule,
- "unique_type": DiscountType.PROMOTION,
- }
- line_discounts_to_create_inputs.append(line_discount_input)
+ line_discount = _create_order_line_discount_for_catalogue_promotion(
+ line, rule_info, line_info.channel
+ )
+ line_discounts_to_create.append(line_discount)
else:
+ rule_discount_amount = _get_rule_discount_amount(
+ line, rule_info, line_info.channel
+ )
update_promotion_discount(
rule,
rule_info,
@@ -379,7 +372,7 @@ def prepare_order_line_discount_objects_for_catalogue_promotions(lines_info):
line_discounts_to_remove.extend(discounts_to_update)
return (
- line_discounts_to_create_inputs,
+ line_discounts_to_create,
line_discounts_to_update,
line_discounts_to_remove,
updated_fields,
diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.py
index 43e7189c89..c067416d89 100644
--- a/saleor/discount/utils/promotion.py
+++ b/saleor/discount/utils/promotion.py
@@ -1,9 +1,10 @@
import datetime
from collections import defaultdict
from collections.abc import Callable, Iterable, Iterator
+from dataclasses import asdict
from decimal import Decimal
from itertools import chain
-from typing import TYPE_CHECKING, NamedTuple, Union
+from typing import TYPE_CHECKING, NamedTuple, Union, cast
from uuid import UUID
import graphene
@@ -34,7 +35,7 @@ from .. import (
RewardType,
RewardValueType,
)
-from ..interface import VariantPromotionRuleInfo, get_rule_translations
+from ..interface import DiscountInfo, VariantPromotionRuleInfo, get_rule_translations
from ..models import (
CheckoutDiscount,
CheckoutLineDiscount,
@@ -432,8 +433,11 @@ def delete_gift_line(
def create_gift_line(
order_or_checkout: Checkout | Order,
gift_listing: "ProductVariantChannelListing",
+ line_discount_data: DiscountInfo,
):
- defaults = _get_defaults_for_gift_line(order_or_checkout, gift_listing)
+ defaults = _get_defaults_for_gift_line(
+ order_or_checkout, gift_listing, line_discount_data
+ )
line, created = order_or_checkout.lines.get_or_create(
is_gift=True, defaults=defaults
)
@@ -452,6 +456,7 @@ def create_gift_line(
def _get_defaults_for_gift_line(
order_or_checkout: Checkout | Order,
gift_listing: "ProductVariantChannelListing",
+ line_discount_data: DiscountInfo,
):
variant_id = gift_listing.variant_id
if isinstance(order_or_checkout, Checkout):
@@ -479,6 +484,10 @@ def _get_defaults_for_gift_line(
"total_price_gross_amount": Decimal(0),
"is_shipping_required": True,
"is_gift_card": False,
+ "unit_discount_amount": line_discount_data.amount_value,
+ "unit_discount_value": line_discount_data.value,
+ "unit_discount_reason": line_discount_data.reason,
+ "unit_discount_type": line_discount_data.value_type,
}
@@ -728,23 +737,25 @@ def create_discount_objects_for_order_promotions(
value_type = best_rule.reward_value_type or RewardValueType.FIXED
amount_value = gift_listing.price_amount if gift_listing else best_discount_amount
value = best_rule.reward_value or amount_value
- discount_object_defaults = {
- "promotion_rule": best_rule,
- "value_type": value_type,
- "value": value,
- "amount_value": amount_value,
- "currency": currency,
- "name": get_discount_name(best_rule, promotion),
- "translated_name": get_discount_translated_name(rule_info),
- "reason": prepare_promotion_discount_reason(rule_info.promotion),
- }
+ line_discount = DiscountInfo(
+ type=DiscountType.ORDER_PROMOTION,
+ promotion_rule=best_rule,
+ value_type=value_type,
+ value=value,
+ amount_value=amount_value,
+ currency=currency,
+ name=get_discount_name(best_rule, promotion),
+ translated_name=get_discount_translated_name(rule_info),
+ reason=prepare_promotion_discount_reason(rule_info.promotion),
+ )
+
if gift_listing:
_handle_gift_reward(
order_or_checkout,
lines_info,
gift_listing,
channel,
- discount_object_defaults,
+ line_discount,
rule_info,
)
gift_promotion_applied = True
@@ -752,7 +763,7 @@ def create_discount_objects_for_order_promotions(
discount_object = _handle_order_promotion(
order_or_checkout,
lines_info,
- discount_object_defaults,
+ line_discount,
rule_info,
)
return gift_promotion_applied, discount_object
@@ -762,19 +773,19 @@ def create_discount_objects_for_order_promotions(
def _handle_order_promotion(
order_or_checkout: Order | Checkout,
lines_info: list["EditableOrderLineInfo"] | list["CheckoutLineInfo"],
- discount_object_defaults: dict,
+ line_discount_data: DiscountInfo,
rule_info: VariantPromotionRuleInfo,
):
discount_object, created = order_or_checkout.discounts.get_or_create(
type=DiscountType.ORDER_PROMOTION,
- defaults=discount_object_defaults,
+ defaults=asdict(line_discount_data),
)
- discount_amount = discount_object_defaults["amount_value"]
-
+ discount_amount = line_discount_data.amount_value
+ promotion_rule = cast(PromotionRule, line_discount_data.promotion_rule)
if not created:
fields_to_update: list[str] = []
update_promotion_discount(
- discount_object_defaults["promotion_rule"],
+ promotion_rule,
rule_info,
discount_amount,
discount_object,
@@ -793,7 +804,7 @@ def _handle_gift_reward(
lines_info: list[EditableOrderLineInfo] | list[CheckoutLineInfo],
gift_listing: ProductVariantChannelListing,
channel: "Channel",
- discount_object_defaults: dict,
+ line_discount_data: DiscountInfo,
rule_info: VariantPromotionRuleInfo,
):
discount_model = (
@@ -802,14 +813,16 @@ def _handle_gift_reward(
else OrderLineDiscount
)
with transaction.atomic():
- line, line_created = create_gift_line(order_or_checkout, gift_listing)
+ line, line_created = create_gift_line(
+ order_or_checkout, gift_listing, line_discount_data
+ )
(
line_discount,
discount_created,
) = discount_model.objects.get_or_create( # type: ignore[attr-defined]
type=DiscountType.ORDER_PROMOTION,
line=line,
- defaults=discount_object_defaults,
+ defaults=asdict(line_discount_data),
)
if not discount_created:
@@ -817,10 +830,11 @@ def _handle_gift_reward(
if line_discount.line_id != line.id:
line_discount.line = line
fields_to_update.append("line_id")
+ promotion_rule = cast(PromotionRule, line_discount.promotion_rule)
update_promotion_discount(
- discount_object_defaults["promotion_rule"],
+ promotion_rule,
rule_info,
- discount_object_defaults["amount_value"],
+ line_discount_data.amount_value,
line_discount,
fields_to_update,
)
diff --git a/saleor/discount/utils/voucher.py b/saleor/discount/utils/voucher.py
index a4056f8ae6..9e0d68709f 100644
--- a/saleor/discount/utils/voucher.py
+++ b/saleor/discount/utils/voucher.py
@@ -1,5 +1,5 @@
from collections.abc import Iterable, Sequence
-from dataclasses import dataclass
+from dataclasses import asdict, dataclass
from decimal import Decimal
from typing import TYPE_CHECKING, Optional, cast
from uuid import UUID
@@ -15,6 +15,7 @@ from ...core.taxes import zero_money
from ...core.utils.promo_code import InvalidPromoCode
from ...order.models import Order
from .. import DiscountType, VoucherType
+from ..interface import DiscountInfo, VoucherInfo
from ..models import (
DiscountValueType,
NotApplicable,
@@ -33,7 +34,6 @@ if TYPE_CHECKING:
from ...order.fetch import EditableOrderLineInfo
from ...order.models import OrderLine
from ...plugins.manager import PluginsManager
- from ..interface import VoucherInfo
from ..models import Voucher
@@ -346,7 +346,16 @@ def create_or_update_voucher_discount_objects_for_order(
lines_info, use_denormalized_data
)
lines = [line_info.line for line_info in lines_info]
- OrderLine.objects.bulk_update(lines, ["base_unit_price_amount"])
+ OrderLine.objects.bulk_update(
+ lines,
+ [
+ "base_unit_price_amount",
+ "unit_discount_amount",
+ "unit_discount_reason",
+ "unit_discount_type",
+ "unit_discount_value",
+ ],
+ )
def create_or_update_discount_object_from_order_level_voucher(
@@ -406,24 +415,24 @@ def create_or_update_discount_object_from_order_level_voucher(
discount_reason = f"Voucher code: {order.voucher_code}"
discount_name = voucher.name or ""
- discount_object_defaults = {
- "voucher": voucher,
- "value_type": voucher.discount_value_type,
- "value": voucher_channel_listing.discount_value,
- "amount_value": discount_amount.amount,
- "currency": order.currency,
- "reason": discount_reason,
- "name": discount_name,
- "type": DiscountType.VOUCHER,
- "voucher_code": order.voucher_code,
+ discount_data = DiscountInfo(
+ voucher=voucher,
+ value_type=voucher.discount_value_type,
+ value=voucher_channel_listing.discount_value,
+ amount_value=discount_amount.amount,
+ currency=order.currency,
+ reason=discount_reason,
+ name=discount_name,
+ type=DiscountType.VOUCHER,
+ voucher_code=order.voucher_code,
# TODO (SHOPX-914): set translated voucher name
- "translated_name": "",
- }
+ translated_name="",
+ )
with allow_writer():
discount_object, created = order.discounts.get_or_create(
type=DiscountType.VOUCHER,
- defaults=discount_object_defaults,
+ defaults=asdict(discount_data),
)
if not created:
updated_fields: list[str] = []
@@ -461,7 +470,7 @@ def create_or_update_line_discount_objects_from_voucher(
# FIXME: temporary - create_order_line_discount_objects should be moved to shared
from .order import (
create_order_line_discount_objects,
- update_unit_discount_data_on_order_line,
+ update_unit_discount_data_on_order_lines_info,
)
discount_data = prepare_line_discount_objects_for_voucher(
@@ -470,7 +479,7 @@ def create_or_update_line_discount_objects_from_voucher(
modified_lines_info = create_order_line_discount_objects(lines_info, discount_data)
if modified_lines_info:
_reduce_base_unit_price_for_voucher_discount(modified_lines_info)
- update_unit_discount_data_on_order_line(modified_lines_info)
+ update_unit_discount_data_on_order_lines_info(modified_lines_info)
# TODO (SHOPX-912): share the method with checkout
@@ -484,7 +493,7 @@ def prepare_line_discount_objects_for_voucher(
conditions from the moment of the voucher application. Otherwise, the latest
voucher values will be retrieved from the database.
"""
- line_discounts_to_create_inputs: list[dict] = []
+ line_discounts_to_create: list[OrderLineDiscount] = []
line_discounts_to_update: list[OrderLineDiscount] = []
line_discounts_to_remove: list[OrderLineDiscount] = []
updated_fields: list[str] = []
@@ -560,24 +569,24 @@ def prepare_line_discount_objects_for_voucher(
)
line_discounts_to_update.append(discount_to_update)
else:
- line_discount_input = {
- "line": line,
- "type": DiscountType.VOUCHER,
- "value_type": discount_value_type,
- "value": discount_value,
- "amount_value": discount_amount,
- "currency": line.currency,
- "name": discount_name,
- "translated_name": None,
- "reason": discount_reason,
- "voucher": voucher,
- "unique_type": DiscountType.VOUCHER,
- "voucher_code": code,
- }
- line_discounts_to_create_inputs.append(line_discount_input)
+ line_discount_to_create = OrderLineDiscount(
+ line=line,
+ type=DiscountType.VOUCHER,
+ value_type=discount_value_type,
+ value=discount_value,
+ amount_value=discount_amount,
+ currency=line.currency,
+ name=discount_name,
+ translated_name=None,
+ reason=discount_reason,
+ voucher=voucher,
+ unique_type=DiscountType.VOUCHER,
+ voucher_code=code,
+ )
+ line_discounts_to_create.append(line_discount_to_create)
return (
- line_discounts_to_create_inputs,
+ line_discounts_to_create,
line_discounts_to_update,
line_discounts_to_remove,
updated_fields,
diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.py
index faa916a777..501b4f990b 100644
--- a/saleor/graphql/checkout/mutations/utils.py
+++ b/saleor/graphql/checkout/mutations/utils.py
@@ -2,7 +2,7 @@ import datetime
import uuid
from collections import defaultdict
from collections.abc import Iterable
-from dataclasses import dataclass, field
+from dataclasses import asdict, dataclass, field
from decimal import Decimal
from typing import TYPE_CHECKING, Any, cast
@@ -31,6 +31,7 @@ from ....checkout.utils import (
)
from ....core.exceptions import InsufficientStock, PermissionDenied
from ....discount import DiscountType, DiscountValueType
+from ....discount.interface import DiscountInfo
from ....discount.models import CheckoutLineDiscount, PromotionRule
from ....discount.utils.promotion import (
create_gift_line,
@@ -568,17 +569,19 @@ def apply_gift_reward_if_applicable_on_checkout_creation(
if not gift_listing:
return
+ line_discount_data = DiscountInfo(
+ type=DiscountType.ORDER_PROMOTION,
+ amount_value=best_discount_amount,
+ value_type=DiscountValueType.FIXED,
+ value=best_discount_amount,
+ promotion_rule=best_rule,
+ currency=checkout.currency,
+ )
with transaction.atomic():
- line, _line_created = create_gift_line(checkout, gift_listing)
- CheckoutLineDiscount.objects.create(
- type=DiscountType.ORDER_PROMOTION,
- line=line,
- amount_value=best_discount_amount,
- value_type=DiscountValueType.FIXED,
- value=best_discount_amount,
- promotion_rule=best_rule,
- currency=checkout.currency,
+ line, _line_created = create_gift_line(
+ checkout, gift_listing, line_discount_data
)
+ CheckoutLineDiscount.objects.create(line=line, **asdict(line_discount_data))
def _set_checkout_base_subtotal_and_total_on_checkout_creation(
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 2fb07784c4..8c85761971 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -1324,7 +1324,7 @@ def test_add_checkout_lines_gift_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(123):
+ with django_assert_num_queries(124):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
diff --git a/saleor/graphql/order/tests/deprecated/test_order.py b/saleor/graphql/order/tests/deprecated/test_order.py
index 9401b2e5b1..070578d098 100644
--- a/saleor/graphql/order/tests/deprecated/test_order.py
+++ b/saleor/graphql/order/tests/deprecated/test_order.py
@@ -664,7 +664,9 @@ def test_update_order_line_discount_old_id(
assert discount_data["value"] == str(value)
assert discount_data["value_type"] == DiscountValueTypeEnum.FIXED.value
- assert discount_data["amount_value"] == str(unit_discount.amount)
+ assert discount_data["amount_value"] == str(
+ quantize_price(unit_discount.amount, order.currency)
+ )
ORDER_LINE_DISCOUNT_REMOVE = """
@@ -672,6 +674,11 @@ mutation OrderLineDiscountRemove($orderLineId: ID!){
orderLineDiscountRemove(orderLineId: $orderLineId){
orderLine{
id
+ unitPrice{
+ net{
+ amount
+ }
+ }
}
errors{
field
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
index a081747539..d2f28e8877 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
@@ -1404,10 +1404,6 @@ def test_draft_order_complete_with_catalogue_and_order_discount(
expected_unit_discount_amount = rule_catalogue_value
assert line_2["totalPrice"]["net"]["amount"] == float(line_2_total)
- assert line_2["unitDiscount"]["amount"] == expected_unit_discount_amount
- assert line_2["unitDiscountReason"] == expected_discount_reason
- assert line_2["unitDiscountType"] == DiscountValueType.FIXED.upper()
- assert line_2["unitDiscountValue"] == rule_catalogue_value
assigned_discount_objects = line_2["discounts"]
assert len(assigned_discount_objects) == 1
@@ -1495,10 +1491,6 @@ def test_draft_order_complete_with_catalogue_and_gift_discount(
expected_line_2_unit_discount_amount = rule_catalogue_value
assert line_2["totalPrice"]["net"]["amount"] == line_2_total
- assert line_2["unitDiscount"]["amount"] == rule_catalogue_value
- assert line_2["unitDiscountReason"] == expected_line_2_discount_reason
- assert line_2["unitDiscountType"] == DiscountValueType.FIXED.upper()
- assert line_2["unitDiscountValue"] == rule_catalogue_value
assigned_discount_objects = line_2["discounts"]
assert len(assigned_discount_objects) == 1
diff --git a/saleor/graphql/order/tests/mutations/test_order_discount.py b/saleor/graphql/order/tests/mutations/test_order_discount.py
index 7f246404eb..326cc147ae 100644
--- a/saleor/graphql/order/tests/mutations/test_order_discount.py
+++ b/saleor/graphql/order/tests/mutations/test_order_discount.py
@@ -16,6 +16,7 @@ from .....order import OrderEvents, OrderStatus
from .....order.calculations import fetch_order_prices_if_expired
from .....order.error_codes import OrderErrorCode
from .....order.interface import OrderTaxedPricesData
+from .....order.utils import invalidate_order_prices
from ....discount.enums import DiscountValueTypeEnum
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -1171,8 +1172,13 @@ mutation OrderLineDiscountUpdate($input: OrderDiscountCommonInput!, $orderLineId
"""
+@patch(
+ "saleor.graphql.order.mutations.order_line_discount_update.invalidate_order_prices",
+ wraps=invalidate_order_prices,
+)
@pytest.mark.parametrize("status", [OrderStatus.DRAFT, OrderStatus.UNCONFIRMED])
def test_update_order_line_discount(
+ mocked_invalidate_order_prices,
status,
draft_order_with_fixed_discount_order,
staff_api_client,
@@ -1279,7 +1285,9 @@ def test_update_order_line_discount(
assert discount_data["value"] == str(value)
assert discount_data["value_type"] == value_type.value
- assert discount_data["amount_value"] == str(unit_discount.amount)
+ assert discount_data["amount_value"] == str(
+ quantize_price(unit_discount.amount, currency=order.currency)
+ )
line_discount = line_to_discount.discounts.get()
assert line_discount.type == DiscountType.MANUAL
@@ -1288,6 +1296,8 @@ def test_update_order_line_discount(
assert line_discount.reason == reason
assert line_discount.amount_value == value * line_to_discount.quantity
+ mocked_invalidate_order_prices.assert_called_once_with(order, save=True)
+
def test_update_order_line_discount_by_user_no_channel_access(
draft_order_with_fixed_discount_order,
@@ -1321,7 +1331,12 @@ def test_update_order_line_discount_by_user_no_channel_access(
assert_no_permission(response)
+@patch(
+ "saleor.graphql.order.mutations.order_line_discount_update.invalidate_order_prices",
+ wraps=invalidate_order_prices,
+)
def test_update_order_line_discount_by_app(
+ mocked_invalidate_order_prices,
draft_order_with_fixed_discount_order,
app_api_client,
permission_manage_orders,
@@ -1374,7 +1389,9 @@ def test_update_order_line_discount_by_app(
assert discount_data["value"] == str(value)
assert discount_data["value_type"] == value_type.value
- assert discount_data["amount_value"] == str(unit_discount.amount)
+ assert discount_data["amount_value"] == str(
+ quantize_price(unit_discount.amount, unit_discount.currency)
+ )
line_discount = line_to_discount.discounts.get()
assert line_discount.type == DiscountType.MANUAL
@@ -1383,6 +1400,8 @@ def test_update_order_line_discount_by_app(
assert line_discount.reason == reason
assert line_discount.amount_value == value * line_to_discount.quantity
+ mocked_invalidate_order_prices.assert_called_once_with(order, save=True)
+
@pytest.mark.parametrize("status", [OrderStatus.DRAFT, OrderStatus.UNCONFIRMED])
def test_update_order_line_discount_line_with_discount(
@@ -1475,7 +1494,9 @@ def test_update_order_line_discount_line_with_discount(
assert discount_data["value"] == str(value)
assert discount_data["value_type"] == value_type.value
- assert discount_data["amount_value"] == str(unit_discount.amount)
+ assert discount_data["amount_value"] == str(
+ quantize_price(unit_discount.amount, unit_discount.currency)
+ )
assert discount_data["old_value"] == str(line_discount_value_before_update)
assert discount_data["old_value_type"] == DiscountValueTypeEnum.FIXED.value
diff --git a/saleor/graphql/order/tests/mutations/test_order_line_update.py b/saleor/graphql/order/tests/mutations/test_order_line_update.py
index 55985d3d18..d7c9be6190 100644
--- a/saleor/graphql/order/tests/mutations/test_order_line_update.py
+++ b/saleor/graphql/order/tests/mutations/test_order_line_update.py
@@ -793,6 +793,12 @@ def test_order_line_update_catalogue_discount(
assert discount.amount_value != initial_discount_amount
assert discount.amount_value == unit_discount * new_quantity
+ assert line_data["unitDiscountType"] == discount.value_type.upper()
+ assert line_data["unitDiscountValue"] == discount.value
+ assert Decimal(line_data["unitDiscount"]["amount"]) == quantize_price(
+ unit_discount, currency
+ )
+
def test_order_line_update_apply_once_per_order_voucher_discount(
order_with_lines,
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index 6a159bed3c..19aad9330d 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -21,7 +21,7 @@ from ..discount.utils.order import (
handle_order_promotion,
refresh_manual_line_discount_object,
refresh_order_line_discount_objects_for_catalogue_promotions,
- update_unit_discount_data_on_order_line,
+ update_unit_discount_data_on_order_lines_info,
)
from ..discount.utils.voucher import (
create_or_update_line_discount_objects_from_voucher,
@@ -95,9 +95,6 @@ def fetch_order_prices_if_expired(
# on the every recalculation
handle_order_promotion(order, lines_info, database_connection_name)
- # update `OrderLine.unit_discount_...` fields
- update_unit_discount_data_on_order_line(lines_info)
-
lines = [line_info.line for line_info in lines_info]
calculate_prices(
order,
@@ -144,11 +141,6 @@ def fetch_order_prices_if_expired(
"undiscounted_total_price_net_amount",
"undiscounted_total_price_gross_amount",
"tax_rate",
- "unit_discount_amount",
- "unit_discount_reason",
- "unit_discount_type",
- "unit_discount_value",
- "base_unit_price_amount",
],
)
@@ -594,7 +586,7 @@ def refresh_order_base_prices_and_discounts(
create_or_update_line_discount_objects_from_voucher(lines_info_to_update)
# update unit discount fields based on updated discounts
- update_unit_discount_data_on_order_line(lines_info)
+ update_unit_discount_data_on_order_lines_info(lines_info)
# set price expiration time
expiration_time = calculate_draft_order_line_price_expiration_date(
diff --git a/saleor/order/tests/fixtures/order.py b/saleor/order/tests/fixtures/order.py
index dd0f52a00e..7a1722ca7d 100644
--- a/saleor/order/tests/fixtures/order.py
+++ b/saleor/order/tests/fixtures/order.py
@@ -14,6 +14,7 @@ from ....core.prices import quantize_price
from ....core.taxes import zero_money
from ....discount import DiscountType, RewardType, RewardValueType, VoucherType
from ....discount.models import NotApplicable, Voucher
+from ....discount.utils.order import update_unit_discount_data_on_order_line
from ....discount.utils.voucher import (
get_products_voucher_discount,
validate_voucher_in_order,
@@ -544,7 +545,7 @@ def order_with_lines_and_catalogue_promotion(
currency=currency,
)
- line.discounts.create(
+ discount = line.discounts.create(
type=DiscountType.PROMOTION,
value_type=RewardValueType.FIXED,
value=reward_value,
@@ -560,11 +561,16 @@ def order_with_lines_and_catalogue_promotion(
total = quantize_price(line.base_unit_price_amount * line.quantity, currency)
line.total_price_net_amount = total
line.total_price_gross_amount = quantize_price(total * Decimal("1.23"), currency)
+ update_unit_discount_data_on_order_line(line, [discount])
line.save(
update_fields=[
"base_unit_price_amount",
"total_price_net_amount",
"total_price_gross_amount",
+ "unit_discount_amount",
+ "unit_discount_reason",
+ "unit_discount_type",
+ "unit_discount_value",
]
)
return order
diff --git a/saleor/order/tests/test_fetch_order_prices.py b/saleor/order/tests/test_fetch_order_prices.py
index 5b06a43b19..9e5135ec42 100644
--- a/saleor/order/tests/test_fetch_order_prices.py
+++ b/saleor/order/tests/test_fetch_order_prices.py
@@ -6,11 +6,7 @@ import pytest
from ...core.prices import quantize_price
from ...core.taxes import zero_money
from ...discount import DiscountType, DiscountValueType, VoucherType
-from ...discount.models import (
- OrderDiscount,
- OrderLineDiscount,
- PromotionRule,
-)
+from ...discount.models import OrderDiscount, OrderLineDiscount, PromotionRule
from ...discount.utils.voucher import (
create_or_update_voucher_discount_objects_for_order,
)
@@ -134,11 +130,6 @@ def test_fetch_order_prices_catalogue_discount_flat_rates(
assert order.subtotal_net_amount == order.total_net_amount - shipping_net_price
assert order.subtotal_gross_amount == order.subtotal_net_amount * tax_rate
- assert line_1.unit_discount_amount == reward_value
- assert line_1.unit_discount_reason == f"Promotion: {promotion_id}"
- assert line_1.unit_discount_type == DiscountValueType.FIXED
- assert line_1.unit_discount_value == reward_value
-
@pytest.mark.parametrize("create_new_discounts", [True, False])
def test_fetch_order_prices_order_discount_flat_rates(
@@ -1213,10 +1204,6 @@ def test_fetch_order_prices_manual_discount_and_catalogue_discount_flat_rates(
assert line_1.unit_price_gross_amount == round_up(
line_1.unit_price_net_amount * tax_rate
)
- assert line_1.unit_discount_amount == rule_catalogue_reward
- assert line_1.unit_discount_reason == f"Promotion: {promotion_id}"
- assert line_1.unit_discount_value == rule_catalogue_reward
- assert line_1.unit_discount_type == DiscountValueType.FIXED
variant_2 = line_2.variant
variant_2_listing = variant_2.channel_listings.get(channel=order.channel)
@@ -1950,11 +1937,6 @@ def test_fetch_order_prices_catalogue_discount_prices_entered_with_tax_tax_exemp
)
assert order.subtotal_gross_amount == order.subtotal_net_amount
- assert line_1.unit_discount_amount == reward_value
- assert line_1.unit_discount_reason == f"Promotion: {promotion_id}"
- assert line_1.unit_discount_type == DiscountValueType.FIXED
- assert line_1.unit_discount_value == reward_value
-
def test_fetch_order_prices_removing_catalogue_promotion_doesnt_remove_discount(
order_with_lines_and_catalogue_promotion,
diff --git a/saleor/order/tests/test_fetch_order_prices_line_price_expiration.py b/saleor/order/tests/test_fetch_order_prices_line_price_expiration.py
index 1e6f2609fe..3118b0af39 100644
--- a/saleor/order/tests/test_fetch_order_prices_line_price_expiration.py
+++ b/saleor/order/tests/test_fetch_order_prices_line_price_expiration.py
@@ -8,11 +8,7 @@ from django.utils import timezone
from ...core.prices import quantize_price
from ...core.taxes import zero_money
from ...discount import DiscountType, DiscountValueType, RewardValueType, VoucherType
-from ...discount.models import (
- OrderLineDiscount,
- Promotion,
- PromotionRule,
-)
+from ...discount.models import OrderLineDiscount, Promotion, PromotionRule
from ...discount.utils.voucher import (
create_or_update_voucher_discount_objects_for_order,
)
@@ -1580,7 +1576,9 @@ def test_fetch_order_prices_single_line_expired_apply_once_per_order_voucher_new
assert line_2.total_price_gross_amount == quantize_price(
line_2.total_price_net_amount * tax_rate, currency
)
- assert line_2.unit_discount_amount == expected_unit_discount_2
+ assert line_2.unit_discount_amount == quantize_price(
+ expected_unit_discount_2, currency
+ )
assert line_2.unit_discount_reason == f"Voucher code: {order.voucher_code}"
discount_2 = line_2.discounts.get()
diff --git a/saleor/order/tests/test_fetch_order_prices_tax_app.py b/saleor/order/tests/test_fetch_order_prices_tax_app.py
index 59d34d299d..8c9881ad0e 100644
--- a/saleor/order/tests/test_fetch_order_prices_tax_app.py
+++ b/saleor/order/tests/test_fetch_order_prices_tax_app.py
@@ -240,9 +240,6 @@ def test_fetch_order_prices_catalogue_discount_tax_app(
assert line_1.unit_price_net_amount == line_1_unit_price_net
assert line_1.unit_price_gross_amount == line_1_unit_price_gross
- assert line_1.unit_discount_reason == f"Promotion: {promotion_id}"
- assert line_1.unit_discount_amount == reward_value
-
assert line_2.undiscounted_total_price_net_amount == line_2_total_price_net
assert line_2.undiscounted_total_price_gross_amount == line_2_total_price_gross
assert line_2.undiscounted_unit_price_net_amount == line_2_unit_price_net
@@ -254,9 +251,6 @@ def test_fetch_order_prices_catalogue_discount_tax_app(
assert line_2.unit_price_net_amount == line_2_unit_price_net
assert line_2.unit_price_gross_amount == line_2_unit_price_gross
- assert line_2.unit_discount_reason is None
- assert line_2.unit_discount_amount == Decimal(0)
-
def test_fetch_order_prices_order_discount_tax_app(
order_with_lines_and_order_promotion,
diff --git a/saleor/order/tests/test_refresh_order_base_prices_and_discounts.py b/saleor/order/tests/test_refresh_order_base_prices_and_discounts.py
index f22c767dc5..cda2465c6f 100644
--- a/saleor/order/tests/test_refresh_order_base_prices_and_discounts.py
+++ b/saleor/order/tests/test_refresh_order_base_prices_and_discounts.py
@@ -481,14 +481,18 @@ def test_refresh_order_base_prices_apply_once_per_order_voucher_new_cheapest(
assert line_2.undiscounted_base_unit_price_amount == new_variant_2_price
assert line_2.base_unit_price_amount == expected_unit_price_2
- assert line_2.unit_discount_amount == expected_unit_discount_2
+ assert line_2.unit_discount_amount == quantize_price(
+ expected_unit_discount_2, currency
+ )
with pytest.raises(OrderLineDiscount.DoesNotExist):
discount_1.refresh_from_db()
assert not line_1.discounts.exists()
discount_2 = line_2.discounts.get()
- assert discount_2.amount.amount == expected_discount_amount_2
+ assert discount_2.amount.amount == quantize_price(
+ expected_discount_amount_2, currency
+ )
assert discount_2.value == new_voucher_unit_discount
assert discount_2.value_type == DiscountValueType.PERCENTAGE
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index c8ede2e617..ab65b99fbb 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -28,12 +28,9 @@ from ..discount.utils.manual_discount import apply_discount_to_value
from ..discount.utils.order import (
create_order_line_discount_objects_for_catalogue_promotions,
update_catalogue_promotion_discount_amount_for_order,
+ update_unit_discount_data_on_order_line,
)
-from ..discount.utils.promotion import (
- delete_gift_lines_qs,
- get_sale_id,
- prepare_promotion_discount_reason,
-)
+from ..discount.utils.promotion import delete_gift_lines_qs, get_sale_id
from ..discount.utils.voucher import (
create_or_update_discount_object_from_order_level_voucher,
create_or_update_line_discount_objects_from_voucher,
@@ -325,31 +322,13 @@ def create_order_line(
)
unit_discount = line.undiscounted_unit_price - line.unit_price
- if unit_discount.gross:
- if rules_info:
- line_discounts = (
- create_order_line_discount_objects_for_catalogue_promotions(
- line, rules_info, channel
- )
- )
- promotion = rules_info[0].promotion
- line.sale_id = get_sale_id(promotion)
- line.unit_discount_reason = (
- prepare_promotion_discount_reason(rules_info[0].promotion)
- if line_discounts
- else None
- )
-
- tax_configuration = channel.tax_configuration
- prices_entered_with_tax = tax_configuration.prices_entered_with_tax
-
- if prices_entered_with_tax:
- discount_amount = unit_discount.gross
- else:
- discount_amount = unit_discount.net
- line.unit_discount = discount_amount
- line.unit_discount_type = DiscountValueType.FIXED
- line.unit_discount_value = discount_amount.amount
+ if unit_discount.gross and rules_info:
+ line_discounts = create_order_line_discount_objects_for_catalogue_promotions(
+ line, rules_info, channel
+ )
+ promotion = rules_info[0].promotion
+ line.sale_id = get_sale_id(promotion)
+ update_unit_discount_data_on_order_line(line, line_discounts)
line.save(
update_fields=[
@@ -909,123 +888,124 @@ def update_discount_for_order_line(
value: Decimal | None,
):
"""Update discount fields for order line. Apply discount to the price."""
- current_value = order_line.unit_discount_value
- current_value_type = order_line.unit_discount_type
- value = value or current_value
- value_type = value_type or current_value_type
- fields_to_update = []
- if reason is not None:
- order_line.unit_discount_reason = reason
- fields_to_update.append("unit_discount_reason")
+ line_discounts = list(order_line.discounts.all())
+ _remove_invalid_discounts_for_adding_manual(line_discounts)
+ manual_line_discount = _get_manual_order_line_discount(line_discounts)
+ if not manual_line_discount:
+ current_value = None
+ current_value_type = None
+ manual_line_discount = OrderLineDiscount.objects.create(
+ line=order_line,
+ type=DiscountType.MANUAL,
+ currency=order.currency,
+ unique_type=DiscountType.MANUAL,
+ )
+ line_discounts.append(manual_line_discount)
+ else:
+ current_value = manual_line_discount.value
+ current_value_type = manual_line_discount.value_type
+
+ value = value or current_value or Decimal(0)
+ value_type = value_type or current_value_type or DiscountValueType.FIXED
+
+ undiscounted_base_unit_price = order_line.undiscounted_base_unit_price
+ currency = undiscounted_base_unit_price.currency
+
+ _update_order_line_discount_object(
+ value,
+ value_type,
+ reason,
+ order_line.quantity,
+ undiscounted_base_unit_price,
+ manual_line_discount,
+ )
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
base_unit_price = apply_discount_to_value(
value, value_type, currency, undiscounted_base_unit_price
)
-
- order_line.unit_discount = undiscounted_base_unit_price - base_unit_price
-
- order_line.unit_price = TaxedMoney(base_unit_price, base_unit_price)
order_line.base_unit_price = base_unit_price
- 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
- )
- order_line.undiscounted_total_price = (
- order_line.quantity * order_line.undiscounted_unit_price
- )
- fields_to_update.extend(
- [
- "tax_rate",
- "unit_discount_value",
- "unit_discount_amount",
- "unit_discount_type",
- "unit_discount_reason",
- "unit_price_gross_amount",
- "unit_price_net_amount",
- "total_price_net_amount",
- "total_price_gross_amount",
- "base_unit_price_amount",
- "undiscounted_unit_price_gross_amount",
- "undiscounted_unit_price_net_amount",
- "undiscounted_total_price_gross_amount",
- "undiscounted_total_price_net_amount",
- ]
- )
+ update_unit_discount_data_on_order_line(order_line, line_discounts)
+ fields_to_update = [
+ "unit_discount_value",
+ "unit_discount_amount",
+ "unit_discount_type",
+ "unit_discount_reason",
+ "base_unit_price_amount",
+ ]
+ order_line.save(update_fields=fields_to_update)
- # Save lines before calculating the taxes as some plugin can fetch all order data
- # from db
- order_line.save(update_fields=fields_to_update)
- _update_manual_order_line_discount_object(
- value, value_type, reason, order_line, order.currency
- )
+def _remove_invalid_discounts_for_adding_manual(
+ order_line_discounts: list[OrderLineDiscount],
+):
+ """Remove all line discounts except the single manual line discount."""
+ discount_to_delete = []
+ current_manual_discount = None
+ for discount in order_line_discounts:
+ if discount.type == DiscountType.MANUAL and not current_manual_discount:
+ current_manual_discount = discount
+ else:
+ discount_to_delete.append(discount)
+ if discount_to_delete:
+ for discount in discount_to_delete:
+ order_line_discounts.remove(discount)
+ OrderLineDiscount.objects.filter(
+ id__in=[discount.id for discount in discount_to_delete]
+ ).delete()
-def _update_manual_order_line_discount_object(
- value, value_type, reason, order_line, currency
-):
+
+def _get_manual_order_line_discount(
+ order_line_discounts: list[OrderLineDiscount],
+) -> OrderLineDiscount | None:
discount_to_update = None
- discount_to_delete_ids = []
- discounts = order_line.discounts.all()
- for discount in discounts:
- if discount.type == DiscountType.MANUAL and not discount_to_update:
+ for discount in order_line_discounts:
+ if discount.type == DiscountType.MANUAL:
discount_to_update = discount
- else:
- discount_to_delete_ids.append(discount.pk)
+ break
+ return discount_to_update
- if discount_to_delete_ids:
- OrderLineDiscount.objects.filter(id__in=discount_to_delete_ids).delete()
- amount_value = quantize_price(
- order_line.unit_discount.amount * order_line.quantity, currency
- )
- if not discount_to_update:
- order_line.discounts.create(
- type=DiscountType.MANUAL,
- value_type=value_type,
- value=value,
- amount_value=amount_value,
- currency=currency,
- reason=reason,
- unique_type=DiscountType.MANUAL,
+def _update_order_line_discount_object(
+ value: Decimal,
+ value_type: str,
+ reason: str | None,
+ quantity: int,
+ base_unit_price: Money,
+ line_discount: OrderLineDiscount,
+):
+ update_fields = []
+ if line_discount.value_type != value_type:
+ line_discount.value_type = value_type
+ update_fields.append("value_type")
+ if line_discount.value != value:
+ line_discount.value = value
+ update_fields.append("value")
+ if reason is not None and line_discount.reason != reason:
+ line_discount.reason = reason
+ update_fields.append("reason")
+
+ if {"value", "value_type"}.intersection(update_fields):
+ discounted_base_unit = apply_discount_to_value(
+ line_discount.value,
+ line_discount.value_type,
+ base_unit_price.currency,
+ base_unit_price,
)
- else:
- update_fields = []
- if discount_to_update.value_type != value_type:
- discount_to_update.value_type = value_type
- update_fields.append("value_type")
- if discount_to_update.value != value:
- discount_to_update.value = value
- discount_to_update.amount_value = amount_value
- update_fields.extend(["value", "amount_value"])
- if discount_to_update.reason != reason:
- discount_to_update.reason = reason
- update_fields.append("reason")
- discount_to_update.save(update_fields=update_fields)
+ line_base_total = base_unit_price * quantity
+ discounted_base_total = discounted_base_unit * quantity
+ line_discount.amount = line_base_total - discounted_base_total
+ update_fields.append("amount_value")
+ line_discount.save(update_fields=update_fields)
def remove_discount_from_order_line(order_line: OrderLine, order: "Order"):
"""Drop discount applied to order line. Restore undiscounted price."""
- order_line.unit_price = TaxedMoney(
- net=order_line.undiscounted_base_unit_price,
- gross=order_line.undiscounted_base_unit_price,
- )
+ order_line.discounts.all().delete()
+ update_unit_discount_data_on_order_line(order_line, [])
order_line.base_unit_price = order_line.undiscounted_base_unit_price
- order_line.undiscounted_unit_price = TaxedMoney(
- net=order_line.undiscounted_base_unit_price,
- gross=order_line.undiscounted_base_unit_price,
- )
- order_line.unit_discount_amount = Decimal(0)
- order_line.unit_discount_value = Decimal(0)
- order_line.unit_discount_reason = ""
- order_line.total_price = order_line.unit_price * order_line.quantity
order_line.save(
update_fields=[
"unit_discount_value",
@@ -1039,7 +1019,6 @@ def remove_discount_from_order_line(order_line: OrderLine, order: "Order"):
"tax_rate",
]
)
- order_line.discounts.all().delete()
# Manual discounts take precedence over vouchers, overriding them when applied.
# However, this does not entirely dissociate the voucher from the order.