Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Migrate invoice email to plugin (#6302)
Maciej Korycinski5bca0c9d997e
diff --git a/saleor/core/notify_events.py b/saleor/core/notify_events.pyindex 80cbbab8ea..faae439bb3 100644--- a/saleor/core/notify_events.py+++ b/saleor/core/notify_events.py@@ -5,6 +5,7 @@ class UserNotifyEvent:ACCOUNT_CHANGE_EMAIL_CONFIRM = "account_change_email_confirm"ACCOUNT_DELETE = "account_delete"ACCOUNT_SET_CUSTOMER_PASSWORD = "account_set_customer_password"+ INVOICE_READY = "invoice_ready"CHOICES = [ACCOUNT_CONFIRMATION,@@ -13,6 +14,7 @@ class UserNotifyEvent:ACCOUNT_CHANGE_EMAIL_CONFIRM,ACCOUNT_DELETE,ACCOUNT_SET_CUSTOMER_PASSWORD,+ INVOICE_READY,]diff --git a/saleor/graphql/invoice/mutations.py b/saleor/graphql/invoice/mutations.pyindex 3961305e5c..30db3ee4f3 100644--- a/saleor/graphql/invoice/mutations.py+++ b/saleor/graphql/invoice/mutations.py@@ -4,8 +4,8 @@ from django.core.exceptions import ValidationErrorfrom ...core import JobStatusfrom ...core.permissions import OrderPermissionsfrom ...invoice import events, models-from ...invoice.emails import send_invoicefrom ...invoice.error_codes import InvoiceErrorCode+from ...invoice.notifications import send_invoicefrom ...order import OrderStatus, events as order_eventsfrom ..core.mutations import ModelDeleteMutation, ModelMutationfrom ..core.types.common import InvoiceError@@ -261,12 +261,12 @@ class InvoiceUpdate(ModelMutation):return InvoiceUpdate(invoice=instance)-class InvoiceSendEmail(ModelMutation):+class InvoiceSendNotification(ModelMutation):class Arguments:id = graphene.ID(required=True, description="ID of an invoice to be sent.")class Meta:- description = "Send an invoice by email."+ description = "Send an invoice notification to the customer."model = models.Invoicepermissions = (OrderPermissions.MANAGE_ORDERS,)error_type_class = InvoiceError@@ -303,10 +303,10 @@ class InvoiceSendEmail(ModelMutation):def perform_mutation(cls, _root, info, **data):instance = cls.get_instance(info, **data)cls.clean_instance(info, instance)- send_invoice.delay(instance.pk, info.context.user.pk)+ send_invoice(instance, info.context.user, info.context.plugins)order_events.invoice_sent_event(order=instance.order,user=info.context.user,email=instance.order.get_customer_email(),)- return InvoiceSendEmail(invoice=instance)+ return InvoiceSendNotification(invoice=instance)diff --git a/saleor/graphql/invoice/schema.py b/saleor/graphql/invoice/schema.pyindex e7102d45de..3bd8b0c1f0 100644--- a/saleor/graphql/invoice/schema.py+++ b/saleor/graphql/invoice/schema.py@@ -5,7 +5,7 @@ from .mutations import (InvoiceDelete,InvoiceRequest,InvoiceRequestDelete,- InvoiceSendEmail,+ InvoiceSendNotification,InvoiceUpdate,)@@ -16,4 +16,4 @@ class InvoiceMutations(graphene.ObjectType):invoice_create = InvoiceCreate.Field()invoice_delete = InvoiceDelete.Field()invoice_update = InvoiceUpdate.Field()- invoice_send_email = InvoiceSendEmail.Field()+ invoice_send_notification = InvoiceSendNotification.Field()diff --git a/saleor/graphql/invoice/tests/test_send_invoice_email.py b/saleor/graphql/invoice/tests/test_send_invoice_notification.pysimilarity index 69%rename from saleor/graphql/invoice/tests/test_send_invoice_email.pyrename to saleor/graphql/invoice/tests/test_send_invoice_notification.pyindex 271824291c..a7ddca1aff 100644--- a/saleor/graphql/invoice/tests/test_send_invoice_email.py+++ b/saleor/graphql/invoice/tests/test_send_invoice_notification.py@@ -3,14 +3,15 @@ from unittest.mock import patchimport graphenefrom ....core import JobStatus+from ....core.notify_events import NotifyEventTypefrom ....graphql.tests.utils import get_graphql_content-from ....invoice.emails import collect_invoice_data_for_emailfrom ....invoice.models import Invoice, InvoiceEvent, InvoiceEvents+from ....invoice.notifications import get_invoice_payloadfrom ....order import OrderEventsINVOICE_SEND_EMAIL_MUTATION = """- mutation invoiceSendEmail($id: ID!) {- invoiceSendEmail(+ mutation invoiceSendNotification($id: ID!) {+ invoiceSendNotification(id: $id) {invoiceErrors {@@ -22,9 +23,9 @@ INVOICE_SEND_EMAIL_MUTATION = """"""-@patch("saleor.invoice.emails.send_templated_mail")-def test_invoice_send_email(- email_mock, staff_api_client, permission_manage_orders, order+@patch("saleor.plugins.manager.PluginsManager.notify")+def test_invoice_send_notification(+ mock_notify, staff_api_client, permission_manage_orders, order):number = "01/12/2020/TEST"url = "http://www.example.com"@@ -36,9 +37,10 @@ def test_invoice_send_email(INVOICE_SEND_EMAIL_MUTATION, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)- call_args = collect_invoice_data_for_email(invoice, "order/send_invoice")- email_mock.assert_called_once_with(**call_args)- assert not content["data"]["invoiceSendEmail"]["invoiceErrors"]+ expected_payload = get_invoice_payload(invoice)++ mock_notify.assert_called_once_with(NotifyEventType.INVOICE_READY, expected_payload)+ assert not content["data"]["invoiceSendNotification"]["invoiceErrors"]assert InvoiceEvent.objects.filter(type=InvoiceEvents.SENT,user=staff_api_client.user,@@ -53,9 +55,9 @@ def test_invoice_send_email().exists()-@patch("saleor.invoice.emails.send_templated_mail")-def test_invoice_send_email_pending(- email_mock, staff_api_client, permission_manage_orders, order+@patch("saleor.plugins.manager.PluginsManager.notify")+def test_invoice_send_notification_pending(+ mock_notify, staff_api_client, permission_manage_orders, order):invoice = Invoice.objects.create(order=order, number=None, url=None, status=JobStatus.PENDING@@ -65,19 +67,19 @@ def test_invoice_send_email_pending(INVOICE_SEND_EMAIL_MUTATION, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)- errors = content["data"]["invoiceSendEmail"]["invoiceErrors"]+ errors = content["data"]["invoiceSendNotification"]["invoiceErrors"]assert errors == [{"field": "invoice", "code": "NOT_READY"},{"field": "url", "code": "URL_NOT_SET"},{"field": "number", "code": "NUMBER_NOT_SET"},]- email_mock.assert_not_called()+ mock_notify.assert_not_called()assert not order.events.filter(type=OrderEvents.INVOICE_SENT).exists()-@patch("saleor.invoice.emails.send_templated_mail")-def test_invoice_send_email_without_url_and_number(- email_mock, staff_api_client, permission_manage_orders, order+@patch("saleor.plugins.manager.PluginsManager.notify")+def test_invoice_send_notification_without_url_and_number(+ mock_notify, staff_api_client, permission_manage_orders, order):invoice = Invoice.objects.create(order=order, number=None, url=None, status=JobStatus.SUCCESS@@ -87,19 +89,19 @@ def test_invoice_send_email_without_url_and_number(INVOICE_SEND_EMAIL_MUTATION, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)- errors = content["data"]["invoiceSendEmail"]["invoiceErrors"]+ errors = content["data"]["invoiceSendNotification"]["invoiceErrors"]assert errors == [{"field": "url", "code": "URL_NOT_SET"},{"field": "number", "code": "NUMBER_NOT_SET"},]- email_mock.assert_not_called()+ mock_notify.assert_not_called()assert not order.events.filter(type=OrderEvents.INVOICE_SENT).exists()-@patch("saleor.invoice.emails.send_templated_mail")+@patch("saleor.plugins.manager.PluginsManager.notify")@patch("saleor.order.models.Order.get_customer_email")def test_invoice_send_email_without_email(- order_mock, email_mock, staff_api_client, permission_manage_orders, order+ order_mock, mock_notify, staff_api_client, permission_manage_orders, order):order_mock.return_value = Noneinvoice = Invoice.objects.create(@@ -113,8 +115,8 @@ def test_invoice_send_email_without_email(INVOICE_SEND_EMAIL_MUTATION, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)- email_mock.assert_not_called()+ mock_notify.assert_not_called()assert order_mock.called- errors = content["data"]["invoiceSendEmail"]["invoiceErrors"]+ errors = content["data"]["invoiceSendNotification"]["invoiceErrors"]assert errors == [{"field": "order", "code": "EMAIL_NOT_SET"}]assert not order.events.filter(type=OrderEvents.INVOICE_SENT).exists()diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 5df08e7b29..d85d620169 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2200,7 +2200,7 @@ type InvoiceRequestDelete {invoice: Invoice}-type InvoiceSendEmail {+type InvoiceSendNotification {errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")invoiceErrors: [InvoiceError!]!invoice: Invoice@@ -2740,7 +2740,7 @@ type Mutation {invoiceCreate(input: InvoiceCreateInput!, orderId: ID!): InvoiceCreateinvoiceDelete(id: ID!): InvoiceDeleteinvoiceUpdate(id: ID!, input: UpdateInvoiceInput!): InvoiceUpdate- invoiceSendEmail(id: ID!): InvoiceSendEmail+ invoiceSendNotification(id: ID!): InvoiceSendNotificationgiftCardActivate(id: ID!): GiftCardActivategiftCardCreate(input: GiftCardCreateInput!): GiftCardCreategiftCardDeactivate(id: ID!): GiftCardDeactivatediff --git a/saleor/invoice/emails.py b/saleor/invoice/emails.pydeleted file mode 100644index 1f80919137..0000000000--- a/saleor/invoice/emails.py+++ /dev/null@@ -1,34 +0,0 @@-from templated_email import send_templated_mail--from ..account.models import User-from ..celeryconf import app-from ..core.emails import get_email_context-from ..invoice import events-from ..plugins.manager import get_plugins_manager-from .models import Invoice---def collect_invoice_data_for_email(invoice, template):- """Collect the required data for sending emails."""- send_kwargs, email_context = get_email_context()-- email_context["number"] = invoice.number- email_context["download_url"] = invoice.url-- return {- "recipient_list": [invoice.order.get_customer_email()],- "template_name": template,- "context": email_context,- **send_kwargs,- }---def send_invoice(invoice_pk, staff_user_pk):- """Send an invoice to user of related order with URL to download it."""- invoice = Invoice.objects.select_related("order").get(pk=invoice_pk)- email_data = collect_invoice_data_for_email(invoice, "order/send_invoice")- send_templated_mail(**email_data)- events.invoice_sent_event(user=User.objects.get(pk=staff_user_pk), invoice=invoice)- manager = get_plugins_manager()- manager.invoice_sent(invoice, invoice.order.get_customer_email())diff --git a/saleor/invoice/notifications.py b/saleor/invoice/notifications.pynew file mode 100644index 0000000000..2b2792d0f4--- /dev/null+++ b/saleor/invoice/notifications.py@@ -0,0 +1,22 @@+from ..account.models import User+from ..core.notify_events import NotifyEventType+from ..invoice import events+from ..plugins.manager import PluginsManager+from .models import Invoice+++def get_invoice_payload(invoice):+ return {+ "id": invoice.id,+ "number": invoice.number,+ "download_url": invoice.url,+ "recipient": invoice.order.get_customer_email(),+ }+++def send_invoice(invoice: "Invoice", staff_user: "User", manager: "PluginsManager"):+ """Send an invoice to user of related order with URL to download it."""+ invoice_payload = get_invoice_payload(invoice)+ manager.notify(NotifyEventType.INVOICE_READY, invoice_payload)+ manager.invoice_sent(invoice, invoice.order.get_customer_email()) # type: ignore+ events.invoice_sent_event(user=staff_user, invoice=invoice)diff --git a/saleor/invoice/tests/__init__.py b/saleor/invoice/tests/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/invoice/tests/test_notifications.py b/saleor/invoice/tests/test_notifications.pynew file mode 100644index 0000000000..0a6dedf717--- /dev/null+++ b/saleor/invoice/tests/test_notifications.py@@ -0,0 +1,13 @@+from ..models import Invoice+from ..notifications import get_invoice_payload+++def test_collect_invoice_data_for_email(order):+ number = "01/12/2020/TEST"+ url = "http://www.example.com"+ invoice = Invoice.objects.create(number=number, url=url, order=order)+ payload = get_invoice_payload(invoice)+ assert payload["id"] == invoice.id+ assert payload["number"] == number+ assert payload["download_url"] == url+ assert payload["recipient"] == order.user.emaildiff --git a/saleor/order/tests/test_emails.py b/saleor/order/tests/test_emails.pyindex 7dc5649ebe..1c28eda766 100644--- a/saleor/order/tests/test_emails.py+++ b/saleor/order/tests/test_emails.py@@ -4,8 +4,6 @@ from unittest import mockimport pytestfrom templated_email import get_connection-from ...invoice import emails as invoice_emails-from ...invoice.models import Invoicefrom ...order import OrderEvents, emails as emailsfrom ..utils import add_variant_to_draft_order@@ -21,19 +19,6 @@ def test_collect_data_for_order_confirmation_email(order):assert "schema_markup" in email_context-def test_collect_invoice_data_for_email(order):- number = "01/12/2020/TEST"- url = "http://www.example.com"- invoice = Invoice.objects.create(number=number, url=url, order=order)- email_data = invoice_emails.collect_invoice_data_for_email(- invoice, "order/send_invoice"- )- email_context = email_data["context"]- assert email_context["number"] == number- assert email_context["download_url"] == url- assert email_data["recipient_list"] == [order.user.email]--def test_collect_data_for_fulfillment_email(fulfilled_order):template = emails.CONFIRM_FULFILLMENT_TEMPLATEfulfillment = fulfilled_order.fulfillments.first()diff --git a/saleor/plugins/user_email/emails.py b/saleor/plugins/user_email/emails.pyindex f3287cb894..1ee36d95e3 100644--- a/saleor/plugins/user_email/emails.py+++ b/saleor/plugins/user_email/emails.py@@ -2,6 +2,7 @@ from ...account.models import Userfrom .tasks import (send_account_confirmation_email_task,send_account_delete_confirmation_email_task,+ send_invoice_task,send_password_reset_email_task,send_request_email_change_email_task,send_set_user_password_email_task,@@ -62,3 +63,11 @@ def handle_account_set_customer_password(payload):send_set_user_password_email_task.delay(payload["email"], payload["redirect_url"], payload["token"])+++def handle_send_invoice(payload):+ send_invoice_task.delay(+ recipient_email=payload["recipient"],+ invoice_number=payload["number"],+ invoice_download_url=payload["download_url"],+ )diff --git a/saleor/plugins/user_email/plugin.py b/saleor/plugins/user_email/plugin.pyindex 460e1f62e6..403f0b8154 100644--- a/saleor/plugins/user_email/plugin.py+++ b/saleor/plugins/user_email/plugin.py@@ -10,6 +10,7 @@ from .emails import (handle_account_delete,handle_account_password_reset_event,handle_account_set_customer_password,+ handle_send_invoice,)logger = logging.getLogger(__name__)@@ -28,6 +29,7 @@ event_map = {UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_CONFIRM: handle_account_change_email_confirm,UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_REQUEST: handle_account_change_email_request,UserNotifyEvent.ACCOUNT_PASSWORD_RESET: handle_account_password_reset_event,+ UserNotifyEvent.INVOICE_READY: handle_send_invoice,}@@ -61,6 +63,7 @@ class UserEmailPlugin(BasePlugin):def notify(self, event: NotifyEventType, payload: dict, previous_value):if not self.active:return previous_value+if event not in UserNotifyEvent.CHOICES:return previous_valueif event not in event_map:diff --git a/saleor/plugins/user_email/tasks.py b/saleor/plugins/user_email/tasks.pyindex 4bba37d281..8449c8d6a3 100644--- a/saleor/plugins/user_email/tasks.py+++ b/saleor/plugins/user_email/tasks.py@@ -110,3 +110,17 @@ def _send_set_password_email(recipient_email, password_set_url):context=ctx,**send_kwargs,)+++def send_invoice_task(recipient_email, invoice_number, invoice_download_url):+ """Send an invoice to user of related order with URL to download it."""+ send_kwargs, ctx = get_email_context()+ ctx["number"] = invoice_number+ ctx["download_url"] = invoice_download_url+ send_templated_mail(+ template_name="order/send_invoice",+ recipient_list=[recipient_email],+ context=ctx,+ **send_kwargs,+ )