Skip to content

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

Update order email payload (#6938)

Maciej Korycinski3e124cca39af
diff --git a/.isort.cfg b/.isort.cfg
index f8067be68d..8cc6cfedac 100644
--- a/.isort.cfg
+++ b/.isort.cfg
@@ -1,2 +1,2 @@
[settings]
-known_third_party = Adyen,PIL,authorizenet,babel,boto3,braintree,celery,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,google,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html2text,html_to_draftjs,i18naddress,jaeger_client,jwt,kombu,lxml,markdown,measurement,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,prices,promise,pybars,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sentry_sdk,storages,stripe,tqdm,urllib3,versatileimagefield,weasyprint
+known_third_party = Adyen,PIL,authorizenet,babel,boto3,braintree,celery,dateutil,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,google,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html2text,html_to_draftjs,i18naddress,jaeger_client,jwt,kombu,lxml,markdown,measurement,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,prices,promise,pybars,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sentry_sdk,storages,stripe,tqdm,urllib3,versatileimagefield,weasyprint
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index d518ad8a88..0721db9c99 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -26,7 +26,7 @@ from ..discount.utils import (
from ..order import OrderLineData, OrderStatus
from ..order.actions import order_created
from ..order.models import Order, OrderLine
-from ..order.notifications import send_order_confirmation, send_staff_order_confirmation
+from ..order.notifications import send_order_confirmation
from ..payment import PaymentError, gateway
from ..payment.models import Payment, Transaction
from ..payment.utils import store_customer_id
@@ -397,12 +397,6 @@ def _create_order(
transaction.on_commit(
lambda: send_order_confirmation(order, checkout.redirect_url, plugin_manager)
)
- # TODO we can drop it and subscribe admin and user email plugins to the same event
- transaction.on_commit(
- lambda: send_staff_order_confirmation(
- order, checkout.redirect_url, plugin_manager
- )
- )
return order
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index 51b9ba81c5..918ead99ba 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -157,8 +157,6 @@ def test_create_order_captured_payment_creates_expected_events(
assert placement_event.date # ensure a date was set
assert not placement_event.parameters # should not have any additional parameters
- # mock_send_staff_order_confirmation.assert_called_once_with(order.pk)
-
@mock.patch("saleor.plugins.manager.PluginsManager.notify")
def test_create_order_captured_payment_creates_expected_events_anonymous_user(
@@ -399,8 +397,6 @@ def test_create_order_preauth_payment_creates_expected_events(
assert placement_event.date # ensure a date was set
assert not placement_event.parameters # should not have any additional parameters
- # mock_send_staff_order_confirmation.assert_called_once_with(order.pk)
-
@mock.patch("saleor.plugins.manager.PluginsManager.notify")
def test_create_order_preauth_payment_creates_expected_events_anonymous_user(
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 50c4407485..8a7bc49aff 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -3,7 +3,7 @@ from urllib.parse import urljoin
import graphene
from django.conf import settings
-from ....product.templatetags.product_images import get_thumbnail
+from ....product.product_images import get_thumbnail
from ..enums import (
AccountErrorCode,
AppErrorCode,
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 14c151a09b..79ec1ed7f0 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -13,7 +13,7 @@ from ...order import OrderStatus, models
from ...order.models import FulfillmentStatus
from ...order.utils import get_order_country, get_valid_shipping_methods_for_order
from ...plugins.manager import get_plugins_manager
-from ...product.templatetags.product_images import get_product_image_thumbnail
+from ...product.product_images import get_product_image_thumbnail
from ...warehouse import models as warehouse_models
from ..account.types import User
from ..account.utils import requestor_has_access
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 4b8117ba96..ff043397e6 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -13,10 +13,7 @@ from ....core.permissions import OrderPermissions, ProductPermissions
from ....core.utils import get_currency_for_country
from ....core.weight import convert_weight_to_default_weight_unit
from ....product import models
-from ....product.templatetags.product_images import (
- get_product_image_thumbnail,
- get_thumbnail,
-)
+from ....product.product_images import get_product_image_thumbnail, get_thumbnail
from ....product.utils import calculate_revenue_for_variant
from ....product.utils.availability import (
get_product_availability,
diff --git a/saleor/order/notifications.py b/saleor/order/notifications.py
index 84e40a567f..6ae6127dcd 100644
--- a/saleor/order/notifications.py
+++ b/saleor/order/notifications.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, Iterable, Optional
+from typing import TYPE_CHECKING, Iterable, List, Optional
from urllib.parse import urlencode
from django.forms import model_to_dict
@@ -7,7 +7,8 @@ from ..account.models import StaffNotificationRecipient
from ..core.notifications import get_site_context
from ..core.notify_events import NotifyEventType
from ..core.utils.url import prepare_url
-from ..product.models import DigitalContentUrl
+from ..product.models import DigitalContentUrl, Product, ProductImage, ProductVariant
+from ..product.product_images import AVAILABLE_PRODUCT_SIZES, get_thumbnail
from .models import FulfillmentLine, Order, OrderLine
if TYPE_CHECKING:
@@ -16,6 +17,70 @@ if TYPE_CHECKING:
from ..account.models import User # noqa: F401
+def get_image_payload(instance: ProductImage):
+ image_file = instance.image if instance else None
+ return {
+ size: get_thumbnail(image_file, size, "thumbnail")
+ for size in AVAILABLE_PRODUCT_SIZES
+ }
+
+
+def get_default_images_payload(images: List[ProductImage]):
+ first_image_payload = None
+ first_image = images[0] if images else None
+ if first_image:
+ first_image_payload = ({"original": get_image_payload(first_image)},)
+ images_payload = None
+ if images:
+ images_payload = [{"original": get_image_payload(image) for image in images}]
+ return {"first_image": first_image_payload, "images": images_payload}
+
+
+def get_product_attributes(product):
+ attributes = product.attributes.all()
+ attributes_payload = []
+ for attr in attributes:
+ attributes_payload.append(
+ {
+ "assignment": {
+ "attribute": {
+ "slug": attr.assignment.attribute.slug,
+ "name": attr.assignment.attribute.name,
+ }
+ },
+ "values": [
+ {
+ "name": value.get("name"),
+ "value": value.get("value"),
+ "slug": value.get("slug"),
+ "file_url": value.get("file_url"),
+ }
+ for value in attr.values.values("name", "value", "slug", "file_url")
+ ],
+ }
+ )
+ return attributes_payload
+
+
+def get_product_payload(product: Product):
+ images = list(product.images.all())
+ return {
+ "id": product.id,
+ "attributes": get_product_attributes(product),
+ "weight": str(product.weight or ""),
+ **get_default_images_payload(images),
+ }
+
+
+def get_product_variant_payload(variant: ProductVariant):
+ images = list(variant.images.all())
+ return {
+ "id": variant.id,
+ "weight": str(variant.weight or ""),
+ **get_default_images_payload(images),
+ }
+
+
def get_order_line_payload(line: "OrderLine"):
digital_url = ""
if line.is_digital:
@@ -23,9 +88,11 @@ def get_order_line_payload(line: "OrderLine"):
digital_url = content.get_absolute_url() if content else None # type: ignore
return {
"id": line.id,
+ "product": get_product_payload(line.variant.product), # type: ignore
"product_name": line.product_name,
"translated_product_name": line.translated_product_name or line.product_name,
"variant_name": line.variant_name,
+ "variant": get_product_variant_payload(line.variant), # type: ignore
"translated_variant_name": line.translated_variant_name or line.variant_name,
"product_sku": line.product_sku,
"quantity": line.quantity,
@@ -98,6 +165,12 @@ def get_default_order_payload(order: "Order", redirect_url: str = ""):
subtotal = order.get_subtotal()
tax = order.total_gross_amount - order.total_net_amount
+ lines = order.lines.prefetch_related(
+ "variant__product__images",
+ "variant__images",
+ "variant__product__attributes__assignment__attribute",
+ "variant__product__attributes__values",
+ ).all()
order_payload = model_to_dict(order, fields=ORDER_MODEL_FIELDS)
order_payload.update(
{
@@ -111,7 +184,7 @@ def get_default_order_payload(order: "Order", redirect_url: str = ""):
"subtotal_net_amount": subtotal.net.amount,
"tax_amount": tax,
"discount_name": order.translated_discount_name or order.discount_name,
- "lines": get_lines_payload(order.lines.all()),
+ "lines": get_lines_payload(lines),
"billing_address": get_address_payload(order.billing_address),
"shipping_address": get_address_payload(order.shipping_address),
"shipping_method_name": order.shipping_method_name,
@@ -167,20 +240,7 @@ def send_order_confirmation(order, redirect_url, manager):
}
manager.notify(NotifyEventType.ORDER_CONFIRMATION, payload)
-
-def send_order_confirmed(order, user, manager):
- """Send email which tells customer that order has been confirmed."""
- payload = {
- "order": get_default_order_payload(order, order.redirect_url),
- "recipient_email": order.get_customer_email(),
- "requester_user_id": user.id,
- **get_site_context(),
- }
- manager.notify(NotifyEventType.ORDER_CONFIRMED, payload)
-
-
-def send_staff_order_confirmation(order, redirect_url, manager):
- """Send staff notification with order confirmation."""
+ # Prepare staff notification for this order
staff_notifications = StaffNotificationRecipient.objects.filter(
active=True, user__is_active=True, user__is_staff=True
)
@@ -189,13 +249,24 @@ def send_staff_order_confirmation(order, redirect_url, manager):
]
if recipient_emails:
payload = {
- "order": get_default_order_payload(order, redirect_url),
+ "order": payload["order"],
"recipient_list": recipient_emails,
**get_site_context(),
}
manager.notify(NotifyEventType.STAFF_ORDER_CONFIRMATION, payload=payload)
+def send_order_confirmed(order, user, manager):
+ """Send email which tells customer that order has been confirmed."""
+ payload = {
+ "order": get_default_order_payload(order, order.redirect_url),
+ "recipient_email": order.get_customer_email(),
+ "requester_user_id": user.id,
+ **get_site_context(),
+ }
+ manager.notify(NotifyEventType.ORDER_CONFIRMED, payload)
+
+
def send_fulfillment_confirmation_to_customer(order, fulfillment, user, manager):
payload = get_default_fulfillment_payload(order, fulfillment)
payload["requester_user_id"] = user.id if user else None
diff --git a/saleor/order/tests/test_notifications.py b/saleor/order/tests/test_notifications.py
index e49b60d394..2eab4261bd 100644
--- a/saleor/order/tests/test_notifications.py
+++ b/saleor/order/tests/test_notifications.py
@@ -1,5 +1,7 @@
from unittest import mock
+from measurement.measures import Weight
+
from ...core.notify_events import NotifyEventType
from ...order import notifications
from ...plugins.manager import get_plugins_manager
@@ -15,7 +17,33 @@ from ..utils import add_variant_to_draft_order
def test_get_order_line_payload(order_line):
+ order_line.variant.product.weight = Weight(kg=5)
+ order_line.variant.product.save()
+
payload = get_order_line_payload(order_line)
+
+ attributes = order_line.variant.product.attributes.all()
+ expected_attributes_payload = []
+ for attr in attributes:
+ expected_attributes_payload.append(
+ {
+ "assignment": {
+ "attribute": {
+ "slug": attr.assignment.attribute.slug,
+ "name": attr.assignment.attribute.name,
+ }
+ },
+ "values": [
+ {
+ "name": value.name,
+ "value": value.value,
+ "slug": value.slug,
+ "file_url": value.file_url,
+ }
+ for value in attr.values.all()
+ ],
+ }
+ )
unit_tax_amount = (
order_line.unit_price_gross_amount - order_line.unit_price_net_amount
)
@@ -23,6 +51,19 @@ def test_get_order_line_payload(order_line):
total_net = order_line.unit_price_net * order_line.quantity
total_tax = total_gross - total_net
assert payload == {
+ "variant": {
+ "id": order_line.variant_id,
+ "first_image": None,
+ "images": None,
+ "weight": "",
+ },
+ "product": {
+ "attributes": expected_attributes_payload,
+ "first_image": None,
+ "images": None,
+ "weight": "5.0 kg",
+ "id": order_line.variant.product.id,
+ },
"translated_product_name": order_line.translated_product_name
or order_line.product_name,
"translated_variant_name": order_line.translated_variant_name
@@ -161,35 +202,6 @@ def test_send_email_payment_confirmation(mocked_notify, site_settings, payment_d
)
[email protected]("saleor.plugins.manager.PluginsManager.notify")
-def test_send_staff_emails_without_notification_recipient(
- mocked_notify, order, site_settings
-):
- manager = get_plugins_manager()
- notifications.send_staff_order_confirmation(
- order, "http://www.example.com/", manager
- )
- mocked_notify.assert_not_called()
-
-
[email protected]("saleor.plugins.manager.PluginsManager.notify")
-def test_send_staff_emails(
- mocked_notify, order, site_settings, staff_notification_recipient
-):
- manager = get_plugins_manager()
- redirect_url = "http://www.example.com/"
- notifications.send_staff_order_confirmation(order, redirect_url, manager)
- expected_payload = {
- "order": get_default_order_payload(order, redirect_url),
- "recipient_list": [staff_notification_recipient.get_email()],
- "site_name": "mirumee.com",
- "domain": "mirumee.com",
- }
- mocked_notify.assert_called_once_with(
- NotifyEventType.STAFF_ORDER_CONFIRMATION, payload=expected_payload
- )
-
-
@mock.patch("saleor.plugins.manager.PluginsManager.notify")
def test_send_email_order_confirmation(mocked_notify, order, site_settings):
manager = get_plugins_manager()
diff --git a/saleor/plugins/email_common.py b/saleor/plugins/email_common.py
index f21d121129..f136129f28 100644
--- a/saleor/plugins/email_common.py
+++ b/saleor/plugins/email_common.py
@@ -1,4 +1,5 @@
import logging
+import operator
import os
import re
from dataclasses import dataclass
@@ -6,6 +7,7 @@ from decimal import Decimal, InvalidOperation
from email.headerregistry import Address
from typing import List, Optional
+import dateutil.parser
import html2text
import i18naddress
import pybars
@@ -17,6 +19,7 @@ from django.core.mail import send_mail
from django.core.mail.backends.smtp import EmailBackend
from django_prices.utils.locale import get_locale_data
+from ..product.product_images import get_thumbnail_size
from .base_plugin import ConfigurationTypeField
from .error_codes import PluginErrorCode
from .models import PluginConfiguration
@@ -127,6 +130,35 @@ def format_address(this, address, include_phone=True, inline=False, latin=False)
return pybars.strlist(["<br>".join(address_lines)])
+def format_datetime(this, date, date_format=None):
+ """Convert datetime to a required format."""
+ date = dateutil.parser.isoparse(date)
+ if date_format is None:
+ date_format = "%d-%m-%Y"
+ return date.strftime(date_format)
+
+
+def get_product_image_thumbnail(this, size, image):
+ """Use provided size to get a correct image."""
+ expected_size = get_thumbnail_size(size, "thumbnail", "products", on_demand=False)
+ return image["original"][expected_size]
+
+
+def compare(this, val1, compare_operator, val2):
+ """Compare two values based on the provided operator."""
+ operators = {
+ "==": operator.eq,
+ "!=": operator.neg,
+ "<": operator.lt,
+ "<=": operator.le,
+ ">=": operator.ge,
+ ">": operator.gt,
+ }
+ if compare_operator not in operators:
+ return False
+ return operators[compare_operator](val1, val2)
+
+
def price(this, net_amount, gross_amount, currency, display_gross=False):
amount = net_amount
if display_gross:
@@ -175,6 +207,9 @@ def send_email(
helpers = {
"format_address": format_address,
"price": price,
+ "format_datetime": format_datetime,
+ "get_product_image_thumbnail": get_product_image_thumbnail,
+ "compare": compare,
}
message = template(context, helpers=helpers)
subject_message = subject_template(context, helpers)
diff --git a/saleor/product/templatetags/product_images.py b/saleor/product/product_images.py
similarity index 86%
rename from saleor/product/templatetags/product_images.py
rename to saleor/product/product_images.py
index 24d205bca8..5298406297 100644
--- a/saleor/product/templatetags/product_images.py
+++ b/saleor/product/product_images.py
@@ -1,13 +1,12 @@
import logging
import re
import warnings
+from typing import List
-from django import template
from django.conf import settings
from django.templatetags.static import static
logger = logging.getLogger(__name__)
-register = template.Library()
# cache available sizes at module level
@@ -22,6 +21,18 @@ def get_available_sizes():
AVAILABLE_SIZES = get_available_sizes()
+def get_available_product_sizes() -> List[str]:
+ """Get list of available product sizes."""
+ sizes = AVAILABLE_SIZES["products"]
+ product_sizes = []
+ for size in sizes:
+ product_sizes.append(size.strip("thumbnail__"))
+ return product_sizes
+
+
+AVAILABLE_PRODUCT_SIZES = get_available_product_sizes()
+
+
def choose_placeholder(size=""):
# type: (str) -> str
"""Assign a placeholder at least as big as provided size if possible.
@@ -53,12 +64,13 @@ def get_available_sizes_by_method(method, rendition_key_set):
return sizes
-def get_thumbnail_size(size, method, rendition_key_set):
+def get_thumbnail_size(size, method, rendition_key_set, on_demand=None):
"""Return the closest larger size if not more than 2 times larger.
Otherwise, return the closest smaller size
"""
- on_demand = settings.VERSATILEIMAGEFIELD_SETTINGS["create_images_on_demand"]
+ if on_demand is None:
+ on_demand = settings.VERSATILEIMAGEFIELD_SETTINGS["create_images_on_demand"]
if isinstance(size, int):
size_str = "%sx%s" % (size, size)
else:
@@ -82,7 +94,6 @@ def get_thumbnail_size(size, method, rendition_key_set):
return None
def get_thumbnail(image_file, size, method, rendition_key_set="products"):
if image_file:
used_size = get_thumbnail_size(size, method, rendition_key_set)
@@ -97,7 +108,6 @@ def get_thumbnail(image_file, size, method, rendition_key_set="products"):
return static(choose_placeholder("%sx%s" % (size, size)))
def get_product_image_thumbnail(instance, size, method):
image_file = instance.image if instance else None
return get_thumbnail(image_file, size, method)
diff --git a/saleor/product/templatetags/__init__.py b/saleor/product/templatetags/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/saleor/product/tests/test_product_tags.py b/saleor/product/tests/test_product_tags.py
index 9ffb648505..29ba3e534c 100644
--- a/saleor/product/tests/test_product_tags.py
+++ b/saleor/product/tests/test_product_tags.py
@@ -4,7 +4,7 @@ import pytest
from django.templatetags.static import static
from django.test import override_settings
-from ..templatetags.product_images import (
+from ..product_images import (
choose_placeholder,
get_product_image_thumbnail,
get_thumbnail,
@@ -26,7 +26,7 @@ def test_get_thumbnail():
def test_get_thumbnail_no_instance(monkeypatch):
monkeypatch.setattr(
- "saleor.product.templatetags.product_images.choose_placeholder",
+ "saleor.product.product_images.choose_placeholder",
lambda x: "placeholder",
)
output = get_thumbnail(image_file=None, size=10, method="crop")
@@ -35,7 +35,7 @@ def test_get_thumbnail_no_instance(monkeypatch):
def test_get_product_image_thumbnail_no_instance(monkeypatch):
monkeypatch.setattr(
- "saleor.product.templatetags.product_images.choose_placeholder",
+ "saleor.product.product_images.choose_placeholder",
lambda x: "placeholder",
)
output = get_product_image_thumbnail(instance=None, size=10, method="crop")
@@ -43,7 +43,7 @@ def test_get_product_image_thumbnail_no_instance(monkeypatch):
@patch(
- "saleor.product.templatetags.product_images.AVAILABLE_SIZES",
+ "saleor.product.product_images.AVAILABLE_SIZES",
{
"products": (
"thumbnail__800x800",
@@ -63,7 +63,7 @@ def test_get_thumbnail_to_larger():
@patch(
- "saleor.product.templatetags.product_images.AVAILABLE_SIZES",
+ "saleor.product.product_images.AVAILABLE_SIZES",
{
"products": (
"crop__10x10",
@@ -83,7 +83,7 @@ def test_get_thumbnail_to_smaller():
@patch(
- "saleor.product.templatetags.product_images.AVAILABLE_SIZES",
+ "saleor.product.product_images.AVAILABLE_SIZES",
{"products": ("thumbnail__800x800",)},
)
@override_settings(