Skip to content

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

Expose line-level discounts through the `OrderLineDiscount` object (#17510)

Maciej Korycinskiab1a3cb9cdcb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 232faf58e2..5d558ee8c0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -64,6 +64,8 @@ All notable, unreleased changes to this project will be documented in this file.
- `CheckoutCreateInput` now accepts `metadata` and `privateMetadata` fields, so `checkoutCreate` can now create checkout with metadata in a single call - #17503 by @lkostrowski
- `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
### Webhooks
diff --git a/saleor/graphql/discount/dataloaders.py b/saleor/graphql/discount/dataloaders.py
index e51c61c20f..2bb3dc1e22 100644
--- a/saleor/graphql/discount/dataloaders.py
+++ b/saleor/graphql/discount/dataloaders.py
@@ -12,6 +12,7 @@ from ...discount.models import (
CheckoutDiscount,
CheckoutLineDiscount,
OrderDiscount,
+ OrderLineDiscount,
Promotion,
PromotionEvent,
PromotionRule,
@@ -238,7 +239,20 @@ class OrderDiscountsByOrderIDLoader(DataLoader[UUID, list[OrderDiscount]]):
discount_map = defaultdict(list)
for discount in discounts:
discount_map[discount.order_id].append(discount)
- return [discount_map.get(order_id, []) for order_id in keys]
+ return [discount_map[order_id] for order_id in keys]
+
+
+class OrderLineDiscountsByOrderLineIDLoader(DataLoader[UUID, list[OrderDiscount]]):
+ context_key = "orderlinediscounts_by_orderline_id"
+
+ def batch_load(self, keys):
+ discounts = OrderLineDiscount.objects.using(
+ self.database_connection_name
+ ).filter(line_id__in=keys)
+ discount_map = defaultdict(list)
+ for discount in discounts:
+ discount_map[discount.line_id].append(discount)
+ return [discount_map[line_id] for line_id in keys]
class CheckoutLineDiscountsByCheckoutLineIdLoader(
diff --git a/saleor/graphql/discount/types/discounts.py b/saleor/graphql/discount/types/discounts.py
index ab49c670ec..242a025263 100644
--- a/saleor/graphql/discount/types/discounts.py
+++ b/saleor/graphql/discount/types/discounts.py
@@ -1,16 +1,25 @@
+from typing import TypeVar
+
import graphene
+from django.db.models.base import Model
from graphene import relay
+from ....core.prices import quantize_price
from ....discount import models
from ....permission.enums import OrderPermissions
from ...core import ResolveInfo
+from ...core.descriptions import ADDED_IN_321
+from ...core.doc_category import DOC_CATEGORY_ORDERS
from ...core.fields import PermissionsField
from ...core.scalars import PositiveDecimal
from ...core.types import ModelObjectType, Money
+from ...order.dataloaders import OrderLineByIdLoader
from ..enums import DiscountValueTypeEnum, OrderDiscountTypeEnum
+N = TypeVar("N", bound=Model)
+
-class OrderDiscount(ModelObjectType[models.OrderDiscount]):
+class BaseOrderDiscount(ModelObjectType[N]):
id = graphene.GlobalID(required=True, description="The ID of discount applied.")
type = OrderDiscountTypeEnum(
required=True,
@@ -37,8 +46,23 @@ class OrderDiscount(ModelObjectType[models.OrderDiscount]):
OrderPermissions.MANAGE_ORDERS,
],
)
+
+ class Meta:
+ abstract = True
+
+
+class OrderDiscount(BaseOrderDiscount[models.OrderDiscount]):
amount = graphene.Field(
- Money, description="Returns amount of discount.", required=True
+ Money,
+ description="Returns amount of discount.",
+ required=True,
+ deprecation_reason="Use `total` instead.",
+ )
+
+ total = graphene.Field(
+ Money,
+ required=True,
+ description="The amount of discount applied to the order." + ADDED_IN_321,
)
class Meta:
@@ -51,3 +75,40 @@ class OrderDiscount(ModelObjectType[models.OrderDiscount]):
@staticmethod
def resolve_reason(root: models.OrderDiscount, _info: ResolveInfo):
return root.reason
+
+ @staticmethod
+ def resolve_total(root: models.OrderLineDiscount, info):
+ return root.amount
+
+
+class OrderLineDiscount(BaseOrderDiscount[models.OrderLineDiscount]):
+ total = graphene.Field(
+ Money,
+ required=True,
+ description="The discount amount applied to the line item.",
+ )
+ unit = graphene.Field(
+ Money,
+ required=True,
+ description="The discount amount applied to the single line unit.",
+ )
+
+ class Meta:
+ description = "Represent the discount applied to order line."
+ doc_category = DOC_CATEGORY_ORDERS
+ model = models.OrderLineDiscount
+
+ @staticmethod
+ def resolve_total(root: models.OrderLineDiscount, info):
+ return root.amount
+
+ @staticmethod
+ def resolve_unit(root: models.OrderLineDiscount, info):
+ def with_order_line(order_line):
+ if not order_line:
+ return root.amount
+ return quantize_price(root.amount / order_line.quantity, root.currency)
+
+ return (
+ OrderLineByIdLoader(info.context).load(root.line_id).then(with_order_line)
+ )
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
index 0abf94b115..07b1ab037b 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
@@ -20,10 +20,7 @@ from .....discount.utils.voucher import (
)
from .....order import OrderOrigin, OrderStatus
from .....order import events as order_events
-from .....order.actions import (
- call_order_event,
- order_created,
-)
+from .....order.actions import call_order_event, order_created
from .....order.calculations import fetch_order_prices_if_expired
from .....order.error_codes import OrderErrorCode
from .....order.interface import OrderTaxedPricesData
@@ -1291,6 +1288,9 @@ DRAFT_ORDER_COMPLETE_WITH_DISCOUNTS_MUTATION = """
amount {
amount
}
+ total {
+ amount
+ }
valueType
type
reason
@@ -1310,6 +1310,17 @@ DRAFT_ORDER_COMPLETE_WITH_DISCOUNTS_MUTATION = """
unitDiscountReason
unitDiscountType
isGift
+ discounts{
+ valueType
+ value
+ reason
+ total{
+ amount
+ }
+ unit{
+ amount
+ }
+ }
}
}
}
@@ -1356,8 +1367,8 @@ def test_draft_order_complete_with_catalogue_and_order_discount(
order_discount = order_data["discounts"][0]
assert order_discount["amount"]["amount"] == 25.00 == rule_total_value
+ assert order_discount["total"]["amount"] == 25.00 == rule_total_value
assert order_discount["reason"] == f"Promotion: {order_promotion_id}"
- assert order_discount["amount"]["amount"] == 25.00 == rule_total_value
assert order_discount["valueType"] == DiscountValueType.FIXED.upper()
lines_db = order.lines.all()
@@ -1380,6 +1391,7 @@ def test_draft_order_complete_with_catalogue_and_order_discount(
assert line_1["unitDiscount"]["amount"] == 0.00
assert line_1["unitDiscountReason"] is None
assert line_1["unitDiscountValue"] == 0.00
+ assert len(line_1["discounts"]) == 0
line_2_total = quantize_price(
line_2_db.undiscounted_total_price_net_amount
@@ -1387,12 +1399,28 @@ def test_draft_order_complete_with_catalogue_and_order_discount(
- line_2_order_discount_portion,
currency,
)
+
+ expected_discount_reason = f"Promotion: {catalogue_promotion_id}"
+ expected_unit_discount_amount = rule_catalogue_value
+
assert line_2["totalPrice"]["net"]["amount"] == float(line_2_total)
- assert line_2["unitDiscount"]["amount"] == rule_catalogue_value
- assert line_2["unitDiscountReason"] == f"Promotion: {catalogue_promotion_id}"
+ assert line_2["unitDiscount"]["amount"] == expected_unit_discount_amount
+ assert line_2["unitDiscountReason"] == expected_discount_reason
assert line_2["unitDiscountType"] == DiscountValueType.FIXED.upper()
assert line_2["unitDiscountValue"] == rule_catalogue_value
+ assigned_discount_objects = line_2["discounts"]
+ assert len(assigned_discount_objects) == 1
+ assigned_discount = assigned_discount_objects[0]
+ assert assigned_discount["reason"] == expected_discount_reason
+ assert assigned_discount["valueType"] == DiscountValueType.FIXED.upper()
+ assert (
+ assigned_discount["total"]["amount"]
+ == expected_unit_discount_amount * line_2_db.quantity
+ )
+ assert assigned_discount["unit"]["amount"] == expected_unit_discount_amount
+ assert assigned_discount["value"] == rule_catalogue_value
+
total = (
order.undiscounted_total_net_amount
- line_2["quantity"] * rule_catalogue_value
@@ -1456,24 +1484,51 @@ def test_draft_order_complete_with_catalogue_and_gift_discount(
assert line_1["unitDiscount"]["amount"] == 0.00
assert line_1["unitDiscountReason"] is None
assert line_1["unitDiscountValue"] == 0.00
+ assert len(line_1["discounts"]) == 0
line_2_total = quantize_price(
line_2_db.undiscounted_total_price_net_amount
- rule_catalogue_value * line_2_db.quantity,
currency,
)
+ expected_line_2_discount_reason = f"Promotion: {catalogue_promotion_id}"
+ expected_line_2_unit_discount_amount = rule_catalogue_value
+
assert line_2["totalPrice"]["net"]["amount"] == line_2_total
assert line_2["unitDiscount"]["amount"] == rule_catalogue_value
- assert line_2["unitDiscountReason"] == f"Promotion: {catalogue_promotion_id}"
+ assert line_2["unitDiscountReason"] == expected_line_2_discount_reason
assert line_2["unitDiscountType"] == DiscountValueType.FIXED.upper()
assert line_2["unitDiscountValue"] == rule_catalogue_value
+ assigned_discount_objects = line_2["discounts"]
+ assert len(assigned_discount_objects) == 1
+ assigned_discount = assigned_discount_objects[0]
+ assert assigned_discount["reason"] == expected_line_2_discount_reason
+ assert assigned_discount["valueType"] == DiscountValueType.FIXED.upper()
+ assert (
+ assigned_discount["total"]["amount"]
+ == expected_line_2_unit_discount_amount * line_2_db.quantity
+ )
+ assert assigned_discount["unit"]["amount"] == expected_line_2_unit_discount_amount
+ assert assigned_discount["value"] == rule_catalogue_value
+
+ expected_gift_line_discount_reason = f"Promotion: {gift_promotion_id}"
+
assert gift_line["totalPrice"]["net"]["amount"] == 0.00
assert gift_line["unitDiscount"]["amount"] == gift_price
- assert gift_line["unitDiscountReason"] == f"Promotion: {gift_promotion_id}"
+ assert gift_line["unitDiscountReason"] == expected_gift_line_discount_reason
assert gift_line["unitDiscountType"] == DiscountValueType.FIXED.upper()
assert gift_line["unitDiscountValue"] == gift_price
+ assigned_gift_line_discount_objects = gift_line["discounts"]
+ assert len(assigned_discount_objects) == 1
+ assigned_gift_line_discount = assigned_gift_line_discount_objects[0]
+ assert assigned_gift_line_discount["reason"] == expected_gift_line_discount_reason
+ assert assigned_gift_line_discount["valueType"] == DiscountValueType.FIXED.upper()
+ assert assigned_gift_line_discount["unit"]["amount"] == gift_price
+ assert assigned_gift_line_discount["total"]["amount"] == gift_price
+ assert assigned_gift_line_discount["value"] == gift_price
+
total = (
order.undiscounted_total_net_amount - rule_catalogue_value * line_2_db.quantity
)
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 949d9a1ba5..f19bd490d6 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -58,6 +58,9 @@ DRAFT_ORDER_CREATE_MUTATION = """
}
discountName
discounts {
+ total {
+ amount
+ }
amount {
amount
}
@@ -138,6 +141,17 @@ DRAFT_ORDER_CREATE_MUTATION = """
unitDiscountValue
isGift
isPriceOverridden
+ discounts{
+ valueType
+ value
+ reason
+ unit{
+ amount
+ }
+ total{
+ amount
+ }
+ }
}
}
}
@@ -820,14 +834,23 @@ def test_draft_order_create_with_voucher_specific_product(
discounted_line_data["totalPrice"]["gross"]["amount"]
== discounted_variant_total
)
- assert (
- discounted_line_data["unitDiscount"]["amount"]
- == discount_amount / variant_0_qty
- )
+
+ expected_discount_amount = discount_amount / variant_0_qty
+ assert discounted_line_data["unitDiscount"]["amount"] == expected_discount_amount
assert (
discounted_line_data["unitDiscountType"] == voucher.discount_value_type.upper()
)
- assert discounted_line_data["unitDiscountReason"] == f"Voucher code: {code}"
+ expected_discount_reason = f"Voucher code: {code}"
+ assert discounted_line_data["unitDiscountReason"] == expected_discount_reason
+
+ assigned_discount_objects = discounted_line_data["discounts"]
+ assert len(assigned_discount_objects) == 1
+ assigned_discount = assigned_discount_objects[0]
+ assert assigned_discount["reason"] == expected_discount_reason
+ assert assigned_discount["valueType"] == voucher.discount_value_type.upper()
+ assert assigned_discount["unit"]["amount"] == expected_discount_amount
+ assert assigned_discount["total"]["amount"] == discount_amount
+ assert assigned_discount["value"] == voucher.channel_listings.get().discount_value
assert line_1_data["productVariantId"] == variant_1_id
assert line_1_data["quantity"] == variant_1_qty
@@ -838,6 +861,7 @@ def test_draft_order_create_with_voucher_specific_product(
assert line_1_data["unitDiscount"]["amount"] == 0
assert line_1_data["unitDiscountType"] is None
assert line_1_data["unitDiscountReason"] is None
+ assert len(line_1_data["discounts"]) == 0
assert order.discounts.count() == 0
@@ -964,6 +988,7 @@ def test_draft_order_create_with_voucher_apply_once_per_order(
discounted_line_data["totalPrice"]["gross"]["amount"]
== discounted_variant_total
)
+
assert (
discounted_line_data["unitDiscount"]["amount"]
== discount_amount / variant_0_qty
@@ -971,7 +996,17 @@ def test_draft_order_create_with_voucher_apply_once_per_order(
assert (
discounted_line_data["unitDiscountType"] == voucher.discount_value_type.upper()
)
- assert discounted_line_data["unitDiscountReason"] == f"Voucher code: {code}"
+ expected_discount_reason = f"Voucher code: {code}"
+ assert discounted_line_data["unitDiscountReason"] == expected_discount_reason
+
+ assigned_discount_objects = discounted_line_data["discounts"]
+ assert len(assigned_discount_objects) == 1
+ assigned_discount = assigned_discount_objects[0]
+ assert assigned_discount["reason"] == expected_discount_reason
+ assert assigned_discount["valueType"] == voucher.discount_value_type.upper()
+ assert assigned_discount["total"]["amount"] == discount_amount
+ assert assigned_discount["unit"]["amount"] == discount_amount / variant_0_qty
+ assert assigned_discount["value"] == voucher.channel_listings.get().discount_value
assert line_1_data["productVariantId"] == variant_1_id
assert line_1_data["quantity"] == variant_1_qty
@@ -982,6 +1017,7 @@ def test_draft_order_create_with_voucher_apply_once_per_order(
assert line_1_data["unitDiscount"]["amount"] == 0
assert line_1_data["unitDiscountType"] is None
assert line_1_data["unitDiscountReason"] is None
+ assert len(line_1_data["discounts"]) == 0
assert order.discounts.count() == 0
@@ -2767,6 +2803,7 @@ def test_draft_order_create_with_custom_price_and_catalogue_promotion(
line_1_unit_discount = custom_price * reward_value / 100
promotion_id = graphene.Node.to_global_id("Promotion", promotion_rule.promotion_id)
+ expected_discount_reason = f"Promotion: {promotion_id}"
line_data_1 = {
"productVariantId": variant_id,
"quantity": quantity,
@@ -2788,13 +2825,23 @@ def test_draft_order_create_with_custom_price_and_catalogue_promotion(
"amount": float((custom_price - line_1_unit_discount) * quantity),
},
},
- "unitDiscountReason": f"Promotion: {promotion_id}",
+ "unitDiscountReason": expected_discount_reason,
"unitDiscountType": RewardValueType.PERCENTAGE.upper(),
"unitDiscountValue": reward_value,
"isPriceOverridden": True,
"isGift": False,
+ "discounts": [
+ {
+ "total": {"amount": Decimal(line_1_unit_discount * quantity)},
+ "unit": {"amount": Decimal(line_1_unit_discount)},
+ "reason": expected_discount_reason,
+ "value": reward_value,
+ "valueType": RewardValueType.PERCENTAGE.upper(),
+ }
+ ],
}
assert line_data_1 in data["lines"]
+
line_2_unit_discount = variant_price * reward_value / 100
line_data_2 = {
"productVariantId": variant_id,
@@ -2817,11 +2864,20 @@ def test_draft_order_create_with_custom_price_and_catalogue_promotion(
"amount": float((variant_price - line_2_unit_discount) * quantity),
},
},
- "unitDiscountReason": f"Promotion: {promotion_id}",
+ "unitDiscountReason": expected_discount_reason,
"unitDiscountType": RewardValueType.PERCENTAGE.upper(),
"unitDiscountValue": reward_value,
"isPriceOverridden": False,
"isGift": False,
+ "discounts": [
+ {
+ "total": {"amount": Decimal(line_2_unit_discount * quantity)},
+ "unit": {"amount": Decimal(line_2_unit_discount)},
+ "reason": expected_discount_reason,
+ "value": reward_value,
+ "valueType": RewardValueType.PERCENTAGE.upper(),
+ }
+ ],
}
assert line_data_2 in data["lines"]
@@ -2908,9 +2964,11 @@ def test_draft_order_create_product_catalogue_promotion(
assert order.search_vector
+ expected_unit_discount = reward_value
+
assert len(data["lines"]) == 1
line_data = data["lines"][0]
- assert line_data["unitDiscount"]["amount"] == reward_value
+ assert line_data["unitDiscount"]["amount"] == expected_unit_discount
assert (
line_data["unitPrice"]["gross"]["amount"]
== variant_channel_listing.discounted_price_amount
@@ -2919,15 +2977,26 @@ def test_draft_order_create_product_catalogue_promotion(
line_data["undiscountedUnitPrice"]["gross"]["amount"]
== variant_channel_listing.price_amount
)
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ expected_discount_reason = f"Promotion: {promotion_id}"
+
line_total = variant_channel_listing.discounted_price_amount * quantity
assert line_data["totalPrice"]["gross"]["amount"] == line_total
- assert line_data["unitDiscountReason"]
- assert line_data["unitDiscountType"]
-
+ assert line_data["unitDiscountReason"] == expected_discount_reason
+ assert line_data["unitDiscountType"] == rule.reward_value_type.upper()
line = order.lines.first()
assert line.discounts.count() == 1
assert line.sale_id
+ assigned_discount_objects = line_data["discounts"]
+ assert len(assigned_discount_objects) == 1
+ assigned_discount = assigned_discount_objects[0]
+ assert assigned_discount["reason"] == expected_discount_reason
+ assert assigned_discount["valueType"] == rule.reward_value_type.upper()
+ assert assigned_discount["unit"]["amount"] == expected_unit_discount
+ assert assigned_discount["total"]["amount"] == expected_unit_discount * quantity
+ assert assigned_discount["value"] == rule.reward_value
+
assert data["total"]["gross"]["amount"] == shipping_total + line_total
assert (
data["undiscountedTotal"]["gross"]["amount"]
@@ -3041,9 +3110,11 @@ def test_draft_order_create_product_catalogue_promotion_flat_taxes(
assert order.search_vector
+ expected_unit_discount = reward_value
+
assert len(data["lines"]) == 1
line_data = data["lines"][0]
- assert line_data["unitDiscount"]["amount"] == reward_value
+ assert line_data["unitDiscount"]["amount"] == expected_unit_discount
assert (
line_data["unitPrice"]["gross"]["amount"]
== variant_channel_listing.discounted_price_amount
@@ -3052,15 +3123,28 @@ def test_draft_order_create_product_catalogue_promotion_flat_taxes(
line_data["undiscountedUnitPrice"]["gross"]["amount"]
== variant_channel_listing.price_amount
)
+
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ expected_discount_reason = f"Promotion: {promotion_id}"
+
line_total = variant_channel_listing.discounted_price_amount * quantity
assert line_data["totalPrice"]["gross"]["amount"] == line_total
- assert line_data["unitDiscountReason"]
+ assert line_data["unitDiscountReason"] == expected_discount_reason
assert line_data["unitDiscountType"]
line = order.lines.first()
assert line.discounts.count() == 1
assert line.sale_id
+ assigned_discount_objects = line_data["discounts"]
+ assert len(assigned_discount_objects) == 1
+ assigned_discount = assigned_discount_objects[0]
+ assert assigned_discount["reason"] == expected_discount_reason
+ assert assigned_discount["valueType"] == rule.reward_value_type.upper()
+ assert assigned_discount["unit"]["amount"] == expected_unit_discount
+ assert assigned_discount["total"]["amount"] == expected_unit_discount * quantity
+ assert assigned_discount["value"] == rule.reward_value
+
assert data["total"]["gross"]["amount"] == shipping_total + line_total
assert (
data["undiscountedTotal"]["gross"]["amount"]
@@ -3171,6 +3255,7 @@ def test_draft_order_create_order_promotion_flat_rates(
assert order["shippingPrice"]["gross"]["amount"] == float(shipping_price_gross)
assert len(order["discounts"]) == 1
+ assert order["discounts"][0]["total"]["amount"] == discount_amount
assert order["discounts"][0]["amount"]["amount"] == discount_amount
assert order["discounts"][0]["reason"] == f"Promotion: {promotion_id}"
assert order["discounts"][0]["type"] == DiscountType.ORDER_PROMOTION.upper()
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_update.py b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
index fc1e01110e..69f8a4030b 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
@@ -109,6 +109,10 @@ DRAFT_ORDER_UPDATE_MUTATION = """
}
}
discounts {
+ total {
+ amount
+ currency
+ }
amount {
amount
currency
@@ -141,6 +145,17 @@ DRAFT_ORDER_UPDATE_MUTATION = """
unitDiscountType
unitDiscountValue
isGift
+ discounts{
+ valueType
+ value
+ reason
+ unit{
+ amount
+ }
+ total{
+ amount
+ }
+ }
}
shippingPrice {
gross {
@@ -264,11 +279,12 @@ def test_draft_order_update_with_voucher_entire_order(
)
assert len(data["order"]["discounts"]) == 1
- assert (
- data["order"]["discounts"][0]["amount"]["amount"]
- == voucher_listing.discount_value
- )
- assert data["order"]["discounts"][0]["amount"]["currency"] == currency
+ discount = data["order"]["discounts"][0]
+ assert discount["amount"]["amount"] == voucher_listing.discount_value
+ assert discount["amount"]["currency"] == currency
+
+ assert discount["total"]["amount"] == voucher_listing.discount_value
+ assert discount["total"]["currency"] == currency
assert not data["errors"]
order.refresh_from_db()
@@ -355,6 +371,10 @@ def test_draft_order_update_with_voucher_specific_product(
)
lines_data = data["order"]["lines"]
discounted_line_data, line_1_data = lines_data
+
+ expected_discount_reason = f"Voucher code: {code}"
+ expected_unit_discount = discount_amount / discounted_line.quantity
+ expected_total_discount = discount_amount
assert (
discounted_line_data["unitPrice"]["net"]["amount"]
== discounted_variant_total / discounted_line.quantity
@@ -362,14 +382,20 @@ def test_draft_order_update_with_voucher_specific_product(
assert (
discounted_line_data["totalPrice"]["net"]["amount"] == discounted_variant_total
)
- assert (
- discounted_line_data["unitDiscount"]["amount"]
- == discount_amount / discounted_line.quantity
- )
+ assert discounted_line_data["unitDiscount"]["amount"] == expected_unit_discount
assert (
discounted_line_data["unitDiscountType"] == voucher.discount_value_type.upper()
)
- assert discounted_line_data["unitDiscountReason"] == f"Voucher code: {code}"
+ assert discounted_line_data["unitDiscountReason"] == expected_discount_reason
+
+ assigned_discount_objects = discounted_line_data["discounts"]
+ assert len(assigned_discount_objects) == 1
+ assigned_discount = assigned_discount_objects[0]
+ assert assigned_discount["reason"] == expected_discount_reason
+ assert assigned_discount["valueType"] == voucher.discount_value_type.upper()
+ assert assigned_discount["unit"]["amount"] == expected_unit_discount
+ assert assigned_discount["total"]["amount"] == expected_total_discount
+ assert assigned_discount["value"] == voucher.channel_listings.get().discount_value
line_1_total = line_1.undiscounted_base_unit_price_amount * line_1.quantity
assert line_1_data["unitPrice"]["net"]["amount"] == line_1_total / line_1.quantity
@@ -377,6 +403,7 @@ def test_draft_order_update_with_voucher_specific_product(
assert line_1_data["unitDiscount"]["amount"] == 0
assert line_1_data["unitDiscountType"] is None
assert line_1_data["unitDiscountReason"] is None
+ assert len(line_1_data["discounts"]) == 0
order.refresh_from_db()
assert order.voucher_code == voucher.code
@@ -451,19 +478,41 @@ def test_draft_order_update_with_voucher_apply_once_per_order(
)
lines_data = data["order"]["lines"]
discounted_line_data, line_1_data = lines_data
+
+ expected_discount_reason = f"Voucher code: {code}"
+ expected_total_discount = discount_amount
+ expected_unit_discount = quantize_price(
+ Decimal(discount_amount / discounted_line.quantity), order.currency
+ )
+
assert discounted_line_data["unitPrice"]["net"]["amount"] == float(
round(discounted_variant_total / discounted_line.quantity, 2)
)
assert (
discounted_line_data["totalPrice"]["net"]["amount"] == discounted_variant_total
)
- assert discounted_line_data["unitDiscount"]["amount"] == float(
- round(discount_amount / discounted_line.quantity, 2)
+ assert (
+ quantize_price(
+ Decimal(discounted_line_data["unitDiscount"]["amount"]), order.currency
+ )
+ == expected_unit_discount
)
assert (
discounted_line_data["unitDiscountType"] == voucher.discount_value_type.upper()
)
- assert discounted_line_data["unitDiscountReason"] == f"Voucher code: {code}"
+ assert discounted_line_data["unitDiscountReason"] == expected_discount_reason
+
+ assigned_discount_objects = discounted_line_data["discounts"]
+ assert len(assigned_discount_objects) == 1
+ assigned_discount = assigned_discount_objects[0]
+ assert assigned_discount["reason"] == expected_discount_reason
+ assert assigned_discount["valueType"] == voucher.discount_value_type.upper()
+ assert (
+ quantize_price(Decimal(assigned_discount["unit"]["amount"]), order.currency)
+ == expected_unit_discount
+ )
+ assert assigned_discount["total"]["amount"] == expected_total_discount
+ assert assigned_discount["value"] == voucher.channel_listings.get().discount_value
line_1_total = line_1.undiscounted_base_unit_price_amount * line_1.quantity
assert line_1_data["unitPrice"]["net"]["amount"] == line_1_total / line_1.quantity
@@ -471,6 +520,7 @@ def test_draft_order_update_with_voucher_apply_once_per_order(
assert line_1_data["unitDiscount"]["amount"] == 0
assert line_1_data["unitDiscountType"] is None
assert line_1_data["unitDiscountReason"] is None
+ assert len(line_1_data["discounts"]) == 0
order.refresh_from_db()
assert order.voucher_code == voucher.code
@@ -2062,10 +2112,12 @@ def test_draft_order_update_order_promotion(
order = content["data"]["draftOrderUpdate"]["order"]
assert len(order["discounts"]) == 1
discount_amount = reward_value / 100 * (undiscounted_total - shipping_price)
- assert order["discounts"][0]["amount"]["amount"] == discount_amount
- assert order["discounts"][0]["reason"] == f"Promotion: {promotion_id}"
- assert order["discounts"][0]["type"] == DiscountType.ORDER_PROMOTION.upper()
- assert order["discounts"][0]["valueType"] == RewardValueType.PERCENTAGE.upper()
+ discount = order["discounts"][0]
+ assert discount["amount"]["amount"] == discount_amount
+ assert discount["total"]["amount"] == discount_amount
+ assert discount["reason"] == f"Promotion: {promotion_id}"
+ assert discount["type"] == DiscountType.ORDER_PROMOTION.upper()
+ assert discount["valueType"] == RewardValueType.PERCENTAGE.upper()
assert (
order["subtotal"]["net"]["amount"]
@@ -2117,12 +2169,23 @@ def test_draft_order_update_gift_promotion(
assert len(lines) == 3
gift_line = [line for line in lines if line["isGift"]][0]
+ expected_discount_reason = f"Promotion: {promotion_id}"
+
assert gift_line["totalPrice"]["net"]["amount"] == 0.00
assert gift_line["unitDiscount"]["amount"] == gift_price
- assert gift_line["unitDiscountReason"] == f"Promotion: {promotion_id}"
+ assert gift_line["unitDiscountReason"] == expected_discount_reason
assert gift_line["unitDiscountType"] == RewardValueType.FIXED.upper()
assert gift_line["unitDiscountValue"] == gift_price
+ assigned_discount_objects = gift_line["discounts"]
+ assert len(assigned_discount_objects) == 1
+ assigned_discount = assigned_discount_objects[0]
+ assert assigned_discount["reason"] == expected_discount_reason
+ assert assigned_discount["valueType"] == RewardValueType.FIXED.upper()
+ assert assigned_discount["total"]["amount"] == gift_price
+ assert assigned_discount["unit"]["amount"] == gift_price
+ assert assigned_discount["value"] == gift_price
+
assert (
order["subtotal"]["net"]["amount"]
== draft_order.undiscounted_total_net_amount
diff --git a/saleor/graphql/order/tests/queries/test_order_line.py b/saleor/graphql/order/tests/queries/test_order_line.py
index 524fa3f3ae..c0a27793b0 100644
--- a/saleor/graphql/order/tests/queries/test_order_line.py
+++ b/saleor/graphql/order/tests/queries/test_order_line.py
@@ -6,6 +6,7 @@ from django.core.files import File
from prices import Money, TaxedMoney
from .....core.prices import quantize_price
+from .....discount import DiscountType, DiscountValueType
from .....order import OrderStatus
from .....order.interface import OrderTaxedPricesData
from .....thumbnail.models import Thumbnail
@@ -760,3 +761,60 @@ def test_order_query_undiscounted_prices_no_tax(
first_order_data_line_price = order_data["lines"][0]["undiscountedUnitPrice"]
assert first_order_data_line_price["net"]["amount"] == line.unit_price.net.amount
assert first_order_data_line_price["gross"]["amount"] == line.unit_price.net.amount
+
+
+def test_order_line_returns_discount_object(
+ staff_api_client, order_with_lines, permission_group_all_perms_all_channels
+):
+ # given
+ expected_amount = Decimal("6")
+ expected_reason = "test"
+
+ line = order_with_lines.lines.first()
+ line.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.FIXED,
+ value=expected_amount,
+ amount_value=expected_amount,
+ currency=line.currency,
+ reason=expected_reason,
+ )
+
+ query = """
+ query OrderQuery($id: ID) {
+ order(id: $id) {
+ lines {
+ discounts{
+ valueType
+ value
+ reason
+ unit{
+ amount
+ }
+ total{
+ amount
+ }
+ }
+ }
+ }
+ }
+ """
+
+ permission_group_all_perms_all_channels.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables={"id": to_global_id_or_none(order_with_lines)}
+ )
+
+ # then
+ content = get_graphql_content(response)
+ line_discounts = content["data"]["order"]["lines"][0]["discounts"]
+
+ assert line_discounts
+ line_discount = line_discounts[0]
+ assert line_discount["valueType"] == DiscountValueType.FIXED.upper()
+ assert line_discount["reason"] == expected_reason
+ assert line_discount["value"] == expected_amount
+ assert line_discount["unit"]["amount"] == expected_amount / line.quantity
+ assert line_discount["total"]["amount"] == expected_amount
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index e661a325cf..41b5bf165f 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -72,6 +72,7 @@ from ..core.descriptions import (
ADDED_IN_318,
ADDED_IN_319,
ADDED_IN_320,
+ ADDED_IN_321,
DEPRECATED_IN_3X_INPUT,
PREVIEW_FEATURE,
)
@@ -95,7 +96,11 @@ from ..core.types import (
from ..core.types.sync_webhook_control import SyncWebhookControlContextModelObjectType
from ..core.utils import str_to_enum
from ..decorators import one_of_permissions_required
-from ..discount.dataloaders import OrderDiscountsByOrderIDLoader, VoucherByIdLoader
+from ..discount.dataloaders import (
+ OrderDiscountsByOrderIDLoader,
+ OrderLineDiscountsByOrderLineIDLoader,
+ VoucherByIdLoader,
+)
from ..discount.enums import DiscountValueTypeEnum
from ..discount.types import Voucher
from ..giftcard.dataloaders import GiftCardsByOrderIdLoader
@@ -1084,6 +1089,10 @@ class OrderLine(
is_gift = graphene.Boolean(
description="Determine if the line is a gift." + ADDED_IN_319 + PREVIEW_FEATURE,
)
+ discounts = NonNullList(
+ "saleor.graphql.discount.types.discounts.OrderLineDiscount",
+ description="List of applied discounts" + ADDED_IN_321,
+ )
class Meta:
default_resolver = (
@@ -1419,6 +1428,22 @@ class OrderLine(
check_private_metadata_privilege(root.node, info)
return resolve_metadata(root.node.tax_class_private_metadata)
+ @staticmethod
+ def resolve_discounts(root: SyncWebhookControlContext[models.OrderLine], info):
+ line = root.node
+
+ def with_manager_and_order(data):
+ manager, order = data
+ with allow_writer_in_context(info.context):
+ fetch_order_prices_if_expired(
+ order, manager, allow_sync_webhooks=root.allow_sync_webhooks
+ )
+ return OrderLineDiscountsByOrderLineIDLoader(info.context).load(line.id)
+
+ manager = get_plugin_manager_promise(info.context)
+ order = OrderByIdLoader(info.context).load(line.order_id)
+ return Promise.all([manager, order]).then(with_manager_and_order)
+
@federated_entity("id")
class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Order]]):
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 609fc7ae5e..4f9da189d4 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -11182,6 +11182,13 @@ type OrderLine implements Node & ObjectWithMetadata @doc(category: "Orders") {
Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
isGift: Boolean
+
+ """
+ List of applied discounts
+
+ Added in Saleor 3.21.
+ """
+ discounts: [OrderLineDiscount!]
}
"""
@@ -11211,6 +11218,48 @@ type Allocation implements Node @doc(category: "Products") {
warehouse: Warehouse!
}
+"""Represent the discount applied to order line."""
+type OrderLineDiscount @doc(category: "Orders") {
+ """The ID of discount applied."""
+ id: ID!
+
+ """The type of applied discount: Sale, Voucher or Manual."""
+ type: OrderDiscountType!
+
+ """The name of applied discount."""
+ name: String
+
+ """Translated name of the applied discount."""
+ translatedName: String
+
+ """Type of the discount: fixed or percent"""
+ valueType: DiscountValueTypeEnum!
+
+ """Value of the discount. Can store fixed value or percent value"""
+ value: PositiveDecimal!
+
+ """
+ Explanation for the applied discount.
+
+ Requires one of the following permissions: MANAGE_ORDERS.
+ """
+ reason: String
+
+ """The discount amount applied to the line item."""
+ total: Money!
+
+ """The discount amount applied to the single line unit."""
+ unit: Money!
+}
+
+enum OrderDiscountType @doc(category: "Discounts") {
+ SALE
+ VOUCHER
+ MANUAL
+ PROMOTION
+ ORDER_PROMOTION
+}
+
enum OrderAction @doc(category: "Payments") {
"""Represents the capture action."""
CAPTURE
@@ -11757,15 +11806,14 @@ type OrderDiscount implements Node @doc(category: "Discounts") {
reason: String
"""Returns amount of discount."""
- amount: Money!
-}
+ amount: Money! @deprecated(reason: "Use `total` instead.")
-enum OrderDiscountType @doc(category: "Discounts") {
- SALE
- VOUCHER
- MANUAL
- PROMOTION
- ORDER_PROMOTION
+ """
+ The amount of discount applied to the order.
+
+ Added in Saleor 3.21.
+ """
+ total: Money!
}
type OrderError @doc(category: "Orders") {