Skip to content

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

Fix draft order shipping method update (#13103)

Jakubd56d904f996a
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index 704e738454..05f5baacb1 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -6,7 +6,7 @@ from django.core.exceptions import ValidationError
from ....account.models import User
from ....checkout import AddressType
-from ....core.taxes import TaxError, zero_money
+from ....core.taxes import TaxError
from ....core.tracing import traced_atomic_transaction
from ....core.utils.url import validate_storefront_url
from ....order import OrderOrigin, OrderStatus, events, models
@@ -19,7 +19,6 @@ from ....order.utils import (
update_order_display_gross_prices,
)
from ....permission.enums import OrderPermissions
-from ....shipping import models as shipping_models
from ....shipping.utils import convert_to_shipping_method_data
from ...account.i18n import I18nMixin
from ...account.types import AddressInput
@@ -43,10 +42,10 @@ from ...shipping.utils import get_shipping_model_by_object_id
from ..types import Order
from ..utils import (
OrderLineData,
- get_shipping_method_availability_error,
validate_product_is_published_in_channel,
validate_variant_channel_listings,
)
+from .utils import SHIPPING_METHOD_UPDATE_FIELDS, ShippingMethodUpdateMixin
class OrderLineInput(BaseInputObjectType):
@@ -130,7 +129,9 @@ class DraftOrderCreateInput(DraftOrderInput):
doc_category = DOC_CATEGORY_ORDERS
-class DraftOrderCreate(ModelWithRestrictedChannelAccessMutation, I18nMixin):
+class DraftOrderCreate(
+ ModelWithRestrictedChannelAccessMutation, ShippingMethodUpdateMixin, I18nMixin
+):
class Arguments:
input = DraftOrderCreateInput(
required=True, description="Fields required to create an order."
@@ -171,9 +172,11 @@ class DraftOrderCreate(ModelWithRestrictedChannelAccessMutation, I18nMixin):
redirect_url = data.pop("redirect_url", None)
channel_id = data.pop("channel_id", None)
manager = get_plugin_manager_promise(info.context).get()
- shipping_method = get_shipping_model_by_object_id(
- object_id=data.pop("shipping_method", None), raise_error=False
- )
+ shipping_method_input = {}
+ if "shipping_method" in data:
+ shipping_method_input["shipping_method"] = get_shipping_model_by_object_id(
+ object_id=data.pop("shipping_method", None), raise_error=False
+ )
if email := data.get("user_email", None):
try:
@@ -183,7 +186,7 @@ class DraftOrderCreate(ModelWithRestrictedChannelAccessMutation, I18nMixin):
data["user"] = None
cleaned_input = super().clean_input(info, instance, data, **kwargs)
-
+ cleaned_input.update(shipping_method_input)
channel = cls.clean_channel_id(info, instance, cleaned_input, channel_id)
voucher = cleaned_input.get("voucher", None)
@@ -195,8 +198,6 @@ class DraftOrderCreate(ModelWithRestrictedChannelAccessMutation, I18nMixin):
lines = data.pop("lines", None)
cls.clean_lines(cleaned_input, lines, channel)
-
- cleaned_input["shipping_method"] = shipping_method
cleaned_input["status"] = OrderStatus.DRAFT
cleaned_input["origin"] = OrderOrigin.DRAFT
@@ -366,14 +367,6 @@ class DraftOrderCreate(ModelWithRestrictedChannelAccessMutation, I18nMixin):
def _commit_changes(
cls, info: ResolveInfo, instance, cleaned_input, is_new_instance, app
):
- if shipping_method := cleaned_input["shipping_method"]:
- instance.shipping_method_name = shipping_method.name
- tax_class = shipping_method.tax_class
- if tax_class:
- instance.shipping_tax_class = tax_class
- instance.shipping_tax_class_name = tax_class.name
- instance.shipping_tax_class_private_metadata = tax_class.metadata
- instance.shipping_tax_class_metadata = tax_class.private_metadata
super().save(info, instance, cleaned_input)
# Create draft created event if the instance is from scratch
@@ -382,56 +375,6 @@ class DraftOrderCreate(ModelWithRestrictedChannelAccessMutation, I18nMixin):
order=instance, user=info.context.user, app=app
)
- @classmethod
- def _update_shipping_price(
- cls,
- info: ResolveInfo,
- instance: models.Order,
- cleaned_input,
- shipping_channel_listing,
- ):
- if shipping_address := cleaned_input.get("shipping_address"):
- instance.shipping_address = shipping_address
- if (
- instance.shipping_method
- and instance.shipping_address
- and instance.is_shipping_required()
- ):
- shipping_method_data = convert_to_shipping_method_data(
- instance.shipping_method,
- shipping_channel_listing,
- )
- manager = get_plugin_manager_promise(info.context).get()
- error = get_shipping_method_availability_error(
- instance, shipping_method_data, manager
- )
- if error:
- raise ValidationError({"shipping_method": error})
-
- instance.base_shipping_price = shipping_channel_listing.price
- else:
- instance.base_shipping_price = zero_money(instance.currency)
-
- @classmethod
- def _get_shipping_channel_listing(cls, instance, cleaned_input):
- if shipping_method := cleaned_input["shipping_method"]:
- shipping_channel_listing = (
- shipping_models.ShippingMethodChannelListing.objects.filter(
- shipping_method=shipping_method, channel__id=instance.channel_id
- ).first()
- )
- if not shipping_channel_listing:
- raise ValidationError(
- {
- "shipping_method": ValidationError(
- "Shipping method not available in the given channel.",
- code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
- )
- }
- )
- return shipping_channel_listing
- return None
-
@classmethod
def should_invalidate_prices(cls, instance, cleaned_input, is_new_instance) -> bool:
# Force price recalculation for all new instances
@@ -461,14 +404,27 @@ class DraftOrderCreate(ModelWithRestrictedChannelAccessMutation, I18nMixin):
app,
manager
):
+ updated_fields = []
with traced_atomic_transaction():
- shipping_channel_listing = cls._get_shipping_channel_listing(
- instance, cleaned_input
- )
-
+ shipping_channel_listing = None
# Process addresses
cls._save_addresses(instance, cleaned_input)
+ if "shipping_method" in cleaned_input:
+ method = cleaned_input["shipping_method"]
+ if method is None:
+ cls.clear_shipping_method_from_order(instance)
+ else:
+ shipping_channel_listing = cls.validate_shipping_channel_listing(
+ method, instance
+ )
+ shipping_method_data = convert_to_shipping_method_data(
+ method,
+ shipping_channel_listing,
+ )
+ cls.update_shipping_method(instance, method, shipping_method_data)
+ updated_fields.extend(SHIPPING_METHOD_UPDATE_FIELDS)
+
# Save any changes create/update the draft
cls._commit_changes(info, instance, cleaned_input, is_new_instance, app)
@@ -492,21 +448,20 @@ class DraftOrderCreate(ModelWithRestrictedChannelAccessMutation, I18nMixin):
cls.call_event(manager.draft_order_updated, instance)
# Post-process the results
- updated_fields = [
- "weight",
- "search_vector",
- "updated_at",
- "display_gross_prices",
- ]
+ updated_fields.extend(
+ [
+ "weight",
+ "search_vector",
+ "updated_at",
+ "display_gross_prices",
+ ]
+ )
if cls.should_invalidate_prices(instance, cleaned_input, is_new_instance):
invalidate_order_prices(instance)
- cls._update_shipping_price(
- info, instance, cleaned_input, shipping_channel_listing
- )
+ cls._update_shipping_price(instance, shipping_channel_listing)
updated_fields.extend(
["should_refresh_prices", "base_shipping_price_amount"]
)
-
recalculate_order_weight(instance)
update_order_search_vector(instance, save=False)
diff --git a/saleor/graphql/order/mutations/draft_order_update.py b/saleor/graphql/order/mutations/draft_order_update.py
index 92405a241a..e80fdfc442 100644
--- a/saleor/graphql/order/mutations/draft_order_update.py
+++ b/saleor/graphql/order/mutations/draft_order_update.py
@@ -58,6 +58,7 @@ class DraftOrderUpdate(DraftOrderCreate, ModelWithExtRefMutation):
"shipping_address",
"billing_address",
"shipping_method",
+ "lines",
]
)
diff --git a/saleor/graphql/order/mutations/order_update_shipping.py b/saleor/graphql/order/mutations/order_update_shipping.py
index bb42f34401..a6c3b11342 100644
--- a/saleor/graphql/order/mutations/order_update_shipping.py
+++ b/saleor/graphql/order/mutations/order_update_shipping.py
@@ -1,10 +1,8 @@
import graphene
from django.core.exceptions import ValidationError
-from ....core.taxes import zero_money, zero_taxed_money
-from ....order import models
+from ....order import OrderStatus, models
from ....order.error_codes import OrderErrorCode
-from ....order.utils import invalidate_order_prices
from ....permission.enums import OrderPermissions
from ....shipping import models as shipping_models
from ....shipping.utils import convert_to_shipping_method_data
@@ -15,7 +13,12 @@ from ...core.types import BaseInputObjectType, OrderError
from ...plugins.dataloaders import get_plugin_manager_promise
from ...shipping.types import ShippingMethod
from ..types import Order
-from .utils import EditableOrderValidationMixin, clean_order_update_shipping
+from .utils import (
+ SHIPPING_METHOD_UPDATE_FIELDS,
+ EditableOrderValidationMixin,
+ ShippingMethodUpdateMixin,
+ clean_order_update_shipping,
+)
class OrderUpdateShippingInput(BaseInputObjectType):
@@ -29,7 +32,9 @@ class OrderUpdateShippingInput(BaseInputObjectType):
doc_category = DOC_CATEGORY_ORDERS
-class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
+class OrderUpdateShipping(
+ EditableOrderValidationMixin, ShippingMethodUpdateMixin, BaseMutation
+):
order = graphene.Field(Order, description="Order with updated shipping method.")
class Arguments:
@@ -101,32 +106,8 @@ class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
}
)
- order.shipping_method = None
- order.base_shipping_price = zero_money(order.currency)
- order.shipping_price = zero_taxed_money(order.currency)
- order.shipping_method_name = None
- order.shipping_tax_class = None
- order.shipping_tax_class_name = None
- order.shipping_tax_class_private_metadata = {}
- order.shipping_tax_class_metadata = {}
- invalidate_order_prices(order)
- order.save(
- update_fields=[
- "currency",
- "shipping_method",
- "shipping_price_net_amount",
- "shipping_price_gross_amount",
- "base_shipping_price_amount",
- "shipping_method_name",
- "shipping_tax_class",
- "shipping_tax_class_name",
- "shipping_tax_class_private_metadata",
- "shipping_tax_class_metadata",
- "shipping_tax_rate",
- "should_refresh_prices",
- "updated_at",
- ]
- )
+ cls.clear_shipping_method_from_order(order)
+ order.save(update_fields=SHIPPING_METHOD_UPDATE_FIELDS)
return OrderUpdateShipping(order=order)
method_id: str = input["shipping_method"]
@@ -139,54 +120,19 @@ class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
"postal_code_rules"
),
)
- shipping_channel_listing = (
- shipping_models.ShippingMethodChannelListing.objects.filter(
- shipping_method=method, channel=order.channel
- ).first()
- )
- if not shipping_channel_listing:
- raise ValidationError(
- {
- "shipping_method": ValidationError(
- "Shipping method not available in the given channel.",
- code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
- )
- }
- )
+ shipping_channel_listing = cls.validate_shipping_channel_listing(method, order)
shipping_method_data = convert_to_shipping_method_data(
method,
shipping_channel_listing,
)
manager = get_plugin_manager_promise(info.context).get()
- clean_order_update_shipping(order, shipping_method_data, manager)
-
- order.shipping_method = method
- order.shipping_method_name = method.name
-
- tax_class = method.tax_class
- if tax_class:
- order.shipping_tax_class = tax_class
- order.shipping_tax_class_name = tax_class.name
- order.shipping_tax_class_private_metadata = tax_class.private_metadata
- order.shipping_tax_class_metadata = tax_class.metadata
-
- order.base_shipping_price = shipping_method_data.price
- invalidate_order_prices(order)
- order.save(
- update_fields=[
- "currency",
- "shipping_method",
- "shipping_method_name",
- "shipping_tax_class",
- "shipping_tax_class_name",
- "shipping_tax_class_private_metadata",
- "shipping_tax_class_metadata",
- "base_shipping_price_amount",
- "should_refresh_prices",
- "updated_at",
- ]
- )
+ if order.status != OrderStatus.DRAFT:
+ clean_order_update_shipping(order, shipping_method_data, manager)
+ cls.update_shipping_method(order, method, shipping_channel_listing)
+ cls._update_shipping_price(order, shipping_channel_listing)
+
+ order.save(update_fields=SHIPPING_METHOD_UPDATE_FIELDS)
# Post-process the results
cls.call_event(manager.order_updated, order)
return OrderUpdateShipping(order=order)
diff --git a/saleor/graphql/order/mutations/utils.py b/saleor/graphql/order/mutations/utils.py
index 7258fb4c49..3441e352b2 100644
--- a/saleor/graphql/order/mutations/utils.py
+++ b/saleor/graphql/order/mutations/utils.py
@@ -2,14 +2,33 @@ from typing import Optional
from django.core.exceptions import ValidationError
+from ....core.taxes import zero_money, zero_taxed_money
from ....order import ORDER_EDITABLE_STATUS, OrderStatus, events
from ....order.error_codes import OrderErrorCode
+from ....order.utils import invalidate_order_prices
from ....payment import PaymentError
from ....payment import models as payment_models
from ....plugins.manager import PluginsManager
from ....shipping.interface import ShippingMethodData
+from ....shipping.models import ShippingMethodChannelListing
from ..utils import get_shipping_method_availability_error
+SHIPPING_METHOD_UPDATE_FIELDS = [
+ "currency",
+ "shipping_method",
+ "shipping_price_net_amount",
+ "shipping_price_gross_amount",
+ "base_shipping_price_amount",
+ "shipping_method_name",
+ "shipping_tax_class",
+ "shipping_tax_class_name",
+ "shipping_tax_class_private_metadata",
+ "shipping_tax_class_metadata",
+ "shipping_tax_rate",
+ "should_refresh_prices",
+ "updated_at",
+]
+
class EditableOrderValidationMixin:
class Meta:
@@ -29,6 +48,72 @@ class EditableOrderValidationMixin:
return order
+class ShippingMethodUpdateMixin:
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def clear_shipping_method_from_order(cls, order):
+ order.shipping_method = None
+ order.base_shipping_price = zero_money(order.currency)
+ order.shipping_price = zero_taxed_money(order.currency)
+ order.shipping_method_name = None
+ order.shipping_tax_rate = None
+ order.shipping_tax_class = None
+ order.shipping_tax_class_name = None
+ order.shipping_tax_class_private_metadata = {}
+ order.shipping_tax_class_metadata = {}
+ invalidate_order_prices(order)
+
+ @classmethod
+ def update_shipping_method(cls, order, method, shipping_method_data):
+ order.shipping_method = method
+ order.shipping_method_name = method.name
+
+ tax_class = method.tax_class
+ if tax_class:
+ order.shipping_tax_class = tax_class
+ order.shipping_tax_class_name = tax_class.name
+ order.shipping_tax_class_private_metadata = tax_class.private_metadata
+ order.shipping_tax_class_metadata = tax_class.metadata
+ invalidate_order_prices(order)
+
+ @classmethod
+ def validate_shipping_channel_listing(cls, method, order):
+ shipping_channel_listing = ShippingMethodChannelListing.objects.filter(
+ shipping_method=method, channel=order.channel
+ ).first()
+ if not shipping_channel_listing:
+ raise ValidationError(
+ {
+ "shipping_method": ValidationError(
+ "Shipping method not available in the given channel.",
+ code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
+ )
+ }
+ )
+ return shipping_channel_listing
+
+ @classmethod
+ def _update_shipping_price(
+ cls,
+ order,
+ shipping_channel_listing,
+ ):
+ if not shipping_channel_listing:
+ order.base_shipping_price = zero_money(order.currency)
+ return
+
+ if (
+ order.shipping_method
+ and order.shipping_address
+ and order.is_shipping_required()
+ ):
+ order.base_shipping_price = shipping_channel_listing.price
+ else:
+ order.base_shipping_price = zero_money(order.currency)
+
+
def clean_order_update_shipping(
order, method: ShippingMethodData, manager: "PluginsManager"
):
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 e3f1316a4a..4e033bd2d6 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
@@ -527,7 +527,7 @@ def test_draft_order_update_with_non_unique_external_reference(
assert error["message"] == "Order with this External reference already exists."
-DRAFT_ORDER_UPDATE_MUTATION_SHIPPING_METHOD = """
+DRAFT_ORDER_UPDATE_SHIPPING_METHOD_MUTATION = """
mutation draftUpdate($id: ID!, $shippingMethod: ID){
draftOrderUpdate(
id: $id,
@@ -542,6 +542,15 @@ DRAFT_ORDER_UPDATE_MUTATION_SHIPPING_METHOD = """
order {
shippingMethodName
shippingPrice {
+ net {
+ amount
+ }
+ gross {
+ amount
+ }
+ tax {
+ amount
+ }
net {
amount
}
@@ -549,13 +558,118 @@ DRAFT_ORDER_UPDATE_MUTATION_SHIPPING_METHOD = """
amount
}
}
- userEmail
+ shippingTaxRate
+ userEmail
}
}
}
"""
+def test_draft_order_update_shipping_method_from_different_channel(
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ address_usa,
+ shipping_method_channel_PLN,
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = draft_order
+ order.shipping_address = address_usa
+ order.save(update_fields=["shipping_address"])
+ query = DRAFT_ORDER_UPDATE_SHIPPING_METHOD_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method_channel_PLN.id
+ )
+ variables = {"id": order_id, "shippingMethod": shipping_method_id}
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderUpdate"]
+
+ # then
+ assert len(data["errors"]) == 1
+ assert not data["order"]
+ error = data["errors"][0]
+ assert error["code"] == OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name
+ assert error["field"] == "shippingMethod"
+
+
+def test_draft_order_update_shipping_method_prices_updates(
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ address_usa,
+ shipping_method,
+ shipping_method_weight_based,
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = draft_order
+ order.shipping_address = address_usa
+ order.shipping_method = shipping_method
+ order.save(update_fields=["shipping_address", "shipping_method"])
+ assert shipping_method.channel_listings.first().price_amount == 10
+ method_2 = shipping_method_weight_based
+ m2_channel_listing = method_2.channel_listings.first()
+ m2_channel_listing.price_amount = 15
+ m2_channel_listing.save(update_fields=["price_amount"])
+ query = DRAFT_ORDER_UPDATE_SHIPPING_METHOD_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ shipping_method_id = graphene.Node.to_global_id("ShippingMethod", method_2.id)
+ variables = {"id": order_id, "shippingMethod": shipping_method_id}
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderUpdate"]
+ order.refresh_from_db()
+
+ # then
+ assert not data["errors"]
+ assert data["order"]["shippingMethodName"] == method_2.name
+ assert data["order"]["shippingPrice"]["net"]["amount"] == 15.0
+
+
+def test_draft_order_update_shipping_method_clear_with_none(
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ address_usa,
+ shipping_method,
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = draft_order
+ order.shipping_address = address_usa
+ order.shipping_method = shipping_method
+ order.save(update_fields=["shipping_address", "shipping_method"])
+ query = DRAFT_ORDER_UPDATE_SHIPPING_METHOD_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id, "shippingMethod": None}
+ zero_shipping_price_data = {
+ "tax": {"amount": 0.0},
+ "net": {"amount": 0.0},
+ "gross": {"amount": 0.0},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderUpdate"]
+ order.refresh_from_db()
+
+ # then
+ assert not data["errors"]
+ assert data["order"]["shippingMethodName"] is None
+ assert data["order"]["shippingPrice"] == zero_shipping_price_data
+ assert data["order"]["shippingTaxRate"] == 0.0
+ assert order.shipping_method is None
+
+
def test_draft_order_update_shipping_method(
staff_api_client, permission_group_manage_orders, draft_order, shipping_method
):
@@ -566,7 +680,7 @@ def test_draft_order_update_shipping_method(
order.base_shipping_price = zero_money(order.currency)
order.save()
- query = DRAFT_ORDER_UPDATE_MUTATION_SHIPPING_METHOD
+ query = DRAFT_ORDER_UPDATE_SHIPPING_METHOD_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
variables = {
@@ -616,7 +730,7 @@ def test_draft_order_update_no_shipping_method_channel_listings(
shipping_method.channel_listings.all().delete()
- query = DRAFT_ORDER_UPDATE_MUTATION_SHIPPING_METHOD
+ query = DRAFT_ORDER_UPDATE_SHIPPING_METHOD_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
variables = {
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index d3fdc56725..372a509053 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -1456,7 +1456,7 @@ class Order(ModelObjectType[models.Order]):
root, manager, lines
) or Decimal(0)
- lines = OrderLinesByOrderIdLoader(info.context)
+ lines = OrderLinesByOrderIdLoader(info.context).load(root.id)
manager = get_plugin_manager_promise(info.context)
return Promise.all([lines, manager]).then(_resolve_shipping_tax_rate)