Skip to content

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

Add unit_discount fields to order bulk create (#16894)

Krzysztof Waliczek805c759cc449
diff --git a/saleor/graphql/order/bulk_mutations/order_bulk_create.py b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
index e64d016b86..f572d024f8 100644
--- a/saleor/graphql/order/bulk_mutations/order_bulk_create.py
+++ b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
@@ -25,6 +25,7 @@ from ....core.tracing import traced_atomic_transaction
from ....core.utils.url import validate_storefront_url
from ....core.weight import zero_weight
from ....discount.models import OrderDiscount, VoucherCode
+from ....discount.utils.manual_discount import apply_discount_to_value
from ....giftcard.models import GiftCard
from ....invoice.models import Invoice
from ....order import (
@@ -48,7 +49,7 @@ from ....warehouse.models import Stock, Warehouse
from ...account.i18n import I18nMixin
from ...account.types import AddressInput
from ...core import ResolveInfo
-from ...core.descriptions import ADDED_IN_318
+from ...core.descriptions import ADDED_IN_318, ADDED_IN_319
from ...core.doc_category import DOC_CATEGORY_ORDERS
from ...core.enums import ErrorPolicy, ErrorPolicyEnum, LanguageCodeEnum
from ...core.mutations import BaseMutation
@@ -56,6 +57,7 @@ from ...core.scalars import DateTime, PositiveDecimal, WeightScalar
from ...core.types import BaseInputObjectType, BaseObjectType, NonNullList
from ...core.types.common import OrderBulkCreateError
from ...core.utils import from_global_id_or_error
+from ...discount.enums import DiscountValueTypeEnum
from ...meta.inputs import MetadataInput
from ...payment.mutations.transaction.transaction_create import (
TransactionCreate,
@@ -272,6 +274,9 @@ class LineAmounts:
total_net: Decimal
unit_gross: Decimal
unit_net: Decimal
+ unit_discount_value: Decimal
+ unit_discount_type: Optional[str]
+ unit_discount_reason: Optional[str]
undiscounted_total_gross: Decimal
undiscounted_total_net: Decimal
undiscounted_unit_gross: Decimal
@@ -480,6 +485,20 @@ class OrderBulkCreateOrderLineInput(BaseInputObjectType):
required=True,
description="Price of the order line excluding applied discount.",
)
+ unit_discount_reason = graphene.String(
+ required=False,
+ description="Reason of the discount on order line." + ADDED_IN_319,
+ )
+ unit_discount_type = graphene.Field(
+ DiscountValueTypeEnum,
+ required=False,
+ description="Type of the discount: fixed or percent" + ADDED_IN_319,
+ )
+ unit_discount_value = PositiveDecimal(
+ description="Value of the discount. Can store fixed value or percent value"
+ + ADDED_IN_319,
+ required=False,
+ )
warehouse = graphene.ID(
required=True,
description="The ID of the warehouse, where the line will be allocated.",
@@ -1080,6 +1099,11 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
net_amount = line_input["total_price"]["net"]
undiscounted_gross_amount = line_input["undiscounted_total_price"]["gross"]
undiscounted_net_amount = line_input["undiscounted_total_price"]["net"]
+
+ unit_discount_reason = line_input.get("unit_discount_reason")
+ unit_discount_type = line_input.get("unit_discount_type")
+ unit_discount_value = line_input.get("unit_discount_value", Decimal(0))
+
quantity = line_input["quantity"]
tax_rate = line_input.get("tax_rate", None)
@@ -1146,11 +1170,35 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
undiscounted_unit_price_net_amount - unit_price_net_amount
)
+ if (
+ unit_discount_value
+ and unit_discount_type
+ and Money(unit_price_net_amount, currency)
+ != apply_discount_to_value(
+ unit_discount_value,
+ unit_discount_type,
+ currency,
+ Money(undiscounted_unit_price_net_amount, currency),
+ )
+ ):
+ order_data.errors.append(
+ OrderBulkError(
+ message=(
+ "Provided discount value doesn't match with provided line amounts."
+ ),
+ path=f"lines.{index}.unit_discount_value",
+ code=OrderBulkCreateErrorCode.PRICE_ERROR,
+ )
+ )
+
return LineAmounts(
total_gross=gross_amount,
total_net=net_amount,
unit_gross=unit_price_gross_amount,
unit_net=unit_price_net_amount,
+ unit_discount_reason=unit_discount_reason,
+ unit_discount_type=unit_discount_type,
+ unit_discount_value=unit_discount_value,
undiscounted_total_gross=undiscounted_gross_amount,
undiscounted_total_net=undiscounted_net_amount,
undiscounted_unit_gross=undiscounted_unit_price_gross_amount,
@@ -1632,6 +1680,9 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
is_gift_card=order_line_input["is_gift_card"],
currency=order_input["currency"],
quantity=line_amounts.quantity,
+ unit_discount_reason=line_amounts.unit_discount_reason,
+ unit_discount_type=line_amounts.unit_discount_type,
+ unit_discount_value=line_amounts.unit_discount_value,
unit_price_net_amount=line_amounts.unit_net,
unit_price_gross_amount=line_amounts.unit_gross,
total_price_net_amount=line_amounts.total_net,
diff --git a/saleor/graphql/order/tests/mutations/test_order_bulk_create.py b/saleor/graphql/order/tests/mutations/test_order_bulk_create.py
index ae05949cd9..b38c9fd993 100644
--- a/saleor/graphql/order/tests/mutations/test_order_bulk_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_bulk_create.py
@@ -11,6 +11,7 @@ from .....account.models import Address
from .....core import JobStatus
from .....core.prices import quantize_price
from .....discount.models import OrderDiscount
+from .....discount.utils.manual_discount import DiscountValueType
from .....invoice.models import Invoice
from .....order import (
OrderAuthorizeStatus,
@@ -90,6 +91,9 @@ ORDER_BULK_CREATE = """
unitDiscount {
amount
}
+ unitDiscountValue
+ unitDiscountReason
+ unitDiscountType
totalPrice {
gross {
amount
@@ -491,6 +495,126 @@ def order_bulk_input_with_multiple_order_lines_and_fulfillments(
return order
+ ("discount_type_enum", "discount_type", "discount_value"),
+ [
+ (DiscountValueTypeEnum.FIXED, DiscountValueType.FIXED, Decimal("10")),
+ (DiscountValueTypeEnum.PERCENTAGE, DiscountValueType.PERCENTAGE, Decimal("50")),
+ ],
+)
+def test_order_bulk_create_unit_discount(
+ discount_type_enum,
+ discount_type,
+ discount_value,
+ staff_api_client,
+ permission_manage_orders,
+ permission_manage_orders_import,
+ permission_manage_users,
+ order_bulk_input,
+ channel_PLN,
+ variant,
+):
+ # given
+ discount_reason = "test"
+
+ order = order_bulk_input
+ order["externalReference"] = "ext-ref-1"
+ order["lines"][0]["unitDiscountValue"] = discount_value
+ order["lines"][0]["unitDiscountType"] = discount_type_enum.name
+ order["lines"][0]["unitDiscountReason"] = discount_reason
+
+ order["lines"][0]["totalPrice"]["net"] = 50
+ order["lines"][0]["totalPrice"]["gross"] = 60
+
+ staff_api_client.user.user_permissions.add(
+ permission_manage_orders_import,
+ permission_manage_orders,
+ permission_manage_users,
+ )
+ variables = {
+ "orders": [order],
+ "stockUpdatePolicy": StockUpdatePolicyEnum.SKIP.name,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_BULK_CREATE, variables)
+ content = get_graphql_content(response)
+
+ # then
+ assert content["data"]["orderBulkCreate"]["count"] == 1
+ data = content["data"]["orderBulkCreate"]["results"]
+ assert not data[0]["errors"]
+
+ order = data[0]["order"]
+ assert order["externalReference"] == "ext-ref-1"
+ assert order["created"]
+ assert order["status"] == OrderStatus.DRAFT.upper()
+ db_order = Order.objects.get()
+ assert db_order.external_reference == "ext-ref-1"
+ assert db_order.created_at
+ assert db_order.status == OrderStatus.DRAFT
+
+ order_line = order["lines"][0]
+ assert order_line["variant"]["id"] == graphene.Node.to_global_id(
+ "ProductVariant", variant.id
+ )
+ assert order_line["unitDiscountType"] == discount_type_enum.name
+ assert order_line["unitDiscountValue"] == discount_value
+ assert order_line["unitDiscountReason"] == discount_reason
+ db_order_line = OrderLine.objects.get()
+ assert db_order_line.variant == variant
+ assert db_order_line.unit_discount_type == discount_type
+ assert db_order_line.unit_discount_value == discount_value
+ assert db_order_line.unit_discount_reason == discount_reason
+ assert db_order.lines.first() == db_order_line
+
+
+def test_order_bulk_create_unit_discount_mismatched_discount(
+ staff_api_client,
+ permission_manage_orders,
+ permission_manage_orders_import,
+ permission_manage_users,
+ order_bulk_input,
+ channel_PLN,
+ variant,
+):
+ # given
+ discount_reason = "test"
+
+ order = order_bulk_input
+ order["externalReference"] = "ext-ref-1"
+ order["lines"][0]["unitDiscountValue"] = 50
+ order["lines"][0]["unitDiscountType"] = DiscountValueTypeEnum.FIXED.name
+ order["lines"][0]["unitDiscountReason"] = discount_reason
+
+ staff_api_client.user.user_permissions.add(
+ permission_manage_orders_import,
+ permission_manage_orders,
+ permission_manage_users,
+ )
+ variables = {
+ "orders": [order],
+ "stockUpdatePolicy": StockUpdatePolicyEnum.SKIP.name,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_BULK_CREATE, variables)
+ content = get_graphql_content(response)
+
+ # then
+ assert content["data"]["orderBulkCreate"]["count"] == 0
+ errors = content["data"]["orderBulkCreate"]["results"][0]["errors"]
+ assert len(errors) == 1
+
+ error0 = content["data"]["orderBulkCreate"]["results"][0]["errors"][0]
+ assert (
+ error0["message"]
+ == "Provided discount value doesn't match with provided line amounts."
+ )
+ assert error0["path"] == "lines.0.unit_discount_value"
+ assert error0["code"] == OrderBulkCreateErrorCode.PRICE_ERROR.name
+
+
def test_order_bulk_create(
staff_api_client,
permission_manage_orders,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index fb43400937..ed0152ea08 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -24361,6 +24361,27 @@ input OrderBulkCreateOrderLineInput @doc(category: "Orders") {
"""Price of the order line excluding applied discount."""
undiscountedTotalPrice: TaxedMoneyInput!
+ """
+ Reason of the discount on order line.
+
+ Added in Saleor 3.19.
+ """
+ unitDiscountReason: String
+
+ """
+ Type of the discount: fixed or percent
+
+ Added in Saleor 3.19.
+ """
+ unitDiscountType: DiscountValueTypeEnum
+
+ """
+ Value of the discount. Can store fixed value or percent value
+
+ Added in Saleor 3.19.
+ """
+ unitDiscountValue: PositiveDecimal
+
"""The ID of the warehouse, where the line will be allocated."""
warehouse: ID!