Skip to content

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

Update order mutations - explicitly save changed fields in DraftOrderUpdate, do not call `DRAFT_ORDER_UPDATED` event when nothing changed (#17532)

Iga Karbowiak108b6173db56
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f955f75dbe..f3c1b082e5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -39,6 +39,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Queries: `orders`, `draftOrders` and `me.orders` will no longer trigger external calls to calculate taxes: the `ORDER_CALCULATE_TAXES` webhooks and plugins (including AvataxPlugin) - #17421 by @korycins
- Queries: `orders`, `draftOrders` and `me.orders` will no longer trigger external calls to filter the available shipping methods (`ORDER_FILTER_SHIPPING_METHODS`) - #17425 by @korycins
- Drop `change_user_address` method from plugin manager - #17495 by @IKarbowiak
+- `DraftOrderUpdate` do not call `DRAFT_ORDER_UPDATED` anymore in case nothing changed - #17532 by @IKarbowiak
- `OrderUpdate` mutation do not call `ORDER_UPDATED` anymore in case nothing changed - #17507 by @IKarbowiak
### GraphQL API
diff --git a/saleor/graphql/order/mutations/draft_order_cleaner.py b/saleor/graphql/order/mutations/draft_order_cleaner.py
new file mode 100644
index 0000000000..08fe397318
--- /dev/null
+++ b/saleor/graphql/order/mutations/draft_order_cleaner.py
@@ -0,0 +1,132 @@
+from django.core.exceptions import ValidationError
+
+from ....channel.models import Channel
+from ....core.utils.url import validate_storefront_url
+from ....discount.models import Voucher, VoucherCode
+from ....discount.utils.voucher import (
+ get_active_voucher_code,
+ get_voucher_code_instance,
+)
+from ....order.error_codes import OrderErrorCode
+
+
+def clean_redirect_url(redirect_url: str, cleaned_input: dict):
+ if not redirect_url:
+ return
+
+ try:
+ validate_storefront_url(redirect_url)
+ except ValidationError as e:
+ e.code = OrderErrorCode.INVALID.value
+ raise ValidationError({"redirect_url": e}) from e
+
+ cleaned_input["redirect_url"] = redirect_url
+
+
+def clean_voucher_and_voucher_code(channel: "Channel", cleaned_input: dict):
+ voucher = cleaned_input.get("voucher", None)
+ voucher_code = cleaned_input.get("voucher_code", None)
+ if voucher and voucher_code:
+ raise ValidationError(
+ {
+ "voucher": ValidationError(
+ "You cannot use both a voucher and a voucher code for the same "
+ "order. Please choose one.",
+ code=OrderErrorCode.INVALID.value,
+ )
+ }
+ )
+
+ if "voucher" in cleaned_input:
+ clean_voucher(voucher, channel, cleaned_input)
+ elif "voucher_code" in cleaned_input:
+ clean_voucher_code(voucher_code, channel, cleaned_input)
+
+
+def clean_voucher(voucher: Voucher | None, channel: Channel, cleaned_input: dict):
+ # We need to clean voucher_code as well
+ if voucher is None:
+ cleaned_input["voucher_code"] = None
+ return
+
+ if isinstance(voucher, VoucherCode):
+ raise ValidationError(
+ {
+ "voucher": ValidationError(
+ "You cannot use voucherCode in the voucher input. "
+ "Please use voucherCode input instead with a valid voucher code.",
+ code=OrderErrorCode.INVALID_VOUCHER.value,
+ )
+ }
+ )
+
+ code_instance = None
+ if channel.include_draft_order_in_voucher_usage:
+ # Validate voucher when it's included in voucher usage calculation
+ try:
+ code_instance = get_active_voucher_code(voucher, channel.slug)
+ except ValidationError as e:
+ raise ValidationError(
+ {
+ "voucher": ValidationError(
+ "Voucher is invalid.",
+ code=OrderErrorCode.INVALID_VOUCHER.value,
+ )
+ }
+ ) from e
+ else:
+ clean_voucher_listing(voucher, channel, "voucher")
+ if not code_instance:
+ code_instance = voucher.codes.first()
+ if code_instance:
+ cleaned_input["voucher_code"] = code_instance.code
+ cleaned_input["voucher_code_instance"] = code_instance
+
+
+def clean_voucher_code(voucher_code: str | None, channel: Channel, cleaned_input: dict):
+ # We need to clean voucher instance as well
+ if voucher_code is None:
+ cleaned_input["voucher"] = None
+ return
+ if channel.include_draft_order_in_voucher_usage:
+ # Validate voucher when it's included in voucher usage calculation
+ try:
+ code_instance = get_voucher_code_instance(voucher_code, channel.slug)
+ except ValidationError as e:
+ raise ValidationError(
+ {
+ "voucher_code": ValidationError(
+ "Voucher code is invalid.",
+ code=OrderErrorCode.INVALID_VOUCHER_CODE.value,
+ )
+ }
+ ) from e
+ voucher = code_instance.voucher
+ else:
+ code_instance = VoucherCode.objects.filter(code=voucher_code).first()
+ if not code_instance:
+ raise ValidationError(
+ {
+ "voucher": ValidationError(
+ "Invalid voucher code.",
+ code=OrderErrorCode.INVALID_VOUCHER_CODE.value,
+ )
+ }
+ )
+ voucher = code_instance.voucher
+ clean_voucher_listing(voucher, channel, "voucher_code")
+ cleaned_input["voucher"] = voucher
+ cleaned_input["voucher_code"] = voucher_code
+ cleaned_input["voucher_code_instance"] = code_instance
+
+
+def clean_voucher_listing(voucher: "Voucher", channel: "Channel", field: str):
+ if not voucher.channel_listings.filter(channel=channel).exists():
+ raise ValidationError(
+ {
+ field: ValidationError(
+ "Voucher not available for this order.",
+ code=OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.value,
+ )
+ }
+ )
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index ddd427a8d8..f9f854acac 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -7,14 +7,9 @@ from ....account.models import User
from ....checkout import AddressType
from ....core.taxes import TaxError
from ....core.tracing import traced_atomic_transaction
-from ....core.utils.url import validate_storefront_url
-from ....discount.models import Voucher, VoucherCode
from ....discount.utils.voucher import (
create_or_update_voucher_discount_objects_for_order,
- get_active_voucher_code,
- get_voucher_code_instance,
increase_voucher_usage,
- release_voucher_code_usage,
)
from ....order import OrderOrigin, OrderStatus, events, models
from ....order.actions import call_order_event
@@ -32,7 +27,6 @@ from ...account.i18n import I18nMixin
from ...account.mixins import AddressMetadataMixin
from ...account.types import AddressInput
from ...app.dataloaders import get_app_promise
-from ...channel.types import Channel
from ...core import ResolveInfo
from ...core.context import SyncWebhookControlContext
from ...core.descriptions import (
@@ -55,10 +49,11 @@ from ..utils import (
validate_product_is_published_in_channel,
validate_variant_channel_listings,
)
+from . import draft_order_cleaner
from .utils import (
- SHIPPING_METHOD_UPDATE_FIELDS,
ShippingMethodUpdateMixin,
get_variant_rule_info_map,
+ save_addresses,
)
@@ -186,7 +181,6 @@ class DraftOrderCreateInput(DraftOrderInput):
class DraftOrderCreate(
AddressMetadataMixin,
ModelWithRestrictedChannelAccessMutation,
- ShippingMethodUpdateMixin,
I18nMixin,
):
class Arguments:
@@ -206,9 +200,6 @@ class DraftOrderCreate(
@classmethod
def get_instance_channel_id(cls, instance, **data):
- if channel_id := instance.channel_id:
- return channel_id
-
channel_id = data["input"].get("channel_id")
if not channel_id:
raise ValidationError(
@@ -229,9 +220,8 @@ class DraftOrderCreate(
shipping_address = data.pop("shipping_address", None)
billing_address = data.pop("billing_address", None)
redirect_url = data.pop("redirect_url", None)
- channel_id = data.pop("channel_id", None)
- manager = get_plugin_manager_promise(info.context).get()
shipping_method_input = {}
+ manager = get_plugin_manager_promise(info.context).get()
if "shipping_method" in data:
shipping_method_input["shipping_method"] = get_shipping_model_by_object_id(
object_id=data.pop("shipping_method", None),
@@ -247,15 +237,13 @@ class DraftOrderCreate(
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)
- voucher_code = cleaned_input.get("voucher_code", None)
- cls.clean_voucher_and_voucher_code(voucher, voucher_code)
- if "voucher" in cleaned_input:
- cls.clean_voucher(voucher, channel, cleaned_input)
- elif "voucher_code" in cleaned_input:
- cls.clean_voucher_code(voucher_code, channel, cleaned_input)
+ # channel ID is required for draft order creation
+ # if not provided get_instance_channel_id will raise a validation error
+ channel = cleaned_input.pop("channel_id")
+ cleaned_input["channel"] = channel
+
+ draft_order_cleaner.clean_voucher_and_voucher_code(channel, cleaned_input)
if channel:
cleaned_input["currency"] = channel.currency_code
@@ -269,129 +257,59 @@ class DraftOrderCreate(
info, instance, cleaned_input, shipping_address, billing_address, manager
)
- if redirect_url:
- cls.clean_redirect_url(redirect_url)
- cleaned_input["redirect_url"] = redirect_url
+ draft_order_cleaner.clean_redirect_url(redirect_url, cleaned_input)
return cleaned_input
@classmethod
- def clean_channel_id(cls, info: ResolveInfo, instance, cleaned_input, channel_id):
- if channel_id:
- if hasattr(instance, "channel"):
- raise ValidationError(
- {
- "channel_id": ValidationError(
- "Can't update existing order channel id.",
- code=OrderErrorCode.NOT_EDITABLE.value,
- )
- }
- )
- channel = cls.get_node_or_error(info, channel_id, only_type=Channel)
- cleaned_input["channel"] = channel
- return channel
- return instance.channel if hasattr(instance, "channel") else None
-
- @classmethod
- def clean_voucher_and_voucher_code(cls, voucher, voucher_code):
- if voucher and voucher_code:
- raise ValidationError(
- {
- "voucher": ValidationError(
- "You cannot use both a voucher and a voucher code for the same "
- "order. Please choose one.",
- code=OrderErrorCode.INVALID.value,
- )
- }
+ def clean_addresses(
+ cls,
+ info: ResolveInfo,
+ instance,
+ cleaned_input,
+ shipping_address,
+ billing_address,
+ manager,
+ ):
+ save_shipping_address = cleaned_input.get("save_shipping_address")
+ save_billing_address = cleaned_input.get("save_billing_address")
+ if shipping_address:
+ shipping_address = cls.validate_address(
+ shipping_address,
+ address_type=AddressType.SHIPPING,
+ instance=instance.shipping_address,
+ info=info,
)
-
- @classmethod
- def clean_voucher(cls, voucher, channel, cleaned_input):
- # We need to clean voucher_code as well
- if voucher is None:
- cleaned_input["voucher_code"] = None
- return
-
- if isinstance(voucher, VoucherCode):
+ cleaned_input["shipping_address"] = shipping_address
+ cleaned_input["draft_save_shipping_address"] = (
+ save_shipping_address or False
+ )
+ elif save_shipping_address is not None:
raise ValidationError(
{
- "voucher": ValidationError(
- "You cannot use voucherCode in the voucher input. "
- "Please use voucherCode input instead with a valid voucher code.",
- code=OrderErrorCode.INVALID_VOUCHER.value,
+ "save_shipping_address": ValidationError(
+ "This option can only be selected if a shipping address "
+ "is provided.",
+ code=OrderErrorCode.MISSING_ADDRESS_DATA.value,
)
}
)
-
- code_instance = None
- if channel.include_draft_order_in_voucher_usage:
- # Validate voucher when it's included in voucher usage calculation
- try:
- code_instance = get_active_voucher_code(voucher, channel.slug)
- except ValidationError as e:
- raise ValidationError(
- {
- "voucher": ValidationError(
- "Voucher is invalid.",
- code=OrderErrorCode.INVALID_VOUCHER.value,
- )
- }
- ) from e
- else:
- cls.clean_voucher_listing(voucher, channel, "voucher")
- if not code_instance:
- code_instance = voucher.codes.first()
- if code_instance:
- cleaned_input["voucher_code"] = code_instance.code
- cleaned_input["voucher_code_instance"] = code_instance
-
- @classmethod
- def clean_voucher_code(
- cls, voucher_code: str | None, channel: Channel, cleaned_input: dict
- ):
- # We need to clean voucher instance as well
- if voucher_code is None:
- cleaned_input["voucher"] = None
- return
- if channel.include_draft_order_in_voucher_usage:
- # Validate voucher when it's included in voucher usage calculation
- try:
- code_instance = get_voucher_code_instance(voucher_code, channel.slug)
- except ValidationError as e:
- raise ValidationError(
- {
- "voucher_code": ValidationError(
- "Voucher code is invalid.",
- code=OrderErrorCode.INVALID_VOUCHER_CODE.value,
- )
- }
- ) from e
- voucher = code_instance.voucher
- else:
- code_instance = VoucherCode.objects.filter(code=voucher_code).first()
- if not code_instance:
- raise ValidationError(
- {
- "voucher": ValidationError(
- "Invalid voucher code.",
- code=OrderErrorCode.INVALID_VOUCHER_CODE.value,
- )
- }
- )
- voucher = code_instance.voucher
- cls.clean_voucher_listing(voucher, channel, "voucher_code")
- cleaned_input["voucher"] = voucher
- cleaned_input["voucher_code"] = voucher_code
- cleaned_input["voucher_code_instance"] = code_instance
-
- @classmethod
- def clean_voucher_listing(cls, voucher: "Voucher", channel: "Channel", field: str):
- if not voucher.channel_listings.filter(channel=channel).exists():
+ if billing_address:
+ billing_address = cls.validate_address(
+ billing_address,
+ address_type=AddressType.BILLING,
+ instance=instance.billing_address,
+ info=info,
+ )
+ cleaned_input["billing_address"] = billing_address
+ cleaned_input["draft_save_billing_address"] = save_billing_address or False
+ elif save_billing_address is not None:
raise ValidationError(
{
- field: ValidationError(
- "Voucher not available for this order.",
- code=OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.value,
+ "save_billing_address": ValidationError(
+ "This option can only be selected if a billing address "
+ "is provided.",
+ code=OrderErrorCode.MISSING_ADDRESS_DATA.value,
)
}
)
@@ -448,78 +366,6 @@ class DraftOrderCreate(
grouped_lines_data += list(lines_data_map.values())
cleaned_input["lines_data"] = grouped_lines_data
- @classmethod
- def clean_addresses(
- cls,
- info: ResolveInfo,
- instance,
- cleaned_input,
- shipping_address,
- billing_address,
- manager,
- ):
- save_shipping_address = cleaned_input.get("save_shipping_address")
- save_billing_address = cleaned_input.get("save_billing_address")
- if shipping_address:
- shipping_address = cls.validate_address(
- shipping_address,
- address_type=AddressType.SHIPPING,
- instance=instance.shipping_address,
- info=info,
- )
- cleaned_input["shipping_address"] = shipping_address
- cleaned_input["draft_save_shipping_address"] = (
- save_shipping_address or False
- )
- elif save_shipping_address is not None:
- raise ValidationError(
- {
- "save_shipping_address": ValidationError(
- "This option can only be selected if a shipping address "
- "is provided.",
- code=OrderErrorCode.MISSING_ADDRESS_DATA.value,
- )
- }
- )
- if billing_address:
- billing_address = cls.validate_address(
- billing_address,
- address_type=AddressType.BILLING,
- instance=instance.billing_address,
- info=info,
- )
- cleaned_input["billing_address"] = billing_address
- cleaned_input["draft_save_billing_address"] = save_billing_address or False
- elif save_billing_address is not None:
- raise ValidationError(
- {
- "save_billing_address": ValidationError(
- "This option can only be selected if a billing address "
- "is provided.",
- code=OrderErrorCode.MISSING_ADDRESS_DATA.value,
- )
- }
- )
-
- @classmethod
- def clean_redirect_url(cls, redirect_url):
- try:
- validate_storefront_url(redirect_url)
- except ValidationError as e:
- e.code = OrderErrorCode.INVALID.value
- raise ValidationError({"redirect_url": e}) from e
-
- @staticmethod
- def _save_addresses(instance: models.Order, cleaned_input):
- shipping_address = cleaned_input.get("shipping_address")
- if shipping_address:
- shipping_address.save()
- instance.shipping_address = shipping_address.get_copy()
- billing_address = cleaned_input.get("billing_address")
- if billing_address:
- billing_address.save()
- instance.billing_address = billing_address.get_copy()
-
@staticmethod
def _save_lines(info, instance, lines_data, app, manager):
if lines_data:
@@ -540,54 +386,14 @@ class DraftOrderCreate(
order_lines=lines,
)
- @classmethod
- def _commit_changes(
- cls, info: ResolveInfo, instance, cleaned_input, is_new_instance, app
- ):
- super().save(info, instance, cleaned_input)
-
- # Create draft created event if the instance is from scratch
- if is_new_instance:
- events.draft_order_created_event(
- order=instance, user=info.context.user, app=app
- )
-
- @classmethod
- def should_invalidate_prices(cls, cleaned_input, is_new_instance) -> bool:
- # Force price recalculation for all new instances
- return is_new_instance
-
@classmethod
def save(cls, info: ResolveInfo, instance, cleaned_input):
manager = get_plugin_manager_promise(info.context).get()
app = get_app_promise(info.context).get()
- return cls._save_draft_order(
- info,
- instance,
- cleaned_input,
- is_new_instance=True,
- app=app,
- manager=manager,
- )
- @classmethod
- def _save_draft_order(
- cls,
- info: ResolveInfo,
- instance,
- cleaned_input,
- *,
- is_new_instance,
- app,
- manager,
- old_voucher=None,
- old_voucher_code=None,
- ):
- updated_fields = []
with traced_atomic_transaction():
- shipping_channel_listing = None
# Process addresses
- cls._save_addresses(instance, cleaned_input)
+ save_addresses(instance, cleaned_input)
try:
# Process any lines to add
@@ -603,80 +409,46 @@ class DraftOrderCreate(
if "shipping_method" in cleaned_input:
method = cleaned_input["shipping_method"]
if method is None:
- cls.clear_shipping_method_from_order(instance)
+ ShippingMethodUpdateMixin.clear_shipping_method_from_order(instance)
else:
- shipping_channel_listing = cls.validate_shipping_channel_listing(
- method, instance
+ ShippingMethodUpdateMixin.process_shipping_method(
+ instance, method, manager, update_shipping_discount=False
)
- cls.update_shipping_method(instance, method)
- cls.assign_shipping_price(instance, shipping_channel_listing)
- # for new instance the shipping discount is created later
- if not is_new_instance:
- cls.update_shipping_discount(instance)
-
- updated_fields.extend(SHIPPING_METHOD_UPDATE_FIELDS)
if instance.undiscounted_base_shipping_price_amount is None:
instance.undiscounted_base_shipping_price_amount = (
instance.base_shipping_price_amount
)
- updated_fields.append("undiscounted_base_shipping_price_amount")
if "voucher" in cleaned_input:
cls.handle_order_voucher(
cleaned_input,
instance,
- is_new_instance,
- old_voucher,
- old_voucher_code,
)
- # Save any changes create/update the draft
- cls._commit_changes(info, instance, cleaned_input, is_new_instance, app)
-
update_order_display_gross_prices(instance)
-
- # Post-process the results
- updated_fields.extend(
- [
- "weight",
- "search_vector",
- "updated_at",
- "display_gross_prices",
- ]
- )
- if cls.should_invalidate_prices(cleaned_input, is_new_instance):
- invalidate_order_prices(instance)
- updated_fields.extend(["should_refresh_prices"])
+ invalidate_order_prices(instance)
recalculate_order_weight(instance)
update_order_search_vector(instance, save=False)
- instance.save(update_fields=updated_fields)
- if is_new_instance:
- call_order_event(
- manager,
- WebhookEventAsyncType.DRAFT_ORDER_CREATED,
- instance,
- )
- else:
- call_order_event(
- manager,
- WebhookEventAsyncType.DRAFT_ORDER_UPDATED,
- instance,
- )
+ instance.save()
+
+ events.draft_order_created_event(
+ order=instance, user=info.context.user, app=app
+ )
+ call_order_event(
+ manager,
+ WebhookEventAsyncType.DRAFT_ORDER_CREATED,
+ instance,
+ )
@classmethod
def handle_order_voucher(
cls,
cleaned_input,
instance: models.Order,
- is_new_instance: bool,
- old_voucher: Voucher | None,
- old_voucher_code: str | None,
):
voucher = cleaned_input["voucher"]
- if voucher is None and old_voucher is None:
- return
# create or update voucher discount object
create_or_update_voucher_discount_objects_for_order(instance)
@@ -698,10 +470,6 @@ class DraftOrderCreate(
user_email,
increase_voucher_customer_usage=False,
)
- elif not is_new_instance and old_voucher:
- # handle removing voucher
- voucher_code = VoucherCode.objects.filter(code=old_voucher_code).first()
- release_voucher_code_usage(voucher_code, old_voucher, user_email)
@classmethod
def success_response(cls, order):
diff --git a/saleor/graphql/order/mutations/draft_order_update.py b/saleor/graphql/order/mutations/draft_order_update.py
index 6b0882310e..94ee108e53 100644
--- a/saleor/graphql/order/mutations/draft_order_update.py
+++ b/saleor/graphql/order/mutations/draft_order_update.py
@@ -1,21 +1,53 @@
import graphene
from django.core.exceptions import ValidationError
+from ....account.models import User
+from ....checkout import AddressType
+from ....core.tracing import traced_atomic_transaction
+from ....discount.models import VoucherCode
+from ....discount.utils.voucher import (
+ create_or_update_voucher_discount_objects_for_order,
+ increase_voucher_usage,
+ release_voucher_code_usage,
+)
from ....order import OrderStatus, models
+from ....order.actions import call_order_event
from ....order.error_codes import OrderErrorCode
+from ....order.search import update_order_search_vector
+from ....order.utils import (
+ invalidate_order_prices,
+ update_order_display_gross_prices,
+)
from ....permission.enums import OrderPermissions
-from ...app.dataloaders import get_app_promise
+from ....webhook.event_types import WebhookEventAsyncType
+from ...account.i18n import I18nMixin
+from ...account.mixins import AddressMetadataMixin
from ...core import ResolveInfo
from ...core.context import SyncWebhookControlContext
-from ...core.mutations import ModelWithExtRefMutation
+from ...core.mutations import (
+ ModelWithExtRefMutation,
+ ModelWithRestrictedChannelAccessMutation,
+)
from ...core.types import OrderError
from ...meta.inputs import MetadataInput
from ...plugins.dataloaders import get_plugin_manager_promise
+from ...shipping.utils import get_shipping_model_by_object_id
from ..types import Order
-from .draft_order_create import DraftOrderCreate, DraftOrderInput
+from . import draft_order_cleaner
+from .draft_order_create import DraftOrderInput
+from .utils import (
+ SHIPPING_METHOD_UPDATE_FIELDS,
+ ShippingMethodUpdateMixin,
+ save_addresses,
+)
-class DraftOrderUpdate(DraftOrderCreate, ModelWithExtRefMutation):
+class DraftOrderUpdate(
+ AddressMetadataMixin,
+ ModelWithRestrictedChannelAccessMutation,
+ ModelWithExtRefMutation,
+ I18nMixin,
+):
class Arguments:
id = graphene.ID(required=False, description="ID of a draft order to update.")
external_reference = graphene.String(
@@ -66,18 +98,221 @@ class DraftOrderUpdate(DraftOrderCreate, ModelWithExtRefMutation):
)
@classmethod
- def save(cls, info: ResolveInfo, instance, cleaned_input):
+ def clean_input(
+ cls, info: ResolveInfo, instance: models.Order, data: dict, **kwargs
+ ):
+ cls.clean_channel_id(instance, data)
manager = get_plugin_manager_promise(info.context).get()
- app = get_app_promise(info.context).get()
- return cls._save_draft_order(
- info,
- instance,
- cleaned_input,
- is_new_instance=False,
- app=app,
- manager=manager,
+ shipping_address = data.pop("shipping_address", None)
+ billing_address = data.pop("billing_address", None)
+ redirect_url = data.pop("redirect_url", None)
+
+ 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),
+ error_field="shipping_method",
+ )
+
+ if email := data.get("user_email", None):
+ try:
+ user = User.objects.get(email=email, is_active=True)
+ data["user"] = graphene.Node.to_global_id("User", user.id)
+ except User.DoesNotExist:
+ data["user"] = None
+
+ cleaned_input = super().clean_input(info, instance, data, **kwargs)
+
+ cleaned_input.update(shipping_method_input)
+
+ channel = instance.channel or cleaned_input.get("channel_id")
+ draft_order_cleaner.clean_voucher_and_voucher_code(channel, cleaned_input)
+
+ cls.clean_addresses(
+ info, instance, cleaned_input, shipping_address, billing_address, manager
)
+ draft_order_cleaner.clean_redirect_url(redirect_url, cleaned_input)
+
+ return cleaned_input
+
+ @classmethod
+ def clean_channel_id(cls, instance, data):
+ if data.get("channel_id"):
+ if hasattr(instance, "channel"):
+ raise ValidationError(
+ {
+ "channel_id": ValidationError(
+ "Can't update existing order channel id.",
+ code=OrderErrorCode.NOT_EDITABLE.value,
+ )
+ }
+ )
+
+ @classmethod
+ def clean_addresses(
+ cls,
+ info: ResolveInfo,
+ instance,
+ cleaned_input,
+ shipping_address,
+ billing_address,
+ manager,
+ ):
+ save_shipping_address = cleaned_input.get("save_shipping_address")
+ save_billing_address = cleaned_input.get("save_billing_address")
+ if shipping_address:
+ shipping_address = cls.validate_address(
+ shipping_address,
+ address_type=AddressType.SHIPPING,
+ instance=instance.shipping_address,
+ info=info,
+ )
+ cleaned_input["shipping_address"] = shipping_address
+ cleaned_input["draft_save_shipping_address"] = (
+ save_shipping_address or False
+ )
+ elif save_shipping_address is not None:
+ raise ValidationError(
+ {
+ "save_shipping_address": ValidationError(
+ "This option can only be selected if a shipping address "
+ "is provided.",
+ code=OrderErrorCode.MISSING_ADDRESS_DATA.value,
+ )
+ }
+ )
+ if billing_address:
+ billing_address = cls.validate_address(
+ billing_address,
+ address_type=AddressType.BILLING,
+ instance=instance.billing_address,
+ info=info,
+ )
+ cleaned_input["billing_address"] = billing_address
+ cleaned_input["draft_save_billing_address"] = save_billing_address or False
+ elif save_billing_address is not None:
+ raise ValidationError(
+ {
+ "save_billing_address": ValidationError(
+ "This option can only be selected if a billing address "
+ "is provided.",
+ code=OrderErrorCode.MISSING_ADDRESS_DATA.value,
+ )
+ }
+ )
+
+ @classmethod
+ def _save(
+ cls,
+ info: ResolveInfo,
+ instance,
+ cleaned_input,
+ old_voucher,
+ old_voucher_code,
+ changed_fields,
+ ):
+ updated_fields = changed_fields
+ manager = get_plugin_manager_promise(info.context).get()
+ with traced_atomic_transaction():
+ # Process addresses
+ address_fields = save_addresses(instance, cleaned_input)
+ updated_fields.extend(address_fields)
+
+ if "shipping_method" in cleaned_input:
+ method = cleaned_input["shipping_method"]
+ if method is None:
+ ShippingMethodUpdateMixin.clear_shipping_method_from_order(instance)
+ else:
+ ShippingMethodUpdateMixin.process_shipping_method(
+ instance, method, manager, update_shipping_discount=True
+ )
+ updated_fields.extend(SHIPPING_METHOD_UPDATE_FIELDS)
+
+ if instance.undiscounted_base_shipping_price_amount is None:
+ instance.undiscounted_base_shipping_price_amount = (
+ instance.base_shipping_price_amount
+ )
+ updated_fields.append("undiscounted_base_shipping_price_amount")
+
+ if "voucher" in cleaned_input:
+ cls.handle_order_voucher(
+ cleaned_input,
+ instance,
+ old_voucher,
+ old_voucher_code,
+ )
+
+ # In case nothing change, do not update perform post-process actions;
+ # do not call the `DRAFT_ORDER_UPDATED` event.
+ if not updated_fields:
+ return
+
+ if (
+ "shipping_address" in updated_fields
+ or "billing_address" in updated_fields
+ ):
+ update_order_display_gross_prices(instance)
+ updated_fields.append("display_gross_prices")
+
+ update_order_search_vector(instance, save=False)
+ # Post-process the results
+ updated_fields.extend(
+ [
+ "search_vector",
+ "updated_at",
+ ]
+ )
+
+ if cls.should_invalidate_prices(cleaned_input):
+ invalidate_order_prices(instance)
+ updated_fields.extend(["should_refresh_prices"])
+
+ instance.save(update_fields=updated_fields)
+
+ call_order_event(
+ manager,
+ WebhookEventAsyncType.DRAFT_ORDER_UPDATED,
+ instance,
+ )
+
+ @classmethod
+ def handle_order_voucher(
+ cls,
+ cleaned_input,
+ instance: models.Order,
+ old_voucher,
+ old_voucher_code,
+ ):
+ voucher = cleaned_input["voucher"]
+ if voucher is None and old_voucher is None:
+ return
+
+ # create or update voucher discount object
+ create_or_update_voucher_discount_objects_for_order(instance)
+
+ # handle voucher usage
+ user_email = instance.user_email
+ if not user_email and instance.user:
+ user_email = instance.user.email
+
+ channel = instance.channel
+ if not channel.include_draft_order_in_voucher_usage:
+ return
+
+ if voucher:
+ code_instance = cleaned_input.pop("voucher_code_instance", None)
+ increase_voucher_usage(
+ voucher,
+ code_instance,
+ user_email,
+ increase_voucher_customer_usage=False,
+ )
+ elif old_voucher:
+ # handle removing voucher
+ voucher_code = VoucherCode.objects.filter(code=old_voucher_code).first()
+ release_voucher_code_usage(voucher_code, old_voucher, user_email)
+
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
instance = cls.get_instance(info, **data)
@@ -85,10 +320,10 @@ class DraftOrderUpdate(DraftOrderCreate, ModelWithExtRefMutation):
cls.check_channel_permissions(info, [channel_id])
+ old_instance_data = instance.serialize_for_comparison()
old_voucher = instance.voucher
old_voucher_code = instance.voucher_code
- data = data.get("input")
-
+ data = data["input"]
cleaned_input = cls.clean_input(info, instance, data)
metadata_list: list[MetadataInput] = cleaned_input.pop("metadata", None)
private_metadata_list: list[MetadataInput] = cleaned_input.pop(
@@ -108,26 +343,21 @@ class DraftOrderUpdate(DraftOrderCreate, ModelWithExtRefMutation):
instance, metadata_collection, private_metadata_collection
)
cls.clean_instance(info, instance)
- cls.save_draft_order(
- info, instance, cleaned_input, old_voucher, old_voucher_code
+ new_instance_data = instance.serialize_for_comparison()
+ changed_fields = cls.diff_instance_data_fields(
+ instance.comparison_fields,
+ old_instance_data,
+ new_instance_data,
+ )
+ cls._save(
+ info, instance, cleaned_input, old_voucher, old_voucher_code, changed_fields
)
cls._save_m2m(info, instance, cleaned_input)
return DraftOrderUpdate(order=SyncWebhookControlContext(node=instance))
@classmethod
- def save_draft_order(
- cls, info: ResolveInfo, instance, cleaned_input, old_voucher, old_voucher_code
- ):
- manager = get_plugin_manager_promise(info.context).get()
- app = get_app_promise(info.context).get()
- return cls._save_draft_order(
- info,
- instance,
- cleaned_input,
- is_new_instance=False,
- app=app,
- manager=manager,
- old_voucher=old_voucher,
- old_voucher_code=old_voucher_code,
- )
+ def get_instance_channel_id(cls, instance, **data):
+ if channel_id := instance.channel_id:
+ return channel_id
+ return None
diff --git a/saleor/graphql/order/mutations/order_update_shipping.py b/saleor/graphql/order/mutations/order_update_shipping.py
index 5d2bf5eb3e..05c93d553f 100644
--- a/saleor/graphql/order/mutations/order_update_shipping.py
+++ b/saleor/graphql/order/mutations/order_update_shipping.py
@@ -3,12 +3,11 @@ from typing import cast
import graphene
from django.core.exceptions import ValidationError
-from ....order import OrderStatus, models
+from ....order import models
from ....order.actions import call_order_event
from ....order.error_codes import OrderErrorCode
from ....permission.enums import OrderPermissions
from ....shipping import models as shipping_models
-from ....shipping.utils import convert_to_shipping_method_data
from ....webhook.deprecated_event_types import WebhookEventType
from ....webhook.event_types import WebhookEventAsyncType
from ...core import ResolveInfo
@@ -23,7 +22,6 @@ from .utils import (
SHIPPING_METHOD_UPDATE_FIELDS,
EditableOrderValidationMixin,
ShippingMethodUpdateMixin,
- clean_order_update_shipping,
)
@@ -38,9 +36,7 @@ class OrderUpdateShippingInput(BaseInputObjectType):
doc_category = DOC_CATEGORY_ORDERS
-class OrderUpdateShipping(
- EditableOrderValidationMixin, ShippingMethodUpdateMixin, BaseMutation
-):
+class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
order = graphene.Field(Order, description="Order with updated shipping method.")
class Arguments:
@@ -125,7 +121,7 @@ class OrderUpdateShipping(
}
)
- cls.clear_shipping_method_from_order(order)
+ ShippingMethodUpdateMixin.clear_shipping_method_from_order(order)
order.save(update_fields=SHIPPING_METHOD_UPDATE_FIELDS)
call_order_event(manager, event_to_emit, order)
@@ -142,18 +138,10 @@ class OrderUpdateShipping(
"postal_code_rules"
),
)
- 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()
+ ShippingMethodUpdateMixin.process_shipping_method(
+ order, method, manager, update_shipping_discount=True
)
-
- if order.status != OrderStatus.DRAFT:
- clean_order_update_shipping(order, shipping_method_data, manager)
- cls.update_shipping_method(order, method)
- cls.update_shipping_price(order, shipping_channel_listing)
-
order.save(update_fields=SHIPPING_METHOD_UPDATE_FIELDS)
# Post-process the results
diff --git a/saleor/graphql/order/mutations/utils.py b/saleor/graphql/order/mutations/utils.py
index 9526602d54..b9514d309f 100644
--- a/saleor/graphql/order/mutations/utils.py
+++ b/saleor/graphql/order/mutations/utils.py
@@ -18,7 +18,8 @@ from ....payment import models as payment_models
from ....plugins.manager import PluginsManager
from ....product import models as product_models
from ....shipping.interface import ShippingMethodData
-from ....shipping.models import ShippingMethodChannelListing
+from ....shipping.models import ShippingMethod, ShippingMethodChannelListing
+from ....shipping.utils import convert_to_shipping_method_data
from ....webhook.event_types import WebhookEventAsyncType
from ..utils import get_shipping_method_availability_error
@@ -59,9 +60,6 @@ class EditableOrderValidationMixin:
class ShippingMethodUpdateMixin:
- class Meta:
- abstract = True
-
@classmethod
def clear_shipping_method_from_order(cls, order):
order.shipping_method = None
@@ -77,7 +75,7 @@ class ShippingMethodUpdateMixin:
invalidate_order_prices(order)
@classmethod
- def update_shipping_method(cls, order, method):
+ def update_shipping_method(cls, order: models.Order, method: ShippingMethod):
order.shipping_method = method
order.shipping_method_name = method.name
@@ -131,7 +129,7 @@ class ShippingMethodUpdateMixin:
order.undiscounted_base_shipping_price = zero_money(order.currency)
@classmethod
- def update_shipping_discount(cls, order):
+ def update_shipping_discount(cls, order: models.Order):
if shipping_discount := order.discounts.filter(
voucher__type=VoucherType.SHIPPING
).first():
@@ -148,6 +146,27 @@ class ShippingMethodUpdateMixin:
shipping_discount.amount = shipping_discount_amount
shipping_discount.save(update_fields=["amount_value"])
+ @classmethod
+ def process_shipping_method(
+ cls,
+ order: models.Order,
+ method: ShippingMethod,
+ manager: "PluginsManager",
+ update_shipping_discount: bool,
+ ):
+ shipping_channel_listing = cls.validate_shipping_channel_listing(method, order)
+ if order.status != OrderStatus.DRAFT:
+ shipping_method_data = convert_to_shipping_method_data(
+ method,
+ shipping_channel_listing,
+ )
+ clean_order_update_shipping(order, shipping_method_data, manager)
+ cls.update_shipping_method(order, method)
+ cls.assign_shipping_price(order, shipping_channel_listing)
+ # for new instance the shipping discount is created later
+ if update_shipping_discount:
+ cls.update_shipping_discount(order)
+
def clean_order_update_shipping(
order, method: ShippingMethodData, manager: "PluginsManager"
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 06ccdf0b46..5cbdbb74db 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -10,6 +10,7 @@ from django.utils import timezone
from freezegun import freeze_time
from prices import Money
+from .....account.models import Address
from .....checkout import AddressType
from .....core.models import EventDelivery
from .....core.prices import quantize_price
@@ -179,6 +180,8 @@ def test_draft_order_create_with_voucher_entire_order(
{"variantId": variant_0_id, "quantity": variant_0_qty},
{"variantId": variant_1_id, "quantity": variant_1_qty},
]
+
+ address_count = Address.objects.count()
shipping_address = graphql_address_data
shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
@@ -296,6 +299,9 @@ def test_draft_order_create_with_voucher_entire_order(
for line in order_lines:
assert line.is_price_overridden is False
+ # ensure shipping and billing address instances were created
+ assert Address.objects.count() == address_count + 2
+
def test_draft_order_create_with_voucher_and_voucher_code(
staff_api_client,
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 5ccec369ae..8ede259bc4 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
@@ -2350,7 +2350,7 @@ def test_draft_order_update_replace_entire_order_voucher_with_shipping_voucher(
@patch(
- "saleor.graphql.order.mutations.draft_order_create.call_order_event",
+ "saleor.graphql.order.mutations.draft_order_update.call_order_event",
wraps=call_order_event,
)
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -2445,7 +2445,7 @@ def test_draft_order_update_triggers_webhooks(
@patch(
- "saleor.graphql.order.mutations.draft_order_create.call_order_event",
+ "saleor.graphql.order.mutations.draft_order_update.call_order_event",
wraps=call_order_event,
)
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -3035,3 +3035,59 @@ def test_draft_order_update_with_voucher_apply_once_per_order_and_manual_line_di
assert line_1.unit_discount_reason is None
assert discounted_line.discounts.count() == 1
+
+
+@patch(
+ "saleor.graphql.order.mutations.draft_order_update.update_order_search_vector",
+)
+@patch(
+ "saleor.graphql.order.mutations.draft_order_update.call_order_event",
+ wraps=call_order_event,
+)
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
+def test_draft_order_update_nothing_changed(
+ wrapped_call_order_event,
+ mocked_update_order_search_vector,
+ setup_order_webhooks,
+ staff_api_client,
+ permission_group_manage_orders,
+ order_with_lines,
+ settings,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ order.save()
+
+ (
+ tax_webhook,
+ shipping_filter_webhook,
+ draft_order_updated_webhook,
+ ) = setup_order_webhooks(WebhookEventAsyncType.DRAFT_ORDER_UPDATED)
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ query = DRAFT_ORDER_UPDATE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {
+ "id": order_id,
+ "input": {
+ "userEmail": order.user_email,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderUpdate"]
+ assert not data["errors"]
+
+ # ensure the update fields were empty
+ mocked_update_order_search_vector.assert_not_called()
+
+ # confirm that order events were not triggered
+ assert not wrapped_call_order_event.called
+
+ # confirm that event delivery was generated for each async webhook.
+ assert not EventDelivery.objects.filter(webhook_id=draft_order_updated_webhook.id)
diff --git a/saleor/graphql/order/tests/test_utils.py b/saleor/graphql/order/tests/test_utils.py
index 47ec8573d4..e4bfdef8c8 100644
--- a/saleor/graphql/order/tests/test_utils.py
+++ b/saleor/graphql/order/tests/test_utils.py
@@ -1,7 +1,9 @@
import pytest
+from ....account.models import Address
from ....order import OrderStatus
from ....order.utils import invalidate_order_prices
+from ..mutations.utils import save_addresses
@pytest.mark.parametrize(
@@ -44,3 +46,62 @@ def test_invalidate_order_prices_save(order, save, invalid_prices):
assert order.should_refresh_prices
order.refresh_from_db()
assert order.should_refresh_prices is invalid_prices
+
+
+def test_save_addresses_both_addresses(order):
+ # given
+ address_count = Address.objects.count()
+ cleaned_input = {
+ "billing_address": Address(first_name="Billing", last_name="Test"),
+ "shipping_address": Address(first_name="Shipping", last_name="Test"),
+ }
+
+ # when
+ update_fields = save_addresses(order, cleaned_input)
+
+ # then
+ assert set(update_fields) == {"billing_address", "shipping_address"}
+ assert Address.objects.count() == address_count + 2
+
+
+def test_save_addresses_only_billing_address(order):
+ # given
+ address_count = Address.objects.count()
+ cleaned_input = {
+ "billing_address": Address(first_name="Billing", last_name="Test"),
+ }
+
+ # when
+ update_fields = save_addresses(order, cleaned_input)
+
+ # then
+ assert set(update_fields) == {"billing_address"}
+ assert Address.objects.count() == address_count + 1
+
+
+def test_save_addresses_only_shipping_address(order):
+ # given
+ address_count = Address.objects.count()
+ cleaned_input = {
+ "shipping_address": Address(first_name="Shipping", last_name="Test"),
+ }
+
+ # when
+ update_fields = save_addresses(order, cleaned_input)
+
+ # then
+ assert set(update_fields) == {"shipping_address"}
+ assert Address.objects.count() == address_count + 1
+
+
+def test_save_addresses_empty(order):
+ # given
+ address_count = Address.objects.count()
+ cleaned_input = {}
+
+ # when
+ update_fields = save_addresses(order, cleaned_input)
+
+ # then
+ assert update_fields == []
+ assert Address.objects.count() == address_count
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 88dbda3521..21e0cd83ba 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -408,6 +408,8 @@ class Order(ModelWithMetadata, ModelWithExternalReference):
"channel",
"metadata",
"private_metadata",
+ "draft_save_billing_address",
+ "draft_save_shipping_address",
]
def serialize_for_comparison(self):