Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
feat(orders): notify staff when `draftOrderComplete()` is called (#19863)
Mikail8385ca60ecef
diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.pyindex 9702db62c1..8482bd7ee9 100644--- a/saleor/graphql/order/mutations/draft_order_complete.py+++ b/saleor/graphql/order/mutations/draft_order_complete.py@@ -18,6 +18,7 @@ from ....order.calculations import fetch_order_prices_if_expiredfrom ....order.error_codes import OrderErrorCodefrom ....order.fetch import OrderInfo, OrderLineInfofrom ....order.models import OrderLine+from ....order.notifications import send_order_confirmationfrom ....order.search import prepare_order_search_vector_valuefrom ....order.utils import (get_order_country,@@ -27,12 +28,14 @@ from ....order.utils import (from ....permission.enums import OrderPermissionsfrom ....warehouse.management import allocate_preorders, allocate_stocksfrom ....warehouse.reservations import is_reservation_enabled+from ....webhook.event_types import WebhookEventAsyncTypefrom ...app.dataloaders import get_app_promisefrom ...core import ResolveInfofrom ...core.context import SyncWebhookControlContextfrom ...core.doc_category import DOC_CATEGORY_ORDERSfrom ...core.mutations import BaseMutationfrom ...core.types import OrderError+from ...core.utils import WebhookEventInfofrom ...plugins.dataloaders import get_plugin_manager_promisefrom ...site.dataloaders import get_site_promisefrom ..types import Order@@ -56,6 +59,15 @@ class DraftOrderComplete(BaseMutation):permissions = (OrderPermissions.MANAGE_ORDERS,)error_type_class = OrderErrorerror_type_field = "order_errors"+ webhook_events_info = [+ WebhookEventInfo(+ type=WebhookEventAsyncType.NOTIFY_USER,+ description=(+ "Optionally triggered when staff notification recipients are "+ "configured."+ ),+ )+ ]@classmethoddef update_user_fields(cls, order: models.Order):@@ -270,4 +282,13 @@ class DraftOrderComplete(BaseMutation):from_draft=True,))+ transaction.on_commit(+ # Notify staff about order creation+ lambda: send_order_confirmation(+ order_info=order_info,+ redirect_url=order.redirect_url,+ manager=manager,+ notify_customer=False,+ )+ )return DraftOrderComplete(order=SyncWebhookControlContext(node=order))diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.pyindex 2baf0b0bbb..04b6bb90a8 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py@@ -1,6 +1,6 @@import datetimefrom decimal import Decimal-from unittest.mock import ANY, call, patch+from unittest.mock import ANY, MagicMock, call, patchimport grapheneimport pytest@@ -114,7 +114,12 @@ def test_draft_order_complete(staff_user,draft_order,customer_user,+ mocker,):+ mocked_send_order_confirmation: MagicMock = mocker.patch(+ "saleor.graphql.order.mutations.draft_order_complete.send_order_confirmation"+ )+# givenorder = draft_orderorder.user = customer_user@@ -171,6 +176,14 @@ def test_draft_order_complete(customer_user.refresh_from_db()assert customer_user.number_of_orders == user_orders_count + 1+ # Should have notified staff+ mocked_send_order_confirmation.assert_called_once_with(+ order_info=ANY,+ redirect_url=order.redirect_url,+ manager=ANY,+ notify_customer=False,+ )+def test_draft_order_complete_no_automatically_confirm_all_new_orders(staff_api_client,diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 090cd7b0f9..da4a404e4a 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -19639,11 +19639,14 @@ type Mutation {Completes creating an order.Requires one of the following permissions: MANAGE_ORDERS.++ Triggers the following webhook events:+ - NOTIFY_USER (async): Optionally triggered when staff notification recipients are configured."""draftOrderComplete("""ID of the order that will be completed."""id: ID!- ): DraftOrderComplete @doc(category: "Orders")+ ): DraftOrderComplete @doc(category: "Orders") @webhookEventsInfo(asyncEvents: [NOTIFY_USER], syncEvents: [])"""Creates a new draft order.@@ -27471,8 +27474,11 @@ type PageReorderAttributeValues @doc(category: "Pages") {Completes creating an order.Requires one of the following permissions: MANAGE_ORDERS.++Triggers the following webhook events:+- NOTIFY_USER (async): Optionally triggered when staff notification recipients are configured."""-type DraftOrderComplete @doc(category: "Orders") {+type DraftOrderComplete @doc(category: "Orders") @webhookEventsInfo(asyncEvents: [NOTIFY_USER], syncEvents: []) {"""Completed order."""order: OrderorderErrors: [OrderError!]! @deprecated(reason: "Use `errors` field instead.")diff --git a/saleor/order/notifications.py b/saleor/order/notifications.pyindex 0971d53cec..49f6629357 100644--- a/saleor/order/notifications.py+++ b/saleor/order/notifications.py@@ -405,7 +405,7 @@ def prepare_order_details_url(order: Order, redirect_url: str) -> str:return prepare_url(params, redirect_url)-def send_order_confirmation(order_info, redirect_url, manager):+def send_order_confirmation(order_info, redirect_url, manager, *, notify_customer=True):"""Send notification with order confirmation."""def _generate_payload():@@ -416,12 +416,13 @@ def send_order_confirmation(order_info, redirect_url, manager):}return payload- handler = NotifyHandler(_generate_payload)- manager.notify(- NotifyEventType.ORDER_CONFIRMATION,- payload_func=handler.payload,- channel_slug=order_info.channel.slug,- )+ if notify_customer is True:+ handler = NotifyHandler(_generate_payload)+ manager.notify(+ NotifyEventType.ORDER_CONFIRMATION,+ payload_func=handler.payload,+ channel_slug=order_info.channel.slug,+ )# Prepare staff notification for this orderstaff_notifications = StaffNotificationRecipient.objects.filter(diff --git a/saleor/order/tests/test_notifications.py b/saleor/order/tests/test_notifications.pyindex 1906a2aa6e..65cce5f432 100644--- a/saleor/order/tests/test_notifications.py+++ b/saleor/order/tests/test_notifications.py@@ -3,6 +3,7 @@ from functools import partialfrom unittest import mockimport graphene+import pytestfrom django.core.files import Filefrom measurement.measures import Weightfrom prices import Money, fixed_discount@@ -450,6 +451,68 @@ def test_send_email_order_confirmation_with_staff_recipients(assert called_kwargs["payload_func"]() == expected_payload+ ("_case", "input_kwargs", "expects_customers_notify"),+ [+ # When ``notify_customer`` argument is omitted, then it should notify everyone+ ("default args should notify customers", {}, True),+ (+ "notify_customer=True should notify customers",+ {"notify_customer": True},+ True,+ ),+ (+ "notify_customer=False should not notify customers",+ {"notify_customer": False},+ False,+ ),+ ],+)[email protected]("saleor.plugins.manager.PluginsManager.notify")+def test_send_email_order_confirmation_only_to_staff(+ mocked_notify,+ order,+ staff_notification_recipient, # needed to dispatch staff notification+ _case: str,+ input_kwargs: dict,+ expects_customers_notify: bool,+):+ """Calling with ``notify_customer=False`` shouldn't notify customers.++ When calling ``send_order_confirmation()`` with ``notify_customer=False``+ it shouldn't notify customers, and instead only notify staff users.+ """++ # given+ manager = get_plugins_manager(allow_replica=False)+ redirect_url = "https://www.example.com"+ order_info = fetch_order_info(order)++ # when+ notifications.send_order_confirmation(+ order_info,+ redirect_url,+ manager,+ **input_kwargs,+ )++ # then+ expected_calls = [+ mock.call(NotifyEventType.STAFF_ORDER_CONFIRMATION, payload_func=mock.ANY),+ ]+ if expects_customers_notify is True:+ expected_calls.insert(+ 0,+ mock.call(+ NotifyEventType.ORDER_CONFIRMATION,+ payload_func=mock.ANY,+ channel_slug=order.channel.slug,+ ),+ )++ mocked_notify.assert_has_calls(expected_calls)++@mock.patch("saleor.plugins.manager.PluginsManager.notify")def test_send_confirmation_emails_without_addresses_for_payment(mocked_notify,