Skip to content

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

Fix shipping price update (#11832)

Krzysztof Waliczek9568da5ee015
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index d538da5e88..2ada04ad86 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -7,7 +7,7 @@ from graphene.types import InputObjectType
from ....account.models import User
from ....checkout import AddressType
-from ....core.taxes import TaxError
+from ....core.taxes import TaxError, zero_money
from ....core.tracing import traced_atomic_transaction
from ....core.utils.url import validate_storefront_url
from ....order import OrderOrigin, OrderStatus, events, models
@@ -20,6 +20,8 @@ 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
from ...app.dataloaders import get_app_promise
@@ -35,6 +37,7 @@ 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,
)
@@ -285,12 +288,6 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
billing_address.save()
instance.billing_address = billing_address.get_copy()
- @staticmethod
- def _parse_shipping_method_name(instance: models.Order, cleaned_input):
- shipping_method = cleaned_input.get("shipping_method")
- if shipping_method:
- instance.shipping_method_name = shipping_method.name
-
@staticmethod
def _save_lines(info, instance, lines_data, app, manager):
if lines_data:
@@ -331,9 +328,55 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
order=instance, user=info.context.user, app=app
)
- instance.save(
- update_fields=["billing_address", "shipping_address", "updated_at"]
- )
+ @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:
@@ -365,12 +408,13 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
manager
):
with traced_atomic_transaction():
+ shipping_channel_listing = cls._get_shipping_channel_listing(
+ instance, cleaned_input
+ )
+
# Process addresses
cls._save_addresses(instance, cleaned_input)
- # Parse shipping name
- cls._parse_shipping_method_name(instance, cleaned_input)
-
# Save any changes create/update the draft
cls._commit_changes(info, instance, cleaned_input, is_new_instance, app)
@@ -402,7 +446,13 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
]
if cls.should_invalidate_prices(instance, cleaned_input, is_new_instance):
invalidate_order_prices(instance)
- updated_fields.append("should_refresh_prices")
+ cls._update_shipping_price(
+ info, instance, cleaned_input, 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/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
index fa05b3e980..e6205e6c05 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -159,6 +159,10 @@ def test_draft_order_create(
assert order.shipping_address
assert order.search_vector
assert order.external_reference == external_reference
+ shipping_total = shipping_method.channel_listings.get(
+ channel_id=order.channel_id
+ ).get_total()
+ assert order.base_shipping_price == shipping_total
# Ensure the correct event was created
created_draft_event = OrderEvent.objects.get(
@@ -254,6 +258,10 @@ def test_draft_order_create_with_same_variant_and_force_new_line(
assert order.billing_address
assert order.shipping_address
assert order.search_vector
+ shipping_total = shipping_method.channel_listings.get(
+ channel_id=order.channel_id
+ ).get_total()
+ assert order.base_shipping_price == shipping_total
# Ensure the correct event was created
created_draft_event = OrderEvent.objects.get(
@@ -342,6 +350,10 @@ def test_draft_order_create_with_inactive_channel(
assert not order.billing_address
assert order.shipping_method == shipping_method
assert order.shipping_address.first_name == graphql_address_data["firstName"]
+ shipping_total = shipping_method.channel_listings.get(
+ channel_id=order.channel_id
+ ).get_total()
+ assert order.base_shipping_price == shipping_total
# Ensure the correct event was created
created_draft_event = OrderEvent.objects.get(
@@ -425,6 +437,10 @@ def test_draft_order_create_without_sku(
assert order.shipping_method == shipping_method
assert order.billing_address
assert order.shipping_address
+ shipping_total = shipping_method.channel_listings.get(
+ channel_id=order.channel_id
+ ).get_total()
+ assert order.base_shipping_price == shipping_total
order_line = order.lines.get(variant=variant)
assert order_line.product_sku is None
@@ -491,6 +507,11 @@ def test_draft_order_create_variant_with_0_price(
assert order.shipping_method == shipping_method
assert order.shipping_address.first_name == graphql_address_data["firstName"]
+ shipping_total = shipping_method.channel_listings.get(
+ channel_id=order.channel_id
+ ).get_total()
+ assert order.base_shipping_price == shipping_total
+
# Ensure the correct event was created
created_draft_event = OrderEvent.objects.get(
type=order_events.OrderEvents.DRAFT_CREATED
@@ -948,6 +969,83 @@ def test_draft_order_create_with_channel(
assert not order.billing_address
assert order.shipping_method == shipping_method
assert order.shipping_address.first_name == graphql_address_data["firstName"]
+ shipping_total = shipping_method.channel_listings.get(
+ channel_id=order.channel_id
+ ).get_total()
+ assert order.base_shipping_price == shipping_total
+
+ # Ensure the correct event was created
+ created_draft_event = OrderEvent.objects.get(
+ type=order_events.OrderEvents.DRAFT_CREATED
+ )
+ assert created_draft_event.user == staff_user
+ assert created_draft_event.parameters == {}
+
+
+def test_draft_order_create_product_without_shipping(
+ staff_api_client,
+ permission_manage_orders,
+ staff_user,
+ customer_user,
+ product_without_shipping,
+ shipping_method,
+ voucher,
+ graphql_address_data,
+ channel_USD,
+):
+ # given
+ query = DRAFT_ORDER_CREATE_MUTATION
+
+ # Ensure no events were created yet
+ assert not OrderEvent.objects.exists()
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant = product_without_shipping.variants.first()
+
+ variant.quantity = 2
+ variant.save()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ discount = "10"
+ customer_note = "Test note"
+ variant_list = [
+ {"variantId": variant_id, "quantity": 1},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
+ variables = {
+ "user": user_id,
+ "discount": discount,
+ "channel": channel_id,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ assert not content["data"]["draftOrderCreate"]["errors"]
+ data = content["data"]["draftOrderCreate"]["order"]
+ assert data["status"] == OrderStatus.DRAFT.upper()
+ assert data["voucher"]["code"] == voucher.code
+ assert data["customerNote"] == customer_note
+
+ order = Order.objects.first()
+ assert order.user == customer_user
+ assert order.channel.id == channel_USD.id
+ # billing address should be copied
+ assert not order.billing_address
+ assert order.shipping_method == shipping_method
+ assert order.shipping_address.first_name == graphql_address_data["firstName"]
+ assert order.base_shipping_price == Money(0, "USD")
# Ensure the correct event was created
created_draft_event = OrderEvent.objects.get(
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 89ad8a1ba5..507688b8f7 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
@@ -1,5 +1,8 @@
import graphene
+from prices import TaxedMoney
+from .....core.prices import quantize_price
+from .....core.taxes import zero_money
from .....order import OrderStatus
from .....order.error_codes import OrderErrorCode
from .....order.models import OrderEvent
@@ -489,3 +492,114 @@ def test_draft_order_update_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."
+
+
+DRAFT_ORDER_UPDATE_MUTATION_SHIPPING_METHOD = """
+ mutation draftUpdate($id: ID!, $shippingMethod: ID){
+ draftOrderUpdate(
+ id: $id,
+ input: {
+ shippingMethod: $shippingMethod
+ }) {
+ errors {
+ field
+ message
+ code
+ }
+ order {
+ shippingMethodName
+ shippingPrice {
+ net {
+ amount
+ }
+ gross {
+ amount
+ }
+ }
+ userEmail
+ }
+ }
+ }
+"""
+
+
+def test_draft_order_update_shipping_method(
+ staff_api_client, permission_manage_orders, draft_order, shipping_method
+):
+ # given
+ order = draft_order
+ order.shipping_method = None
+ order.base_shipping_price = zero_money(order.currency)
+ order.save()
+
+ query = DRAFT_ORDER_UPDATE_MUTATION_SHIPPING_METHOD
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ variables = {
+ "id": order_id,
+ "shippingMethod": method_id,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ order.refresh_from_db()
+
+ shipping_total = shipping_method.channel_listings.get(
+ channel_id=order.channel_id
+ ).get_total()
+ shipping_price = TaxedMoney(shipping_total, shipping_total)
+
+ data = content["data"]["draftOrderUpdate"]
+ assert not data["errors"]
+
+ assert data["order"]["shippingMethodName"] == shipping_method.name
+ assert data["order"]["shippingPrice"]["net"]["amount"] == quantize_price(
+ shipping_price.net.amount, shipping_price.currency
+ )
+ assert data["order"]["shippingPrice"]["gross"]["amount"] == quantize_price(
+ shipping_price.gross.amount, shipping_price.currency
+ )
+
+ assert order.base_shipping_price == shipping_total
+ assert order.shipping_method == shipping_method
+ assert order.base_shipping_price == shipping_total
+ assert order.shipping_price_net == shipping_price.net
+ assert order.shipping_price_gross == shipping_price.gross
+
+
+def test_draft_order_update_no_shipping_method_channel_listings(
+ staff_api_client, permission_manage_orders, draft_order, shipping_method
+):
+ # given
+ order = draft_order
+ order.shipping_method = None
+ order.base_shipping_price = zero_money(order.currency)
+ order.save()
+
+ shipping_method.channel_listings.all().delete()
+
+ query = DRAFT_ORDER_UPDATE_MUTATION_SHIPPING_METHOD
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ variables = {
+ "id": order_id,
+ "shippingMethod": method_id,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderUpdate"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name
+ assert errors[0]["field"] == "shippingMethod"
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 4969835b37..f3afae3bbd 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -981,9 +981,6 @@ class Order(ModelObjectType[models.Order]):
undiscounted_total = graphene.Field(
TaxedMoney, description="Undiscounted total amount of the order.", required=True
)
- shipping_price = graphene.Field(
- TaxedMoney, description="Total price of shipping.", required=True
- )
shipping_method = graphene.Field(
ShippingMethod,
description="Shipping method for this order.",