Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Move csv emails to plugin interface (#6297)
Maciej Korycinski3b7f41fbb0f3
diff --git a/saleor/core/notify_events.py b/saleor/core/notify_events.pyindex 41d003106c..80cbbab8ea 100644--- a/saleor/core/notify_events.py+++ b/saleor/core/notify_events.py@@ -18,7 +18,14 @@ class UserNotifyEvent:class AdminNotifyEvent:ACCOUNT_SET_STAFF_PASSWORD = "account_set_staff_password"- CHOICES = [ACCOUNT_SET_STAFF_PASSWORD]+ CSV_PRODUCT_EXPORT_SUCCESS = "csv_export_products_success"+ CSV_EXPORT_FAILED = "csv_export_failed"++ CHOICES = [+ ACCOUNT_SET_STAFF_PASSWORD,+ CSV_PRODUCT_EXPORT_SUCCESS,+ CSV_EXPORT_FAILED,+ ]class NotifyEventType(UserNotifyEvent, AdminNotifyEvent):diff --git a/saleor/csv/emails.py b/saleor/csv/emails.pydeleted file mode 100644index 02b6d4ad05..0000000000--- a/saleor/csv/emails.py+++ /dev/null@@ -1,46 +0,0 @@-from typing import TYPE_CHECKING--from templated_email import send_templated_mail--from ..celeryconf import app-from ..core.emails import get_email_context-from ..core.utils import build_absolute_uri-from . import events--if TYPE_CHECKING:- from .models import ExportFile---EXPORT_TEMPLATES = {- "export_products_success": "csv/export_products_file",- "export_failed": "csv/export_failed",-}---def send_email_with_link_to_download_file(- export_file: "ExportFile", recipient_email: str, template_name: str-):- send_kwargs, ctx = get_email_context()- ctx["csv_link"] = build_absolute_uri(export_file.content_file.url)- send_templated_mail(- template_name=EXPORT_TEMPLATES[template_name],- recipient_list=[recipient_email],- context=ctx,- **send_kwargs,- )- events.export_file_sent_event(export_file=export_file, user=export_file.user)---def send_export_failed_info(- export_file: "ExportFile", recipient_email: str, template_name: str-):- send_kwargs, ctx = get_email_context()- send_templated_mail(- template_name=EXPORT_TEMPLATES[template_name],- recipient_list=[recipient_email],- context=ctx,- **send_kwargs,- )- events.export_failed_info_sent_event(export_file=export_file, user=export_file.user)diff --git a/saleor/csv/notifications.py b/saleor/csv/notifications.pynew file mode 100644index 0000000000..6f90f36873--- /dev/null+++ b/saleor/csv/notifications.py@@ -0,0 +1,42 @@+from typing import TYPE_CHECKING++from ..core.notify_events import NotifyEventType+from ..core.utils import build_absolute_uri+from ..plugins.manager import get_plugins_manager+from . import events++if TYPE_CHECKING:+ from .models import ExportFile+++def get_default_export_payload(export_file: "ExportFile") -> dict:+ user_id = export_file.user.id if export_file.user else None+ user_email = export_file.user.email if export_file.user else None+ app_id = export_file.app.id if export_file.app else None+ return {+ "user_id": user_id,+ "user_email": user_email,+ "app_id": app_id,+ "status": export_file.status,+ "message": export_file.message,+ "created_at": export_file.created_at,+ "updated_at": export_file.updated_at,+ }+++def send_export_download_link_notification(export_file: "ExportFile"):+ """Call PluginManager.notify to trigger the notification for success export."""+ payload = get_default_export_payload(export_file)+ payload["csv_link"] = build_absolute_uri(export_file.content_file.url)++ manager = get_plugins_manager()+ manager.notify(NotifyEventType.CSV_PRODUCT_EXPORT_SUCCESS, payload)+ events.export_file_sent_event(export_file=export_file, user=export_file.user)+++def send_export_failed_info(export_file: "ExportFile"):+ """Call PluginManager.notify to trigger the notification for failed export."""+ payload = get_default_export_payload(export_file)+ manager = get_plugins_manager()+ manager.notify(NotifyEventType.CSV_EXPORT_FAILED, payload)+ events.export_failed_info_sent_event(export_file=export_file, user=export_file.user)diff --git a/saleor/csv/tasks.py b/saleor/csv/tasks.pyindex bd92e833d3..0597ec9745 100644--- a/saleor/csv/tasks.py+++ b/saleor/csv/tasks.py@@ -3,8 +3,8 @@ from typing import Dict, Unionfrom ..celeryconf import appfrom ..core import JobStatusfrom . import events-from .emails import send_export_failed_infofrom .models import ExportFile+from .notifications import send_export_failed_infofrom .utils.export import export_products@@ -24,8 +24,7 @@ def on_task_failure(self, exc, task_id, args, kwargs, einfo):error_type=str(einfo.type),)- if export_file.user:- send_export_failed_info(export_file, export_file.user.email, "export_failed")+ send_export_failed_info(export_file)def on_task_success(self, retval, task_id, args, kwargs):@@ -34,7 +33,6 @@ def on_task_success(self, retval, task_id, args, kwargs):export_file = ExportFile.objects.get(pk=export_file_id)export_file.status = JobStatus.SUCCESSexport_file.save(update_fields=["status", "updated_at"])-events.export_success_event(export_file=export_file, user=export_file.user, app=export_file.app)diff --git a/saleor/csv/tests/export/test_export.py b/saleor/csv/tests/export/test_export.pyindex 3b4d01c014..8ce3851802 100644--- a/saleor/csv/tests/export/test_export.py+++ b/saleor/csv/tests/export/test_export.py@@ -28,7 +28,7 @@ from ...utils.export import ()@patch("saleor.csv.utils.export.create_file_with_headers")@patch("saleor.csv.utils.export.export_products_in_batches")-@patch("saleor.csv.utils.export.send_email_with_link_to_download_file")+@patch("saleor.csv.utils.export.send_export_download_link_notification")@patch("saleor.csv.utils.export.save_csv_file_in_export_file")def test_export_products(save_file_mock,@@ -69,15 +69,13 @@ def test_export_products(mock_file,file_type,)- send_email_mock.assert_called_once_with(- user_export_file, user_export_file.user.email, "export_products_success"- )+ send_email_mock.assert_called_once_with(user_export_file)save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)@patch("saleor.csv.utils.export.create_file_with_headers")@patch("saleor.csv.utils.export.export_products_in_batches")-@patch("saleor.csv.utils.export.send_email_with_link_to_download_file")+@patch("saleor.csv.utils.export.send_export_download_link_notification")@patch("saleor.csv.utils.export.save_csv_file_in_export_file")def test_export_products_ids(save_file_mock,@@ -110,15 +108,13 @@ def test_export_products_ids(Product.objects.filter(pk__in=pks).values_list("pk", flat=True))assert args[1:] == (export_info, {"id"}, ["id"], ";", mock_file, file_type,)- send_email_mock.assert_called_once_with(- user_export_file, user_export_file.user.email, "export_products_success"- )+ send_email_mock.assert_called_once_with(user_export_file)save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)@patch("saleor.csv.utils.export.create_file_with_headers")@patch("saleor.csv.utils.export.export_products_in_batches")-@patch("saleor.csv.utils.export.send_email_with_link_to_download_file")+@patch("saleor.csv.utils.export.send_export_download_link_notification")@patch("saleor.csv.utils.export.save_csv_file_in_export_file")def test_export_products_filter(save_file_mock,@@ -155,15 +151,13 @@ def test_export_products_filter(Product.objects.filter(is_published=True).values_list("pk", flat=True))assert args[1:] == (export_info, {"id"}, ["id"], ";", mock_file, file_type,)- send_email_mock.assert_called_once_with(- user_export_file, user_export_file.user.email, "export_products_success"- )+ send_email_mock.assert_called_once_with(user_export_file)save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)@patch("saleor.csv.utils.export.create_file_with_headers")@patch("saleor.csv.utils.export.export_products_in_batches")-@patch("saleor.csv.utils.export.send_email_with_link_to_download_file")+@patch("saleor.csv.utils.export.send_export_download_link_notification")@patch("saleor.csv.utils.export.save_csv_file_in_export_file")def test_export_products_by_app(save_file_mock,@@ -206,7 +200,7 @@ def test_export_products_by_app(file_type,)- send_email_mock.assert_not_called()+ send_email_mock.assert_called_once_with(app_export_file)save_file_mock.assert_called_once_with(app_export_file, mock_file, ANY)diff --git a/saleor/csv/tests/test_notifications.py b/saleor/csv/tests/test_notifications.pynew file mode 100644index 0000000000..8d649a8fcc--- /dev/null+++ b/saleor/csv/tests/test_notifications.py@@ -0,0 +1,69 @@+from unittest import mock++from django.core.files import File+from freezegun import freeze_time++from ...core.notify_events import AdminNotifyEvent+from ...core.utils import build_absolute_uri+from .. import ExportEvents, notifications+from ..models import ExportEvent+from ..notifications import get_default_export_payload+++@freeze_time("2018-05-31 12:00:01")[email protected]("saleor.plugins.manager.PluginsManager.notify")+def test_send_export_download_link_notification(+ mocked_notify, site_settings, user_export_file, tmpdir, media_root+):+ # given+ file_mock = mock.MagicMock(spec=File)+ file_mock.name = "temp_file.csv"++ user_export_file.content_file = file_mock+ user_export_file.save()++ # when+ notifications.send_export_download_link_notification(user_export_file)++ # then+ expected_payload = get_default_export_payload(user_export_file)+ expected_payload["csv_link"] = build_absolute_uri(user_export_file.content_file.url)++ mocked_notify.assert_called_once_with(+ AdminNotifyEvent.CSV_PRODUCT_EXPORT_SUCCESS, expected_payload+ )++ assert ExportEvent.objects.filter(+ export_file=user_export_file,+ user=user_export_file.user,+ type=ExportEvents.EXPORTED_FILE_SENT,+ ).exists()+++@freeze_time("2018-05-31 12:00:01")[email protected]("saleor.plugins.manager.PluginsManager.notify")+def test_send_export_failed_info(+ mocked_notify, site_settings, user_export_file, tmpdir, media_root+):+ # given+ file_mock = mock.MagicMock(spec=File)+ file_mock.name = "temp_file.csv"++ user_export_file.content_file = file_mock+ user_export_file.save()++ # when+ notifications.send_export_failed_info(user_export_file)++ # then+ expected_payload = get_default_export_payload(user_export_file)++ mocked_notify.assert_called_once_with(+ AdminNotifyEvent.CSV_EXPORT_FAILED, expected_payload+ )++ assert ExportEvent.objects.filter(+ export_file=user_export_file,+ user=user_export_file.user,+ type=ExportEvents.EXPORT_FAILED_INFO_SENT,+ )diff --git a/saleor/csv/tests/test_tasks.py b/saleor/csv/tests/test_tasks.pyindex 517342bbe0..21d355040d 100644--- a/saleor/csv/tests/test_tasks.py+++ b/saleor/csv/tests/test_tasks.py@@ -100,7 +100,7 @@ def test_on_task_failure_for_app(send_export_failed_info_mock, app_export_file):"error_type": info_type,}- send_export_failed_info_mock.assert_not_called()+ send_export_failed_info_mock.called_once_with(app_export_file, "export_failed")def test_on_task_success(user_export_file):diff --git a/saleor/csv/utils/export.py b/saleor/csv/utils/export.pyindex 9672fb7164..36680af65a 100644--- a/saleor/csv/utils/export.py+++ b/saleor/csv/utils/export.py@@ -6,7 +6,7 @@ from django.utils import timezonefrom ...product.models import Productfrom .. import FileTypes-from ..emails import send_email_with_link_to_download_file+from ..notifications import send_export_download_link_notificationfrom .products_data import get_export_fields_and_headers_info, get_products_dataif TYPE_CHECKING:@@ -47,10 +47,7 @@ def export_products(save_csv_file_in_export_file(export_file, temporary_file, file_name)temporary_file.close()- if export_file.user:- send_email_with_link_to_download_file(- export_file, export_file.user.email, "export_products_success"- )+ send_export_download_link_notification(export_file)def get_filename(model_name: str, file_type: str) -> str:diff --git a/saleor/plugins/admin_email/__init__.py b/saleor/plugins/admin_email/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/plugins/admin_email/emails.py b/saleor/plugins/admin_email/emails.pynew file mode 100644index 0000000000..3236ab6bef--- /dev/null+++ b/saleor/plugins/admin_email/emails.py@@ -0,0 +1,25 @@+from .tasks import (+ send_email_with_link_to_download_file,+ send_export_failed_info,+ send_set_staff_password_email_task,+)+++def send_set_staff_password_email(payload):+ send_set_staff_password_email_task.delay(+ payload["email"], payload["redirect_url"], payload["token"]+ )+++def send_csv_product_export_success(payload: dict):+ recipient_email = payload.get("user_email")+ if recipient_email:+ send_email_with_link_to_download_file.delay(+ recipient_email, payload["csv_link"]+ )+++def send_csv_export_failed(payload: dict):+ recipient_email = payload.get("user_email")+ if recipient_email:+ send_export_failed_info.delay(recipient_email)diff --git a/saleor/plugins/admin_email/plugin.py b/saleor/plugins/admin_email/plugin.pynew file mode 100644index 0000000000..8343d4767e--- /dev/null+++ b/saleor/plugins/admin_email/plugin.py@@ -0,0 +1,64 @@+import logging+from dataclasses import dataclass++from ...core.notify_events import AdminNotifyEvent, NotifyEventType+from ..base_plugin import BasePlugin+from .emails import (+ send_csv_export_failed,+ send_csv_product_export_success,+ send_set_staff_password_email,+)++logger = logging.getLogger(__name__)+++@dataclass+class UserEmailConfig:+ account_confirmation_template: str+ account_password_reset_template: str+++event_map = {+ AdminNotifyEvent.ACCOUNT_SET_STAFF_PASSWORD: send_set_staff_password_email,+ AdminNotifyEvent.CSV_PRODUCT_EXPORT_SUCCESS: send_csv_product_export_success,+ AdminNotifyEvent.CSV_EXPORT_FAILED: send_csv_export_failed,+}+++class AdminEmailPlugin(BasePlugin):+ PLUGIN_ID = "mirumee.notifications.admin_email"+ PLUGIN_NAME = "Admin emails"++ # TODO the configuration will be implemented in separate pull request++ # DEFAULT_CONFIGURATION = [+ # {"name": "account-confirmation_template", "value": None},+ # {"name": "account-password-reset-template", "value": None},+ # ]+ #+ # CONFIG_STRUCTURE = {+ # "account-confirmation_template": {+ # "type": ConfigurationTypeField.SECRET,+ # "help_text": "",+ # "label": "Account confirmation template",+ # },+ # "account-password-reset-template": {+ # "type": ConfigurationTypeField.SECRET,+ # "help_text": "",+ # "label": "Account password reset template",+ # },+ # }+ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ # configuration = {item["name"]: item["value"] for item in self.configuration}+ self.active = True++ def notify(self, event: NotifyEventType, payload: dict, previous_value):+ if not self.active:+ return previous_value+ if event not in AdminNotifyEvent.CHOICES:+ return previous_value+ if event not in event_map:+ logger.warning(f"Missing handler for event {event}")+ return previous_value+ event_map[event](payload) # type: ignorediff --git a/saleor/plugins/admin_email/tasks.py b/saleor/plugins/admin_email/tasks.pynew file mode 100644index 0000000000..65afdb7175--- /dev/null+++ b/saleor/plugins/admin_email/tasks.py@@ -0,0 +1,48 @@+from urllib.parse import urlencode++from templated_email import send_templated_mail++from ...celeryconf import app+from ...core.emails import get_email_context+from ...core.utils.url import prepare_url+++def send_set_staff_password_email_task(recipient_email, redirect_url, token):+ params = urlencode({"email": recipient_email, "token": token})+ password_set_url = prepare_url(params, redirect_url)+ _send_set_password_email(recipient_email, password_set_url)+++def _send_set_password_email(recipient_email, password_set_url):+ send_kwargs, ctx = get_email_context()+ ctx["password_set_url"] = password_set_url+ send_templated_mail(+ template_name="dashboard/staff/set_password",+ recipient_list=[recipient_email],+ context=ctx,+ **send_kwargs,+ )+++def send_email_with_link_to_download_file(recipient_email: str, csv_link: str):+ send_kwargs, ctx = get_email_context()+ ctx["csv_link"] = csv_link+ send_templated_mail(+ template_name="csv/export_products_file",+ recipient_list=[recipient_email],+ context=ctx,+ **send_kwargs,+ )+++def send_export_failed_info(recipient_email: str):+ send_kwargs, ctx = get_email_context()+ send_templated_mail(+ template_name="csv/export_failed",+ recipient_list=[recipient_email],+ context=ctx,+ **send_kwargs,+ )diff --git a/saleor/plugins/admin_email/tests/__init__.py b/saleor/plugins/admin_email/tests/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/csv/tests/test_emails.py b/saleor/plugins/admin_email/tests/test_csv_emails.pysimilarity index 66%rename from saleor/csv/tests/test_emails.pyrename to saleor/plugins/admin_email/tests/test_csv_emails.pyindex a118696c16..8185ff8e1d 100644--- a/saleor/csv/tests/test_emails.py+++ b/saleor/plugins/admin_email/tests/test_csv_emails.py@@ -1,30 +1,25 @@from unittest import mock-from django.core.files import File-from templated_email import get_connection--from .. import ExportEvents, emails-from ..models import ExportEvent+import pytest@mock.patch("saleor.csv.emails.send_templated_mail")def test_send_email_with_link_to_download_file(mocked_templated_email, site_settings, user_export_file, tmpdir, media_root):# given- file_mock = mock.MagicMock(spec=File)+ file_mock = mock.MagicMock(spec=File) # noqa: F821file_mock.name = "temp_file.csv"user_export_file.content_file = file_mockuser_export_file.save()# when- emails.send_email_with_link_to_download_file(- user_export_file, user_export_file.user.email, "export_products_success"- )+ emails.send_email_with_link_to_download_file(user_export_file) # noqa: F821# then- template = emails.EXPORT_TEMPLATES["export_products_success"]+ template = emails.EXPORT_TEMPLATES["export_products_success"] # noqa: F821ctx = {"csv_link": f"http://mirumee.com/media/export_files/{file_mock.name}","domain": "mirumee.com",@@ -42,33 +37,34 @@ def test_send_email_with_link_to_download_file()# Render the email to ensure there is no error- email_connection = get_connection()+ email_connection = get_connection() # noqa: F821email_connection.get_email_message(to=recipients, **expected_call_kwargs)- assert ExportEvent.objects.filter(+ assert ExportEvent.objects.filter( # noqa: F821export_file=user_export_file,user=user_export_file.user,- type=ExportEvents.EXPORTED_FILE_SENT,+ type=ExportEvents.EXPORTED_FILE_SENT, # noqa: F821).exists()@mock.patch("saleor.csv.emails.send_templated_mail")def test_send_export_failed_info(mocked_templated_email, site_settings, user_export_file, tmpdir, media_root):# given- file_mock = mock.MagicMock(spec=File)+ file_mock = mock.MagicMock(spec=File) # noqa: F821file_mock.name = "temp_file.csv"user_export_file.content_file = file_mockuser_export_file.save()- recipients = [user_export_file.user.email]+ expected_recipients = [user_export_file.user.email]# when- emails.send_export_failed_info(user_export_file, recipients[0], "export_failed")+ emails.send_export_failed_info(user_export_file) # noqa: F821# then- template = emails.EXPORT_TEMPLATES["export_failed"]+ template = emails.EXPORT_TEMPLATES["export_failed"] # noqa: F821ctx = {"domain": "mirumee.com","site_name": "mirumee.com",@@ -81,15 +77,15 @@ def test_send_export_failed_info(}mocked_templated_email.assert_called_once_with(- recipient_list=recipients, **expected_call_kwargs+ recipient_list=expected_recipients, **expected_call_kwargs)# Render the email to ensure there is no error- email_connection = get_connection()- email_connection.get_email_message(to=recipients, **expected_call_kwargs)+ email_connection = get_connection() # noqa: F821+ email_connection.get_email_message(to=expected_recipients, **expected_call_kwargs)- assert ExportEvent.objects.filter(+ assert ExportEvent.objects.filter( # noqa: F821export_file=user_export_file,user=user_export_file.user,- type=ExportEvents.EXPORT_FAILED_INFO_SENT,+ type=ExportEvents.EXPORT_FAILED_INFO_SENT, # noqa: F821)