Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Make sure that adding manual order discount always use correct prices (#17546)
Maciej Korycinski716be111ef3c
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 5d22c79c7d..dbf88ebfad 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -9,7 +9,7 @@ import graphenefrom django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django.db import transaction-from django.db.models import prefetch_related_objects+from django.db.models import QuerySet, prefetch_related_objectsfrom django.utils import timezonefrom prices import Money@@ -123,7 +123,7 @@ def invalidate_checkout_prices(return updated_fields-def checkout_lines_qs_select_for_update():+def checkout_lines_qs_select_for_update() -> QuerySet[CheckoutLine]:return CheckoutLine.objects.order_by("id").select_for_update(of=(["self"]))diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.pyindex e9399c9ae5..43e7189c89 100644--- a/saleor/discount/utils/promotion.py+++ b/saleor/discount/utils/promotion.py@@ -400,12 +400,31 @@ def _get_available_for_purchase_variant_ids(@allow_writer()+def delete_gift_lines_qs(+ order_or_checkout: Checkout | Order,+):+ from ...checkout.utils import checkout_lines_qs_select_for_update+ from ...order.utils import order_lines_qs_select_for_update++ with transaction.atomic():+ if isinstance(order_or_checkout, Checkout):+ locked_checkout_lines_qs = checkout_lines_qs_select_for_update()+ locked_checkout_lines_qs.filter(+ checkout_id=order_or_checkout.pk, is_gift=True+ ).delete()+ else:+ locked_order_lines_qs = order_lines_qs_select_for_update()+ locked_order_lines_qs.filter(+ order_id=order_or_checkout.pk, is_gift=True+ ).delete()++def delete_gift_line(order_or_checkout: Checkout | Order,lines_info: list["CheckoutLineInfo"] | list["EditableOrderLineInfo"],):if gift_line_infos := [line for line in lines_info if line.line.is_gift]:- order_or_checkout.lines.filter(is_gift=True).delete() # type: ignore[misc]+ delete_gift_lines_qs(order_or_checkout)for gift_line_info in gift_line_infos:lines_info.remove(gift_line_info) # type: ignore[arg-type]diff --git a/saleor/graphql/order/mutations/order_discount_add.py b/saleor/graphql/order/mutations/order_discount_add.pyindex 06ba607c9a..f2ec55e07f 100644--- a/saleor/graphql/order/mutations/order_discount_add.py+++ b/saleor/graphql/order/mutations/order_discount_add.py@@ -5,16 +5,18 @@ from django.core.exceptions import ValidationErrorfrom ....core.tracing import traced_atomic_transactionfrom ....order import events, models-from ....order.calculations import fetch_order_prices_if_expiredfrom ....order.error_codes import OrderErrorCode-from ....order.utils import create_order_discount_for_order, get_order_discounts+from ....order.utils import (+ create_manual_order_discount,+ get_order_discounts,+ invalidate_order_prices,+)from ....permission.enums import OrderPermissionsfrom ...app.dataloaders import get_app_promisefrom ...core import ResolveInfofrom ...core.context import SyncWebhookControlContextfrom ...core.doc_category import DOC_CATEGORY_ORDERSfrom ...core.types import OrderError-from ...plugins.dataloaders import get_plugin_manager_promisefrom ..types import Orderfrom .order_discount_common import OrderDiscountCommon, OrderDiscountCommonInput@@ -61,7 +63,6 @@ class OrderDiscountAdd(OrderDiscountCommon):def perform_mutation( # type: ignore[override]cls, _root, info: ResolveInfo, /, *, input, order_id: str):- manager = get_plugin_manager_promise(info.context).get()order = cls.get_node_or_error(info, order_id, only_type=Order)order = cast(models.Order, order)cls.check_channel_permissions(info, [order.channel_id])@@ -72,18 +73,14 @@ class OrderDiscountAdd(OrderDiscountCommon):value = input.get("value")app = get_app_promise(info.context).get()with traced_atomic_transaction():- order_discount = create_order_discount_for_order(+ order_discount = create_manual_order_discount(order, reason, value_type, value)- # Calling refreshing prices because it's set proper discount amount- # on OrderDiscount.- order, _ = fetch_order_prices_if_expired(order, manager, force_update=True)- order_discount.refresh_from_db()-events.order_discount_added_event(order=order,user=info.context.user,app=app,order_discount=order_discount,)+ invalidate_order_prices(order, save=True)return OrderDiscountAdd(order=SyncWebhookControlContext(order))diff --git a/saleor/graphql/order/tests/mutations/test_order_discount.py b/saleor/graphql/order/tests/mutations/test_order_discount.pyindex 4e6749c6f2..7f246404eb 100644--- a/saleor/graphql/order/tests/mutations/test_order_discount.py+++ b/saleor/graphql/order/tests/mutations/test_order_discount.py@@ -8,7 +8,7 @@ from prices import Money, TaxedMoney, fixed_discount, percentage_discountfrom .....core.prices import quantize_pricefrom .....core.taxes import zero_money-from .....discount import DiscountType, DiscountValueType+from .....discount import DiscountType, DiscountValueType, VoucherTypefrom .....discount.utils.voucher import (create_or_update_voucher_discount_objects_for_order,)@@ -26,14 +26,6 @@ mutation OrderDiscountAdd($orderId: ID!, $input: OrderDiscountCommonInput!){lines{id}- total{- gross{- amount- }- net{- amount- }- }}errors{field@@ -102,7 +94,11 @@ def test_add_fixed_order_discount_order_is_not_draft(@pytest.mark.parametrize("status", [OrderStatus.DRAFT, OrderStatus.UNCONFIRMED])def test_add_fixed_order_discount_to_order(- status, draft_order, staff_api_client, permission_group_manage_orders+ status,+ draft_order,+ staff_api_client,+ permission_group_manage_orders,+ plugins_manager,):# givenorder = draft_order@@ -128,6 +124,9 @@ def test_add_fixed_order_discount_to_order(errors = data["errors"]assert len(errors) == 0+ assert order.should_refresh_prices+ fetch_order_prices_if_expired(order, plugins_manager)+# Use `net` values in comparison due to that fixture have taxes incluted in# prices but after recalculation taxes are removed because in tests we# don't use any tax app.@@ -148,12 +147,16 @@ def test_add_fixed_order_discount_to_order(assert discount_data["value"] == str(value)assert discount_data["value_type"] == DiscountValueTypeEnum.FIXED.value- assert discount_data["amount_value"] == str(order_discount.amount.amount)+ assert Decimal(discount_data["amount_value"]) == order_discount.amount.amount@pytest.mark.parametrize("status", [OrderStatus.DRAFT, OrderStatus.UNCONFIRMED])def test_add_percentage_order_discount_to_order(- status, draft_order, staff_api_client, permission_group_manage_orders+ status,+ draft_order,+ staff_api_client,+ permission_group_manage_orders,+ plugins_manager,):order = draft_orderorder.status = status@@ -184,6 +187,9 @@ def test_add_percentage_order_discount_to_order(errors = data["errors"]assert len(errors) == 0+ assert order.should_refresh_prices+ fetch_order_prices_if_expired(order, plugins_manager)+# Use `net` values in comparison due to that fixture have taxes included in# prices but after recalculation taxes are removed because in tests we# don't use any tax app.@@ -205,7 +211,7 @@ def test_add_percentage_order_discount_to_order(assert discount_data["value"] == str(value)assert discount_data["value_type"] == DiscountValueTypeEnum.PERCENTAGE.value- assert discount_data["amount_value"] == str(order_discount.amount.amount)+ assert Decimal(discount_data["amount_value"]) == order_discount.amount.amountdef test_add_order_discount_to_order_by_user_no_channel_access(@@ -234,7 +240,7 @@ def test_add_order_discount_to_order_by_user_no_channel_access(def test_add_fixed_order_discount_to_order_by_app(- draft_order, app_api_client, permission_manage_orders+ draft_order, app_api_client, permission_manage_orders, plugins_manager):# givenorder = draft_order@@ -262,12 +268,6 @@ def test_add_fixed_order_discount_to_order_by_app(errors = data["errors"]assert len(errors) == 0- # Use `net` values in comparison due to that fixture have taxes incluted in- # prices but after recalculation taxes are removed because in tests we- # don't use any tax app.- assert order.undiscounted_total.net == total_before_order_discount.net- assert expected_net == order.total.net.amount-assert order.discounts.count() == 1order_discount = order.discounts.first()assert order_discount.value == value@@ -282,20 +282,155 @@ def test_add_fixed_order_discount_to_order_by_app(assert discount_data["value"] == str(value)assert discount_data["value_type"] == DiscountValueTypeEnum.FIXED.value- assert discount_data["amount_value"] == str(order_discount.amount.amount)+ assert Decimal(discount_data["amount_value"]) == order_discount.amount.amount++ assert order.should_refresh_prices+ fetch_order_prices_if_expired(order, plugins_manager)++ # Use `net` values in comparison due to that fixture have taxes incluted in+ # prices but after recalculation taxes are removed because in tests we+ # don't use any tax app.+ assert order.undiscounted_total.net == total_before_order_discount.net+ assert expected_net == order.total.net.amount+++def test_add_manual_discount_replaces_entire_voucher(+ order_with_lines,+ staff_api_client,+ permission_group_manage_orders,+ voucher,+ plugins_manager,+):+ """Order discount based on voucher:entire_order should be replaced with manual."""+ # given+ order = order_with_lines+ order.status = OrderStatus.DRAFT+ order.save(update_fields=["status", "should_refresh_prices"])++ expected_voucher_discount_amount = Decimal("12")+ assert voucher.type == VoucherType.ENTIRE_ORDER+ assert voucher.discount_value_type == DiscountValueType.FIXED++ voucher.channel_listings.update(discount_value=expected_voucher_discount_amount)++ order.discounts.create(+ type=DiscountType.VOUCHER,+ value_type=DiscountValueType.FIXED,+ value=expected_voucher_discount_amount,+ amount_value=expected_voucher_discount_amount,+ currency=order.currency,+ )++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ manual_discount_value = Decimal("10.00")++ variables = {+ "orderId": graphene.Node.to_global_id("Order", order.pk),+ "input": {+ "valueType": DiscountValueTypeEnum.PERCENTAGE.name,+ "value": manual_discount_value,+ },+ }++ # when+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)+ content = get_graphql_content(response)++ # then+ data = content["data"]["orderDiscountAdd"]+ order.refresh_from_db()+ assert not data["errors"]++ assert order.discounts.count() == 1++ expected_discount_amount = order.undiscounted_total.net * (+ manual_discount_value / Decimal(100)+ )+ manual_discount = order.discounts.get(type=DiscountType.MANUAL)+ assert manual_discount.value == manual_discount_value+ assert manual_discount.value_type == DiscountValueType.PERCENTAGE+ assert manual_discount.amount.amount == expected_discount_amount.amount++ assert order.should_refresh_prices+ fetch_order_prices_if_expired(order, plugins_manager)++ assert (+ order.total_net_amount+ == order.undiscounted_total_net_amount - expected_discount_amount.amount+ )+ assert (+ order.shipping_price_net_amount + order.subtotal_net_amount+ == order.total_net_amount+ )+++def test_add_manual_discount_keeps_shipping_voucher(+ draft_order_with_free_shipping_voucher,+ staff_api_client,+ permission_group_manage_orders,+ plugins_manager,+):+ """Order discount based on voucher:shipping should be retained when adding manual."""+ # given+ order = draft_order_with_free_shipping_voucher++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ manual_discount_value = Decimal("10.00")++ variables = {+ "orderId": graphene.Node.to_global_id("Order", order.pk),+ "input": {+ "valueType": DiscountValueTypeEnum.FIXED.name,+ "value": manual_discount_value,+ },+ }++ # when+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)+ content = get_graphql_content(response)++ # then+ data = content["data"]["orderDiscountAdd"]+ order.refresh_from_db()+ assert not data["errors"]++ assert order.discounts.count() == 2++ shipping_discount = order.discounts.get(type=DiscountType.VOUCHER)+ assert shipping_discount.value == Decimal("100")+ assert shipping_discount.value_type == DiscountValueType.PERCENTAGE+ assert shipping_discount.amount == order.undiscounted_base_shipping_price++ manual_discount = order.discounts.get(type=DiscountType.MANUAL)+ assert manual_discount.value == manual_discount_value+ assert manual_discount.value_type == DiscountValueType.FIXED+ assert manual_discount.amount.amount == manual_discount_value++ applied_discount_amount = manual_discount_value + shipping_discount.amount_value++ assert order.should_refresh_prices+ fetch_order_prices_if_expired(order, plugins_manager)+ assert (+ order.total_net_amount+ == order.undiscounted_total_net_amount - applied_discount_amount+ )+ assert (+ order.shipping_price_net_amount + order.subtotal_net_amount+ == order.total_net_amount+ )-def test_add_manual_discount_to_order_with_order_discount(+def test_add_manual_discount_replaces_order_promotion(order_with_lines_and_order_promotion,staff_api_client,permission_group_manage_orders,+ plugins_manager,):"""Order discount should be deleted in a favour of manual discount."""# givenorder = order_with_lines_and_order_promotionorder.status = OrderStatus.DRAFTorder.save(update_fields=["status"])- order_discount = order.discounts.get()permission_group_manage_orders.user_set.add(staff_api_client.user)discount_value = Decimal("10.00")@@ -317,16 +452,16 @@ def test_add_manual_discount_to_order_with_order_discount(order.refresh_from_db()assert not data["errors"]- with pytest.raises(order_discount._meta.model.DoesNotExist):- order_discount.refresh_from_db()-assert order.discounts.count() == 1- manual_discount = order.discounts.get()+ manual_discount = order.discounts.get(type=DiscountType.MANUAL)assert manual_discount.value == discount_valueassert manual_discount.value_type == DiscountValueType.FIXEDassert manual_discount.amount.amount == discount_value+ assert order.should_refresh_prices+ fetch_order_prices_if_expired(order, plugins_manager)+assert (order.total_net_amount == order.undiscounted_total_net_amount - discount_value)@@ -336,10 +471,11 @@ def test_add_manual_discount_to_order_with_order_discount()-def test_add_manual_discount_to_order_with_gift_discount(+def test_add_manual_discount_replaces_gift_discount(order_with_lines_and_gift_promotion,staff_api_client,permission_group_manage_orders,+ plugins_manager,):"""Order discount should be deleted in a favour of manual discount."""# given@@ -349,7 +485,8 @@ def test_add_manual_discount_to_order_with_gift_discount(assert order.lines.count() == 3gift_line = order.lines.filter(is_gift=True).first()- gift_discount = gift_line.discounts.get()+ assert gift_line+ assert gift_line.discounts.get()permission_group_manage_orders.user_set.add(staff_api_client.user)discount_value = Decimal("10.00")@@ -372,20 +509,17 @@ def test_add_manual_discount_to_order_with_gift_discount(assert not data["errors"]assert order.lines.count() == 2-- with pytest.raises(gift_line._meta.model.DoesNotExist):- gift_line.refresh_from_db()-- with pytest.raises(gift_discount._meta.model.DoesNotExist):- gift_discount.refresh_from_db()+ assert not order.lines.filter(is_gift=True).first()assert order.discounts.count() == 1- manual_discount = order.discounts.get()+ manual_discount = order.discounts.get(type=DiscountType.MANUAL)assert manual_discount.value == discount_valueassert manual_discount.value_type == DiscountValueType.FIXEDassert manual_discount.amount.amount == discount_value+ assert order.should_refresh_prices+ fetch_order_prices_if_expired(order, plugins_manager)assert (order.total_net_amount == order.undiscounted_total_net_amount - discount_value)diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 45f2937dfe..c8ede2e617 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -30,6 +30,7 @@ from ..discount.utils.order import (update_catalogue_promotion_discount_amount_for_order,)from ..discount.utils.promotion import (+ delete_gift_lines_qs,get_sale_id,prepare_promotion_discount_reason,)@@ -70,6 +71,7 @@ from . import (OrderStatus,events,)+from .base_calculations import base_order_totalfrom .error_codes import OrderErrorCodefrom .fetch import OrderLineInfo, fetch_draft_order_lines_infofrom .models import Order, OrderGrantedRefund, OrderLine@@ -89,7 +91,7 @@ def order_qs_select_for_update():return Order.objects.order_by("id").select_for_update(of=(["self"]))-def order_lines_qs_select_for_update():+def order_lines_qs_select_for_update() -> QuerySet[OrderLine]:return OrderLine.objects.order_by("pk").select_for_update(of=["self"])@@ -849,34 +851,39 @@ def get_order_discounts(order: Order) -> list[OrderDiscount]:return list(order.discounts.filter(type=DiscountType.MANUAL))-def create_order_discount_for_order(+def create_manual_order_discount(order: Order,reason: str,value_type: str,value: Decimal,- type: str | None = None,-):+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+) -> OrderDiscount:"""Add new order discount and update the prices."""-- current_total: TaxedMoney = order.undiscounted_totalcurrency = order.currency-- gross_total = apply_discount_to_value(- value, value_type, currency, current_total.gross- )-- new_amount = quantize_price((current_total - gross_total).gross, currency)- kwargs = {} if not type else {"type": type}-+ order_lines = order.lines.using(database_connection_name).all()+ has_gift_line = any(line.is_gift for line in order_lines)with transaction.atomic():# Manual order discount does not stack with other order-level discountsorder.discounts.exclude(voucher__type=VoucherType.SHIPPING).delete()- order_discount = order.discounts.create(+ if has_gift_line:+ delete_gift_lines_qs(order)+ current_total = base_order_total(+ order, order_lines, database_connection_name=database_connection_name+ )+ total_with_manual_discount = apply_discount_to_value(+ value, value_type, currency, current_total+ )+ manual_discount_amount = quantize_price(+ (current_total - total_with_manual_discount), currency+ )+ order_discount = OrderDiscount.objects.create(value_type=value_type,value=value,reason=reason,- amount=new_amount, # type: ignore[misc]- **kwargs,+ amount_value=manual_discount_amount.amount,+ currency=currency,+ order=order,+ type=DiscountType.MANUAL,)return order_discountdiff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.pyindex 3e03c4996d..ae55b36c26 100644--- a/saleor/plugins/webhook/tests/test_webhook.py+++ b/saleor/plugins/webhook/tests/test_webhook.py@@ -31,14 +31,14 @@ from ....core.models import EventDelivery, EventDeliveryAttempt, EventPayloadfrom ....core.notification.utils import get_site_contextfrom ....core.notify import NotifyEventTypefrom ....core.utils.url import prepare_url-from ....discount import RewardType, RewardValueType+from ....discount import DiscountType, DiscountValueType, RewardType, RewardValueTypefrom ....discount.interface import VariantPromotionRuleInfofrom ....discount.utils.checkout import (create_or_update_discount_objects_from_promotion_for_checkout,)from ....graphql.discount.enums import DiscountValueTypeEnumfrom ....graphql.discount.utils import convert_migrated_sale_predicate_to_catalogue_info-from ....graphql.order.tests.mutations.test_order_discount import ORDER_DISCOUNT_ADD+from ....graphql.order.tests.mutations.test_order_discount import ORDER_DISCOUNT_UPDATEfrom ....graphql.product.tests.mutations.test_product_create import (CREATE_PRODUCT_MUTATION,)@@ -2446,17 +2446,27 @@ def test_trigger_webhook_sync_with_subscription_within_mutation_use_default_db(webhook = subscription_calculate_taxes_for_ordersettings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]mocked_get_webhooks_for_event.return_value = [webhook]++ order_discount = draft_order.discounts.create(+ value_type=DiscountValueType.FIXED,+ value=Decimal("10"),+ amount_value=Decimal("10"),+ currency=draft_order.currency,+ type=DiscountType.MANUAL,+ )+variables = {- "orderId": graphene.Node.to_global_id("Order", draft_order.pk),+ "discountId": graphene.Node.to_global_id("OrderDiscount", order_discount.pk),"input": {"valueType": DiscountValueTypeEnum.PERCENTAGE.name,"value": Decimal("50"),},}+app_api_client.app.permissions.add(permission_manage_orders)# when- app_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)+ app_api_client.post_graphql(ORDER_DISCOUNT_UPDATE, variables)# thenmocked_generate_payload.assert_called_once()diff --git a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.pyindex d51820e2ed..ca968d7cfb 100644--- a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py+++ b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py@@ -22,10 +22,7 @@ from ....graphql.core.utils import to_global_id_or_nonefrom ....order import OrderStatusfrom ....order.calculations import fetch_order_prices_if_expiredfrom ....order.models import Order-from ....order.utils import (- create_order_discount_for_order,- update_discount_for_order_line,-)+from ....order.utils import create_manual_order_discount, update_discount_for_order_linefrom ....plugins.manager import get_plugins_managerfrom ....tax import TaxableObjectDiscountTypefrom ...event_types import WebhookEventSyncType@@ -1270,12 +1267,11 @@ def test_order_calculate_taxes_order_voucher_and_manual_discount(order.save(update_fields=["voucher_id"])manual_reward = Decimal(10)- create_order_discount_for_order(+ create_manual_order_discount(order=order,reason="Manual discount",value_type=DiscountValueType.FIXED,value=manual_reward,- type=DiscountType.MANUAL,)subtotal_manual_reward_portion = (subtotal_amount / total_amount) * manual_reward@@ -1375,12 +1371,11 @@ def test_order_calculate_taxes_order_promotion_and_manual_discount(assert rule.reward_type == RewardType.SUBTOTAL_DISCOUNTmanual_reward = Decimal(10)- create_order_discount_for_order(+ create_manual_order_discount(order=order,reason="Manual discount",value_type=DiscountValueType.FIXED,value=manual_reward,- type=DiscountType.MANUAL,)subtotal_manual_reward_portion = (subtotal_amount / total_amount) * manual_reward@@ -1474,12 +1469,11 @@ def test_order_calculate_taxes_free_shipping_voucher_and_manual_discount_fixed(create_or_update_voucher_discount_objects_for_order(order)manual_reward = Decimal(10)- create_order_discount_for_order(+ create_manual_order_discount(order=order,reason="Manual discount",value_type=DiscountValueType.FIXED,value=manual_reward,- type=DiscountType.MANUAL,)# Since shipping is free, whole manual discount should be applied to subtotal@@ -1576,12 +1570,11 @@ def test_order_calculate_taxes_free_shipping_voucher_and_manual_discount_percenttotal_amount -= shipping_price_amountmanual_reward = Decimal(10)- create_order_discount_for_order(+ create_manual_order_discount(order=order,reason="Manual discount",value_type=DiscountValueType.PERCENTAGE,value=manual_reward,- type=DiscountType.MANUAL,)# Since shipping is free, whole manual discount should be applied to subtotal