Skip to content

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

Fix catalogue discount application on custom price in checkout and draft orders (#16213)

Iga Karbowiak50b46da62a05
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 351e48693a..0f81bb631d 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -19,7 +19,7 @@ from ..checkout.base_calculations import (
base_checkout_delivery_price,
base_checkout_subtotal,
)
-from ..checkout.models import Checkout
+from ..checkout.models import Checkout, CheckoutLine
from ..core.db.connection import allow_writer
from ..core.exceptions import InsufficientStock
from ..core.taxes import zero_money
@@ -58,10 +58,11 @@ if TYPE_CHECKING:
from ..account.models import User
from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ..core.pricing.interface import LineInfo
+ from ..discount.models import Voucher
from ..order.fetch import DraftOrderLineInfo
+ from ..order.models import OrderLine
from ..plugins.manager import PluginsManager
from ..product.managers import ProductVariantQueryset
- from ..product.models import VariantChannelListingPromotionRule
from .interface import VoucherInfo
CatalogueInfo = defaultdict[str, set[Union[int, str]]]
@@ -546,11 +547,13 @@ def prepare_line_discount_objects_for_catalogue_promotions(lines_info):
line_discounts_to_remove.extend(discounts_to_update)
continue
- # discount_amount based on the difference between discounted_price and price
- discount_amount = _get_discount_amount(line_info.channel_listing, line.quantity)
+ # check if the line price is discounted by catalogue promotion
+ discounted_line = _is_discounted_line_by_catalogue_promotion(
+ line_info.channel_listing
+ )
# delete all existing discounts if the line is not discounted or it is a gift
- if not discount_amount or line.is_gift:
+ if not discounted_line or line.is_gift:
line_discounts_to_remove.extend(discounts_to_update)
continue
@@ -558,7 +561,7 @@ def prepare_line_discount_objects_for_catalogue_promotions(lines_info):
rule_info = line_info.rules_info[0]
rule = rule_info.rule
rule_discount_amount = _get_rule_discount_amount(
- rule_info.variant_listing_promotion_rule, line.quantity
+ line, rule_info, line_info.channel
)
discount_name = get_discount_name(rule, rule_info.promotion)
translated_name = get_discount_translated_name(rule_info)
@@ -599,9 +602,10 @@ def prepare_line_discount_objects_for_catalogue_promotions(lines_info):
)
-def _get_discount_amount(
- variant_channel_listing: "ProductVariantChannelListing", line_quantity: int
-) -> Decimal:
+def _is_discounted_line_by_catalogue_promotion(
+ variant_channel_listing: "ProductVariantChannelListing",
+) -> bool:
+ """Return True when the price is discounted by catalogue promotion."""
price_amount = variant_channel_listing.price_amount
discounted_price_amount = variant_channel_listing.discounted_price_amount
@@ -610,20 +614,44 @@ def _get_discount_amount(
or discounted_price_amount is None
or price_amount == discounted_price_amount
):
- return Decimal("0.0")
+ return False
- unit_discount = price_amount - discounted_price_amount
- return unit_discount * line_quantity
+ return True
def _get_rule_discount_amount(
- variant_listing_promotion_rule: Optional["VariantChannelListingPromotionRule"],
- line_quantity: int,
+ line: Union["CheckoutLine", "OrderLine"],
+ rule_info: "VariantPromotionRuleInfo",
+ channel: "Channel",
) -> Decimal:
+ """Calculate the discount amount for catalogue promotion rule.
+
+ When the line has overridden price, the discount is applied on the
+ new overridden base price.
+ """
+ variant_listing_promotion_rule = rule_info.variant_listing_promotion_rule
if not variant_listing_promotion_rule:
return Decimal("0.0")
- discount_amount = variant_listing_promotion_rule.discount_amount
- return discount_amount * line_quantity
+
+ if isinstance(line, CheckoutLine):
+ price_override = (
+ Money(line.price_override, channel.currency_code)
+ if line.price_override is not None
+ else None
+ )
+ else:
+ price_override = (
+ line.undiscounted_base_unit_price if line.is_price_overridden else None
+ )
+
+ if price_override is not None:
+ # calculate discount amount on overridden price
+ discount = rule_info.rule.get_discount(channel.currency_code)
+ discounted_price = discount(price_override)
+ discount_amount = (price_override - discounted_price).amount
+ else:
+ discount_amount = variant_listing_promotion_rule.discount_amount
+ return discount_amount * line.quantity
def get_discount_name(rule: "PromotionRule", promotion: "Promotion"):
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
index d34c0f8a4b..bd69403210 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
@@ -27,7 +27,26 @@ MUTATION_CHECKOUT_CREATE = """
email
quantity
lines {
+ unitPrice {
+ gross {
+ amount
+ }
+ }
+ totalPrice {
+ gross {
+ amount
+ }
+ }
+ undiscountedTotalPrice {
+ amount
+ }
+ undiscountedUnitPrice {
+ amount
+ }
quantity
+ variant {
+ id
+ }
isGift
}
}
@@ -589,6 +608,63 @@ def test_checkout_create_with_custom_price(
assert checkout_line.price_override == price
+def test_checkout_create_with_custom_price_and_catalogue_promotion(
+ app_api_client,
+ variant_on_promotion,
+ channel_USD,
+ permission_handle_checkouts,
+):
+ """Ensure that catalogue promotion is applied on custom price."""
+ # given
+ variant = variant_on_promotion
+
+ promotion_rule = variant.channel_listings.get(
+ channel=channel_USD
+ ).promotion_rules.first()
+ reward_value = promotion_rule.reward_value
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ price = 12
+ quantity = 2
+ variables = {
+ "checkoutInput": {
+ "channel": channel_USD.slug,
+ "lines": [{"quantity": quantity, "variantId": variant_id, "price": price}],
+ "email": test_email,
+ }
+ }
+ assert not Checkout.objects.exists()
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_CHECKOUT_CREATE, variables, permissions=[permission_handle_checkouts]
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutCreate"]
+ assert not data["errors"]
+ assert len(data["checkout"]["lines"]) == 1
+
+ unit_discount = price * reward_value / 100
+ line_data = data["checkout"]["lines"][0]
+ assert line_data["quantity"] == quantity
+ assert line_data["undiscountedUnitPrice"]["amount"] == price
+ assert line_data["undiscountedTotalPrice"]["amount"] == price * quantity
+ assert line_data["unitPrice"]["gross"]["amount"] == price - unit_discount
+ assert (
+ line_data["totalPrice"]["gross"]["amount"] == (price - unit_discount) * quantity
+ )
+
+ checkout = Checkout.objects.first()
+ line = checkout.lines.first()
+ assert line.discounts.count() == 1
+ line_discount = line.discounts.first()
+ assert line_discount.amount_value == unit_discount * quantity
+ assert line_discount.value == reward_value
+ assert line_discount.value_type == promotion_rule.reward_value_type
+
+
def test_checkout_create_with_gift_reward(
api_client, stock, channel_USD, gift_promotion_rule
):
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
index 1b20246740..9bce930875 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
@@ -1047,6 +1047,57 @@ def test_checkout_lines_add_existing_variant_override_previous_custom_price(
assert line.price_override == price
+def test_checkout_lines_add_custom_price_and_catalogue_promotion(
+ app_api_client, checkout, variant_on_promotion, permission_handle_checkouts
+):
+ # given
+ variant = variant_on_promotion
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ price = Decimal("16")
+
+ promotion_rule = variant.channel_listings.get(
+ channel=checkout.channel
+ ).promotion_rules.first()
+ reward_value = promotion_rule.reward_value
+
+ quantity = 2
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [{"variantId": variant_id, "quantity": quantity, "price": price}],
+ "channelSlug": checkout.channel.slug,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_CHECKOUT_LINES_ADD,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesAdd"]
+ assert not data["errors"]
+ assert len(data["checkout"]["lines"]) == 1
+
+ unit_discount = price * reward_value / 100
+ line_data = data["checkout"]["lines"][0]
+ assert line_data["quantity"] == quantity
+ assert line_data["undiscountedUnitPrice"]["amount"] == price
+ assert line_data["undiscountedTotalPrice"]["amount"] == price * quantity
+ assert line_data["unitPrice"]["gross"]["amount"] == price - unit_discount
+ assert (
+ line_data["totalPrice"]["gross"]["amount"] == (price - unit_discount) * quantity
+ )
+
+ line = checkout.lines.first()
+ assert line.discounts.count() == 1
+ line_discount = line.discounts.first()
+ assert line_discount.amount_value == unit_discount * quantity
+ assert line_discount.value == reward_value
+ assert line_discount.value_type == promotion_rule.reward_value_type
+
+
@mock.patch("saleor.plugins.manager.PluginsManager.list_shipping_methods_for_checkout")
def test_checkout_lines_add_deletes_external_shipping_method_if_invalid(
mocked_webhook, app_api_client, checkout_with_item, permission_handle_checkouts
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
index 64c03d118a..5104aa1b28 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
@@ -14,6 +14,7 @@ from .....checkout.utils import (
calculate_checkout_quantity,
invalidate_checkout,
)
+from .....discount import RewardValueType
from .....plugins.manager import get_plugins_manager
from .....product.models import ProductChannelListing
from .....warehouse.models import Reservation, Stock
@@ -34,6 +35,14 @@ MUTATION_CHECKOUT_LINES_UPDATE = """
variant {
id
}
+ undiscountedUnitPrice {
+ amount
+ }
+ unitPrice {
+ gross {
+ amount
+ }
+ }
}
totalPrice {
gross {
@@ -660,6 +669,171 @@ def test_checkout_lines_update_with_custom_price_override_existing_price(
assert calculate_checkout_quantity(lines) == 1
+def test_checkout_lines_update_with_custom_price_and_fixed_catalogue_promotion(
+ app_api_client, checkout_with_item_on_promotion, permission_handle_checkouts
+):
+ # given
+ checkout = checkout_with_item_on_promotion
+
+ assert checkout.lines.count() == 1
+
+ line = checkout.lines.first()
+ old_line_qty = line.quantity
+ line_qty = 1
+ assert line_qty != old_line_qty
+ line_discount = line.discounts.first()
+ old_line_discount_amount_value = line_discount.amount_value
+ reward_value = line_discount.value
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant_id)
+ custom_price = Decimal("15")
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [
+ {"variantId": variant_id, "quantity": line_qty, "price": custom_price}
+ ],
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_CHECKOUT_LINES_UPDATE,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["checkoutLinesUpdate"]
+ assert not data["errors"]
+ checkout_data = data["checkout"]
+ assert checkout_data["totalPrice"]["gross"]["amount"] == custom_price - reward_value
+ assert len(checkout_data["lines"]) == 1
+ line_data = data["checkout"]["lines"][0]
+ assert line_data["quantity"] == line_qty
+ assert line_data["undiscountedUnitPrice"]["amount"] == custom_price
+ assert line_data["unitPrice"]["gross"]["amount"] == custom_price - reward_value
+
+ line_discount.refresh_from_db()
+ assert line_discount.amount_value == reward_value
+ assert line_discount.amount_value != old_line_discount_amount_value
+
+
+def test_checkout_lines_update_with_custom_price_and_percentage_catalogue_promotion(
+ app_api_client, checkout_with_item_on_promotion, permission_handle_checkouts
+):
+ # given
+ checkout = checkout_with_item_on_promotion
+
+ assert checkout.lines.count() == 1
+
+ line = checkout.lines.first()
+ old_line_qty = line.quantity
+ line_qty = 2
+ assert line_qty != old_line_qty
+ line_discount = line.discounts.first()
+ old_line_discount_amount_value = line_discount.amount_value
+
+ promotion_rule = line_discount.promotion_rule
+ reward_value_type = RewardValueType.PERCENTAGE
+ reward_value = Decimal("50")
+ promotion_rule.reward_value_type = reward_value_type
+ promotion_rule.reward_value = reward_value
+ promotion_rule.save(update_fields=["reward_value_type", "reward_value"])
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant_id)
+ custom_price = Decimal("40")
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [
+ {"variantId": variant_id, "quantity": line_qty, "price": custom_price}
+ ],
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_CHECKOUT_LINES_UPDATE,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ unit_discount_amount = custom_price * promotion_rule.reward_value / 100
+ discount_amount = unit_discount_amount * line_qty
+
+ data = content["data"]["checkoutLinesUpdate"]
+ assert not data["errors"]
+ checkout_data = data["checkout"]
+ assert (
+ checkout_data["totalPrice"]["gross"]["amount"]
+ == custom_price * line_qty - discount_amount
+ )
+ assert len(checkout_data["lines"]) == 1
+ line_data = data["checkout"]["lines"][0]
+ assert line_data["quantity"] == line_qty
+ assert line_data["undiscountedUnitPrice"]["amount"] == custom_price
+ assert (
+ line_data["unitPrice"]["gross"]["amount"] == custom_price - unit_discount_amount
+ )
+
+ line_discount.refresh_from_db()
+ assert line_discount.amount_value == discount_amount
+ assert line_discount.amount_value != old_line_discount_amount_value
+ assert line_discount.value == reward_value
+ assert line_discount.value_type == reward_value_type
+
+
+def test_checkout_lines_update_with_0_custom_price_and_catalogue_promotion(
+ app_api_client, checkout_with_item_on_promotion, permission_handle_checkouts
+):
+ # given
+ checkout = checkout_with_item_on_promotion
+
+ assert checkout.lines.count() == 1
+
+ line = checkout.lines.first()
+ old_line_qty = line.quantity
+ line_qty = 1
+ assert line_qty != old_line_qty
+ line_discount = line.discounts.first()
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant_id)
+ custom_price = Decimal("0")
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [
+ {"variantId": variant_id, "quantity": line_qty, "price": custom_price}
+ ],
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_CHECKOUT_LINES_UPDATE,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["checkoutLinesUpdate"]
+ assert not data["errors"]
+ checkout_data = data["checkout"]
+ assert checkout_data["totalPrice"]["gross"]["amount"] == 0
+ assert len(checkout_data["lines"]) == 1
+ line_data = data["checkout"]["lines"][0]
+ assert line_data["quantity"] == line_qty
+ assert line_data["undiscountedUnitPrice"]["amount"] == 0
+ assert line_data["unitPrice"]["gross"]["amount"] == 0
+
+ line_discount.refresh_from_db()
+ assert line_discount.amount_value == 0
+
+
def test_checkout_lines_update_clear_custom_price(
app_api_client, checkout_with_item, permission_handle_checkouts
):
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
index 5b068a10a1..896104189e 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -51,11 +51,6 @@ DRAFT_ORDER_CREATE_MUTATION = """
reason
}
redirectUrl
- lines {
- productName
- productSku
- quantity
- }
billingAddress{
city
streetAddress1
@@ -127,6 +122,7 @@ DRAFT_ORDER_CREATE_MUTATION = """
unitDiscountType
unitDiscountValue
isGift
+ isPriceOverridden
}
}
}
@@ -2716,6 +2712,121 @@ def test_draft_order_create_with_custom_price_in_order_line(
assert order_line_1.is_price_overridden is True
+def test_draft_order_create_with_custom_price_and_catalogue_promotion(
+ staff_api_client,
+ permission_group_manage_orders,
+ customer_user,
+ variant_on_promotion,
+ channel_USD,
+):
+ # given
+ query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ variant = variant_on_promotion
+
+ variant_listing = variant.channel_listings.get(channel=channel_USD)
+ variant_price = variant_listing.price_amount
+ promotion_rule = variant_listing.promotion_rules.first()
+ reward_value = promotion_rule.reward_value
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+
+ custom_price = 18
+ quantity = 2
+ variant_list = [
+ {
+ "variantId": variant_id,
+ "quantity": quantity,
+ "price": custom_price,
+ "forceNewLine": False,
+ },
+ {
+ "variantId": variant_id,
+ "quantity": quantity,
+ "forceNewLine": True,
+ },
+ ]
+ variables = {
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ "channelId": channel_id,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ assert not content["data"]["draftOrderCreate"]["errors"]
+ data = content["data"]["draftOrderCreate"]["order"]
+ assert data["status"] == OrderStatus.DRAFT.upper()
+ assert len(data["lines"]) == 2
+
+ line_1_unit_discount = custom_price * reward_value / 100
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion_rule.promotion_id)
+ line_data_1 = {
+ "productVariantId": variant_id,
+ "quantity": quantity,
+ "unitDiscount": {
+ "amount": float(line_1_unit_discount),
+ },
+ "unitPrice": {
+ "gross": {
+ "amount": float(custom_price - line_1_unit_discount),
+ },
+ },
+ "undiscountedUnitPrice": {
+ "gross": {
+ "amount": float(custom_price),
+ },
+ },
+ "totalPrice": {
+ "gross": {
+ "amount": float((custom_price - line_1_unit_discount) * quantity),
+ },
+ },
+ "unitDiscountReason": f"Promotion: {promotion_id}",
+ "unitDiscountType": RewardValueType.PERCENTAGE.upper(),
+ "unitDiscountValue": reward_value,
+ "isPriceOverridden": True,
+ "isGift": False,
+ }
+ assert line_data_1 in data["lines"]
+ line_2_unit_discount = variant_price * reward_value / 100
+ line_data_2 = {
+ "productVariantId": variant_id,
+ "quantity": quantity,
+ "unitDiscount": {
+ "amount": float(line_2_unit_discount),
+ },
+ "unitPrice": {
+ "gross": {
+ "amount": float(variant_price - line_2_unit_discount),
+ },
+ },
+ "undiscountedUnitPrice": {
+ "gross": {
+ "amount": float(variant_price),
+ },
+ },
+ "totalPrice": {
+ "gross": {
+ "amount": float((variant_price - line_2_unit_discount) * quantity),
+ },
+ },
+ "unitDiscountReason": f"Promotion: {promotion_id}",
+ "unitDiscountType": RewardValueType.PERCENTAGE.upper(),
+ "unitDiscountValue": reward_value,
+ "isPriceOverridden": False,
+ "isGift": False,
+ }
+ assert line_data_2 in data["lines"]
+
+
def test_draft_order_create_product_catalogue_promotion(
staff_api_client,
permission_group_manage_orders,
diff --git a/saleor/graphql/order/tests/mutations/test_order_lines_create.py b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
index 1266e2ae75..6cb2bc6e08 100644
--- a/saleor/graphql/order/tests/mutations/test_order_lines_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
@@ -57,6 +57,11 @@ ORDER_LINES_CREATE_MUTATION = """
currency
}
}
+ undiscountedUnitPrice {
+ gross {
+ amount
+ }
+ }
unitDiscount {
amount
}
@@ -946,34 +951,32 @@ def test_invalid_order_when_creating_lines(
draft_order_updated_webhook_mock.assert_not_called()
- ("status", "force_new_line"),
- [(OrderStatus.DRAFT, False), (OrderStatus.UNCONFIRMED, True)],
-)
@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
def test_order_lines_create_with_custom_price(
- product_variant_out_of_stock_webhook_mock,
order_updated_webhook_mock,
draft_order_updated_webhook_mock,
- status,
- force_new_line,
order_with_lines,
permission_group_manage_orders,
staff_api_client,
- variant_with_many_stocks,
):
# give
query = ORDER_LINES_CREATE_MUTATION
order = order_with_lines
- order.status = status
+ order.status = OrderStatus.DRAFT
order.save(update_fields=["status"])
- variant = variant_with_many_stocks
+
+ order_line = order.lines.first()
+ old_qty = order_line.quantity
+
+ lines_count = len(order.lines.all())
+
+ variant = order_line.variant
quantity = 1
order_id = graphene.Node.to_global_id("Order", order.id)
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
custom_price = 18
+ force_new_line = False
variables = {
"orderId": order_id,
"variantId": variant_id,
@@ -987,13 +990,85 @@ def test_order_lines_create_with_custom_price(
response = staff_api_client.post_graphql(query, variables)
# then
+ new_qty = quantity + old_qty
assert_proper_webhook_called_once(
- order, status, draft_order_updated_webhook_mock, order_updated_webhook_mock
+ order,
+ order.status,
+ draft_order_updated_webhook_mock,
+ order_updated_webhook_mock,
)
assert OrderEvent.objects.count() == 1
+
event = OrderEvent.objects.last()
assert event.type == order_events.OrderEvents.ADDED_PRODUCTS
assert len(event.parameters["lines"]) == 1
+ assert len(order.lines.all()) == lines_count
+
+ order_line.refresh_from_db()
+ assert order_line.undiscounted_base_unit_price_amount == custom_price
+ assert order_line.base_unit_price_amount == custom_price
+ assert event.parameters["lines"] == [
+ {"item": str(order_line), "line_pk": str(order_line.pk), "quantity": new_qty}
+ ]
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderLinesCreate"]
+ assert data["orderLines"][0]["productSku"] == variant.sku
+ assert data["orderLines"][0]["productVariantId"] == variant.get_global_id()
+ assert data["orderLines"][0]["quantity"] == new_qty
+ assert data["orderLines"][0]["isPriceOverridden"] is True
+
+
+@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+def test_order_lines_create_with_custom_price_force_new_line(
+ order_updated_webhook_mock,
+ draft_order_updated_webhook_mock,
+ order_with_lines,
+ permission_group_manage_orders,
+ staff_api_client,
+):
+ # give
+ query = ORDER_LINES_CREATE_MUTATION
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+
+ order_line = order.lines.first()
+
+ lines_count = len(order.lines.all())
+
+ variant = order_line.variant
+ quantity = 1
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ custom_price = 18
+ force_new_line = True
+ variables = {
+ "orderId": order_id,
+ "variantId": variant_id,
+ "quantity": quantity,
+ "price": custom_price,
+ "forceNewLine": force_new_line,
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_proper_webhook_called_once(
+ order,
+ order.status,
+ draft_order_updated_webhook_mock,
+ order_updated_webhook_mock,
+ )
+ assert OrderEvent.objects.count() == 1
+ event = OrderEvent.objects.last()
+ assert event.type == order_events.OrderEvents.ADDED_PRODUCTS
+ assert len(event.parameters["lines"]) == 1
+ assert order.lines.count() == lines_count + 1
+
line = OrderLine.objects.last()
assert line.undiscounted_base_unit_price_amount == custom_price
assert line.base_unit_price_amount == custom_price
@@ -1007,3 +1082,128 @@ def test_order_lines_create_with_custom_price(
assert data["orderLines"][0]["productVariantId"] == variant.get_global_id()
assert data["orderLines"][0]["quantity"] == quantity
assert data["orderLines"][0]["isPriceOverridden"] is True
+
+
+def test_order_lines_create_with_custom_price_and_catalogue_discount(
+ order_line_on_promotion,
+ permission_group_manage_orders,
+ staff_api_client,
+):
+ # give
+ query = ORDER_LINES_CREATE_MUTATION
+ order_line = order_line_on_promotion
+ order = order_line.order
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+
+ order_line = order.lines.first()
+ old_qty = order_line.quantity
+
+ lines_count = len(order.lines.all())
+
+ variant = order_line.variant
+ variant_listings = variant.channel_listings.get(channel=order.channel)
+ promotion_rule = variant_listings.promotion_rules.first()
+ promotion_rule.variants.add(variant)
+
+ reward_value = Decimal("5")
+ promotion_rule.reward_value = reward_value
+ promotion_rule.reward_value_type = RewardValueType.FIXED
+ promotion_rule.save(update_fields=["reward_value", "reward_value_type"])
+
+ quantity = 1
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ custom_price = 18
+ force_new_line = False
+ variables = {
+ "orderId": order_id,
+ "variantId": variant_id,
+ "quantity": quantity,
+ "price": custom_price,
+ "forceNewLine": force_new_line,
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+
+ new_qty = quantity + old_qty
+
+ assert order.lines.count() == lines_count
+ order_line.refresh_from_db()
+ data = content["data"]["orderLinesCreate"]
+ line_data = data["orderLines"][0]
+ assert line_data["productSku"] == variant.sku
+ assert line_data["productVariantId"] == variant.get_global_id()
+ assert line_data["quantity"] == new_qty
+ assert line_data["isPriceOverridden"] is True
+ assert line_data["undiscountedUnitPrice"]["gross"]["amount"] == custom_price
+ assert line_data["unitPrice"]["gross"]["amount"] == custom_price - reward_value
+ assert line_data["unitDiscount"]["amount"] == reward_value
+
+
+def test_order_lines_create_with_custom_price_force_new_line_and_catalogue_discount(
+ order_line_on_promotion,
+ permission_group_manage_orders,
+ staff_api_client,
+):
+ # give
+ query = ORDER_LINES_CREATE_MUTATION
+ order_line = order_line_on_promotion
+ order = order_line.order
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+
+ order_line = order.lines.first()
+ lines_count = len(order.lines.all())
+
+ variant = order_line.variant
+ variant_listings = variant.channel_listings.get(channel=order.channel)
+ promotion_rule = variant_listings.promotion_rules.first()
+ promotion_rule.variants.add(variant)
+
+ reward_value = Decimal("5")
+ promotion_rule.reward_value = reward_value
+ promotion_rule.reward_value_type = RewardValueType.FIXED
+ promotion_rule.save(update_fields=["reward_value", "reward_value_type"])
+
+ quantity = 1
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ custom_price = 18
+ force_new_line = True
+ variables = {
+ "orderId": order_id,
+ "variantId": variant_id,
+ "quantity": quantity,
+ "price": custom_price,
+ "forceNewLine": force_new_line,
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+
+ assert order.lines.count() == lines_count + 1
+ data = content["data"]["orderLinesCreate"]
+
+ discounted_line_data = data["orderLines"][0]
+ assert discounted_line_data["productSku"] == variant.sku
+ assert discounted_line_data["productVariantId"] == variant.get_global_id()
+ assert discounted_line_data["quantity"] == quantity
+ assert discounted_line_data["isPriceOverridden"] is True
+ assert (
+ discounted_line_data["undiscountedUnitPrice"]["gross"]["amount"] == custom_price
+ )
+ assert (
+ discounted_line_data["unitPrice"]["gross"]["amount"]
+ == custom_price - reward_value
+ )
+ assert discounted_line_data["unitDiscount"]["amount"] == reward_value
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index acb92b0842..7679282bfa 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -1028,16 +1028,41 @@ class OrderLine(ModelObjectType[models.OrderLine]):
)
@staticmethod
- def resolve_unit_discount_type(root: models.OrderLine, _info):
- return root.unit_discount_type
+ def resolve_unit_discount_type(root: models.OrderLine, info):
+ def _resolve_unit_discount_type(data):
+ order, lines, manager = data
+ return calculations.order_line_unit_discount_type(
+ order, root, manager, lines
+ )
+
+ order = OrderByIdLoader(info.context).load(root.order_id)
+ lines = OrderLinesByOrderIdLoader(info.context).load(root.order_id)
+ manager = get_plugin_manager_promise(info.context)
+ return Promise.all([order, lines, manager]).then(_resolve_unit_discount_type)
@staticmethod
- def resolve_unit_discount_value(root: models.OrderLine, _info):
- return root.unit_discount_value
+ def resolve_unit_discount_value(root: models.OrderLine, info):
+ def _resolve_unit_discount_value(data):
+ order, lines, manager = data
+ return calculations.order_line_unit_discount_value(
+ order, root, manager, lines
+ )
+
+ order = OrderByIdLoader(info.context).load(root.order_id)
+ lines = OrderLinesByOrderIdLoader(info.context).load(root.order_id)
+ manager = get_plugin_manager_promise(info.context)
+ return Promise.all([order, lines, manager]).then(_resolve_unit_discount_value)
@staticmethod
- def resolve_unit_discount(root: models.OrderLine, _info):
- return root.unit_discount
+ def resolve_unit_discount(root: models.OrderLine, info):
+ def _resolve_unit_discount(data):
+ order, lines, manager = data
+ return calculations.order_line_unit_discount(order, root, manager, lines)
+
+ order = OrderByIdLoader(info.context).load(root.order_id)
+ lines = OrderLinesByOrderIdLoader(info.context).load(root.order_id)
+ manager = get_plugin_manager_promise(info.context)
+ return Promise.all([order, lines, manager]).then(_resolve_unit_discount)
@staticmethod
@traced_resolver
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index 10d568b2ef..b87126fdab 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -525,6 +525,65 @@ def order_line_tax_rate(
return order_line.tax_rate
+def order_line_unit_discount(
+ order: Order,
+ order_line: OrderLine,
+ manager: PluginsManager,
+ lines: Optional[Iterable[OrderLine]] = None,
+ force_update: bool = False,
+) -> Decimal:
+ """Return the line unit discount.
+
+ It takes into account all plugins.
+ If the prices are expired, call all order price calculation methods
+ and save them in the model directly.
+
+ Line unit discount includes discounts from:
+ - catalogue promotion
+ - voucher applied on the line (`SPECIFIC_PRODUCT`, `apply_once_per_order` )
+ - manual line discounts
+ """
+ _, lines = fetch_order_prices_if_expired(order, manager, lines, force_update)
+ order_line = _find_order_line(lines, order_line)
+ return order_line.unit_discount
+
+
+def order_line_unit_discount_value(
+ order: Order,
+ order_line: OrderLine,
+ manager: PluginsManager,
+ lines: Optional[Iterable[OrderLine]] = None,
+ force_update: bool = False,
+) -> Decimal:
+ """Return the line unit discount value.
+
+ It takes into account all plugins.
+ If the prices are expired, call all order price calculation methods
+ and save them in the model directly.
+ """
+ _, lines = fetch_order_prices_if_expired(order, manager, lines, force_update)
+ order_line = _find_order_line(lines, order_line)
+ return order_line.unit_discount_value
+
+
+def order_line_unit_discount_type(
+ order: Order,
+ order_line: OrderLine,
+ manager: PluginsManager,
+ lines: Optional[Iterable[OrderLine]] = None,
+ force_update: bool = False,
+) -> Optional[str]:
+ """Return the line unit discount type.
+
+ It takes into account all plugins.
+ If the prices are expired, call all order price calculation methods
+ and save them in the model directly.
+ """
+ _, lines = fetch_order_prices_if_expired(order, manager, lines, force_update)
+ order_line = _find_order_line(lines, order_line)
+ return order_line.unit_discount_type
+
+
def order_shipping(
order: Order,
manager: PluginsManager,
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 764828838e..7476f391af 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -381,6 +381,12 @@ def add_variant_to_order(
old_quantity = line.quantity
new_quantity = old_quantity + line_data.quantity
line_info = OrderLineInfo(line=line, quantity=old_quantity)
+ update_fields: list[str] = []
+ if new_quantity and line_data.price_override is not None:
+ update_line_base_unit_prices_with_custom_price(
+ order, line_data, line, update_fields
+ )
+
change_order_line_quantity(
user,
app,
@@ -390,8 +396,12 @@ def add_variant_to_order(
channel,
manager=manager,
send_event=False,
+ update_fields=update_fields,
)
+ if update_fields:
+ line.save(update_fields=update_fields)
+
if allocate_stock:
increase_allocations(
[
@@ -417,6 +427,38 @@ def add_variant_to_order(
)
+def update_line_base_unit_prices_with_custom_price(
+ order, line_data, line, update_fields
+):
+ channel = order.channel
+ variant = line_data.variant
+ price_override = line_data.price_override
+ rules_info = line_data.rules_info
+ channel_listing = variant.channel_listings.get(channel=channel)
+
+ line.is_price_overridden = True
+ line.base_unit_price = variant.get_price(
+ channel_listing,
+ price_override=price_override,
+ promotion_rules=(
+ [rule_info.rule for rule_info in rules_info] if rules_info else None
+ ),
+ )
+ line.undiscounted_base_unit_price_amount = price_override
+ line.undiscounted_unit_price_gross_amount = price_override
+ line.undiscounted_unit_price_net_amount = price_override
+
+ update_fields.extend(
+ [
+ "is_price_overridden",
+ "undiscounted_base_unit_price_amount",
+ "base_unit_price_amount",
+ "undiscounted_unit_price_gross_amount",
+ "undiscounted_unit_price_net_amount",
+ ]
+ )
+
+
def add_gift_cards_to_order(
checkout_info: "CheckoutInfo",
order: Order,
@@ -514,6 +556,7 @@ def change_order_line_quantity(
channel: "Channel",
manager: "PluginsManager",
send_event=True,
+ update_fields=None,
):
"""Change the quantity of ordered items in a order line."""
line = line_info.line
@@ -541,15 +584,17 @@ def change_order_line_quantity(
line.undiscounted_total_price_net_amount = (
undiscounted_total_price_net_amount.quantize(Decimal("0.001"))
)
- line.save(
- update_fields=[
- "quantity",
- "total_price_net_amount",
- "total_price_gross_amount",
- "undiscounted_total_price_gross_amount",
- "undiscounted_total_price_net_amount",
- ]
- )
+ fields = [
+ "quantity",
+ "total_price_net_amount",
+ "total_price_gross_amount",
+ "undiscounted_total_price_gross_amount",
+ "undiscounted_total_price_net_amount",
+ ]
+ if update_fields:
+ update_fields.extend(fields)
+ else:
+ line.save(update_fields=fields)
else:
delete_order_line(line_info, manager)
diff --git a/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_custom_price_and_fixed_promotion.py b/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_custom_price_and_fixed_promotion.py
new file mode 100644
index 0000000000..4bb9856773
--- /dev/null
+++ b/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_custom_price_and_fixed_promotion.py
@@ -0,0 +1,149 @@
+import pytest
+
+from ......product.tasks import recalculate_discounted_price_for_products_task
+from ....checkout.utils import checkout_lines_update
+from ....product.utils.preparing_product import prepare_product
+from ....promotions.utils import create_promotion, create_promotion_rule
+from ....shop.utils import prepare_default_shop
+from ....utils import assign_permissions
+from ...utils import (
+ checkout_complete,
+ checkout_create,
+ checkout_delivery_method_update,
+ checkout_dummy_payment_create,
+)
+
+
+def test_checkout_custom_price_and_fixed_promotion_core_2138(
+ e2e_not_logged_api_client,
+ e2e_staff_api_client,
+ e2e_app_api_client,
+ shop_permissions,
+ permission_handle_checkouts,
+ permission_manage_product_types_and_attributes,
+ permission_manage_discounts,
+):
+ # Before
+
+ permissions = [
+ *shop_permissions,
+ permission_manage_product_types_and_attributes,
+ permission_manage_discounts,
+ ]
+ assign_permissions(e2e_staff_api_client, permissions)
+
+ app_permissions = [permission_handle_checkouts]
+ assign_permissions(e2e_app_api_client, app_permissions)
+
+ shop_data = prepare_default_shop(e2e_staff_api_client)
+ channel_id = shop_data["channel"]["id"]
+ channel_slug = shop_data["channel"]["slug"]
+ warehouse_id = shop_data["warehouse"]["id"]
+ shipping_method_id = shop_data["shipping_method"]["id"]
+
+ (
+ product_id,
+ product_variant_id,
+ product_variant_price,
+ ) = prepare_product(
+ e2e_staff_api_client, warehouse_id, channel_id, variant_price=20
+ )
+
+ promotion_name = "Promotion Fixed"
+ discount_value = 5
+ discount_type = "FIXED"
+ promotion_rule_name = "rule for product"
+ promotion_type = "CATALOGUE"
+
+ promotion_data = create_promotion(
+ e2e_staff_api_client, promotion_name, promotion_type
+ )
+ promotion_id = promotion_data["id"]
+
+ catalogue_predicate = {"productPredicate": {"ids": [product_id]}}
+
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": promotion_rule_name,
+ "cataloguePredicate": catalogue_predicate,
+ "rewardValue": discount_value,
+ "rewardValueType": "FIXED",
+ }
+ promotion_rule = create_promotion_rule(
+ e2e_staff_api_client,
+ input,
+ )
+ product_predicate = promotion_rule["cataloguePredicate"]["productPredicate"]["ids"]
+ assert promotion_rule["channels"][0]["id"] == channel_id
+ assert product_predicate[0] == product_id
+
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
+ # Step 1 - checkoutCreate for product on promotion
+ lines = [
+ {"variantId": product_variant_id, "quantity": 2},
+ ]
+ checkout_data = checkout_create(
+ e2e_not_logged_api_client,
+ lines,
+ channel_slug,
+ set_default_billing_address=True,
+ set_default_shipping_address=True,
+ )
+ checkout_id = checkout_data["id"]
+ checkout_line = checkout_data["lines"][0]
+ unit_price = float(product_variant_price) - discount_value
+
+ assert checkout_data["isShippingRequired"] is True
+ assert checkout_line["unitPrice"]["gross"]["amount"] == unit_price
+ assert checkout_line["undiscountedUnitPrice"]["amount"] == float(
+ product_variant_price
+ )
+
+ # Step 2 - Set DeliveryMethod for checkout.
+ checkout_data = checkout_delivery_method_update(
+ e2e_not_logged_api_client,
+ checkout_id,
+ shipping_method_id,
+ )
+ assert checkout_data["deliveryMethod"]["id"] == shipping_method_id
+ total_gross_amount = checkout_data["totalPrice"]["gross"]["amount"]
+ subtotal_gross_amount = checkout_data["subtotalPrice"]["gross"]["amount"]
+
+ # Step 3 - Set the custom price for the checkout line
+ custom_price = 10
+ line_qty = 1
+ lines = [
+ {"lineId": checkout_line["id"], "quantity": line_qty, "price": custom_price}
+ ]
+ lines_data = checkout_lines_update(e2e_app_api_client, checkout_id, lines)
+ assert len(lines_data["checkout"]["lines"]) == 1
+ line_data = lines_data["checkout"]["lines"][0]
+ assert line_data["undiscountedUnitPrice"]["amount"] == custom_price
+ assert line_data["unitPrice"]["gross"]["amount"] == custom_price - discount_value
+ subtotal_gross_amount = lines_data["checkout"]["subtotalPrice"]["gross"]["amount"]
+ assert subtotal_gross_amount == (custom_price - discount_value) * line_qty
+ total_gross_amount = lines_data["checkout"]["totalPrice"]["gross"]["amount"]
+
+ # Step 4 - Create payment for checkout.
+ checkout_dummy_payment_create(
+ e2e_not_logged_api_client, checkout_id, total_gross_amount
+ )
+
+ # Step 5 - Complete checkout.
+ order_data = checkout_complete(e2e_not_logged_api_client, checkout_id)
+
+ order_line = order_data["lines"][0]
+ assert order_data["status"] == "UNFULFILLED"
+ assert order_data["total"]["gross"]["amount"] == total_gross_amount
+ assert order_data["subtotal"]["gross"]["amount"] == subtotal_gross_amount
+ assert order_line["undiscountedUnitPrice"]["gross"]["amount"] == float(custom_price)
+ assert order_line["unitDiscountType"] == discount_type
+ assert order_line["unitPrice"]["gross"]["amount"] == custom_price - discount_value
+ assert order_line["unitDiscount"]["amount"] == float(discount_value)
+ assert order_line["unitDiscountReason"] == f"Promotion: {promotion_id}"
diff --git a/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_custom_price_and_percentage_promotion.py b/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_custom_price_and_percentage_promotion.py
new file mode 100644
index 0000000000..9b7b6f73da
--- /dev/null
+++ b/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_custom_price_and_percentage_promotion.py
@@ -0,0 +1,147 @@
+import pytest
+
+from ......product.tasks import recalculate_discounted_price_for_products_task
+from ....checkout.utils import checkout_lines_update
+from ....product.utils.preparing_product import prepare_product
+from ....promotions.utils import create_promotion, create_promotion_rule
+from ....shop.utils import prepare_default_shop
+from ....utils import assign_permissions
+from ...utils import (
+ checkout_complete,
+ checkout_create,
+ checkout_delivery_method_update,
+ checkout_dummy_payment_create,
+)
+
+
+def test_checkout_custom_price_and_percentage_promotion_core_2139(
+ e2e_logged_api_client,
+ e2e_staff_api_client,
+ e2e_app_api_client,
+ shop_permissions,
+ permission_handle_checkouts,
+ permission_manage_product_types_and_attributes,
+ permission_manage_discounts,
+):
+ # Before
+
+ permissions = [
+ *shop_permissions,
+ permission_manage_product_types_and_attributes,
+ permission_manage_discounts,
+ ]
+ assign_permissions(e2e_staff_api_client, permissions)
+
+ app_permissions = [permission_handle_checkouts]
+ assign_permissions(e2e_app_api_client, app_permissions)
+
+ shop_data = prepare_default_shop(e2e_staff_api_client)
+ channel_id = shop_data["channel"]["id"]
+ channel_slug = shop_data["channel"]["slug"]
+ warehouse_id = shop_data["warehouse"]["id"]
+ shipping_method_id = shop_data["shipping_method"]["id"]
+
+ (
+ product_id,
+ product_variant_id,
+ product_variant_price,
+ ) = prepare_product(
+ e2e_staff_api_client, warehouse_id, channel_id, variant_price=19.89
+ )
+
+ promotion_name = "Promotion PERCENTAGE"
+ discount_value = 10
+ discount_type = "PERCENTAGE"
+ promotion_rule_name = "rule for product"
+ promotion_type = "CATALOGUE"
+
+ promotion_data = create_promotion(
+ e2e_staff_api_client, promotion_name, promotion_type
+ )
+ promotion_id = promotion_data["id"]
+
+ catalogue_predicate = {"productPredicate": {"ids": [product_id]}}
+
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": promotion_rule_name,
+ "cataloguePredicate": catalogue_predicate,
+ "rewardValue": discount_value,
+ "rewardValueType": discount_type,
+ }
+
+ promotion_rule = create_promotion_rule(e2e_staff_api_client, input)
+ product_predicate = promotion_rule["cataloguePredicate"]["productPredicate"]["ids"]
+ assert promotion_rule["channels"][0]["id"] == channel_id
+ assert product_predicate[0] == product_id
+
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
+ # Step 1 - checkoutCreate for product on promotion
+ lines = [
+ {"variantId": product_variant_id, "quantity": 2},
+ ]
+ checkout_data = checkout_create(
+ e2e_logged_api_client,
+ lines,
+ channel_slug,
+ set_default_billing_address=True,
+ set_default_shipping_address=True,
+ )
+ checkout_id = checkout_data["id"]
+ checkout_line = checkout_data["lines"][0]
+ line_discount = round(float(product_variant_price) * discount_value / 100, 2)
+ unit_price = round(float(product_variant_price) - line_discount, 2)
+
+ assert checkout_data["isShippingRequired"] is True
+ assert checkout_line["unitPrice"]["gross"]["amount"] == unit_price
+ assert checkout_line["undiscountedUnitPrice"]["amount"] == float(
+ product_variant_price
+ )
+
+ # Step 2 - Set DeliveryMethod for checkout.
+ checkout_data = checkout_delivery_method_update(
+ e2e_logged_api_client,
+ checkout_id,
+ shipping_method_id,
+ )
+ assert checkout_data["deliveryMethod"]["id"] == shipping_method_id
+ total_gross_amount = checkout_data["totalPrice"]["gross"]["amount"]
+
+ # Step 3 - Set the custom price for the checkout line
+ custom_price = 10
+ line_qty = 2
+ lines = [
+ {"lineId": checkout_line["id"], "quantity": line_qty, "price": custom_price}
+ ]
+ lines_data = checkout_lines_update(e2e_app_api_client, checkout_id, lines)
+ discount_amount = custom_price * discount_value / 100
+ assert len(lines_data["checkout"]["lines"]) == 1
+ line_data = lines_data["checkout"]["lines"][0]
+ assert line_data["undiscountedUnitPrice"]["amount"] == custom_price
+ assert line_data["unitPrice"]["gross"]["amount"] == custom_price - discount_amount
+ subtotal_gross_amount = lines_data["checkout"]["subtotalPrice"]["gross"]["amount"]
+ assert subtotal_gross_amount == (custom_price - discount_amount) * line_qty
+ total_gross_amount = lines_data["checkout"]["totalPrice"]["gross"]["amount"]
+
+ # Step 4 - Create payment for checkout.
+ checkout_dummy_payment_create(
+ e2e_logged_api_client, checkout_id, total_gross_amount
+ )
+
+ # Step 5 - Complete checkout.
+ order_data = checkout_complete(e2e_logged_api_client, checkout_id)
+
+ order_line = order_data["lines"][0]
+ assert order_data["status"] == "UNFULFILLED"
+ assert order_data["total"]["gross"]["amount"] == total_gross_amount
+ assert order_line["undiscountedUnitPrice"]["gross"]["amount"] == float(custom_price)
+ assert order_line["unitDiscountType"] == "FIXED"
+ assert order_line["unitPrice"]["gross"]["amount"] == custom_price - discount_amount
+ assert order_line["unitDiscount"]["amount"] == discount_amount
+ assert order_line["unitDiscountReason"] == f"Promotion: {promotion_id}"
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index b6f8f0cdc2..ac69c47a57 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -3511,6 +3511,46 @@ def variant_with_many_stocks(variant, warehouses_with_shipping_zone):
return variant
+def variant_on_promotion(
+ product, channel_USD, promotion_rule, warehouse
+) -> ProductVariant:
+ product_variant = ProductVariant.objects.create(
+ product=product, sku="SKU_A", external_reference="SKU_A"
+ )
+ price_amount = Decimal(10)
+ ProductVariantChannelListing.objects.create(
+ variant=product_variant,
+ channel=channel_USD,
+ price_amount=price_amount,
+ discounted_price_amount=price_amount,
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
+ )
+ Stock.objects.create(
+ warehouse=warehouse, product_variant=product_variant, quantity=10
+ )
+
+ promotion_rule.variants.add(product_variant)
+ reward_value = promotion_rule.reward_value
+ discount_amount = price_amount * reward_value / 100
+
+ variant_channel_listing = product_variant.channel_listings.get(channel=channel_USD)
+
+ variant_channel_listing.discounted_price_amount = (
+ variant_channel_listing.price_amount - reward_value
+ )
+ variant_channel_listing.save(update_fields=["discounted_price_amount"])
+
+ variant_channel_listing.variantlistingpromotionrule.create(
+ promotion_rule=promotion_rule,
+ discount_amount=discount_amount,
+ currency=channel_USD.currency_code,
+ )
+
+ return product_variant
+
+
@pytest.fixture
def preorder_variant_global_threshold(product, channel_USD):
product_variant = ProductVariant.objects.create(