Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Send email with link to download csv file with products data

IKarbowiak7267e2727591
diff --git a/saleor/csv/emails.py b/saleor/csv/emails.py
new file mode 100644
index 0000000000..3b8cee4113
--- /dev/null
+++ b/saleor/csv/emails.py
@@ -0,0 +1,24 @@
+from typing import TYPE_CHECKING
+
+from templated_email import send_templated_mail
+
+from ..core.emails import get_email_context
+from ..core.utils import build_absolute_uri
+
+if TYPE_CHECKING:
+ from .models import Job
+
+
+EXPORT_PRODUCTS_CSV_TEMPLATE = "csv/export_products_csv"
+
+
+def send_link_to_download_csv_for_products(job: "Job"):
+ recipient_email = job.user.email
+ send_kwargs, ctx = get_email_context()
+ ctx["csv_link"] = build_absolute_uri(job.content_file.url)
+ send_templated_mail(
+ template_name=EXPORT_PRODUCTS_CSV_TEMPLATE,
+ recipient_list=[recipient_email],
+ context=ctx,
+ **send_kwargs,
+ )
diff --git a/saleor/csv/utils/export.py b/saleor/csv/utils/export.py
index d62fc33975..fff11c1fb7 100644
--- a/saleor/csv/utils/export.py
+++ b/saleor/csv/utils/export.py
@@ -8,8 +8,10 @@ from django.db.models import F
from django.utils import timezone
from ...celeryconf import app
+from ...core.utils import build_absolute_uri
from ...product.models import Product
from .. import JobStatus
+from ..emails import send_link_to_download_csv_for_products
from ..models import Job
if TYPE_CHECKING:
@@ -22,6 +24,7 @@ if TYPE_CHECKING:
def export_products(
scope: Dict[str, Union[str, dict]], job_id: int, delimiter: str = ";"
):
+ job = Job.objects.get(pk=job_id)
queryset = get_product_queryset(scope)
file_name = "product_data_{}.csv".format(datetime.now().strftime("%d_%m_%Y"))
@@ -57,9 +60,11 @@ def export_products(
headers = list(csv_headers_mapping.keys()) + attributes_and_warehouse_headers
create_csv_file_and_update_job(
- export_data, headers, csv_headers_mapping, delimiter, job_id, file_name
+ export_data, headers, csv_headers_mapping, delimiter, job, file_name
)
+ send_link_to_download_csv_for_products(job)
+
def get_product_queryset(scope: Dict[str, Union[str, dict]]) -> "QuerySet":
from ...graphql.product.filters import ProductFilter
@@ -84,7 +89,7 @@ def create_csv_file_and_update_job(
headers: List[str],
csv_headers_mapping: Dict[str, str],
delimiter: str,
- job_id: int,
+ job: Job,
file_name: str,
):
table = etl.fromdicts(export_data, header=headers, missing=" ")
@@ -93,14 +98,13 @@ def create_csv_file_and_update_job(
temporary_file = NamedTemporaryFile()
etl.tocsv(table, temporary_file.name, delimiter=delimiter)
- update_job(job_id, temporary_file, file_name)
+ update_job(job, temporary_file, file_name)
# remove temporary file
temporary_file.close()
-def update_job(job_id: int, temporary_file: IO[bytes], file_name: str):
- job = Job.objects.get(pk=job_id)
+def update_job(job: Job, temporary_file: IO[bytes], file_name: str):
job.content_file.save(file_name, temporary_file)
job.status = JobStatus.SUCCESS # type:ignore
job.ended_at = datetime.now(timezone.get_current_timezone())
@@ -151,7 +155,7 @@ def update_product_data(
product_data["collections"] = ", ".join(
product.collections.values_list("slug", flat=True)
)
- product_data["images"] = get_images_urls(product)
+ product_data["images"] = get_images_uris(product)
product_attributes_data = prepare_attributes_data(product)
product_data.update(product_attributes_data)
@@ -161,7 +165,7 @@ def update_product_data(
def update_variant_data(
variant: "ProductVariant", variant_data: Dict["str", Union["str", bool]]
) -> Tuple[dict, list, list]:
- variant_data["images"] = get_images_urls(variant)
+ variant_data["images"] = get_images_uris(variant)
variant_attribute_data = prepare_attributes_data(variant)
variant_data.update(variant_attribute_data)
@@ -171,8 +175,11 @@ def update_variant_data(
return variant_data, variant_attribute_data.keys(), warehouse_data.keys()
-def get_images_urls(instance: Union[Product, "ProductVariant"]):
- return ", ".join([image.image.url for image in instance.images.all()])
+def get_images_uris(instance: Union[Product, "ProductVariant"]):
+ image_uris = filter(
+ None, [build_absolute_uri(image.image.url) for image in instance.images.all()]
+ )
+ return ", ".join(image_uris)
def prepare_attributes_data(instance: Union[Product, "ProductVariant"]):
diff --git a/templates/templated_email/csv/export_products_csv.email b/templates/templated_email/csv/export_products_csv.email
new file mode 100644
index 0000000000..ff0f921b91
--- /dev/null
+++ b/templates/templated_email/csv/export_products_csv.email
@@ -0,0 +1,19 @@
+{% load i18n %}
+
+{% block subject %}
+ {% trans "Export products data" context "Export products e-mail subject" %}
+{% endblock %}
+
+{% block plain %}
+{% include 'templated_email/shared/_header.email' %}
+
+{% blocktrans context "Export products e-mail text" %}
+Your csv file with products data is ready to download: {{ csv_link }}
+{% endblocktrans %}
+
+{% include 'templated_email/shared/_footer.email' %}
+{% endblock %}
+
+{% block html %}
+{% include 'templated_email/compiled/export_products_csv.html' %}
+{% endblock %}
diff --git a/templates/templated_email/source/export_products_csv.mjml b/templates/templated_email/source/export_products_csv.mjml
new file mode 100644
index 0000000000..2a198120b6
--- /dev/null
+++ b/templates/templated_email/source/export_products_csv.mjml
@@ -0,0 +1,24 @@
+<mjml>
+ <mj-head>
+ <mj-include path="./shared/styles.mjml" />
+ </mj-head>
+ <mj-body>
+ <mj-raw>
+ {% load i18n %}
+ </mj-raw>
+ <mj-include path="./shared/header.mjml" />
+ <mj-section>
+ <mj-column>
+ <mj-text font-size="16px">
+ {% trans "Hi!" context "Standard e-mail greeting" %}
+ </mj-text>
+ <mj-text>
+ {% blocktrans context "Export products e-mail text" %}
+ Your csv file with products data is ready to download: <a href="{{ csv_link }}">{{ csv_link }}</a>
+ {% endblocktrans %}
+ </mj-text>
+ </mj-column>
+ </mj-section>
+ <mj-include path="./shared/footer.mjml" />
+ </mj-body>
+</mjml>
diff --git a/tests/api/test_csv.py b/tests/api/test_csv.py
index 24ff276c7d..f9b86fe410 100644
--- a/tests/api/test_csv.py
+++ b/tests/api/test_csv.py
@@ -56,11 +56,14 @@ def test_export_products_mutation(
)
content = get_graphql_content(response)
data = content["data"]["exportProducts"]
+ job_data = data["job"]
export_products_mock.assert_called_once_with(called_data, ANY)
assert not data["csvErrors"]
assert data["job"]["id"]
+ assert job_data["createdAt"]
+ assert job_data["user"]["email"] == staff_api_client.user.email
@patch("saleor.graphql.csv.mutations.export_products.delay")
@@ -84,6 +87,7 @@ def test_export_products_mutation_ids_scope(
)
content = get_graphql_content(response)
data = content["data"]["exportProducts"]
+ job_data = data["job"]
export_products_mock.assert_called_once()
(call_args, call_kwargs,) = export_products_mock.call_args
@@ -92,6 +96,8 @@ def test_export_products_mutation_ids_scope(
assert not data["csvErrors"]
assert data["job"]["id"]
+ assert job_data["createdAt"]
+ assert job_data["user"]["email"] == staff_api_client.user.email
@pytest.mark.parametrize(
diff --git a/tests/test_csv_export.py b/tests/test_csv_export.py
index dfdae7805c..fba492760c 100644
--- a/tests/test_csv_export.py
+++ b/tests/test_csv_export.py
@@ -19,17 +19,19 @@ from saleor.product.models import Product
@pytest.mark.parametrize("scope", [{"filter": {"is_published": True}}, {"all": ""}])
+@patch("saleor.csv.utils.export.send_link_to_download_csv_for_products")
@patch("saleor.csv.utils.export.update_job")
-def test_export_products(update_job_mock, product_list, job, scope):
+def test_export_products(update_job_mock, send_email_mock, product_list, job, scope):
export_products(scope, job.id)
job.refresh_from_db()
- update_job_mock.called_once_with(job.id, ANY)
+ update_job_mock.called_once_with(job, ANY)
+ send_email_mock.called_once_with(job)
-@override_settings(MEDIA_ROOT=tempfile.gettempdir())
+@patch("saleor.csv.utils.export.send_link_to_download_csv_for_products")
@patch("saleor.csv.utils.export.update_job")
-def test_export_products_ids(update_job_mock, product_list, job):
+def test_export_products_ids(update_job_mock, send_email_mock, product_list, job):
pks = [product.pk for product in product_list[:2]]
assert job.status == JobStatus.PENDING
@@ -39,7 +41,8 @@ def test_export_products_ids(update_job_mock, product_list, job):
export_products({"ids": pks}, job.id)
job.refresh_from_db()
- update_job_mock.called_once_with(job.id, ANY)
+ update_job_mock.called_once_with(job, ANY)
+ send_email_mock.called_once_with(job)
@override_settings(MEDIA_ROOT=tempfile.gettempdir())
@@ -52,7 +55,7 @@ def test_update_job(job):
assert not job.ended_at
assert not job.content_file
- update_job(job.pk, file_mock, file_name)
+ update_job(job, file_mock, file_name)
job.refresh_from_db()
assert job.status.split(".")[1] == JobStatus.SUCCESS.name
@@ -107,7 +110,9 @@ def test_prepare_products_data(product, product_with_image, collection):
product_data["name"] = product.name
product_data["id"] = product.pk
product_data["images"] = (
- "" if not product.images.all() else product.images.first().image.url
+ ""
+ if not product.images.all()
+ else "http://mirumee.com{}".format(product.images.first().image.url)
)
assigned_attribute = product.attributes.first()
@@ -121,7 +126,9 @@ def test_prepare_products_data(product, product_with_image, collection):
for variant in product.variants.all():
variant_data = {}
variant_data["images"] = (
- "" if not variant.images.all() else variant.images.first().image.url
+ ""
+ if not variant.images.all()
+ else "http://mirumee.com{}".format(variant.images.first().image.url)
)
variant_data["sku"] = variant.sku