Skip to content

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

Added custom price to OrderLine. (#12855)

Kyrylo Plaksinc70f6b0edee4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f54749a86d..e41c7bccd4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -54,6 +54,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Upgrade checkout `complete_checkout` to assign guest checkout to account if exists - #12758 by @FremahA
- Remove `ENABLE_ACCOUNT_CONFIRMATION_BY_EMAIL` env variable from settings - ##12781 by @SzymJ
- Match `Orders` to `User` when creating user using OIDC plugin. - #12863 by @kadewu
+- Allow defining a custom price in draft orders - #12855 by @KirillPlaksin
# 3.13.0
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index b937cc7d04..704e738454 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -26,7 +26,12 @@ from ...account.types import AddressInput
from ...app.dataloaders import get_app_promise
from ...channel.types import Channel
from ...core import ResolveInfo
-from ...core.descriptions import ADDED_IN_36, ADDED_IN_310
+from ...core.descriptions import (
+ ADDED_IN_36,
+ ADDED_IN_310,
+ ADDED_IN_314,
+ PREVIEW_FEATURE,
+)
from ...core.doc_category import DOC_CATEGORY_ORDERS
from ...core.mutations import ModelWithRestrictedChannelAccessMutation
from ...core.scalars import PositiveDecimal
@@ -65,6 +70,16 @@ class OrderLineCreateInput(OrderLineInput):
"by skipping the matching logic. " + ADDED_IN_36
),
)
+ price = PositiveDecimal(
+ required=False,
+ description=(
+ "Custom price of the item."
+ "When the line with the same variant "
+ "will be provided multiple times, the last price will be used."
+ + ADDED_IN_314
+ + PREVIEW_FEATURE
+ ),
+ )
class Meta:
doc_category = DOC_CATEGORY_ORDERS
@@ -254,14 +269,20 @@ class DraftOrderCreate(ModelWithRestrictedChannelAccessMutation, I18nMixin):
variant = list(
filter(lambda x: (x.pk == int(variant_db_id)), variants)
)[0]
+ custom_price = line.get("price", None)
if line.get("force_new_line"):
- line_data = OrderLineData(variant_id=variant_db_id, variant=variant)
+ line_data = OrderLineData(
+ variant_id=variant_db_id,
+ variant=variant,
+ price_override=custom_price,
+ )
grouped_lines_data.append(line_data)
else:
line_data = lines_data_map[variant_db_id]
line_data.variant_id = variant_db_id
line_data.variant = variant
+ line_data.price_override = custom_price
if (quantity := line.get("quantity")) is not None:
line_data.quantity += quantity
diff --git a/saleor/graphql/order/mutations/order_lines_create.py b/saleor/graphql/order/mutations/order_lines_create.py
index 140596adda..b29cc4ceba 100644
--- a/saleor/graphql/order/mutations/order_lines_create.py
+++ b/saleor/graphql/order/mutations/order_lines_create.py
@@ -74,6 +74,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
)
quantity = input_line["quantity"]
+ custom_price = input_line.get("price")
if quantity > 0:
if force_new_line or variants_from_existing_lines.count(variant.pk) > 1:
grouped_lines_data.append(
@@ -81,6 +82,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
variant_id=str(variant.id),
variant=variant,
quantity=quantity,
+ price_override=custom_price,
)
)
else:
@@ -97,6 +99,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
line_data.variant = variant
line_data.quantity += quantity
+ line_data.price_override = custom_price
else:
invalid_ids.append(variant_id)
if invalid_ids:
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 0a4ec4e784..97eb5e6e67 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -2,6 +2,7 @@ from datetime import datetime, timedelta
from unittest.mock import ANY, Mock, patch
import graphene
+import pytest
import pytz
from prices import Money
@@ -1417,3 +1418,75 @@ def test_draft_order_create_with_non_unique_external_reference(
assert error["field"] == "externalReference"
assert error["code"] == OrderErrorCode.UNIQUE.name
assert error["message"] == "Order with this External reference already exists."
+
+
[email protected]("force_new_line", (True, False))
+def test_draft_order_create_with_custom_price_in_order_line(
+ force_new_line,
+ staff_api_client,
+ permission_group_manage_orders,
+ customer_user,
+ product_without_shipping,
+ shipping_method,
+ variant,
+ graphql_address_data,
+ channel_USD,
+):
+ # given
+ variant_0 = variant
+ query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variant_1 = product_without_shipping.variants.first()
+ variant_1.quantity = 2
+ variant_1.save()
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)
+ expected_price_variant_0 = 10
+ expected_price_variant_1 = 20
+ variant_list = [
+ {
+ "variantId": variant_0_id,
+ "quantity": 2,
+ "price": expected_price_variant_0,
+ "forceNewLine": force_new_line,
+ },
+ {
+ "variantId": variant_1_id,
+ "quantity": 1,
+ "price": expected_price_variant_1,
+ "forceNewLine": force_new_line,
+ },
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ variables = {
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "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()
+
+ order = Order.objects.first()
+
+ order_line_0 = order.lines.get(variant=variant_0)
+ assert order_line_0.base_unit_price_amount == expected_price_variant_0
+ assert order_line_0.undiscounted_base_unit_price_amount == expected_price_variant_0
+
+ order_line_1 = order.lines.get(variant=variant_1)
+ assert order_line_1.base_unit_price_amount == expected_price_variant_1
+ assert order_line_1.undiscounted_base_unit_price_amount == expected_price_variant_1
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 dc4c74af1d..9d43ca84cf 100644
--- a/saleor/graphql/order/tests/mutations/test_order_lines_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
@@ -17,14 +17,19 @@ from ..utils import assert_proper_webhook_called_once
ORDER_LINES_CREATE_MUTATION = """
mutation OrderLinesCreate(
- $orderId: ID!, $variantId: ID!, $quantity: Int!, $forceNewLine: Boolean
+ $orderId: ID!,
+ $variantId: ID!,
+ $quantity: Int!,
+ $forceNewLine: Boolean,
+ $price: PositiveDecimal,
) {
orderLinesCreate(id: $orderId,
input: [
{
variantId: $variantId,
quantity: $quantity,
- forceNewLine: $forceNewLine
+ forceNewLine: $forceNewLine,
+ price: $price
}
]) {
@@ -735,3 +740,65 @@ def test_invalid_order_when_creating_lines(
assert data["errors"]
order_updated_webhook_mock.assert_not_called()
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.save(update_fields=["status"])
+ variant = variant_with_many_stocks
+ 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
+ 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, 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
+ line = OrderLine.objects.last()
+ assert line.undiscounted_base_unit_price_amount == custom_price
+ assert line.base_unit_price_amount == custom_price
+ assert event.parameters["lines"] == [
+ {"item": str(line), "line_pk": str(line.pk), "quantity": quantity}
+ ]
+
+ 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"] == quantity
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index 72b573d3e4..c3400916de 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -1,4 +1,5 @@
from collections import defaultdict
+from decimal import Decimal
from typing import TYPE_CHECKING, Dict, Iterable, List, Optional
import graphene
@@ -27,6 +28,7 @@ class OrderLineData:
variant_id: Optional[str] = None
variant: Optional[ProductVariant] = None
line_id: Optional[str] = None
+ price_override: Optional[Decimal] = None
quantity: int = 0
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index d0fb5d986c..6b666c56bc 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -21666,6 +21666,15 @@ input OrderLineCreateInput @doc(category: "Orders") {
Added in Saleor 3.6.
"""
forceNewLine: Boolean = false
+
+ """
+ Custom price of the item.When the line with the same variant will be provided multiple times, the last price will be used.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ price: PositiveDecimal
}
"""
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index edbd988376..c2c47239b4 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -1339,3 +1339,108 @@ def test_order_update_charge_data_with_transaction_item_and_payment(
assert order_with_lines.total_charged == Money(
first_charged_amount + second_charged_amount, order_with_lines.currency
)
+
+
+def test_add_variant_to_order_adds_line_for_new_variant_on_sale_with_custom_price(
+ order_with_lines,
+ product,
+ product_translation_fr,
+ sale,
+ discount_info,
+ settings,
+ anonymous_plugins,
+):
+ # given
+ order = order_with_lines
+ variant = product.variants.first()
+ discount_info.variants_ids.add(variant.id)
+ sale.variants.add(variant)
+ lines_before = order.lines.count()
+ settings.LANGUAGE_CODE = "fr"
+ price_override = Decimal(15)
+ line_data = OrderLineData(
+ variant_id=str(variant.id),
+ variant=variant,
+ quantity=1,
+ price_override=price_override,
+ )
+
+ # when
+ add_variant_to_order(
+ order=order,
+ line_data=line_data,
+ user=None,
+ app=None,
+ manager=anonymous_plugins,
+ discounts=[discount_info],
+ )
+
+ # then
+ line = order.lines.last()
+ variant_channel_listing = variant.channel_listings.get(channel=order.channel)
+ sale_channel_listing = sale.channel_listings.first()
+ assert order.lines.count() == lines_before + 1
+ assert line.product_sku == variant.sku
+ assert line.quantity == 1
+ assert variant_channel_listing.price_amount != price_override
+ unit_amount = price_override - sale_channel_listing.discount_value
+ assert line.unit_price == TaxedMoney(
+ net=Money(unit_amount, "USD"), gross=Money(unit_amount, "USD")
+ )
+ assert line.translated_product_name == str(variant.product.translated)
+ assert line.variant_name == str(variant)
+ assert line.product_name == str(variant.product)
+
+ assert line.unit_discount_amount == sale_channel_listing.discount_value
+ assert line.unit_discount_value == sale_channel_listing.discount_value
+ assert line.unit_discount_reason
+
+
+def test_add_variant_to_order_adds_line_with_custom_price_for_new_variant(
+ order_with_lines,
+ product,
+ product_translation_fr,
+ settings,
+ anonymous_plugins,
+):
+ # given
+ order = order_with_lines
+ variant = product.variants.get()
+ lines_before = order.lines.count()
+ settings.LANGUAGE_CODE = "fr"
+ price_override = Decimal(18)
+ line_data = OrderLineData(
+ variant_id=str(variant.id),
+ variant=variant,
+ quantity=1,
+ price_override=price_override,
+ )
+
+ # when
+ add_variant_to_order(
+ order=order,
+ line_data=line_data,
+ user=None,
+ app=None,
+ manager=anonymous_plugins,
+ )
+
+ # then
+ variant_channel_listing = variant.channel_listings.get(channel=order.channel)
+ line = order.lines.last()
+ assert order.lines.count() == lines_before + 1
+ assert variant_channel_listing.price_amount != price_override
+ assert line.product_sku == variant.sku
+ assert line.product_variant_id == variant.get_global_id()
+ assert line.quantity == 1
+ assert line.unit_price == TaxedMoney(
+ net=Money(price_override, "USD"), gross=Money(price_override, "USD")
+ )
+ assert line.translated_product_name == str(variant.product.translated)
+ assert line.variant_name == str(variant)
+ assert line.product_name == str(variant.product)
+ assert line.base_unit_price_amount == price_override
+ assert line.undiscounted_base_unit_price_amount == price_override
+ assert not line.unit_discount_amount
+ assert not line.unit_discount_value
+ assert not line.unit_discount_reason
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index d718415c16..0fae7df609 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -215,6 +215,7 @@ def create_order_line(
channel = order.channel
variant = line_data.variant
quantity = line_data.quantity
+ price_override = line_data.price_override
product = variant.product
collections = product.collections.all()
@@ -222,13 +223,23 @@ def create_order_line(
# vouchers are not applied for new lines in unconfirmed/draft orders
untaxed_unit_price = variant.get_price(
- product, collections, channel, channel_listing, discounts
+ product,
+ collections,
+ channel,
+ channel_listing,
+ discounts,
+ price_override=price_override,
)
if not discounts:
untaxed_undiscounted_price = untaxed_unit_price
else:
untaxed_undiscounted_price = variant.get_price(
- product, collections, channel, channel_listing, []
+ product,
+ collections,
+ channel,
+ channel_listing,
+ [],
+ price_override=price_override,
)
unit_price = TaxedMoney(net=untaxed_unit_price, gross=untaxed_unit_price)
undiscounted_unit_price = TaxedMoney(