Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add flag to control voucher discount propagation (#17587)
Maciej Korycinskic8484f9ab935
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5d558ee8c0..68590af374 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -65,7 +65,8 @@ All notable, unreleased changes to this project will be documented in this file.- `orderUpdate` mutation now allows to update `metadata` and `privateMetadata` via `OrderUpdateInput` - #1508 by @lkostrowski- `DraftOrderInput`, `OrderUpdateInput` and `DraftOrderCreateInput` now allow to provide `languageCode` - #17553 by @lkostrowski- Expose line-level discounts through the `OrderLineDiscount` type, retrievable via the `OrderLine.discounts` API field - #17510 by @korycins-- Introduce total field in OrderDiscount to replace the amount field, with OrderDiscount.amount now deprecated. - #17510 by @korycins+- Introduce total field in OrderDiscount to replace the amount field, with OrderDiscount.amount now deprecated - #17510 by @korycins+- Introduce `useLegacyLineVoucherPropagation` flag to control legacy propagation behavior for specific voucher types - #17587 - by @korycins### Webhooksdiff --git a/saleor/channel/migrations/0020_channel_use_legacy_line_voucher_propagation_for_order.py b/saleor/channel/migrations/0020_channel_use_legacy_line_voucher_propagation_for_order.pynew file mode 100644index 0000000000..a01f56f5ba--- /dev/null+++ b/saleor/channel/migrations/0020_channel_use_legacy_line_voucher_propagation_for_order.py@@ -0,0 +1,25 @@+# Generated by Django 4.2.18 on 2025-04-08 08:34++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("channel", "0019_channel_draft_order_line_price_freeze_period"),+ ]++ operations = [+ migrations.AddField(+ model_name="channel",+ name="use_legacy_line_voucher_propagation_for_order",+ field=models.BooleanField(default=True),+ ),+ migrations.RunSQL(+ sql="""+ ALTER TABLE channel_channel+ ALTER COLUMN use_legacy_line_voucher_propagation_for_order+ SET DEFAULT true;+ """,+ reverse_sql=migrations.RunSQL.noop,+ ),+ ]diff --git a/saleor/channel/models.py b/saleor/channel/models.pyindex 9179a345fa..2a55f3390d 100644--- a/saleor/channel/models.py+++ b/saleor/channel/models.py@@ -54,6 +54,10 @@ class Channel(ModelWithMetadata):default=24, null=True, blank=True)+ # line lvl discounts for orders created from checkout are stored as+ # OrderLineDiscount. This flag controls how we should return it via API.+ use_legacy_line_voucher_propagation_for_order = models.BooleanField(default=True)+class Meta(ModelWithMetadata.Meta):ordering = ("slug",)app_label = "channel"diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 0f8b8beb31..9e1edf5444 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -98,6 +98,7 @@ from .utils import (if TYPE_CHECKING:from ..app.models import App+ from ..channel.models import Channelfrom ..discount.models import Voucher, VoucherChannelListing, VoucherCodefrom ..plugins.manager import PluginsManagerfrom ..site.models import SiteSettings@@ -392,7 +393,7 @@ def _create_line_for_order()line_discounts = _create_order_line_discounts(- checkout_line_info, line, voucher_channel_listing+ checkout_line_info, line, checkout_info.channel, voucher_channel_listing)line.unit_discount_reason = _get_unit_discount_reason(voucher_code,@@ -444,6 +445,7 @@ def _get_unit_discount_reason(def _create_order_line_discount_object_for_voucher(checkout_line_info: "CheckoutLineInfo",order_line: "OrderLine",+ channel: "Channel",voucher_channel_listing: Optional["VoucherChannelListing"],) -> OrderLineDiscount | None:voucher = checkout_line_info.voucher@@ -460,11 +462,20 @@ def _create_order_line_discount_object_for_voucher(code = checkout_line_info.voucher_codediscount_reason = f"Voucher code: {code}"+ if channel.use_legacy_line_voucher_propagation_for_order:+ # Previously voucher discount was always set as fixed value. To keep it in the+ # same way as previously we force the fixed type when legacy flow is used+ value_type = DiscountValueType.FIXED+ value = discount_amount+ else:+ value_type = voucher.discount_value_type+ value = voucher_channel_listing.discount_value+return OrderLineDiscount(line=order_line,type=DiscountType.VOUCHER,- value_type=DiscountValueType.FIXED,- value=discount_amount,+ value_type=value_type,+ value=value,amount_value=discount_amount,currency=order_line.currency,name=discount_name,@@ -479,6 +490,7 @@ def _create_order_line_discount_object_for_voucher(def _create_order_line_discounts(checkout_line_info: "CheckoutLineInfo",order_line: "OrderLine",+ channel: "Channel",voucher_channel_listing: Optional["VoucherChannelListing"],) -> list["OrderLineDiscount"]:line_discounts = []@@ -491,7 +503,10 @@ def _create_order_line_discounts(line_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+ checkout_line_info,+ order_line,+ channel=channel,+ voucher_channel_listing=voucher_channel_listing,)if voucher_line_discount:line_discounts.append(voucher_line_discount)diff --git a/saleor/graphql/channel/mutations/channel_create.py b/saleor/graphql/channel/mutations/channel_create.pyindex 030c6228b7..7d42270a7f 100644--- a/saleor/graphql/channel/mutations/channel_create.py+++ b/saleor/graphql/channel/mutations/channel_create.py@@ -150,6 +150,26 @@ class OrderSettingsInput(BaseInputObjectType):),)+ use_legacy_line_voucher_propagation = graphene.Boolean(+ required=False,+ description=(+ "This flag only affects orders created from checkout and applies "+ "specifically to vouchers of the types: `SPECIFIC_PRODUCT` and "+ "`ENTIRE_ORDER` with `applyOncePerOrder` enabled."+ "\n- When legacy propagation is enabled, discounts from these "+ "vouchers are represented as `OrderDiscount` objects, attached to "+ "the order and returned in the `Order.discounts` field. "+ "Additionally, percentage-based vouchers are converted to "+ "fixed-value discounts."+ "\n- When legacy propagation is disabled, discounts are represented "+ "as `OrderLineDiscount` objects, attached to individual lines and "+ "returned in the `OrderLine.discounts` field. In this case, "+ "percentage-based vouchers retain their original type."+ "\nIn future releases, `OrderLineDiscount` will become the default "+ "behavior, and this flag will be deprecated and removed." + ADDED_IN_321+ ),+ )+class Meta:doc_category = DOC_CATEGORY_ORDERSdiff --git a/saleor/graphql/channel/mutations/utils.py b/saleor/graphql/channel/mutations/utils.pyindex cb4179395c..5e23ab400c 100644--- a/saleor/graphql/channel/mutations/utils.py+++ b/saleor/graphql/channel/mutations/utils.py@@ -82,6 +82,15 @@ def clean_input_order_settings("draft_order_line_price_freeze_period"]+ # For newly created channels, by default use new discount propagation flow+ if instance.pk is None:+ cleaned_input["use_legacy_line_voucher_propagation_for_order"] = False++ if order_settings.get("use_legacy_line_voucher_propagation") is not None:+ cleaned_input["use_legacy_line_voucher_propagation_for_order"] = order_settings[+ "use_legacy_line_voucher_propagation"+ ]+def clean_input_checkout_settings(checkout_settings: dict, cleaned_input: dict):input_to_model_fields = {diff --git a/saleor/graphql/channel/tests/mutations/test_channel_create.py b/saleor/graphql/channel/tests/mutations/test_channel_create.pyindex e5b1a2392a..d7f6636895 100644--- a/saleor/graphql/channel/tests/mutations/test_channel_create.py+++ b/saleor/graphql/channel/tests/mutations/test_channel_create.py@@ -48,6 +48,7 @@ CHANNEL_CREATE_MUTATION = """allowUnpaidOrdersincludeDraftOrderInVoucherUsagedraftOrderLinePriceFreezePeriod+ useLegacyLineVoucherPropagation}checkoutSettings {useLegacyErrorFlow@@ -858,9 +859,9 @@ def test_channel_create_set_automatically_complete_fully_paid_checkouts(assert channel.automatically_complete_fully_paid_checkouts is True[email protected]("allowUnpaid", [True, False])[email protected]("allow_unpaid", [True, False])def test_channel_create_set_allow_unpaid_orders(- allowUnpaid,+ allow_unpaid,permission_manage_channels,staff_api_client,):@@ -875,7 +876,7 @@ def test_channel_create_set_allow_unpaid_orders("slug": slug,"currencyCode": currency_code,"defaultCountry": default_country,- "orderSettings": {"allowUnpaidOrders": allowUnpaid},+ "orderSettings": {"allowUnpaidOrders": allow_unpaid},}}@@ -892,5 +893,50 @@ def test_channel_create_set_allow_unpaid_orders(assert not data["errors"]channel_data = data["channel"]channel = Channel.objects.get()- assert channel_data["orderSettings"]["allowUnpaidOrders"] == allowUnpaid- assert channel.allow_unpaid_orders == allowUnpaid+ assert channel_data["orderSettings"]["allowUnpaidOrders"] == allow_unpaid+ assert channel.allow_unpaid_orders == allow_unpaid+++ ("use_legacy_input", "expected_result"),+ [(True, True), (False, False), (None, False)],+)+def test_channel_create_set_use_legacy_line_voucher_propagation(+ use_legacy_input,+ expected_result,+ permission_manage_channels,+ staff_api_client,+):+ # given+ name = "testName"+ slug = "test_slug"+ currency_code = "USD"+ default_country = "US"+ variables = {+ "input": {+ "name": name,+ "slug": slug,+ "currencyCode": currency_code,+ "defaultCountry": default_country,+ "orderSettings": {"useLegacyLineVoucherPropagation": use_legacy_input},+ }+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_CREATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["channelCreate"]+ assert not data["errors"]+ channel_data = data["channel"]+ channel = Channel.objects.get()+ assert (+ channel_data["orderSettings"]["useLegacyLineVoucherPropagation"]+ == expected_result+ )+ assert channel.use_legacy_line_voucher_propagation_for_order == expected_resultdiff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.pyindex cb30cede3a..899ef37103 100644--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py@@ -48,6 +48,7 @@ CHANNEL_UPDATE_MUTATION = """allowUnpaidOrdersincludeDraftOrderInVoucherUsagedraftOrderLinePriceFreezePeriod+ useLegacyLineVoucherPropagation}}errors{@@ -1629,3 +1630,54 @@ def test_channel_update_default_transaction_flow_strategy_with_payment_permissiochannel_USD.default_transaction_flow_strategy== TransactionFlowStrategyEnum.AUTHORIZATION.value)+++ ("use_legacy_input", "expected_result", "current_value_on_db"),+ [+ (True, True, True),+ (True, True, False),+ (False, False, True),+ (False, False, False),+ (None, True, True),+ (None, False, False),+ ],+)+def test_channel_update_set_use_legacy_line_voucher_propagation(+ use_legacy_input,+ expected_result,+ current_value_on_db,+ permission_manage_channels,+ staff_api_client,+ channel_USD,+):+ # given+ channel_USD.use_legacy_line_voucher_propagation_for_order = current_value_on_db+ channel_USD.save()++ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": channel_id,+ "input": {+ "orderSettings": {"useLegacyLineVoucherPropagation": use_legacy_input},+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["channelUpdate"]+ assert not data["errors"]+ channel_data = data["channel"]+ channel_USD.refresh_from_db()+ assert (+ channel_data["orderSettings"]["useLegacyLineVoucherPropagation"]+ == expected_result+ )+ assert channel_USD.use_legacy_line_voucher_propagation_for_order == expected_resultdiff --git a/saleor/graphql/channel/tests/queries/test_channel.py b/saleor/graphql/channel/tests/queries/test_channel.pyindex fe9d2802b8..ba2da86afa 100644--- a/saleor/graphql/channel/tests/queries/test_channel.py+++ b/saleor/graphql/channel/tests/queries/test_channel.py@@ -312,6 +312,7 @@ QUERY_CHANNEL_ORDER_SETTINGS = """allowUnpaidOrdersincludeDraftOrderInVoucherUsagedraftOrderLinePriceFreezePeriod+ useLegacyLineVoucherPropagation}}}@@ -373,6 +374,11 @@ def test_query_channel_order_settings_as_staff_user(== channel_USD.draft_order_line_price_freeze_period)+ assert (+ channel_data["orderSettings"]["useLegacyLineVoucherPropagation"]+ == channel_USD.use_legacy_line_voucher_propagation_for_order+ )+def test_query_channel_order_settings_as_app(permission_manage_channels,@@ -422,6 +428,10 @@ def test_query_channel_order_settings_as_app(channel_data["orderSettings"]["draftOrderLinePriceFreezePeriod"]== channel_USD.draft_order_line_price_freeze_period)+ assert (+ channel_data["orderSettings"]["useLegacyLineVoucherPropagation"]+ == channel_USD.use_legacy_line_voucher_propagation_for_order+ )def test_query_channel_order_settings_as_staff_user_no_permission(diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.pyindex 824e275dbb..e28c2b9c2a 100644--- a/saleor/graphql/channel/types.py+++ b/saleor/graphql/channel/types.py@@ -211,6 +211,26 @@ class OrderSettings(ObjectType):),)+ use_legacy_line_voucher_propagation = graphene.Boolean(+ required=True,+ description=(+ "This flag only affects orders created from checkout and applies "+ "specifically to vouchers of the types: `SPECIFIC_PRODUCT` and "+ "`ENTIRE_ORDER` with `applyOncePerOrder` enabled."+ "\n- When legacy propagation is enabled, discounts from these "+ "vouchers are represented as `OrderDiscount` objects, attached to "+ "the order and returned in the `Order.discounts` field. "+ "Additionally, percentage-based vouchers are converted to "+ "fixed-value discounts."+ "\n- When legacy propagation is disabled, discounts are represented "+ "as `OrderLineDiscount` objects, attached to individual lines and "+ "returned in the `OrderLine.discounts` field. In this case, "+ "percentage-based vouchers retain their original type."+ "\nIn future releases, `OrderLineDiscount` will become the default "+ "behavior, and this flag will be deprecated and removed." + ADDED_IN_321+ ),+ )+class Meta:description = "Represents the channel-specific order settings."doc_category = DOC_CATEGORY_ORDERS@@ -510,6 +530,9 @@ class Channel(ModelObjectType):draft_order_line_price_freeze_period=(root.draft_order_line_price_freeze_period),+ use_legacy_line_voucher_propagation=(+ root.use_legacy_line_voucher_propagation_for_order+ ),)@staticmethoddiff --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 48e5592d64..50fc4d6d3a 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@@ -1017,16 +1017,36 @@ def test_checkout_with_voucher_complete()+ (+ "use_legacy_voucher_propagation",+ "expected_voucher_discount_value_type",+ "expected_voucher_discount_value",+ ),+ [+ (True, DiscountValueType.FIXED, Decimal("1")),+ (False, DiscountValueType.PERCENTAGE, Decimal(10)),+ ],+)@pytest.mark.integrationdef test_checkout_complete_with_voucher_apply_once_per_order(+ use_legacy_voucher_propagation,+ expected_voucher_discount_value_type,+ expected_voucher_discount_value,user_api_client,checkout_with_voucher_percentage,voucher_percentage,payment_dummy,address,shipping_method,+ channel_USD,):# given+ channel_USD.use_legacy_line_voucher_propagation_for_order = (+ use_legacy_voucher_propagation+ )+ channel_USD.save()+code = voucher_percentage.codes.first()voucher_used_count = code.usedvoucher_percentage.usage_limit = voucher_used_count + 1@@ -1119,11 +1139,14 @@ def test_checkout_complete_with_voucher_apply_once_per_order(assert order_line_discount.type == DiscountType.VOUCHERassert order_line_discount.voucher == voucher_percentageassert order_line_discount.voucher_code == code.code- assert order_line_discount.value_type == DiscountValueType.FIXED+ assert order_line_discount.value_type == expected_voucher_discount_value_type+ assert order_line_discount.value == expected_voucher_discount_valueassert order.voucher == voucher_percentageassert order.voucher.code == code.code+ assert not order.discounts.exists()+assert not Checkout.objects.filter(pk=checkout.pk).exists(), ("Checkout should have been deleted")@@ -1283,15 +1306,35 @@ def test_checkout_with_voucher_complete_product_on_promotion()+ (+ "use_legacy_voucher_propagation",+ "expected_voucher_discount_value_type",+ "expected_voucher_discount_value",+ ),+ [+ (True, DiscountValueType.FIXED, Decimal("3")),+ (False, DiscountValueType.PERCENTAGE, Decimal(10)),+ ],+)def test_checkout_with_voucher_on_specific_product_complete(+ use_legacy_voucher_propagation,+ expected_voucher_discount_value_type,+ expected_voucher_discount_value,user_api_client,checkout_with_item_and_voucher_specific_products,voucher_specific_product_type,payment_dummy,address,shipping_method,+ channel_USD,):# given+ channel_USD.use_legacy_line_voucher_propagation_for_order = (+ use_legacy_voucher_propagation+ )+ channel_USD.save()+code = voucher_specific_product_type.codes.first()voucher_used_count = code.usedvoucher_specific_product_type.usage_limit = voucher_used_count + 1@@ -1378,13 +1421,16 @@ def test_checkout_with_voucher_on_specific_product_complete(assert order_line_discount.type == DiscountType.VOUCHERassert order_line_discount.voucher == voucher_specific_product_typeassert order_line_discount.voucher_code == code.code- assert order_line_discount.value_type == DiscountValueType.FIXED+ assert order_line_discount.value_type == expected_voucher_discount_value_type+ assert order_line_discount.value == expected_voucher_discount_valuecode.refresh_from_db()assert code.used == voucher_used_count + 1assert order.voucher == voucher_specific_product_typeassert order.voucher.code == code.code+ assert not order.discounts.exists()+assert not Checkout.objects.filter(pk=checkout.pk).exists(), ("Checkout should have been deleted")@@ -2364,7 +2410,21 @@ def test_checkout_complete_product_on_old_sale()+ (+ "use_legacy_voucher_propagation",+ "expected_voucher_discount_value_type",+ "expected_voucher_discount_value",+ ),+ [+ (True, DiscountValueType.FIXED, Decimal("1.5")),+ (False, DiscountValueType.PERCENTAGE, Decimal(10)),+ ],+)def test_checkout_with_voucher_on_specific_product_complete_with_product_on_promotion(+ use_legacy_voucher_propagation,+ expected_voucher_discount_value_type,+ expected_voucher_discount_value,user_api_client,checkout_with_item_and_voucher_specific_products,voucher_specific_product_type,@@ -2372,8 +2432,14 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_prompayment_dummy,address,shipping_method,+ channel_USD,):# given+ channel_USD.use_legacy_line_voucher_propagation_for_order = (+ use_legacy_voucher_propagation+ )+ channel_USD.save()+code = voucher_specific_product_type.codes.first()voucher_used_count = code.usedvoucher_specific_product_type.usage_limit = voucher_used_count + 1@@ -2504,7 +2570,8 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_promline_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.value_type == expected_voucher_discount_value_type+ assert line_voucher_discount.value == expected_voucher_discount_valueassert line_voucher_discount.type == DiscountType.VOUCHERassert line_voucher_discount.voucher_code == code.codeunit_discount = (@@ -2534,6 +2601,8 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_promassert order.voucher == voucher_specific_product_typeassert order.voucher.code == code.code+ assert not order.discounts.exists()+assert not Checkout.objects.filter(pk=checkout.pk).exists(), ("Checkout should have been deleted")diff --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 87a699f437..eb257d0c50 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@@ -2245,8 +2245,22 @@ def test_checkout_complete_with_voucher_paid_with_gift_card()+ (+ "use_legacy_voucher_propagation",+ "expected_voucher_discount_value_type",+ "expected_voucher_discount_value",+ ),+ [+ (True, DiscountValueType.FIXED, Decimal("1")),+ (False, DiscountValueType.PERCENTAGE, Decimal(10)),+ ],+)@pytest.mark.integrationdef test_checkout_complete_with_voucher_apply_once_per_order(+ use_legacy_voucher_propagation,+ expected_voucher_discount_value_type,+ expected_voucher_discount_value,user_api_client,checkout_with_voucher_percentage,voucher_percentage,@@ -2254,8 +2268,14 @@ def test_checkout_complete_with_voucher_apply_once_per_order(shipping_method,transaction_events_generator,transaction_item_generator,+ channel_USD,):# given+ channel_USD.use_legacy_line_voucher_propagation_for_order = (+ use_legacy_voucher_propagation+ )+ channel_USD.save()+checkout = checkout_with_voucher_percentagecode = voucher_percentage.codes.first()@@ -2326,11 +2346,14 @@ def test_checkout_complete_with_voucher_apply_once_per_order(assert order_line_discount.type == DiscountType.VOUCHERassert order_line_discount.voucher == voucher_percentageassert order_line_discount.voucher_code == code.code- assert order_line_discount.value_type == DiscountValueType.FIXED+ assert order_line_discount.value_type == expected_voucher_discount_value_type+ assert order_line_discount.value == expected_voucher_discount_valueassert order.voucher == voucher_percentageassert order.voucher.code == code.code+ assert not order.discounts.exists()+assert not Checkout.objects.filter(pk=checkout.pk).exists(), ("Checkout should have been deleted")@@ -2776,7 +2799,21 @@ def test_checkout_with_voucher_complete_product_on_sale()+ (+ "use_legacy_voucher_propagation",+ "expected_voucher_discount_value_type",+ "expected_voucher_discount_value",+ ),+ [+ (True, DiscountValueType.FIXED, Decimal("3")),+ (False, DiscountValueType.PERCENTAGE, Decimal(10)),+ ],+)def test_checkout_with_voucher_on_specific_product_complete(+ use_legacy_voucher_propagation,+ expected_voucher_discount_value_type,+ expected_voucher_discount_value,user_api_client,checkout_with_item_and_voucher_specific_products,voucher_specific_product_type,@@ -2784,8 +2821,14 @@ def test_checkout_with_voucher_on_specific_product_complete(shipping_method,transaction_events_generator,transaction_item_generator,+ channel_USD,):# given+ channel_USD.use_legacy_line_voucher_propagation_for_order = (+ use_legacy_voucher_propagation+ )+ channel_USD.save()+checkout = prepare_checkout_for_test(checkout_with_item_and_voucher_specific_products,address,@@ -2845,13 +2888,16 @@ def test_checkout_with_voucher_on_specific_product_complete(assert order_line_discount.type == DiscountType.VOUCHERassert order_line_discount.voucher == voucher_specific_product_typeassert order_line_discount.voucher_code == code.code- assert order_line_discount.value_type == DiscountValueType.FIXED+ assert order_line_discount.value_type == expected_voucher_discount_value_type+ assert order_line_discount.value == expected_voucher_discount_valuecode.refresh_from_db()assert code.used == voucher_used_count + 1assert order.voucher == voucher_specific_product_typeassert order.voucher.code == code.code+ assert not order.discounts.exists()+assert not Checkout.objects.filter(pk=checkout.pk).exists(), ("Checkout should have been deleted")@@ -3231,7 +3277,21 @@ def test_checkout_complete_multiple_rules_applied()+ (+ "use_legacy_voucher_propagation",+ "expected_voucher_discount_value_type",+ "expected_voucher_discount_value",+ ),+ [+ (True, DiscountValueType.FIXED, Decimal("3")),+ (False, DiscountValueType.PERCENTAGE, Decimal(10)),+ ],+)def test_checkout_with_voucher_on_specific_product_complete_with_product_on_promotion(+ use_legacy_voucher_propagation,+ expected_voucher_discount_value_type,+ expected_voucher_discount_value,user_api_client,checkout_with_item_and_voucher_specific_products,voucher_specific_product_type,@@ -3240,8 +3300,14 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_promshipping_method,transaction_events_generator,transaction_item_generator,+ channel_USD,):# given+ channel_USD.use_legacy_line_voucher_propagation_for_order = (+ use_legacy_voucher_propagation+ )+ channel_USD.save()+checkout = prepare_checkout_for_test(checkout_with_item_and_voucher_specific_products,address,@@ -3255,6 +3321,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_line = checkout.lines.first()checkout_line_variant = checkout_line.variantcheckout_line_variant_id = graphene.Node.to_global_id(@@ -3304,9 +3379,15 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_promorder_line.undiscounted_total_price - order_line.total_price)+ line_voucher_discount = order_line.discounts.get(type=DiscountType.VOUCHER)+ assert line_voucher_discount.value_type == expected_voucher_discount_value_type+ assert line_voucher_discount.value == expected_voucher_discount_value+code.refresh_from_db()assert code.used == voucher_used_count + 1+ assert not order.discounts.exists()+assert not Checkout.objects.filter(pk=checkout.pk).exists(), ("Checkout should have been deleted")diff --git a/saleor/graphql/order/tests/queries/test_order.py b/saleor/graphql/order/tests/queries/test_order.pyindex aaeef20175..856ec6cd0c 100644--- a/saleor/graphql/order/tests/queries/test_order.py+++ b/saleor/graphql/order/tests/queries/test_order.py@@ -22,6 +22,7 @@ from .....payment import ChargeStatus, TransactionActionfrom .....payment.models import TransactionEvent, TransactionItemfrom .....shipping.models import ShippingMethod, ShippingMethodChannelListingfrom .....warehouse.models import Stock, Warehouse+from ....core.utils import to_global_id_or_nonefrom ....order.enums import OrderAuthorizeStatusEnum, OrderChargeStatusEnumfrom ....payment.types import PaymentChargeStatusEnumfrom ....tests.utils import (@@ -117,6 +118,18 @@ query OrdersQuery {amount}}+ discounts{+ id+ valueType+ value+ reason+ total{+ amount+ }+ unit{+ amount+ }+ }}discounts{id@@ -976,14 +989,17 @@ def test_order_discounts_query(assert discount_data["reason"] == discount.reason-def test_order_discounts_query_with_line_lvl_voucher_discount_from_checkout(+def test_order_discounts_with_line_lvl_voucher_discount_from_checkout_and_legacy_flow(staff_api_client,permission_group_manage_orders,permission_group_manage_shipping,order_with_lines,voucher,+ channel_USD,):# given+ channel_USD.use_legacy_line_voucher_propagation_for_order = True+ channel_USD.save()order = order_with_linesorder.voucher = voucher@@ -1022,6 +1038,8 @@ def test_order_discounts_query_with_line_lvl_voucher_discount_from_checkout(permission_group_manage_orders.user_set.add(staff_api_client.user)permission_group_manage_shipping.user_set.add(staff_api_client.user)+ assert not order.discounts.exists()+# whenresponse = staff_api_client.post_graphql(ORDERS_FULL_QUERY)content = get_graphql_content(response)@@ -1041,6 +1059,115 @@ def test_order_discounts_query_with_line_lvl_voucher_discount_from_checkout(assert discount_data["amount"]["amount"] == order_discount_amountassert discount_data["total"]["amount"] == order_discount_amount+ assert len(order_data["lines"][0]["discounts"]) == 0+ assert len(order_data["lines"][1]["discounts"]) == 0+++def test_order_discounts_with_line_lvl_voucher_discount_from_checkout(+ staff_api_client,+ permission_group_manage_orders,+ permission_group_manage_shipping,+ order_with_lines,+ voucher,+ channel_USD,+):+ # given+ channel_USD.use_legacy_line_voucher_propagation_for_order = False+ channel_USD.save()++ 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_discount = Decimal(3)+ 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=first_order_line_discount,+ currency=first_order_line.currency,+ reason="Voucher",+ voucher=voucher,+ voucher_code=voucher.code,+ )++ second_order_line = order.lines.last()+ second_order_line_discount = Decimal(4)+ second_order_line_discount = second_order_line.discounts.create(+ type=DiscountType.VOUCHER,+ value_type=voucher.discount_value_type,+ value=expected_discount_value,+ amount_value=second_order_line_discount,+ 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)++ assert not order.discounts.exists()++ # 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) == 0++ order_lines_data = order_data["lines"]++ first_order_line_id = to_global_id_or_none(first_order_line)+ first_order_line_data = [+ line for line in order_lines_data if line["id"] == first_order_line_id+ ][0]+ assert len(first_order_line_data["discounts"]) == 1+ first_line_discount_data = first_order_line_data["discounts"][0]+ assert first_line_discount_data["id"] == to_global_id_or_none(+ first_order_line_discount+ )+ assert first_line_discount_data["valueType"] == voucher.discount_value_type.upper()+ assert first_line_discount_data["reason"] == expected_reason+ assert (+ first_line_discount_data["unit"]["amount"]+ == first_order_line_discount.amount_value / first_order_line.quantity+ )+ assert (+ first_line_discount_data["total"]["amount"]+ == first_order_line_discount.amount_value+ )++ second_order_line_id = to_global_id_or_none(second_order_line)+ second_order_line_data = [+ line for line in order_lines_data if line["id"] == second_order_line_id+ ][0]++ assert len(second_order_line_data["discounts"]) == 1+ second_line_discount_data = second_order_line_data["discounts"][0]+ assert second_line_discount_data["id"] == to_global_id_or_none(+ second_order_line_discount+ )+ assert second_line_discount_data["valueType"] == voucher.discount_value_type.upper()+ assert second_line_discount_data["reason"] == expected_reason+ assert (+ second_line_discount_data["unit"]["amount"]+ == second_order_line_discount.amount_value / second_order_line.quantity+ )+ assert (+ second_line_discount_data["total"]["amount"]+ == second_order_line_discount.amount_value+ )+def test_order_line_discount_query(staff_api_client,diff --git a/saleor/graphql/order/tests/queries/test_order_line.py b/saleor/graphql/order/tests/queries/test_order_line.pyindex abb07416f9..ffa5de6b3a 100644--- a/saleor/graphql/order/tests/queries/test_order_line.py+++ b/saleor/graphql/order/tests/queries/test_order_line.py@@ -766,8 +766,12 @@ def test_order_query_undiscounted_prices_no_tax(QUERY_WITH_LINE_DISCOUNTS = """query OrderQuery($id: ID) {order(id: $id) {+ discounts {+ id+ }lines {discounts{+ idvalueTypevaluereason@@ -822,10 +826,16 @@ def test_order_line_returns_discount_object(assert 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+def test_order_line_skips_voucher_discount_object_when_checkout_origin_and_legacy_flow(+ staff_api_client,+ order_with_lines,+ permission_group_all_perms_all_channels,+ channel_USD,):# given+ channel_USD.use_legacy_line_voucher_propagation_for_order = True+ channel_USD.save()+expected_amount = Decimal("6")expected_reason = "test"@@ -853,5 +863,57 @@ def test_order_line_skips_voucher_discount_object_when_checkout_origin(# thencontent = get_graphql_content(response)line_discounts = content["data"]["order"]["lines"][0]["discounts"]-assert len(line_discounts) == 0+ assert content["data"]["order"]["discounts"]+++def test_order_line_skips_voucher_discount_object_when_checkout_origin(+ staff_api_client,+ order_with_lines,+ permission_group_all_perms_all_channels,+ channel_USD,+):+ # given+ channel_USD.use_legacy_line_voucher_propagation_for_order = False+ channel_USD.save()++ expected_amount = Decimal("6")+ expected_reason = "test"++ order_with_lines.origin = OrderOrigin.CHECKOUT+ order_with_lines.save()++ line = order_with_lines.lines.first()+ line_discount = 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_data = content["data"]["order"]["lines"][0]["discounts"]+ assert len(line_discounts_data) == 1+ line_discount_data = line_discounts_data[0]++ assert line_discount_data["id"] == to_global_id_or_none(line_discount)+ assert line_discount_data["valueType"] == DiscountValueType.FIXED.upper()+ assert line_discount_data["reason"] == expected_reason+ assert (+ line_discount_data["unit"]["amount"]+ == line_discount.amount_value / line.quantity+ )+ assert line_discount_data["total"]["amount"] == line_discount.amount_value++ assert not content["data"]["order"]["discounts"]diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex 22ffb371c0..6b91140a7f 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -1436,8 +1436,15 @@ class OrderLine(def with_manager_and_order(data):manager, order = data- def handle_line_discount_from_checkout(line_discounts):- if order.origin != OrderOrigin.CHECKOUT:+ def handle_line_discount_from_checkout(data):+ channel, line_discounts = data++ # For legacy propagation, voucher discount was returned as OrderDiscount+ # when legacy is disabled, return the voucher discount as+ # OrderLineDiscount. It is a temporary solution to provide a grace+ # period for migration+ use_legacy = channel.use_legacy_line_voucher_propagation_for_order+ if order.origin != OrderOrigin.CHECKOUT or not use_legacy:return line_discountsdiscounts_to_return = []@@ -1454,11 +1461,12 @@ class OrderLine(fetch_order_prices_if_expired(order, manager, allow_sync_webhooks=root.allow_sync_webhooks)-- return (- OrderLineDiscountsByOrderLineIDLoader(info.context)- .load(line.id)- .then(handle_line_discount_from_checkout)+ channel_loader = ChannelByIdLoader(info.context).load(order.channel_id)+ order_line_discounts = OrderLineDiscountsByOrderLineIDLoader(+ info.context+ ).load(line.id)+ return Promise.all([channel_loader, order_line_discounts]).then(+ handle_line_discount_from_checkout)manager = get_plugin_manager_promise(info.context)@@ -1858,10 +1866,19 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde# Line-lvl voucher discounts are represented as OrderDiscount objects for order# created from checkout.- def wrap_line_discounts_from_checkout(order_discounts):+ def wrap_line_discounts_from_checkout(data):+ channel, order_discounts = data+if order.origin != OrderOrigin.CHECKOUT:return order_discounts+ # voucher discount is stored as OrderLineDiscount object in DB.+ # for backward compatibility, when legacy propagation is enabled+ # we convert the order-line-discounts into single OrderDiscount+ # It is a temporary solution to provide a grace period for migration+ if not channel.use_legacy_line_voucher_propagation_for_order:+ return order_discounts+def wrap_order_line(order_lines):def wrap_order_line_discount(order_line_discounts: list[list[discount_models.OrderLineDiscount]],@@ -1919,11 +1936,10 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Ordefetch_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)+ channel_loader = ChannelByIdLoader(info.context).load(order.channel_id)+ order_discounts = OrderDiscountsByOrderIDLoader(info.context).load(order.id)+ return Promise.all([channel_loader, order_discounts]).then(+ wrap_line_discounts_from_checkout)return get_plugin_manager_promise(info.context).then(with_manager)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 4f9da189d4..821e9b701a 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -5180,6 +5180,16 @@ type OrderSettings {Note: this API is currently in Feature Preview and can be subject to changes at later point."""draftOrderLinePriceFreezePeriod: Hour++ """+ This flag only affects orders created from checkout and applies specifically to vouchers of the types: `SPECIFIC_PRODUCT` and `ENTIRE_ORDER` with `applyOncePerOrder` enabled.+ - When legacy propagation is enabled, discounts from these vouchers are represented as `OrderDiscount` objects, attached to the order and returned in the `Order.discounts` field. Additionally, percentage-based vouchers are converted to fixed-value discounts.+ - When legacy propagation is disabled, discounts are represented as `OrderLineDiscount` objects, attached to individual lines and returned in the `OrderLine.discounts` field. In this case, percentage-based vouchers retain their original type.+ In future releases, `OrderLineDiscount` will become the default behavior, and this flag will be deprecated and removed.++ Added in Saleor 3.21.+ """+ useLegacyLineVoucherPropagation: Boolean!}"""@@ -27532,6 +27542,16 @@ input OrderSettingsInput @doc(category: "Orders") {Note: this API is currently in Feature Preview and can be subject to changes at later point."""draftOrderLinePriceFreezePeriod: Hour++ """+ This flag only affects orders created from checkout and applies specifically to vouchers of the types: `SPECIFIC_PRODUCT` and `ENTIRE_ORDER` with `applyOncePerOrder` enabled.+ - When legacy propagation is enabled, discounts from these vouchers are represented as `OrderDiscount` objects, attached to the order and returned in the `Order.discounts` field. Additionally, percentage-based vouchers are converted to fixed-value discounts.+ - When legacy propagation is disabled, discounts are represented as `OrderLineDiscount` objects, attached to individual lines and returned in the `OrderLine.discounts` field. In this case, percentage-based vouchers retain their original type.+ In future releases, `OrderLineDiscount` will become the default behavior, and this flag will be deprecated and removed.++ Added in Saleor 3.21.+ """+ useLegacyLineVoucherPropagation: Boolean}input CheckoutSettingsInput @doc(category: "Checkout") {diff --git a/saleor/tests/e2e/checkout/discounts/vouchers/test_checkout_use_voucher_for_cheapest_product.py b/saleor/tests/e2e/checkout/discounts/vouchers/test_checkout_use_voucher_for_cheapest_product.pyindex e808e26ae5..bcf83593b0 100644--- a/saleor/tests/e2e/checkout/discounts/vouchers/test_checkout_use_voucher_for_cheapest_product.py+++ b/saleor/tests/e2e/checkout/discounts/vouchers/test_checkout_use_voucher_for_cheapest_product.py@@ -121,11 +121,12 @@ def test_checkout_use_voucher_for_cheapest_product_0907(True,)+ first_line_quantity = 1# Step 1 - Create checkout for productlines = [{"variantId": first_variant_id,- "quantity": 1,+ "quantity": first_line_quantity,},{"variantId": second_variant_id,@@ -201,14 +202,25 @@ def test_checkout_use_voucher_for_cheapest_product_0907(checkout_id,)assert order_data["status"] == "UNFULFILLED"- assert order_data["discounts"][0]["type"] == "VOUCHER"- assert order_data["discounts"][0]["value"] == line_discountassert order_data["voucher"]["code"] == voucher_codeassert order_data["total"]["gross"]["amount"] == total_gross_amountassert order_data["deliveryMethod"]["id"] == shipping_method_id- first_order_line = order_data["lines"][0]+ assert not order_data["discounts"]++ first_order_line_data = order_data["lines"][0]+ assert len(first_order_line_data["discounts"]) == 1+ first_order_line_discount = first_order_line_data["discounts"][0]+ assert first_order_line_discount["type"] == "VOUCHER"+ assert first_order_line_discount["value"] == voucher_discount_value+ assert first_order_line_discount["unit"]["amount"] == line_discount+ assert (+ first_order_line_discount["total"]["amount"]+ == line_discount * first_line_quantity+ )+assert (- first_order_line["unitPrice"]["gross"]["amount"] == discounted_first_line_price+ first_order_line_data["unitPrice"]["gross"]["amount"]+ == discounted_first_line_price)second_order_line = order_data["lines"][1]assert second_order_line["unitPrice"]["gross"]["amount"] == float(diff --git a/saleor/tests/e2e/checkout/discounts/vouchers/test_checkout_with_fixed_voucher_should_not_result_in_negative_variant_price.py b/saleor/tests/e2e/checkout/discounts/vouchers/test_checkout_with_fixed_voucher_should_not_result_in_negative_variant_price.pyindex d276ef40d6..6acf0a5c69 100644--- a/saleor/tests/e2e/checkout/discounts/vouchers/test_checkout_with_fixed_voucher_should_not_result_in_negative_variant_price.py+++ b/saleor/tests/e2e/checkout/discounts/vouchers/test_checkout_with_fixed_voucher_should_not_result_in_negative_variant_price.py@@ -153,10 +153,14 @@ def test_checkout_voucher_should_not_cause_negative_variant_price_CORE_0911(checkout_id,)assert order_data["status"] == "UNFULFILLED"- assert order_data["discounts"][0]["type"] == "VOUCHER"assert order_data["voucher"]["code"] == voucher_codeassert order_data["total"]["gross"]["amount"] == discounted_total_grossassert order_data["deliveryMethod"]["id"] == shipping_method_idassert order_data["shippingPrice"]["gross"]["amount"] == shipping_price+ assert not order_data["discounts"]+order_line = order_data["lines"][0]assert order_line["unitPrice"]["gross"]["amount"] == 0+ assert len(order_line["discounts"]) == 1+ order_line_discount = order_line["discounts"][0]+ assert order_line_discount["type"] == "VOUCHER"diff --git a/saleor/tests/e2e/checkout/utils/checkout_complete.py b/saleor/tests/e2e/checkout/utils/checkout_complete.pyindex 09b62e12c5..de7d777feb 100644--- a/saleor/tests/e2e/checkout/utils/checkout_complete.py+++ b/saleor/tests/e2e/checkout/utils/checkout_complete.py@@ -90,6 +90,17 @@ mutation CheckoutComplete($checkoutId: ID!) {unitDiscountTypeunitDiscountReasonunitDiscountValue+ discounts{+ id+ type+ value+ total{+ amount+ }+ unit{+ amount+ }+ }}discounts {id