Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
SALEOR-4122: ExternalNotificationTrigger mutation (#7821)
mstrumeck9fefbc80cc39
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1a2a4636a7..e3553f2181 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,8 @@ All notable, unreleased changes to this project will be documented in this file.# 3.1.0 [Unreleased]- Extend app by `AppExtension` - #7701 by @korycins+- Add ExternalNotificationTrigger mutation - #7821 by @mstrumeck+- Add Click&Collect feature - #7673 by @kuchichandiff --git a/saleor/account/notifications.py b/saleor/account/notifications.pyindex 739860c31a..31acedbf9a 100644--- a/saleor/account/notifications.py+++ b/saleor/account/notifications.py@@ -3,7 +3,7 @@ from urllib.parse import urlencodefrom django.contrib.auth.tokens import default_token_generator-from ..core.notifications import get_site_context+from ..core.notification.utils import get_site_contextfrom ..core.notify_events import NotifyEventTypefrom ..core.utils.url import prepare_urlfrom .models import User@@ -23,6 +23,15 @@ def get_default_user_payload(user: User):}+def get_user_custom_payload(user: User):+ payload = {+ "user": get_default_user_payload(user),+ "recipient_email": user.email,+ **get_site_context(),+ }+ return payload++def send_password_reset_notification(redirect_url, user, manager, channel_slug: Optional[str], staff=False):diff --git a/saleor/core/notification/__init__.py b/saleor/core/notification/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/core/notification/mutation_handler.py b/saleor/core/notification/mutation_handler.pynew file mode 100644index 0000000000..c90ecb2919--- /dev/null+++ b/saleor/core/notification/mutation_handler.py@@ -0,0 +1,35 @@+def get_external_notification_payload(objects, extra_payload, payload_function):+ return [+ _get_extracted_payload_input(payload_input, extra_payload, payload_function)+ for payload_input in objects+ ]+++def send_notification(+ manager, external_event_type, payloads, channel_slug=None, plugin_id=None+):+ method_kwargs = dict(+ manager=manager,+ external_event_type=external_event_type,+ channel_slug=channel_slug,+ plugin_id=plugin_id,+ )+ if isinstance(payloads, list):+ for payload in payloads:+ trigger_notifications(**method_kwargs, payload=payload)+ else:+ trigger_notifications(**method_kwargs, payload=payloads)+++def trigger_notifications(+ manager, external_event_type, payload, channel_slug=None, plugin_id=None+):+ method_kwargs = dict(event=external_event_type, payload=payload)+ manager.notify(**method_kwargs, plugin_id=plugin_id, channel_slug=channel_slug)+++def _get_extracted_payload_input(payload_input, extra_payload, payload_function):+ payload = payload_function(payload_input)+ payload = payload[0] if type(payload) == list else payload+ payload.update({"extra_payload": extra_payload})+ return payloaddiff --git a/saleor/core/notifications.py b/saleor/core/notification/utils.pysimilarity index 100%rename from saleor/core/notifications.pyrename to saleor/core/notification/utils.pydiff --git a/saleor/core/notification/validation.py b/saleor/core/notification/validation.pynew file mode 100644index 0000000000..170245d10d--- /dev/null+++ b/saleor/core/notification/validation.py@@ -0,0 +1,79 @@+from django.core.exceptions import ValidationError++from ...account.models import User+from ...account.notifications import get_user_custom_payload+from ...core.permissions import AccountPermissions, OrderPermissions+from ...graphql.channel.utils import validate_channel+from ...graphql.core.enums import ExternalNotificationTriggerErrorCode+from ...graphql.utils import resolve_global_ids_to_primary_keys+from ...order.models import Order+from ...order.notifications import get_custom_order_payload++PAYLOAD_MAPPING_FOR_CUSTOM_NOTIFICATION = {+ "User": (+ User,+ get_user_custom_payload,+ AccountPermissions.MANAGE_USERS,+ ),+ "Order": (+ Order,+ get_custom_order_payload,+ OrderPermissions.MANAGE_ORDERS,+ ),+}+++def validate_ids_and_get_model_type_and_pks(data_input):+ if ids := data_input.get("ids"):+ model_type, pks = resolve_global_ids_to_primary_keys(ids)+ return model_type, pks+ raise ValidationError(+ {+ "ids": ValidationError(+ "The obligatory param 'ids' is empty.",+ code=ExternalNotificationTriggerErrorCode.REQUIRED,+ )+ }+ )+++def validate_and_get_external_event_type(data_input):+ if external_event_type := data_input.get("external_event_type"):+ return external_event_type+ raise ValidationError(+ {+ "externalEventType": ValidationError(+ "The obligatory param 'externalEventType' is empty.",+ code=ExternalNotificationTriggerErrorCode.REQUIRED,+ )+ }+ )+++def validate_and_get_channel(data_input, error_class):+ if channel_slug := data_input.get("channel"):+ return validate_channel(channel_slug, error_class).slug+ raise ValidationError(+ {+ "channel": ValidationError(+ "The obligatory param 'channel' is empty.",+ code=ExternalNotificationTriggerErrorCode.REQUIRED.value,+ )+ }+ )+++def validate_and_get_payload_params(model_type):+ if payload_params := PAYLOAD_MAPPING_FOR_CUSTOM_NOTIFICATION.get(model_type):+ return payload_params+ available_object_types = ",".join(PAYLOAD_MAPPING_FOR_CUSTOM_NOTIFICATION.keys())+ raise ValidationError(+ {+ "external_notification_trigger": ValidationError(+ f"Wrong type of object."+ f"ExternalNotificationTrigger is suitable for "+ f"{available_object_types} object types.",+ code=ExternalNotificationTriggerErrorCode.INVALID_MODEL_TYPE,+ )+ }+ )diff --git a/saleor/core/tests/test_notification.py b/saleor/core/tests/test_notification.pynew file mode 100644index 0000000000..3718a146c0--- /dev/null+++ b/saleor/core/tests/test_notification.py@@ -0,0 +1,34 @@+import pytest+from django.core.exceptions import ValidationError++from ...core.notification.validation import validate_and_get_channel+from ...graphql.notifications.error_codes import ExternalNotificationErrorCodes+++def test_validate_and_get_channel_for_non_existing_slug():+ with pytest.raises(ValidationError):+ validate_and_get_channel(+ {"channel": "test-slug"}, ExternalNotificationErrorCodes+ )+++def test_validate_and_get_channel_for_inactive_channel(channel_PLN):+ channel_PLN.is_active = False+ channel_PLN.save()+ assert not channel_PLN.is_active+ with pytest.raises(ValidationError):+ validate_and_get_channel(+ {"channel": channel_PLN.slug}, ExternalNotificationErrorCodes+ )+++def test_validate_and_get_channel_for_lack_of_input():+ with pytest.raises(ValidationError):+ validate_and_get_channel({}, ExternalNotificationErrorCodes)+++def test_validate_and_get_channel(channel_PLN):+ result = validate_and_get_channel(+ {"channel": channel_PLN.slug}, ExternalNotificationErrorCodes+ )+ assert result == channel_PLN.slugdiff --git a/saleor/csv/notifications.py b/saleor/csv/notifications.pyindex 02aa065c1e..304638fa9c 100644--- a/saleor/csv/notifications.py+++ b/saleor/csv/notifications.py@@ -1,6 +1,6 @@from typing import TYPE_CHECKING-from ..core.notifications import get_site_context+from ..core.notification.utils import get_site_contextfrom ..core.notify_events import NotifyEventTypefrom ..core.utils import build_absolute_urifrom ..plugins.manager import get_plugins_managerdiff --git a/saleor/csv/tests/test_notifications.py b/saleor/csv/tests/test_notifications.pyindex 4e362103a0..4bb4558d8c 100644--- a/saleor/csv/tests/test_notifications.py+++ b/saleor/csv/tests/test_notifications.py@@ -3,7 +3,7 @@ from unittest import mockfrom django.core.files import Filefrom freezegun import freeze_time-from ...core.notifications import get_site_context+from ...core.notification.utils import get_site_contextfrom ...core.notify_events import AdminNotifyEventfrom ...core.utils import build_absolute_urifrom .. import notificationsdiff --git a/saleor/graphql/api.py b/saleor/graphql/api.pyindex 4b2d58ecdb..d8b9f958e5 100644--- a/saleor/graphql/api.py+++ b/saleor/graphql/api.py@@ -1,5 +1,6 @@from graphene_federation import build_schema+from ..graphql.notifications.schema import ExternalNotificationMutationsfrom .account.schema import AccountMutations, AccountQueriesfrom .app.schema import AppMutations, AppQueriesfrom .attribute.schema import AttributeMutations, AttributeQueries@@ -60,6 +61,7 @@ class Mutation(CoreMutations,CsvMutations,DiscountMutations,+ ExternalNotificationMutations,PluginsMutations,GiftCardMutations,InvoiceMutations,diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.pyindex 8715e11796..f8b8a04a07 100644--- a/saleor/graphql/core/enums.py+++ b/saleor/graphql/core/enums.py@@ -30,6 +30,7 @@ from ...shipping import error_codes as shipping_error_codesfrom ...warehouse import error_codes as warehouse_error_codesfrom ...webhook import error_codes as webhook_error_codesfrom ...wishlist import error_codes as wishlist_error_codes+from ..notifications import error_codes as external_notifications_error_codesfrom ..shop import error_codes as shop_error_codesfrom .utils import str_to_enum@@ -104,6 +105,9 @@ AppErrorCode = graphene.Enum.from_enum(app_error_codes.AppErrorCode)AttributeErrorCode = graphene.Enum.from_enum(attribute_error_codes.AttributeErrorCode)ChannelErrorCode = graphene.Enum.from_enum(channel_error_codes.ChannelErrorCode)CheckoutErrorCode = graphene.Enum.from_enum(checkout_error_codes.CheckoutErrorCode)+ExternalNotificationTriggerErrorCode = graphene.Enum.from_enum(+ external_notifications_error_codes.ExternalNotificationErrorCodes+)ExportErrorCode = graphene.Enum.from_enum(csv_error_codes.ExportErrorCode)DiscountErrorCode = graphene.Enum.from_enum(discount_error_codes.DiscountErrorCode)PluginErrorCode = graphene.Enum.from_enum(plugin_error_codes.PluginErrorCode)diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.pyindex f0b0cb1023..6357b8ec42 100644--- a/saleor/graphql/core/types/common.py+++ b/saleor/graphql/core/types/common.py@@ -15,6 +15,7 @@ from ..enums import (CollectionErrorCode,DiscountErrorCode,ExportErrorCode,+ ExternalNotificationTriggerErrorCode,GiftCardErrorCode,InvoiceErrorCode,JobStatusEnum,@@ -160,6 +161,12 @@ class ExportError(Error):code = ExportErrorCode(description="The error code.", required=True)+class ExternalNotificationError(Error):+ code = ExternalNotificationTriggerErrorCode(+ description="The error code.", required=True+ )++class MenuError(Error):code = MenuErrorCode(description="The error code.", required=True)diff --git a/saleor/graphql/core/utils/error_codes.py b/saleor/graphql/core/utils/error_codes.pyindex 0b9071364c..c80b466067 100644--- a/saleor/graphql/core/utils/error_codes.py+++ b/saleor/graphql/core/utils/error_codes.py@@ -22,6 +22,7 @@ from ....payment.error_codes import PaymentErrorCodefrom ....plugins.error_codes import PluginErrorCodefrom ....product.error_codes import ProductErrorCodefrom ....shipping.error_codes import ShippingErrorCode+from ...notifications.error_codes import ExternalNotificationErrorCodesfrom ...shop.error_codes import OrderSettingsErrorCodeDJANGO_VALIDATORS_ERROR_CODES = [@@ -60,6 +61,7 @@ SALEOR_ERROR_CODE_ENUMS = [CheckoutErrorCode,ExportErrorCode,DiscountErrorCode,+ ExternalNotificationErrorCodes,PluginErrorCode,GiftCardErrorCode,InvoiceErrorCode,diff --git a/saleor/graphql/notifications/__init__.py b/saleor/graphql/notifications/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/graphql/notifications/error_codes.py b/saleor/graphql/notifications/error_codes.pynew file mode 100644index 0000000000..30bd24619c--- /dev/null+++ b/saleor/graphql/notifications/error_codes.py@@ -0,0 +1,8 @@+from enum import Enum+++class ExternalNotificationErrorCodes(Enum):+ REQUIRED = "required"+ INVALID_MODEL_TYPE = "invalid_model_type"+ NOT_FOUND = "not_found"+ CHANNEL_INACTIVE = "channel_inactive"diff --git a/saleor/graphql/notifications/mutations/__init__.py b/saleor/graphql/notifications/mutations/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/graphql/notifications/mutations/external_notification_trigger.py b/saleor/graphql/notifications/mutations/external_notification_trigger.pynew file mode 100644index 0000000000..327617ca23--- /dev/null+++ b/saleor/graphql/notifications/mutations/external_notification_trigger.py@@ -0,0 +1,97 @@+import graphene++from ....core.exceptions import PermissionDenied+from ....core.notification.mutation_handler import (+ get_external_notification_payload,+ send_notification,+)+from ....core.notification.validation import (+ validate_and_get_channel,+ validate_and_get_external_event_type,+ validate_and_get_payload_params,+ validate_ids_and_get_model_type_and_pks,+)+from ....graphql.core.types.common import ExternalNotificationError+from ....graphql.notifications.error_codes import ExternalNotificationErrorCodes+from ...core.descriptions import ADDED_IN_31+from ...core.mutations import BaseMutation+++class ExternalNotificationTriggerInput(graphene.InputObjectType):+ ids = graphene.List(+ graphene.ID,+ required=True,+ description=(+ "The list of customers or orders node IDs that will be serialized and "+ "included in the notification payload."+ ),+ )+ extra_payload = graphene.JSONString(+ description=(+ "Additional payload that will be merged with "+ "the one based on the bussines object ID."+ )+ )+ external_event_type = graphene.String(+ required=True,+ description=(+ "External event type. This field is passed to a plugin as an event type."+ ),+ )+++class ExternalNotificationTrigger(BaseMutation):+ class Arguments:+ input = ExternalNotificationTriggerInput(+ required=True, description="Input for External Notification Trigger. "+ )+ plugin_id = graphene.String(description="The ID of notification plugin.")+ channel = graphene.String(+ required=True,+ description=(+ "Channel slug. "+ "Saleor will send a notification within a provided channel. "+ "Please, make sure that necessary plugins are active."+ ),+ )++ class Meta:+ description = (+ f"{ADDED_IN_31} Trigger sending a notification "+ "with the notify plugin method. "+ "Serializes nodes provided as ids parameter and includes this data in "+ "the notification payload."+ )+ error_type_class = ExternalNotificationError++ @classmethod+ def perform_mutation(cls, root, info, **data):+ manager = info.context.plugins+ plugin_id = data.get("plugin_id")+ channel_slug = validate_and_get_channel(data, ExternalNotificationErrorCodes)+ if data_input := data.get("input"):+ model_type, pks = validate_ids_and_get_model_type_and_pks(data_input)+ extra_payload = data_input.get("extra_payload")+ external_event_type = validate_and_get_external_event_type(data_input)+ model, payload_function, permission_type = validate_and_get_payload_params(+ model_type+ )+ if cls._requestor_has_permission(info.context, permission_type):+ objects = model.objects.filter(pk__in=pks)+ payload = get_external_notification_payload(+ objects, extra_payload, payload_function+ )+ send_notification(+ manager,+ external_event_type,+ payload,+ channel_slug=channel_slug,+ plugin_id=plugin_id,+ )+ return cls()++ @classmethod+ def _requestor_has_permission(cls, context, permission_type):+ if cls.check_permissions(context, (permission_type,)):+ return True+ raise PermissionDenied()diff --git a/saleor/graphql/notifications/schema.py b/saleor/graphql/notifications/schema.pynew file mode 100644index 0000000000..39cbfa41eb--- /dev/null+++ b/saleor/graphql/notifications/schema.py@@ -0,0 +1,7 @@+import graphene++from .mutations.external_notification_trigger import ExternalNotificationTrigger+++class ExternalNotificationMutations(graphene.ObjectType):+ external_notification_trigger = ExternalNotificationTrigger.Field()diff --git a/saleor/graphql/notifications/tests/__init__.py b/saleor/graphql/notifications/tests/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/graphql/notifications/tests/conftest.py b/saleor/graphql/notifications/tests/conftest.pynew file mode 100644index 0000000000..4c23b9612f--- /dev/null+++ b/saleor/graphql/notifications/tests/conftest.py@@ -0,0 +1,22 @@+import pytest+++def external_notification_trigger_query():+ return """+ mutation ExternalNotificationTrigger(+ $input: ExternalNotificationTriggerInput!+ $pluginId: String+ $channel: String!+ ) {+ externalNotificationTrigger(+ input: $input,+ pluginId: $pluginId+ channel: $channel+ ) {+ errors {+ message+ }+ }+ }+ """diff --git a/saleor/graphql/notifications/tests/test_external_notification_dispatch.py b/saleor/graphql/notifications/tests/test_external_notification_dispatch.pynew file mode 100644index 0000000000..6fb5cafcde--- /dev/null+++ b/saleor/graphql/notifications/tests/test_external_notification_dispatch.py@@ -0,0 +1,41 @@+from unittest.mock import patch++from graphql_relay.node.node import to_global_id++from ....account.models import User+++@patch("saleor.plugins.manager.PluginsManager.notify")+def test_notify_via_external_notification_trigger(+ notify_single_plugin_mock,+ settings,+ staff_users,+ external_notification_trigger_query,+ staff_api_client,+ permission_manage_users,+ channel_PLN,+):++ settings.PLUGINS = [+ "saleor.plugins.tests.sample_plugins.PluginSample",+ ]+ test_template_id = "2efac70d-64ed-4e57-9951-f87e14d7e60e"++ variables = {+ "input": {+ "ids": [to_global_id(User.__name__, user.id) for user in staff_users],+ "extraPayload": '{"recipient_email":"[email protected]"}',+ "externalEventType": test_template_id,+ },+ "pluginId": "mirumee.notifications.sendgrid_email",+ "channel": channel_PLN.slug,+ }++ response = staff_api_client.post_graphql(+ external_notification_trigger_query,+ variables,+ permissions=[permission_manage_users],+ )++ assert response.status_code == 200+ assert notify_single_plugin_mock.call_count == 3diff --git a/saleor/graphql/notifications/tests/test_external_notification_query.py b/saleor/graphql/notifications/tests/test_external_notification_query.pynew file mode 100644index 0000000000..d6fe826101--- /dev/null+++ b/saleor/graphql/notifications/tests/test_external_notification_query.py@@ -0,0 +1,130 @@+import json+from unittest.mock import patch++import pytest+from graphql_relay.node.node import to_global_id++from ....account.models import User+from ....core.notify_events import UserNotifyEvent+from ....graphql.tests.utils import assert_no_permission+from ....plugins.tests.sample_plugins import PluginSample++query_test_invalid_data = [+ (+ {+ "input": {+ "ids": [],+ "extraPayload": json.dumps("{}"),+ "externalEventType": {},+ }+ },+ 400,+ 'Variable "$channel" of required type "String!" was not provided.',+ ),+ (+ {+ "input": {+ "extraPayload": json.dumps("{}"),+ "externalEventType": {},+ },+ "channel": "c-pln",+ },+ 400,+ 'Variable "$input" got invalid value {"externalEventType": {},'+ ' "extraPayload": "\\"{}\\""}.\nIn field "ids": Expected "[ID]!", found null.',+ ),+ (+ {+ "input": {+ "ids": [],+ "extraPayload": json.dumps("{}"),+ },+ "channel": "c-pln",+ },+ 400,+ 'Variable "$input" got invalid value {"extraPayload": "\\"{}\\"",'+ ' "ids": []}.\nIn field "externalEventType": Expected "String!", found null.',+ ),+]++[email protected]("variables, status_code, message", query_test_invalid_data)+def test_external_notification_trigger_query_with_invalid_data(+ variables,+ status_code,+ message,+ external_notification_trigger_query,+ staff_api_client,+ permission_manage_users,+ channel_PLN,+):+ response = staff_api_client.post_graphql(+ external_notification_trigger_query,+ variables,+ permissions=[permission_manage_users],+ check_no_permissions=False,+ )+ assert response.status_code == status_code+ json_response = response.json()+ errors = json_response["errors"]+ assert len(errors) == 1+ assert errors[0]["message"] == message+++@patch("saleor.plugins.manager.PluginsManager.notify")+def test_notify_via_external_notification_trigger_for_plugin_manager(+ plugin_manager_notify_mock,+ settings,+ staff_users,+ external_notification_trigger_query,+ staff_api_client,+ permission_manage_users,+ channel_PLN,+):++ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]++ variables = {+ "input": {+ "ids": [to_global_id(User.__name__, user.id) for user in staff_users],+ "extraPayload": "{}",+ "externalEventType": UserNotifyEvent.ORDER_CANCELED,+ },+ "channel": channel_PLN.slug,+ }++ response = staff_api_client.post_graphql(+ external_notification_trigger_query,+ variables,+ permissions=[permission_manage_users],+ )++ assert response.status_code == 200+ assert plugin_manager_notify_mock.call_count == 3+ assert len(response.json()["data"]["externalNotificationTrigger"]["errors"]) == 0+++@patch("saleor.plugins.manager.PluginsManager.notify")+def test_notify_via_external_notification_trigger_without_permission(+ plugin_manager_notify_mock,+ staff_users,+ external_notification_trigger_query,+ staff_api_client,+ channel_PLN,+):++ variables = {+ "input": {+ "ids": [to_global_id(User.__name__, user.id) for user in staff_users],+ "extraPayload": "{}",+ "externalEventType": UserNotifyEvent.ORDER_CANCELED,+ },+ "channel": channel_PLN.slug,+ "pluginId": PluginSample.PLUGIN_ID,+ }++ response = staff_api_client.post_graphql(+ external_notification_trigger_query, variables+ )+ assert_no_permission(response)+ plugin_manager_notify_mock.assert_not_called()diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 72be86ea5c..89db584b44 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2102,6 +2102,29 @@ type ExternalLogout {errors: [AccountError!]!}+type ExternalNotificationError {+ field: String+ message: String+ code: ExternalNotificationErrorCodes!+}++enum ExternalNotificationErrorCodes {+ REQUIRED+ INVALID_MODEL_TYPE+ NOT_FOUND+ CHANNEL_INACTIVE+}++type ExternalNotificationTrigger {+ errors: [ExternalNotificationError!]!+}++input ExternalNotificationTriggerInput {+ ids: [ID]!+ extraPayload: JSONString+ externalEventType: String!+}+type ExternalObtainAccessTokens {token: StringrefreshToken: String@@ -3761,6 +3784,7 @@ type Mutation {giftCardDeactivate(id: ID!): GiftCardDeactivategiftCardUpdate(id: ID!, input: GiftCardUpdateInput!): GiftCardUpdatepluginUpdate(channelId: ID, id: ID!, input: PluginUpdateInput!): PluginUpdate+ externalNotificationTrigger(channel: String!, input: ExternalNotificationTriggerInput!, pluginId: String): ExternalNotificationTriggersaleCreate(input: SaleInput!): SaleCreatesaleDelete(id: ID!): SaleDeletesaleBulkDelete(ids: [ID]!): SaleBulkDeletediff --git a/saleor/invoice/notifications.py b/saleor/invoice/notifications.pyindex afe4545c72..3f441e8ab7 100644--- a/saleor/invoice/notifications.py+++ b/saleor/invoice/notifications.py@@ -1,6 +1,6 @@from typing import TYPE_CHECKING, Optional-from ..core.notifications import get_site_context+from ..core.notification.utils import get_site_contextfrom ..core.notify_events import NotifyEventTypeif TYPE_CHECKING:diff --git a/saleor/order/notifications.py b/saleor/order/notifications.pyindex bdac0d85fe..2956c8db75 100644--- a/saleor/order/notifications.py+++ b/saleor/order/notifications.py@@ -4,7 +4,7 @@ from urllib.parse import urlencodefrom django.forms import model_to_dictfrom ..account.models import StaffNotificationRecipient-from ..core.notifications import get_site_context+from ..core.notification.utils import get_site_contextfrom ..core.notify_events import NotifyEventTypefrom ..core.utils.url import prepare_urlfrom ..discount import OrderDiscountType@@ -196,6 +196,15 @@ ORDER_MODEL_FIELDS = []+def get_custom_order_payload(order: Order):+ payload = {+ "order": get_default_order_payload(order),+ "recipient_email": order.get_customer_email(),+ **get_site_context(),+ }+ return payload++def get_default_order_payload(order: "Order", redirect_url: str = ""):order_details_url = ""if redirect_url:diff --git a/saleor/order/tests/test_notifications.py b/saleor/order/tests/test_notifications.pyindex 35497e12c9..2316edfd25 100644--- a/saleor/order/tests/test_notifications.py+++ b/saleor/order/tests/test_notifications.py@@ -12,6 +12,7 @@ from ...plugins.manager import get_plugins_managerfrom ...product.models import DigitalContentUrlfrom ..notifications import (get_address_payload,+ get_custom_order_payload,get_default_fulfillment_line_payload,get_default_fulfillment_payload,get_default_order_payload,@@ -20,6 +21,69 @@ from ..notifications import (from ..utils import add_variant_to_order+def test_get_custom_order_payload(order):+ expected_payload = get_custom_order_payload(order)+ assert expected_payload == {+ "order": {+ "id": expected_payload["order"]["id"],+ "private_metadata": {},+ "metadata": {},+ "status": "unfulfilled",+ "language_code": "en",+ "currency": "USD",+ "token": expected_payload["order"]["token"],+ "total_net_amount": 0,+ "undiscounted_total_net_amount": 0,+ "total_gross_amount": 0,+ "undiscounted_total_gross_amount": 0,+ "display_gross_prices": True,+ "channel_slug": "main",+ "created": expected_payload["order"]["created"],+ "shipping_price_net_amount": 0,+ "shipping_price_gross_amount": 0,+ "order_details_url": "",+ "email": "[email protected]",+ "subtotal_gross_amount": expected_payload["order"]["subtotal_gross_amount"],+ "subtotal_net_amount": expected_payload["order"]["subtotal_net_amount"],+ "tax_amount": 0,+ "lines": [],+ "billing_address": {+ "first_name": "John",+ "last_name": "Doe",+ "company_name": "Mirumee Software",+ "street_address_1": "Tęczowa 7",+ "street_address_2": "",+ "city": "WROCŁAW",+ "city_area": "",+ "postal_code": "53-601",+ "country": "PL",+ "country_area": "",+ "phone": "+48713988102",+ },+ "shipping_address": {+ "first_name": "John",+ "last_name": "Doe",+ "company_name": "Mirumee Software",+ "street_address_1": "Tęczowa 7",+ "street_address_2": "",+ "city": "WROCŁAW",+ "city_area": "",+ "postal_code": "53-601",+ "country": "PL",+ "country_area": "",+ "phone": "+48713988102",+ },+ "shipping_method_name": None,+ "voucher_discount": None,+ "discounts": [],+ "discount_amount": 0,+ },+ "recipient_email": "[email protected]",+ "domain": "mirumee.com",+ "site_name": "mirumee.com",+ }++def test_get_order_line_payload(order_line):order_line.variant.product.weight = Weight(kg=5)order_line.variant.product.save()diff --git a/saleor/plugins/admin_email/plugin.py b/saleor/plugins/admin_email/plugin.pyindex cc6e57240c..b71632c178 100644--- a/saleor/plugins/admin_email/plugin.py+++ b/saleor/plugins/admin_email/plugin.py@@ -1,6 +1,6 @@import loggingfrom dataclasses import asdict, dataclass-from typing import Optional+from typing import Optional, Unionfrom django.conf import settings@@ -217,7 +217,7 @@ class AdminEmailPlugin(BasePlugin):],)- def notify(self, event: NotifyEventType, payload: dict, previous_value):+ def notify(self, event: Union[NotifyEventType, str], payload: dict, previous_value):if not self.active:return previous_valueevent_map = get_admin_event_map()diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 41e476a42e..faad050e91 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -964,8 +964,18 @@ class PluginsManager(PaymentInterface):event: "NotifyEventTypeChoice",payload: dict,channel_slug: Optional[str] = None,+ plugin_id: Optional[str] = None,):default_value = None+ if plugin_id:+ plugin = self.get_plugin(plugin_id, channel_slug=channel_slug)+ return self.__run_method_on_single_plugin(+ plugin=plugin,+ method_name="notify",+ previous_value=default_value,+ event=event,+ payload=payload,+ )return self.__run_method_on_plugins("notify", default_value, event, payload, channel_slug=channel_slug)diff --git a/saleor/plugins/sendgrid/plugin.py b/saleor/plugins/sendgrid/plugin.pyindex 2c0036323d..a71b5e5c8d 100644--- a/saleor/plugins/sendgrid/plugin.py+++ b/saleor/plugins/sendgrid/plugin.py@@ -1,9 +1,11 @@import loggingfrom dataclasses import asdict+from typing import Unionfrom django.core.exceptions import ValidationErrorfrom ...core.notify_events import NotifyEventType, UserNotifyEvent+from ...plugins.sendgrid.tasks import send_email_with_dynamic_template_idfrom ..base_plugin import BasePlugin, ConfigurationTypeFieldfrom ..error_codes import PluginErrorCodefrom ..models import PluginConfiguration@@ -209,11 +211,17 @@ class SendgridEmailPlugin(BasePlugin):configuration = {item["name"]: item["value"] for item in self.configuration}self.config = SendgridConfiguration(**configuration)- def notify(self, event: NotifyEventType, payload: dict, previous_value):+ def notify(self, event: Union[NotifyEventType, str], payload: dict, previous_value):if not self.active:return previous_value- if event not in UserNotifyEvent.CHOICES:+ event_in_notify_event = event in UserNotifyEvent.CHOICES++ if not event_in_notify_event:+ logger.info(f"Send email with event {event} as dynamic template ID.")+ send_email_with_dynamic_template_id.delay(+ payload, event, asdict(self.config)+ )return previous_valueif event not in EVENT_MAP:diff --git a/saleor/plugins/sendgrid/tasks.py b/saleor/plugins/sendgrid/tasks.pyindex db280cb681..43b2ec1a0d 100644--- a/saleor/plugins/sendgrid/tasks.py+++ b/saleor/plugins/sendgrid/tasks.py@@ -308,3 +308,20 @@ def send_order_confirmed_email_task(payload: dict, configuration: dict):app_id=payload["requester_app_id"],customer_email=payload["recipient_email"],)+++ autoretry_for=(SendGridException,),+ retry_backoff=CELERY_RETRY_BACKOFF,+ retry_kwargs={"max_retries": CELERY_RETRY_MAX},+ compression="zlib",+)+def send_email_with_dynamic_template_id(+ payload: dict, template_id: str, configuration: dict+):+ configuration = SendgridConfiguration(**configuration)+ send_email(+ configuration=configuration,+ template_id=template_id,+ payload=payload,+ )diff --git a/saleor/plugins/sendgrid/tests/conftest.py b/saleor/plugins/sendgrid/tests/conftest.pyindex 662bc4d89a..daf72d074f 100644--- a/saleor/plugins/sendgrid/tests/conftest.py+++ b/saleor/plugins/sendgrid/tests/conftest.py@@ -1,7 +1,7 @@import pytest+from ....plugins.sendgrid.plugin import SendgridEmailPluginfrom ...manager import get_plugins_manager-from ..plugin import SendgridEmailPlugin@pytest.fixturediff --git a/saleor/plugins/sendgrid/tests/test_plugin.py b/saleor/plugins/sendgrid/tests/test_plugin.pyindex fad23f93d7..d4e412b490 100644--- a/saleor/plugins/sendgrid/tests/test_plugin.py+++ b/saleor/plugins/sendgrid/tests/test_plugin.py@@ -1,10 +1,13 @@+import jsonfrom dataclasses import asdictfrom unittest.mock import MagicMock, patchimport pytestfrom django.core.exceptions import ValidationError+from ....account.notifications import get_user_custom_payloadfrom ....core.notify_events import AdminNotifyEvent, UserNotifyEvent+from ....webhook.payloads import generate_product_variant_payloadfrom ...models import PluginConfigurationfrom ..plugin import EVENT_MAP@@ -14,6 +17,55 @@ def test_get_event_map():assert event in EVENT_MAP+@patch("saleor.plugins.sendgrid.tasks.send_email_with_dynamic_template_id.delay")+def test_notify_via_external_notification_trigger_with_extra_payload(+ mocked_event_map,+ staff_users,+ sendgrid_email_plugin,+):++ extra_payload = {"TEST": "VALUE", "TEST_LIST": ["GUEST1", "GUEST2"]}+ plugin = sendgrid_email_plugin(+ active=True, api_key="AB12", account_password_reset_template_id="123"+ )++ expected_payload = [get_user_custom_payload(user) for user in staff_users]+ for payload in expected_payload:+ payload["extra_payload"] = extra_payload+ test_template_id = "2efac70d-64ed-4e57-9951-f87e14d7e60e"+ plugin.notify(test_template_id, expected_payload, None)++ mocked_event_map.assert_called_once_with(+ expected_payload, test_template_id, asdict(plugin.config)+ )+++@patch("sendgrid.base_interface.BaseInterface.send")+def test_send_notification_to_customers_with_product_variant_payload(+ base_interface_mock,+ staff_users,+ sendgrid_email_plugin,+ product_with_single_variant,+):++ plugin = sendgrid_email_plugin(active=True, api_key="AB12")+ extra_payload = json.dumps(+ json.loads(+ generate_product_variant_payload(product_with_single_variant.variants.all())+ )[0]+ )++ expected_payload = [get_user_custom_payload(user) for user in staff_users]+ for payload in expected_payload:+ payload["extra_payload"] = extra_payload++ test_template_id = "2efac70d-64ed-4e57-9951-f87e14d7e60e"++ plugin.notify(test_template_id, expected_payload[0], None)++ base_interface_mock.assert_called_once()++@patch("saleor.plugins.sendgrid.plugin.EVENT_MAP")def test_notify_when_plugin_disabled(mocked_event_map, sendgrid_email_plugin):mocked_event_task = MagicMock()diff --git a/saleor/plugins/user_email/plugin.py b/saleor/plugins/user_email/plugin.pyindex 53a305f776..c6a6c7376b 100644--- a/saleor/plugins/user_email/plugin.py+++ b/saleor/plugins/user_email/plugin.py@@ -1,6 +1,6 @@import loggingfrom dataclasses import asdict, dataclass-from typing import Optional+from typing import Optional, Unionfrom ...core.notify_events import NotifyEventType, UserNotifyEventfrom ..base_plugin import BasePlugin, ConfigurationTypeField@@ -410,7 +410,7 @@ class UserEmailPlugin(BasePlugin):],)- def notify(self, event: NotifyEventType, payload: dict, previous_value):+ def notify(self, event: Union[NotifyEventType, str], payload: dict, previous_value):if not self.active:return previous_valueevent_map = get_user_event_map()diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex dd44013de6..d718616142 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -1,8 +1,9 @@import jsonimport logging-from typing import TYPE_CHECKING, Any, List, Optional+from typing import TYPE_CHECKING, Any, List, Optional, Unionfrom ...app.models import App+from ...core.notify_events import NotifyEventTypefrom ...core.utils.json_serializer import CustomJsonEncoderfrom ...payment import PaymentError, TransactionKindfrom ...webhook.event_types import WebhookEventType@@ -32,7 +33,6 @@ from .utils import (if TYPE_CHECKING:from ...account.models import Userfrom ...checkout.models import Checkout- from ...core.notify_events import NotifyEventTypefrom ...invoice.models import Invoicefrom ...order.models import Fulfillment, Orderfrom ...page.models import Page@@ -239,12 +239,22 @@ class WebhookPlugin(BasePlugin):WebhookEventType.CHECKOUT_UPDATED, checkout_data)- def notify(self, event: "NotifyEventType", payload: dict, previous_value) -> Any:+ def notify(+ self, event: Union[NotifyEventType, str], payload: dict, previous_value+ ) -> Any:if not self.active:return previous_value++ notify_user_event = WebhookEventType.NOTIFY_USERdata = {"notify_event": event, "payload": payload}++ if event not in NotifyEventType.CHOICES:+ logger.info(+ f"Webhook {notify_user_event} triggered for {event} notify event."+ )+trigger_webhooks_for_event.delay(- WebhookEventType.NOTIFY_USER, json.dumps(data, cls=CustomJsonEncoder)+ notify_user_event, json.dumps(data, cls=CustomJsonEncoder))def page_created(self, page: "Page", previous_value: Any) -> Any:diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.pyindex 372490de92..3a4e050d1a 100644--- a/saleor/plugins/webhook/tests/test_webhook.py+++ b/saleor/plugins/webhook/tests/test_webhook.py@@ -12,7 +12,7 @@ from ....account.notifications import (send_account_confirmation,)from ....app.models import App-from ....core.notifications import get_site_context+from ....core.notification.utils import get_site_contextfrom ....core.notify_events import NotifyEventTypefrom ....core.utils.json_serializer import CustomJsonEncoderfrom ....core.utils.url import prepare_url