Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Create order-line-discount for specific voucher types when order is created from checkout. (#17580)
Maciej Korycinski1d45fabbf69b
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 15379029d9..0f8b8beb31 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -26,10 +26,16 @@ from ..core.taxes import TaxDataError, TaxError, zero_taxed_moneyfrom ..core.tracing import traced_atomic_transactionfrom ..core.transactions import transaction_with_commit_on_errorsfrom ..core.utils.url import validate_storefront_url-from ..discount import DiscountType, DiscountValueType, VoucherType+from ..discount import DiscountType, DiscountValueTypefrom ..discount.models import CheckoutDiscount, NotApplicable, OrderLineDiscountfrom ..discount.utils.promotion import get_sale_id-from ..discount.utils.voucher import increase_voucher_usage, release_voucher_code_usage+from ..discount.utils.voucher import (+ calculate_line_discount_amount_from_voucher,+ increase_voucher_usage,+ is_line_level_voucher,+ is_shipping_voucher,+ release_voucher_code_usage,+)from ..graphql.checkout.utils import (prepare_insufficient_stock_checkout_validation_error,)@@ -92,7 +98,7 @@ from .utils import (if TYPE_CHECKING:from ..app.models import App- from ..discount.models import Voucher, VoucherCode+ from ..discount.models import Voucher, VoucherChannelListing, VoucherCodefrom ..plugins.manager import PluginsManagerfrom ..site.models import SiteSettings@@ -274,6 +280,7 @@ def _create_line_for_order(products_translation: dict[int, str | None],variants_translation: dict[int, str | None],prices_entered_with_tax: bool,+ voucher_channel_listing: Optional["VoucherChannelListing"],) -> OrderLineInfo:"""Create a line for the given order.@@ -346,14 +353,6 @@ def _create_line_for_order(voucher_code = checkout_info.checkout.voucher_codeis_line_voucher_code = bool(checkout_line_info.voucher)- is_shipping_voucher = (- True- if checkout_info.voucher and checkout_info.voucher.type == VoucherType.SHIPPING- else False- )- unit_discount_reason = _get_unit_discount_reason(- voucher_code, is_line_voucher_code, is_shipping_voucher- )tax_class = Noneif product.tax_class_id:@@ -382,7 +381,6 @@ def _create_line_for_order(tax_rate=tax_rate,voucher_code=voucher_code if is_line_voucher_code else None,unit_discount=discount_amount, # money field not supported by mypy_django_plugin # noqa: E501- unit_discount_reason=unit_discount_reason,unit_discount_value=discount_amount.amount, # we store value as fixed discountunit_discount_type=DiscountValueType.FIXED,base_unit_price=base_unit_price, # money field not supported by mypy_django_plugin # noqa: E501@@ -393,21 +391,21 @@ def _create_line_for_order(**get_tax_class_kwargs_for_order_line(tax_class),)- line_discounts = _create_order_line_discounts(checkout_line_info, line)+ line_discounts = _create_order_line_discounts(+ checkout_line_info, line, voucher_channel_listing+ )+ line.unit_discount_reason = _get_unit_discount_reason(+ voucher_code,+ is_line_voucher_code,+ is_shipping_voucher(checkout_info.voucher),+ line_discounts,+ )+if line_discounts:# We might have catalogue and gift predicate promotion so there might be more# than one sale_id.# The sale_id will be set only for the catalogue discount if exists.line.sale_id = _get_sale_id(line_discounts)- promotion_discount_reason = " & ".join(- [discount.reason for discount in line_discounts if discount.reason]- )- unit_discount_reason = (- f"{unit_discount_reason} & {promotion_discount_reason}"- if unit_discount_reason- else promotion_discount_reason- )- line.unit_discount_reason = unit_discount_reasonis_digital = line.is_digitalline_info = OrderLineInfo(@@ -424,18 +422,64 @@ def _create_line_for_order(def _get_unit_discount_reason(- voucher_code: str | None, is_line_voucher_code: bool, is_shipping_voucher: bool+ voucher_code: str | None,+ is_line_voucher_code: bool,+ is_shipping_voucher: bool,+ line_discounts: list[OrderLineDiscount],) -> str | None:- if not voucher_code or is_shipping_voucher:+ voucher_not_applicable = not voucher_code or is_shipping_voucher+ if voucher_not_applicable and not line_discounts:return None- return (- f"{'Voucher code' if is_line_voucher_code else 'Entire order voucher code'}: "- f"{voucher_code}"+ reasons = []+ if not is_line_voucher_code and voucher_code:+ reasons.append(f"Entire order voucher code: {voucher_code}")++ reasons.extend([discount.reason for discount in line_discounts if discount.reason])++ if not reasons:+ return None+ return " & ".join(reasons)+++def _create_order_line_discount_object_for_voucher(+ checkout_line_info: "CheckoutLineInfo",+ order_line: "OrderLine",+ voucher_channel_listing: Optional["VoucherChannelListing"],+) -> OrderLineDiscount | None:+ voucher = checkout_line_info.voucher+ if not voucher or not voucher_channel_listing:+ return None++ total_price = (+ checkout_line_info.variant_discounted_price * checkout_line_info.line.quantity+ )+ discount_amount = calculate_line_discount_amount_from_voucher(+ checkout_line_info, total_price+ ).amount+ discount_name = f"{voucher.name}"+ code = checkout_line_info.voucher_code+ discount_reason = f"Voucher code: {code}"++ return OrderLineDiscount(+ line=order_line,+ type=DiscountType.VOUCHER,+ value_type=DiscountValueType.FIXED,+ value=discount_amount,+ amount_value=discount_amount,+ currency=order_line.currency,+ name=discount_name,+ translated_name=None,+ reason=discount_reason,+ voucher=voucher,+ unique_type=DiscountType.VOUCHER,+ voucher_code=code,)def _create_order_line_discounts(- checkout_line_info: "CheckoutLineInfo", order_line: "OrderLine"+ checkout_line_info: "CheckoutLineInfo",+ order_line: "OrderLine",+ voucher_channel_listing: Optional["VoucherChannelListing"],) -> list["OrderLineDiscount"]:line_discounts = []discounts = checkout_line_info.get_promotion_discounts()@@ -445,6 +489,13 @@ def _create_order_line_discounts(discount_data["promotion_rule_id"] = discount_data.pop("promotion_rule")discount_data["line_id"] = order_line.pkline_discounts.append(OrderLineDiscount(**discount_data))++ voucher_line_discount = _create_order_line_discount_object_for_voucher(+ checkout_line_info, order_line, voucher_channel_listing=voucher_channel_listing+ )+ if voucher_line_discount:+ line_discounts.append(voucher_line_discount)+return line_discounts@@ -512,6 +563,12 @@ def _create_lines_for_order(replace=True,check_reservations=True,)+ voucher = checkout_info.voucher+ voucher_channel_listing = None+ if voucher and is_line_level_voucher(voucher):+ voucher_channel_listing = voucher.channel_listings.filter(+ channel_id=checkout_info.channel.id+ ).first()order_lines_info = [_create_line_for_order(manager,@@ -521,6 +578,7 @@ def _create_lines_for_order(product_translations,variants_translation,prices_entered_with_tax,+ voucher_channel_listing=voucher_channel_listing,)for checkout_line_info in lines]@@ -1187,7 +1245,15 @@ def _handle_allocations_of_order_lines(def _create_order_discount(order: "Order", checkout_info: "CheckoutInfo"):checkout = checkout_info.checkoutcheckout_discount = checkout.discounts.first()++ # Currently, we don't create `CheckoutDiscount` of type VOUCHER, so if there is+ # discount on checkout, but not related `CheckoutDiscount`, we assume it is+ # a voucher discount.is_voucher_discount = checkout.discount and not checkout_discount+ is_order_level_voucher_discount = is_voucher_discount and not is_line_level_voucher(+ checkout_info.voucher+ )+is_promotion_discount = (checkout_discount and checkout_discount.type == DiscountType.ORDER_PROMOTION)@@ -1199,10 +1265,7 @@ def _create_order_discount(order: "Order", checkout_info: "CheckoutInfo"):del discount_data["checkout"]order.discounts.create(**discount_data)- if is_voucher_discount:- # Currently, we don't create `CheckoutDiscount` of type VOUCHER, so if there is- # discount on checkout, but not related `CheckoutDiscount`, we assume it is- # a voucher discount.+ if is_order_level_voucher_discount:# Store voucher as a fixed value as it this the simplest solution for now.# This will be solved when we refactor the voucher logic to use .discounts# relations.diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.pyindex 83ec567aee..48e5592d64 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py@@ -19,7 +19,7 @@ from .....checkout.utils import PRIVATE_META_APP_SHIPPING_IDfrom .....core.exceptions import InsufficientStock, InsufficientStockDatafrom .....core.taxes import TaxError, zero_money, zero_taxed_moneyfrom .....discount import DiscountType, DiscountValueType, RewardValueType-from .....discount.models import CheckoutLineDiscount, Promotion+from .....discount.models import CheckoutLineDiscount, OrderLineDiscount, Promotionfrom .....giftcard import GiftCardEventsfrom .....giftcard.models import GiftCard, GiftCardEventfrom .....order import OrderOrigin, OrderStatus@@ -1110,12 +1110,17 @@ def test_checkout_complete_with_voucher_apply_once_per_order(code.refresh_from_db()assert code.used == voucher_used_count + 1- order_discount = order.discounts.filter(type=DiscountType.VOUCHER).first()- assert order_discount+ order_line_discount = OrderLineDiscount.objects.get()+ assert order_line_discountassert (- order_discount.amount_value+ order_line_discount.amount_value== (order.undiscounted_total - order.total).gross.amount)+ assert order_line_discount.type == DiscountType.VOUCHER+ assert order_line_discount.voucher == voucher_percentage+ assert order_line_discount.voucher_code == code.code+ assert order_line_discount.value_type == DiscountValueType.FIXED+assert order.voucher == voucher_percentageassert order.voucher.code == code.code@@ -1364,12 +1369,16 @@ def test_checkout_with_voucher_on_specific_product_complete(assert order_payment == paymentassert payment.transactions.count() == 1- order_discount = order.discounts.filter(type=DiscountType.VOUCHER).first()- assert order_discount+ order_line_discount = OrderLineDiscount.objects.get()+ assert order_line_discountassert (- order_discount.amount_value+ order_line_discount.amount_value== (order.undiscounted_total - order.total).gross.amount)+ assert order_line_discount.type == DiscountType.VOUCHER+ assert order_line_discount.voucher == voucher_specific_product_type+ assert order_line_discount.voucher_code == code.code+ assert order_line_discount.value_type == DiscountValueType.FIXEDcode.refresh_from_db()assert code.used == voucher_used_count + 1@@ -2370,6 +2379,15 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_promvoucher_specific_product_type.usage_limit = voucher_used_count + 1voucher_specific_product_type.save(update_fields=["usage_limit"])+ voucher_expected_value = Decimal(10)+ voucher_specific_product_type.channel_listings.update(+ discount_value=voucher_expected_value+ )+ assert (+ voucher_specific_product_type.discount_value_type+ == DiscountValueType.PERCENTAGE+ )+checkout = checkout_with_item_and_voucher_specific_productscheckout.shipping_address = addresscheckout.shipping_method = shipping_method@@ -2417,7 +2435,7 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_promdiscount_amount=reward_value,currency=channel.currency_code,)- line_discount = CheckoutLineDiscount.objects.create(+ CheckoutLineDiscount.objects.create(line=checkout_line,type=DiscountType.PROMOTION,value_type=DiscountValueType.FIXED,@@ -2478,11 +2496,21 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_promorder_line.undiscounted_total_price - order_line.total_price)- assert order_line.discounts.count() == 1- line_discount = order_line.discounts.first()- assert line_discount.promotion_rule == rule- assert line_discount.value_type == DiscountValueType.FIXED- assert line_discount.amount_value == reward_value * order_line.quantity+ assert order_line.discounts.count() == 2+ line_promotion_discount = order_line.discounts.get(type=DiscountType.PROMOTION)+ assert line_promotion_discount.promotion_rule == rule+ assert line_promotion_discount.value_type == DiscountValueType.FIXED+ assert line_promotion_discount.amount_value == reward_value * order_line.quantity++ line_voucher_discount = order_line.discounts.get(type=DiscountType.VOUCHER)+ assert line_voucher_discount.voucher == voucher_specific_product_type+ assert line_voucher_discount.value_type == DiscountValueType.FIXED+ assert line_voucher_discount.type == DiscountType.VOUCHER+ assert line_voucher_discount.voucher_code == code.code+ unit_discount = (+ voucher_expected_value / 100 * variant_channel_listing.discounted_price_amount+ )+ assert line_voucher_discount.amount_value == unit_discount * order_line.quantityassert checkout_line_quantity == order_line.quantityassert checkout_line_variant == order_line.variant@@ -2490,8 +2518,8 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_prom"Promotion", catalogue_promotion_without_rules.id)unit_discount_reason = (- f"Voucher code: {voucher_specific_product_type.code}"- f" & Promotion: {order_line.sale_id}"+ f"Promotion: {order_line.sale_id}"+ f" & Voucher code: {voucher_specific_product_type.code}")assert order_line.unit_discount_reason == unit_discount_reasonassert order.shipping_address == addressdiff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.pyindex 625ba54a95..87a699f437 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py@@ -20,7 +20,12 @@ from .....checkout.payment_utils import update_checkout_payment_statusesfrom .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID, add_voucher_to_checkoutfrom .....core.taxes import TaxError, zero_money, zero_taxed_moneyfrom .....discount import DiscountType, DiscountValueType, RewardValueType-from .....discount.models import CheckoutLineDiscount, PromotionRule, Voucher+from .....discount.models import (+ CheckoutLineDiscount,+ OrderLineDiscount,+ PromotionRule,+ Voucher,+)from .....giftcard import GiftCardEventsfrom .....giftcard.models import GiftCard, GiftCardEventfrom .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderOrigin, OrderStatus@@ -2312,12 +2317,17 @@ def test_checkout_complete_with_voucher_apply_once_per_order(code.refresh_from_db()assert code.used == voucher_used_count + 1- order_discount = order.discounts.filter(type=DiscountType.VOUCHER).first()- assert order_discount+ order_line_discount = OrderLineDiscount.objects.get()+ assert order_line_discountassert (- order_discount.amount_value+ order_line_discount.amount_value== (order.undiscounted_total - order.total).gross.amount)+ assert order_line_discount.type == DiscountType.VOUCHER+ assert order_line_discount.voucher == voucher_percentage+ assert order_line_discount.voucher_code == code.code+ assert order_line_discount.value_type == DiscountValueType.FIXED+assert order.voucher == voucher_percentageassert order.voucher.code == code.code@@ -2412,13 +2422,18 @@ def test_checkout_complete_with_voucher_apply_once_per_order_and_gift_card(code.refresh_from_db()assert code.used == voucher_used_count + 1- order_discount = order.discounts.filter(type=DiscountType.VOUCHER).first()- assert order_discount+ order_line_discount = OrderLineDiscount.objects.get()+ assert order_line_discountassert (- order_discount.amount_value+ order_line_discount.amount_value== (order.undiscounted_total - order.total).gross.amount- gift_card_initial_balance)+ assert order_line_discount.type == DiscountType.VOUCHER+ assert order_line_discount.voucher == voucher_percentage+ assert order_line_discount.voucher_code == code.code+ assert order_line_discount.value_type == DiscountValueType.FIXED+assert order.voucher == voucher_percentageassert order.voucher.code == code.code@@ -2821,12 +2836,16 @@ def test_checkout_with_voucher_on_specific_product_complete(order_line.undiscounted_total_price - order_line.total_price)- order_discount = order.discounts.filter(type=DiscountType.VOUCHER).first()- assert order_discount+ order_line_discount = OrderLineDiscount.objects.get()+ assert order_line_discountassert (- order_discount.amount_value+ order_line_discount.amount_value== (order.undiscounted_total - order.total).gross.amount)+ assert order_line_discount.type == DiscountType.VOUCHER+ assert order_line_discount.voucher == voucher_specific_product_type+ assert order_line_discount.voucher_code == code.code+ assert order_line_discount.value_type == DiscountValueType.FIXEDcode.refresh_from_db()assert code.used == voucher_used_count + 1@@ -2917,13 +2936,17 @@ def test_checkout_complete_with_voucher_on_specific_product_and_gift_card(+ shipping_price)- order_discount = order.discounts.filter(type=DiscountType.VOUCHER).first()- assert order_discount+ order_line_discount = OrderLineDiscount.objects.get()+ assert order_line_discountassert (- order_discount.amount_value+ order_line_discount.amount_value== (order.undiscounted_total - order.total).gross.amount- gift_card_initial_balance)+ assert order_line_discount.type == DiscountType.VOUCHER+ assert order_line_discount.voucher == voucher_specific_product_type+ assert order_line_discount.voucher_code == code.code+ assert order_line_discount.value_type == DiscountValueType.FIXEDcode.refresh_from_db()assert code.used == voucher_used_count + 1diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.pyindex 6cacc7665a..607909b6b4 100644--- a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py@@ -22,7 +22,7 @@ from .....core.taxes import (zero_taxed_money,)from .....discount import DiscountType, DiscountValueType, RewardValueType-from .....discount.models import CheckoutLineDiscount+from .....discount.models import CheckoutLineDiscount, OrderLineDiscountfrom .....giftcard import GiftCardEventsfrom .....giftcard.models import GiftCard, GiftCardEventfrom .....order import OrderOrigin, OrderStatus@@ -1012,15 +1012,15 @@ def test_order_from_checkout_with_voucher_apply_once_per_order(assert checkout_line_variant == order_line.variantassert order.shipping_address == addressassert order.shipping_method == checkout.shipping_method- order_discount = order.discounts.filter(type=DiscountType.VOUCHER).first()- assert order_discount+ order_line_discount = OrderLineDiscount.objects.get()+ assert order_line_discountassert (- order_discount.amount_value+ order_line_discount.amount_value== (order.undiscounted_total - order.total).gross.amount)- assert order_discount.type == DiscountType.VOUCHER- assert order_discount.voucher == voucher_percentage- assert order_discount.voucher_code == code.code+ assert order_line_discount.type == DiscountType.VOUCHER+ assert order_line_discount.voucher == voucher_percentage+ assert order_line_discount.voucher_code == code.codecode.refresh_from_db()assert code.used == voucher_used_count + 1@@ -1079,15 +1079,16 @@ def test_order_from_checkout_with_specific_product_voucher(assert checkout_line_variant == order_line.variantassert order.shipping_address == addressassert order.shipping_method == checkout.shipping_method- order_discount = order.discounts.filter(type=DiscountType.VOUCHER).first()- assert order_discount++ order_line_discount = OrderLineDiscount.objects.get()+ assert order_line_discountassert (- order_discount.amount_value+ order_line_discount.amount_value== (order.undiscounted_total - order.total).gross.amount)- assert order_discount.type == DiscountType.VOUCHER- assert order_discount.voucher == voucher_specific_product_type- assert order_discount.voucher_code == code.code+ assert order_line_discount.type == DiscountType.VOUCHER+ assert order_line_discount.voucher == voucher_specific_product_type+ assert order_line_discount.voucher_code == code.codecode.refresh_from_db()assert code.used == voucher_used_count + 1diff --git a/saleor/graphql/order/tests/queries/test_order.py b/saleor/graphql/order/tests/queries/test_order.pyindex 6253c1bfdd..aaeef20175 100644--- a/saleor/graphql/order/tests/queries/test_order.py+++ b/saleor/graphql/order/tests/queries/test_order.py@@ -7,7 +7,8 @@ from prices import Money, TaxedMoneyfrom .....checkout.utils import PRIVATE_META_APP_SHIPPING_IDfrom .....core.prices import quantize_pricefrom .....core.taxes import zero_taxed_money-from .....order import OrderStatus+from .....discount import DiscountType+from .....order import OrderOrigin, OrderStatusfrom .....order.events import transaction_eventfrom .....order.models import Order, OrderGrantedRefundfrom .....order.utils import (@@ -122,6 +123,9 @@ query OrdersQuery {valueTypevaluereason+ total{+ amount+ }amount{amount}@@ -968,9 +972,76 @@ def test_order_discounts_query(assert discount_data["valueType"] == discount.value_type.upper()assert discount_data["value"] == discount.valueassert discount_data["amount"]["amount"] == discount.amount_value+ assert discount_data["total"]["amount"] == discount.amount_valueassert discount_data["reason"] == discount.reason+def test_order_discounts_query_with_line_lvl_voucher_discount_from_checkout(+ staff_api_client,+ permission_group_manage_orders,+ permission_group_manage_shipping,+ order_with_lines,+ voucher,+):+ # given++ order = order_with_lines+ order.voucher = voucher+ order.voucher_code = voucher.code+ order.status = OrderStatus.UNCONFIRMED+ order.origin = OrderOrigin.CHECKOUT+ order.save()++ expected_reason = "Voucher"+ expected_discount_value = Decimal(5)++ first_order_line = order.lines.first()+ first_order_line_discount = first_order_line.discounts.create(+ type=DiscountType.VOUCHER,+ value_type=voucher.discount_value_type,+ value=expected_discount_value,+ amount_value=expected_discount_value,+ currency=first_order_line.currency,+ reason="Voucher",+ voucher=voucher,+ voucher_code=voucher.code,+ )++ second_order_line = order.lines.last()+ second_order_line_discount = second_order_line.discounts.create(+ type=DiscountType.VOUCHER,+ value_type=voucher.discount_value_type,+ value=expected_discount_value,+ amount_value=expected_discount_value,+ currency=second_order_line.currency,+ reason="Voucher",+ voucher=voucher,+ voucher_code=voucher.code,+ )++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ permission_group_manage_shipping.user_set.add(staff_api_client.user)++ # when+ response = staff_api_client.post_graphql(ORDERS_FULL_QUERY)+ content = get_graphql_content(response)++ # then+ order_data = content["data"]["orders"]["edges"][0]["node"]+ discounts_data = order_data.get("discounts")+ assert len(discounts_data) == 1+ discount_data = discounts_data[0]+ _, discount_id = graphene.Node.from_global_id(discount_data["id"])+ assert discount_id == str(first_order_line_discount.id)+ assert discount_data["valueType"] == voucher.discount_value_type.upper()+ assert discount_data["reason"] == expected_reason+ order_discount_amount = (+ first_order_line_discount.amount_value + second_order_line_discount.amount_value+ )+ assert discount_data["amount"]["amount"] == order_discount_amount+ assert discount_data["total"]["amount"] == order_discount_amount++def test_order_line_discount_query(staff_api_client,permission_group_manage_orders,diff --git a/saleor/graphql/order/tests/queries/test_order_line.py b/saleor/graphql/order/tests/queries/test_order_line.pyindex c0a27793b0..abb07416f9 100644--- a/saleor/graphql/order/tests/queries/test_order_line.py+++ b/saleor/graphql/order/tests/queries/test_order_line.py@@ -7,7 +7,7 @@ from prices import Money, TaxedMoneyfrom .....core.prices import quantize_pricefrom .....discount import DiscountType, DiscountValueType-from .....order import OrderStatus+from .....order import OrderOrigin, OrderStatusfrom .....order.interface import OrderTaxedPricesDatafrom .....thumbnail.models import Thumbnailfrom .....warehouse.models import Stock@@ -763,24 +763,7 @@ def test_order_query_undiscounted_prices_no_tax(assert first_order_data_line_price["gross"]["amount"] == line.unit_price.net.amount-def test_order_line_returns_discount_object(- staff_api_client, order_with_lines, permission_group_all_perms_all_channels-):- # given- expected_amount = Decimal("6")- expected_reason = "test"-- line = order_with_lines.lines.first()- line.discounts.create(- type=DiscountType.MANUAL,- value_type=DiscountValueType.FIXED,- value=expected_amount,- amount_value=expected_amount,- currency=line.currency,- reason=expected_reason,- )-- query = """+QUERY_WITH_LINE_DISCOUNTS = """query OrderQuery($id: ID) {order(id: $id) {lines {@@ -800,11 +783,30 @@ def test_order_line_returns_discount_object(}"""++def test_order_line_returns_discount_object(+ staff_api_client, order_with_lines, permission_group_all_perms_all_channels+):+ # given+ expected_amount = Decimal("6")+ expected_reason = "test"++ line = order_with_lines.lines.first()+ line.discounts.create(+ type=DiscountType.MANUAL,+ value_type=DiscountValueType.FIXED,+ value=expected_amount,+ amount_value=expected_amount,+ currency=line.currency,+ reason=expected_reason,+ )+permission_group_all_perms_all_channels.user_set.add(staff_api_client.user)# whenresponse = staff_api_client.post_graphql(- query, variables={"id": to_global_id_or_none(order_with_lines)}+ QUERY_WITH_LINE_DISCOUNTS,+ variables={"id": to_global_id_or_none(order_with_lines)},)# then@@ -818,3 +820,38 @@ def test_order_line_returns_discount_object(assert line_discount["value"] == expected_amountassert line_discount["unit"]["amount"] == expected_amount / line.quantityassert line_discount["total"]["amount"] == expected_amount+++def test_order_line_skips_voucher_discount_object_when_checkout_origin(+ staff_api_client, order_with_lines, permission_group_all_perms_all_channels+):+ # given+ expected_amount = Decimal("6")+ expected_reason = "test"++ order_with_lines.origin = OrderOrigin.CHECKOUT+ order_with_lines.save()++ line = order_with_lines.lines.first()+ line.discounts.create(+ type=DiscountType.VOUCHER,+ value_type=DiscountValueType.FIXED,+ value=expected_amount,+ amount_value=expected_amount,+ currency=line.currency,+ reason=expected_reason,+ )++ permission_group_all_perms_all_channels.user_set.add(staff_api_client.user)++ # when+ response = staff_api_client.post_graphql(+ QUERY_WITH_LINE_DISCOUNTS,+ variables={"id": to_global_id_or_none(order_with_lines)},+ )++ # then+ content = get_graphql_content(response)+ line_discounts = content["data"]["order"]["lines"][0]["discounts"]++ assert len(line_discounts) == 0diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex 41b5bf165f..22ffb371c0 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -16,6 +16,7 @@ from ...core.db.connection import allow_writer_in_contextfrom ...core.prices import quantize_pricefrom ...core.taxes import zero_moneyfrom ...discount import DiscountType+from ...discount import models as discount_modelsfrom ...graphql.checkout.types import DeliveryMethodfrom ...graphql.core.context import (SyncWebhookControlContext,@@ -26,7 +27,7 @@ from ...graphql.core.federation.resolvers import resolve_federation_referencesfrom ...graphql.order.resolvers import resolve_ordersfrom ...graphql.utils import get_user_or_app_from_contextfrom ...graphql.warehouse.dataloaders import StockByIdLoader, WarehouseByIdLoader-from ...order import OrderStatus, calculations, models+from ...order import OrderOrigin, OrderStatus, calculations, modelsfrom ...order.calculations import fetch_order_prices_if_expiredfrom ...order.models import FulfillmentStatusfrom ...order.utils import (@@ -1434,11 +1435,31 @@ class OrderLine(def with_manager_and_order(data):manager, order = data++ def handle_line_discount_from_checkout(line_discounts):+ if order.origin != OrderOrigin.CHECKOUT:+ return line_discounts++ discounts_to_return = []+ for discount in line_discounts:+ # voucher discount propagated on the line is represented by+ # OrderDiscount.+ if discount.type == DiscountType.VOUCHER:+ continue+ discounts_to_return.append(discount)++ return discounts_to_return+with allow_writer_in_context(info.context):fetch_order_prices_if_expired(order, manager, allow_sync_webhooks=root.allow_sync_webhooks)- return OrderLineDiscountsByOrderLineIDLoader(info.context).load(line.id)++ return (+ OrderLineDiscountsByOrderLineIDLoader(info.context)+ .load(line.id)+ .then(handle_line_discount_from_checkout)+ )manager = get_plugin_manager_promise(info.context)order = OrderByIdLoader(info.context).load(line.order_id)@@ -1833,13 +1854,77 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde@staticmethod@prevent_sync_event_circular_querydef resolve_discounts(root: SyncWebhookControlContext[models.Order], info):- @allow_writer_in_context(info.context)+ order = root.node++ # Line-lvl voucher discounts are represented as OrderDiscount objects for order+ # created from checkout.+ def wrap_line_discounts_from_checkout(order_discounts):+ if order.origin != OrderOrigin.CHECKOUT:+ return order_discounts++ def wrap_order_line(order_lines):+ def wrap_order_line_discount(+ order_line_discounts: list[list[discount_models.OrderLineDiscount]],+ ):+ # This affects orders created from checkout and applies+ # specifically to vouchers of the types: `SPECIFIC_PRODUCT` and+ # `ENTIRE_ORDER` with `applyOncePerOrder` enabled.+ # discounts from these vouchers should be represented as+ # OrderDiscount, but they are stored as OrderLineDiscount in+ # database. To not add any breaking change, we create artifical+ # order discount object+ artificial_order_discount = None+ for line_discount_list in order_line_discounts:+ for line_discount in line_discount_list:+ if line_discount.type != DiscountType.VOUCHER:+ continue++ if artificial_order_discount is None:+ artificial_order_discount = (+ discount_models.OrderDiscount(+ id=line_discount.id,+ name=line_discount.name,+ type=line_discount.type,+ value_type=line_discount.value_type,+ value=line_discount.value,+ amount_value=line_discount.amount_value,+ currency=line_discount.currency,+ reason=line_discount.reason,+ translated_name=line_discount.translated_name,+ )+ )+ else:+ artificial_order_discount.amount_value += (+ line_discount.amount_value+ )++ if artificial_order_discount:+ return order_discounts + [artificial_order_discount]+ return order_discounts++ return (+ OrderLineDiscountsByOrderLineIDLoader(info.context)+ .load_many([line.pk for line in order_lines])+ .then(wrap_order_line_discount)+ )++ return (+ OrderLinesByOrderIdLoader(info.context)+ .load(order.id)+ .then(wrap_order_line)+ )+def with_manager(manager):- order = root.node- fetch_order_prices_if_expired(- order, manager, allow_sync_webhooks=root.allow_sync_webhooks+ with allow_writer_in_context(info.context):+ fetch_order_prices_if_expired(+ order, manager, allow_sync_webhooks=root.allow_sync_webhooks+ )++ return (+ OrderDiscountsByOrderIDLoader(info.context)+ .load(order.id)+ .then(wrap_line_discounts_from_checkout))- return OrderDiscountsByOrderIDLoader(info.context).load(order.id)return get_plugin_manager_promise(info.context).then(with_manager)