Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add `notify_customer` flag to `FulfillmentCreated` type (#13620)
Artur08514da91771
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0b717b36cf..a3565acbe5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,9 @@ in 3.17. Use `PaymentSettings.defaultTransactionFlowStrategy` instead.### Saleor Apps+- Add `NOTIFY_CUSTOMER` flag to `FulfillmentCreated` type - #13620, by @Air-t+ - Inform apps if customer should be notified when fulfillment is created.+### Other changes- Fix error in variant available stock calculation - 13593 by @awaisdar001diff --git a/saleor/graphql/order/mutations/order_fulfill.py b/saleor/graphql/order/mutations/order_fulfill.pyindex 9b7d6a8a24..fce0e7939f 100644--- a/saleor/graphql/order/mutations/order_fulfill.py+++ b/saleor/graphql/order/mutations/order_fulfill.py@@ -11,13 +11,14 @@ from ....order import models as order_modelsfrom ....order.actions import OrderFulfillmentLineInfo, create_fulfillmentsfrom ....order.error_codes import OrderErrorCodefrom ....permission.enums import OrderPermissions+from ....webhook.event_types import WebhookEventAsyncTypefrom ...app.dataloaders import get_app_promisefrom ...core import ResolveInfofrom ...core.descriptions import ADDED_IN_36from ...core.doc_category import DOC_CATEGORY_ORDERSfrom ...core.mutations import BaseMutationfrom ...core.types import BaseInputObjectType, NonNullList, OrderError-from ...core.utils import get_duplicated_values+from ...core.utils import WebhookEventInfo, get_duplicated_valuesfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ...site.dataloaders import get_site_promisefrom ...warehouse.types import Warehouse@@ -105,6 +106,16 @@ class OrderFulfill(BaseMutation):permissions = (OrderPermissions.MANAGE_ORDERS,)error_type_class = OrderErrorerror_type_field = "order_errors"+ webhook_events_info = [+ WebhookEventInfo(+ type=WebhookEventAsyncType.FULFILLMENT_CREATED,+ description="A new fulfillment is created.",+ ),+ WebhookEventInfo(+ type=WebhookEventAsyncType.ORDER_FULFILLED,+ description="Order is fulfilled.",+ ),+ ]@classmethoddef clean_lines(cls, order_lines, quantities_for_lines):diff --git a/saleor/graphql/order/tests/mutations/test_order_fulfill.py b/saleor/graphql/order/tests/mutations/test_order_fulfill.pyindex e1ad5b9f64..fbc14e3f67 100644--- a/saleor/graphql/order/tests/mutations/test_order_fulfill.py+++ b/saleor/graphql/order/tests/mutations/test_order_fulfill.py@@ -1,4 +1,4 @@-from unittest.mock import ANY, patch+from unittest.mock import ANY, MagicMock, patchimport grapheneimport pytest@@ -12,6 +12,7 @@ from .....order.models import Fulfillment, FulfillmentLinefrom .....product.models import ProductVariantfrom .....tests.utils import flush_post_commit_hooksfrom .....warehouse.models import Allocation, Stock+from .....webhook.event_types import WebhookEventAsyncTypefrom ....tests.utils import assert_no_permission, get_graphql_contentORDER_FULFILL_MUTATION = """@@ -1484,3 +1485,58 @@ def test_create_digital_fulfillment(get_graphql_content(response)assert mock_email_fulfillment.call_count == 1+++@patch("saleor.core.utils.events.transaction")+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_order_fulfill_fulfillment_created_event_triggered(+ mocked_webhooks,+ mocked_transactions,+ any_webhook,+ subscription_fulfillment_created_webhook,+ staff_api_client,+ staff_user,+ order_with_lines,+ permission_group_manage_orders,+ warehouse,+ site_settings,+ settings,+):+ # given+ mocked_transactions.get_connection.return_value = MagicMock(in_atomic_block=False)+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ site_settings.fulfillment_auto_approve = True+ site_settings.save(update_fields=["fulfillment_auto_approve"])+ order = order_with_lines+ query = ORDER_FULFILL_MUTATION+ order_id = graphene.Node.to_global_id("Order", order.id)+ order_line, order_line2 = order.lines.all()+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)+ order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id)+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)+ variables = {+ "order": order_id,+ "input": {+ "notifyCustomer": True,+ "lines": [+ {+ "orderLineId": order_line_id,+ "stocks": [{"quantity": 3, "warehouse": warehouse_id}],+ },+ {+ "orderLineId": order_line2_id,+ "stocks": [{"quantity": 2, "warehouse": warehouse_id}],+ },+ ],+ "trackingNumber": "test_tracking_number",+ },+ }+ # when+ staff_api_client.post_graphql(query, variables)++ # then+ mocked_webhooks.assert_called_once()+ assert mocked_webhooks.call_args[0][1] == (+ WebhookEventAsyncType.FULFILLMENT_CREATED+ )diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 0087202825..ea66941b3c 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -15887,6 +15887,10 @@ type Mutation {Creates new fulfillments for an order.Requires one of the following permissions: MANAGE_ORDERS.++ Triggers the following webhook events:+ - FULFILLMENT_CREATED (async): A new fulfillment is created.+ - ORDER_FULFILLED (async): Order is fulfilled."""orderFulfill("""Fields required to create a fulfillment."""@@ -15894,7 +15898,7 @@ type Mutation {"""ID of the order to be fulfilled."""order: ID- ): OrderFulfill @doc(category: "Orders")+ ): OrderFulfill @doc(category: "Orders") @webhookEventsInfo(asyncEvents: [FULFILLMENT_CREATED, ORDER_FULFILLED], syncEvents: [])"""Cancels existing fulfillment and optionally restocks items.@@ -23709,8 +23713,12 @@ type OrderConfirm @doc(category: "Orders") {Creates new fulfillments for an order.Requires one of the following permissions: MANAGE_ORDERS.++Triggers the following webhook events:+- FULFILLMENT_CREATED (async): A new fulfillment is created.+- ORDER_FULFILLED (async): Order is fulfilled."""-type OrderFulfill @doc(category: "Orders") {+type OrderFulfill @doc(category: "Orders") @webhookEventsInfo(asyncEvents: [FULFILLMENT_CREATED, ORDER_FULFILLED], syncEvents: []) {"""List of created fulfillments."""fulfillments: [Fulfillment!]@@ -31395,6 +31403,13 @@ type FulfillmentCreated implements Event @doc(category: "Orders") {"""The order the fulfillment belongs to."""order: Order++ """+ If true, send an email notification to the customer.++ Added in Saleor 3.16.+ """+ notifyCustomer: Boolean!}"""diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex ba332d8429..c6bae03da0 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -46,6 +46,7 @@ from ..core.descriptions import (ADDED_IN_313,ADDED_IN_314,ADDED_IN_315,+ ADDED_IN_316,PREVIEW_FEATURE,)from ..core.doc_category import (@@ -1161,12 +1162,35 @@ class FulfillmentBase(AbstractType):class FulfillmentCreated(SubscriptionObjectType, FulfillmentBase):+ notify_customer = graphene.Boolean(+ description=(+ "If true, send an email notification to the customer." + ADDED_IN_316+ ),+ required=True,+ )+class Meta:+ doc_category = DOC_CATEGORY_ORDERSroot_type = "Fulfillment"- enable_dry_run = True+ enable_dry_run = Falseinterfaces = (Event,)description = "Event sent when new fulfillment is created." + ADDED_IN_34+ @staticmethod+ def resolve_fulfillment(root, info: ResolveInfo):+ _, data = root+ return data["fulfillment"]++ @staticmethod+ def resolve_order(root, info: ResolveInfo):+ _, data = root+ return data["fulfillment"].order++ @staticmethod+ def resolve_notify_customer(root, _info: ResolveInfo):+ _, data = root+ return data["notify_customer"]+class FulfillmentCanceled(SubscriptionObjectType, FulfillmentBase):class Meta:diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.pyindex 875854da18..70611dcda9 100644--- a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py@@ -272,7 +272,6 @@ def async_subscription_webhooks_with_root_objects(subscription_invoice_requested_webhook,subscription_invoice_deleted_webhook,subscription_invoice_sent_webhook,- subscription_fulfillment_created_webhook,subscription_fulfillment_canceled_webhook,subscription_fulfillment_approved_webhook,subscription_fulfillment_metadata_updated_webhook,@@ -468,10 +467,6 @@ def async_subscription_webhooks_with_root_objects(events.INVOICE_REQUESTED: [subscription_invoice_requested_webhook, invoice],events.INVOICE_DELETED: [subscription_invoice_deleted_webhook, invoice],events.INVOICE_SENT: [subscription_invoice_sent_webhook, invoice],- events.FULFILLMENT_CREATED: [- subscription_fulfillment_created_webhook,- fulfillment,- ],events.FULFILLMENT_CANCELED: [subscription_fulfillment_canceled_webhook,fulfillment,diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 1262030ed4..fff9a2f46a 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -297,9 +297,8 @@ def order_fulfilled(order=order, user=user, app=app, fulfillment_lines=fulfillment_lines)call_event(manager.order_updated, order)-for fulfillment in fulfillments:- call_event(manager.fulfillment_created, fulfillment)+ call_event(manager.fulfillment_created, fulfillment, notify_customer)if order.status == OrderStatus.FULFILLED:call_event(manager.order_fulfilled, order)diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 5df1cbdec6..f0b9d2096c 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -554,7 +554,7 @@ class BasePlugin:## Overwrite this method if you need to trigger specific logic when a fulfillment is# created.- fulfillment_created: Callable[["Fulfillment", Any], Any]+ fulfillment_created: Callable[["Fulfillment", bool, Any], Any]# Trigger when fulfillment is cancelled.#diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 0eedc3de40..90b1544ebe 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -852,13 +852,16 @@ class PluginsManager(PaymentInterface):default_value = Nonereturn self.__run_method_on_plugins("order_bulk_created", default_value, orders)- def fulfillment_created(self, fulfillment: "Fulfillment"):+ def fulfillment_created(+ self, fulfillment: "Fulfillment", notify_customer: Optional[bool] = True+ ):default_value = Nonereturn self.__run_method_on_plugins("fulfillment_created",default_value,fulfillment,channel_slug=fulfillment.order.channel.slug,+ notify_customer=notify_customer,)def fulfillment_canceled(self, fulfillment: "Fulfillment"):diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex a21e285c8a..34eb6bec79 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -919,14 +919,26 @@ class WebhookPlugin(BasePlugin):order_data, event_type, webhooks, order, self.requestor)- def fulfillment_created(self, fulfillment: "Fulfillment", previous_value):+ def fulfillment_created(+ self,+ fulfillment: "Fulfillment",+ notify_customer: bool = True,+ previous_value: Optional[Any] = None,+ ):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.FULFILLMENT_CREATEDif webhooks := get_webhooks_for_event(event_type):fulfillment_data = generate_fulfillment_payload(fulfillment, self.requestor)trigger_webhooks_async(- fulfillment_data, event_type, webhooks, fulfillment, self.requestor+ fulfillment_data,+ event_type,+ webhooks,+ {+ "notify_customer": notify_customer,+ "fulfillment": fulfillment,+ },+ self.requestor,)def fulfillment_canceled(self, fulfillment: "Fulfillment", previous_value):diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.pyindex a573fa3c84..2855bb2a2e 100644--- a/saleor/plugins/webhook/tasks.py+++ b/saleor/plugins/webhook/tasks.py@@ -108,7 +108,9 @@ def create_deliveries_for_subscriptions(subscribable_object=subscribable_object,subscription_query=webhook.subscription_query,request=initialize_request(- requestor, event_type in WebhookEventSyncType.ALL, event_type=event_type+ requestor,+ event_type in WebhookEventSyncType.ALL,+ event_type=event_type,),app=webhook.app,)@@ -117,7 +119,6 @@ def create_deliveries_for_subscriptions("No payload was generated with subscription for event: %s" % event_type)continue-event_payload = EventPayload(payload=json.dumps({**data}))event_payloads.append(event_payload)event_deliveries.append(@@ -196,7 +197,6 @@ def trigger_webhooks_async("""regular_webhooks, subscription_webhooks = group_webhooks_by_subscription(webhooks)deliveries = []-if regular_webhooks:payload = EventPayload.objects.create(payload=data)deliveries.extend(diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py b/saleor/plugins/webhook/tests/subscription_webhooks/payloads.pyindex cc0fd5155f..ac6a13e6b5 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py@@ -111,9 +111,9 @@ def generate_fulfillment_lines_payload(fulfillment):]-def generate_fulfillment_payload(fulfillment):+def generate_fulfillment_payload(fulfillment, add_notify_customer_field=False):fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.pk)- return {+ payload = {"fulfillment": {"id": fulfillment_id,"fulfillmentOrder": fulfillment.fulfillment_order,@@ -125,6 +125,9 @@ def generate_fulfillment_payload(fulfillment):"id": graphene.Node.to_global_id("Order", fulfillment.order.pk),},}+ if add_notify_customer_field:+ payload["notifyCustomer"] = True+ return payloaddef generate_address_payload(address):diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.pyindex ec44f04c13..d839735fde 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py@@ -1341,6 +1341,7 @@ FULFILLMENT_CREATED = (subscription{event{...on FulfillmentCreated{+ notifyCustomerfulfillment{...FulfillmentDetails}diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.pyindex b249218901..bcf1922e72 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py@@ -1653,11 +1653,19 @@ def test_fulfillment_created(fulfillment, subscription_fulfillment_created_webho# givenwebhooks = [subscription_fulfillment_created_webhook]event_type = WebhookEventAsyncType.FULFILLMENT_CREATED- expected_payload = generate_fulfillment_payload(fulfillment)+ expected_payload = generate_fulfillment_payload(+ fulfillment, add_notify_customer_field=True+ )# when- deliveries = create_deliveries_for_subscriptions(event_type, fulfillment, webhooks)-+ deliveries = create_deliveries_for_subscriptions(+ event_type,+ {+ "fulfillment": fulfillment,+ "notify_customer": True,+ },+ webhooks,+ )# thenassert json.loads(deliveries[0].payload.payload) == expected_payloadassert len(deliveries) == len(webhooks)