Skip to content

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

Allow staff member to receive notification about customers orders

Krzysztof Świątek891b03bedc8a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 460de9c99a..d45d38adae 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Fixed JSON encoding error on Google Analytics reporting - #5004 by @NyanKiyoshi
- Create custom field to translation, use new translation types in translations query - #5007 by @fowczarek
- Take allocated stock in account in `StockAvailability` filter - #5019 by @simonbru
+- Allow staff member to receive notification about customers orders - #4993 by @kswiatek92
## 2.9.0
diff --git a/saleor/account/migrations/0035_staffnotificationrecipient.py b/saleor/account/migrations/0035_staffnotificationrecipient.py
new file mode 100644
index 0000000000..8eb9b4e294
--- /dev/null
+++ b/saleor/account/migrations/0035_staffnotificationrecipient.py
@@ -0,0 +1,44 @@
+# Generated by Django 2.2.6 on 2019-11-22 10:31
+
+from django.conf import settings
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [("account", "0034_service_account_token")]
+
+ operations = [
+ migrations.CreateModel(
+ name="StaffNotificationRecipient",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "staff_email",
+ models.EmailField(
+ blank=True, max_length=254, null=True, unique=True
+ ),
+ ),
+ ("active", models.BooleanField(default=True)),
+ (
+ "user",
+ models.OneToOneField(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="staff_notification",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ )
+ ]
diff --git a/saleor/account/models.py b/saleor/account/models.py
index 4be962aa1b..79fe6643fb 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -276,3 +276,18 @@ class CustomerEvent(models.Model):
def __repr__(self):
return f"{self.__class__.__name__}(type={self.type!r}, user={self.user!r})"
+
+
+class StaffNotificationRecipient(models.Model):
+ user = models.OneToOneField(
+ User,
+ related_name="staff_notification",
+ on_delete=models.CASCADE,
+ blank=True,
+ null=True,
+ )
+ staff_email = models.EmailField(unique=True, blank=True, null=True)
+ active = models.BooleanField(default=True)
+
+ def get_email(self):
+ return self.user.email if self.user else self.staff_email
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index e139b7db2d..86190cd769 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -42,7 +42,7 @@ from ..giftcard.utils import (
remove_gift_card_code_from_checkout,
)
from ..order.actions import order_created
-from ..order.emails import send_order_confirmation
+from ..order.emails import send_order_confirmation, send_staff_order_confirmation
from ..order.models import Order, OrderLine
from ..shipping.models import ShippingMethod
from . import AddressType, logger
@@ -1205,6 +1205,7 @@ def create_order(*, checkout: Checkout, order_data: dict, user: User) -> Order:
# Send the order confirmation email
send_order_confirmation.delay(order.pk, user.pk)
+ send_staff_order_confirmation.delay(order.pk)
return order
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index 6b5bd55ed4..5e2c78bed4 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -379,3 +379,32 @@ class AddressValidationData(graphene.ObjectType):
postal_code_matchers = graphene.List(graphene.String)
postal_code_examples = graphene.List(graphene.String)
postal_code_prefix = graphene.String()
+
+
+class StaffNotificationRecipient(CountableDjangoObjectType):
+ user = graphene.Field(
+ User,
+ description="Returns a user subscribed to email notifications.",
+ required=False,
+ )
+ email = graphene.String(
+ description=(
+ "Returns email address of a user subscribed to email notifications."
+ ),
+ required=False,
+ )
+ active = graphene.Boolean(description="Determines if a notification active.")
+
+ class Meta:
+ description = (
+ "Represents a recipient of email notifications send by Saleor, "
+ "such as notifications about new orders. Notifications can be "
+ "assigned to staff users or arbitrary email addresses."
+ )
+ interfaces = [relay.Node]
+ model = models.StaffNotificationRecipient
+ only_fields = ["user", "active"]
+
+ @staticmethod
+ def resolve_email(root: models.StaffNotificationRecipient, _info):
+ return root.get_email()
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 26f6aa6645..5c94ad2074 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2070,6 +2070,9 @@ type Mutation {
webhookUpdate(id: ID!, input: WebhookUpdateInput!): WebhookUpdate
authorizationKeyAdd(input: AuthorizationKeyInput!, keyType: AuthorizationKeyType!): AuthorizationKeyAdd
authorizationKeyDelete(keyType: AuthorizationKeyType!): AuthorizationKeyDelete
+ staffNotificationRecipientCreate(input: StaffNotificationRecipientInput!): StaffNotificationRecipientCreate
+ staffNotificationRecipientUpdate(id: ID!, input: StaffNotificationRecipientInput!): StaffNotificationRecipientUpdate
+ staffNotificationRecipientDelete(id: ID!): StaffNotificationRecipientDelete
homepageCollectionUpdate(collection: ID): HomepageCollectionUpdate
shopDomainUpdate(input: SiteDomainInput): ShopDomainUpdate
shopSettingsUpdate(input: ShopSettingsInput!): ShopSettingsUpdate
@@ -3892,6 +3895,7 @@ type Shop {
defaultDigitalUrlValidDays: Int
companyAddress: Address
customerSetPasswordUrl: String
+ staffNotificationRecipients: [StaffNotificationRecipient]
}
type ShopAddressUpdate {
@@ -4015,6 +4019,37 @@ enum StaffMemberStatus {
DEACTIVATED
}
+type StaffNotificationRecipient implements Node {
+ user: User
+ active: Boolean
+ id: ID!
+ email: String
+}
+
+type StaffNotificationRecipientCreate {
+ errors: [Error!]
+ shopErrors: [ShopError!]
+ staffNotificationRecipient: StaffNotificationRecipient
+}
+
+type StaffNotificationRecipientDelete {
+ errors: [Error!]
+ shopErrors: [ShopError!]
+ staffNotificationRecipient: StaffNotificationRecipient
+}
+
+input StaffNotificationRecipientInput {
+ user: ID
+ email: String
+ active: Boolean
+}
+
+type StaffNotificationRecipientUpdate {
+ errors: [Error!]
+ shopErrors: [ShopError!]
+ staffNotificationRecipient: StaffNotificationRecipient
+}
+
type StaffUpdate {
errors: [Error!]
accountErrors: [AccountError!]
diff --git a/saleor/graphql/shop/mutations.py b/saleor/graphql/shop/mutations.py
index d34538d29b..61f29d7613 100644
--- a/saleor/graphql/shop/mutations.py
+++ b/saleor/graphql/shop/mutations.py
@@ -3,14 +3,14 @@ from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.management import call_command
-from ...account.models import Address
+from ...account import models as account_models
from ...core.error_codes import ShopErrorCode
from ...core.utils.url import validate_storefront_url
from ...site import models as site_models
from ..account.i18n import I18nMixin
from ..account.types import AddressInput
from ..core.enums import WeightUnitsEnum
-from ..core.mutations import BaseMutation
+from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ..core.types.common import ShopError
from ..product.types import Collection
from .types import AuthorizationKey, AuthorizationKeyType, Shop
@@ -119,7 +119,7 @@ class ShopAddressUpdate(BaseMutation, I18nMixin):
if data:
if not site_settings.company_address:
- company_address = Address()
+ company_address = account_models.Address()
else:
company_address = site_settings.company_address
company_address = cls.validate_address(data, company_address)
@@ -288,3 +288,108 @@ class AuthorizationKeyDelete(BaseMutation):
instance.delete()
return AuthorizationKeyDelete(authorization_key=instance, shop=Shop())
+
+
+class StaffNotificationRecipientInput(graphene.InputObjectType):
+ user = graphene.ID(
+ required=False,
+ description="The ID of the user subscribed to email notifications..",
+ )
+ email = graphene.String(
+ required=False,
+ description="Email address of a user subscribed to email notifications.",
+ )
+ active = graphene.Boolean(
+ required=False, description="Determines if a notification active."
+ )
+
+
+class StaffNotificationRecipientCreate(ModelMutation):
+ class Arguments:
+ input = StaffNotificationRecipientInput(
+ required=True,
+ description="Fields required to create a staff notification recipient.",
+ )
+
+ class Meta:
+ description = "Creates a new staff notification recipient."
+ model = account_models.StaffNotificationRecipient
+ permissions = ("site.manage_settings",)
+ error_type_class = ShopError
+ error_type_field = "shop_errors"
+
+ @classmethod
+ def clean_input(cls, info, instance, data):
+ cleaned_input = super().clean_input(info, instance, data)
+ cls.validate_input(instance, cleaned_input)
+ email = cleaned_input.pop("email", None)
+ if email:
+ staff_user = account_models.User.objects.filter(email=email).first()
+ if staff_user:
+ cleaned_input["user"] = staff_user
+ else:
+ cleaned_input["staff_email"] = email
+ return cleaned_input
+
+ @staticmethod
+ def validate_input(instance, cleaned_input):
+ email = cleaned_input.get("email")
+ user = cleaned_input.get("user")
+ if not email and not user:
+ if instance.id and "user" in cleaned_input or "email" in cleaned_input:
+ raise ValidationError(
+ {
+ "staff_notification": ValidationError(
+ "User and email cannot be set empty",
+ code=ShopErrorCode.INVALID,
+ )
+ }
+ )
+ if not instance.id:
+ raise ValidationError(
+ {
+ "staff_notification": ValidationError(
+ "User or email is required", code=ShopErrorCode.REQUIRED
+ )
+ }
+ )
+ if user and not user.is_staff:
+ raise ValidationError(
+ {
+ "user": ValidationError(
+ "User has to be staff user", code=ShopErrorCode.INVALID
+ )
+ }
+ )
+
+
+class StaffNotificationRecipientUpdate(StaffNotificationRecipientCreate):
+ class Arguments:
+ id = graphene.ID(
+ required=True, description="ID of a staff notification recipient to update."
+ )
+ input = StaffNotificationRecipientInput(
+ required=True,
+ description="Fields required to update a staff notification recipient.",
+ )
+
+ class Meta:
+ description = "Updates a staff notification recipient."
+ model = account_models.StaffNotificationRecipient
+ permissions = ("site.manage_settings",)
+ error_type_class = ShopError
+ error_type_field = "shop_errors"
+
+
+class StaffNotificationRecipientDelete(ModelDeleteMutation):
+ class Arguments:
+ id = graphene.ID(
+ required=True, description="ID of a staff notification recipient to delete."
+ )
+
+ class Meta:
+ description = "Delete staff notification recipient."
+ model = account_models.StaffNotificationRecipient
+ permissions = ("site.manage_settings",)
+ error_type_class = ShopError
+ error_type_field = "shop_errors"
diff --git a/saleor/graphql/shop/schema.py b/saleor/graphql/shop/schema.py
index 40a27c442a..790cf9adae 100644
--- a/saleor/graphql/shop/schema.py
+++ b/saleor/graphql/shop/schema.py
@@ -9,6 +9,9 @@ from .mutations import (
ShopDomainUpdate,
ShopFetchTaxRates,
ShopSettingsUpdate,
+ StaffNotificationRecipientCreate,
+ StaffNotificationRecipientDelete,
+ StaffNotificationRecipientUpdate,
)
from .types import Shop
@@ -24,6 +27,10 @@ class ShopMutations(graphene.ObjectType):
authorization_key_add = AuthorizationKeyAdd.Field()
authorization_key_delete = AuthorizationKeyDelete.Field()
+ staff_notification_recipient_create = StaffNotificationRecipientCreate.Field()
+ staff_notification_recipient_update = StaffNotificationRecipientUpdate.Field()
+ staff_notification_recipient_delete = StaffNotificationRecipientDelete.Field()
+
homepage_collection_update = HomepageCollectionUpdate.Field()
shop_domain_update = ShopDomainUpdate.Field()
shop_settings_update = ShopSettingsUpdate.Field()
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index 3837124671..3b3ded8a67 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -5,12 +5,13 @@ from django_countries import countries
from django_prices_vatlayer.models import VAT
from phonenumbers import COUNTRY_CODE_TO_REGION_CODE
+from ...account import models as account_models
from ...core.permissions import get_permissions
from ...core.utils import get_client_ip, get_country_by_ip
from ...menu import models as menu_models
from ...product import models as product_models
from ...site import models as site_models
-from ..account.types import Address
+from ..account.types import Address, StaffNotificationRecipient
from ..core.enums import WeightUnitsEnum
from ..core.types.common import CountryDisplay, LanguageDisplay, PermissionDisplay
from ..core.utils import get_node_optimized, str_to_enum
@@ -146,6 +147,11 @@ class Shop(graphene.ObjectType):
description="URL of a view where customers can set their password.",
required=False,
)
+ staff_notification_recipients = graphene.List(
+ StaffNotificationRecipient,
+ description="List of staff notification recipients.",
+ required=False,
+ )
class Meta:
description = (
@@ -309,3 +315,8 @@ class Shop(graphene.ObjectType):
@permission_required("site.manage_settings")
def resolve_default_digital_url_valid_days(_, info):
return info.context.site.settings.default_digital_url_valid_days
+
+ @staticmethod
+ @permission_required("site.manage_settings")
+ def resolve_staff_notification_recipients(_, info):
+ return account_models.StaffNotificationRecipient.objects.all()
diff --git a/saleor/order/emails.py b/saleor/order/emails.py
index 161f4f006a..c41e392e48 100644
--- a/saleor/order/emails.py
+++ b/saleor/order/emails.py
@@ -1,6 +1,7 @@
from django.urls import reverse
from templated_email import send_templated_mail
+from ..account.models import StaffNotificationRecipient
from ..celeryconf import app
from ..core.emails import get_email_context
from ..core.utils import build_absolute_uri
@@ -9,6 +10,7 @@ from . import events
from .models import Fulfillment, Order
CONFIRM_ORDER_TEMPLATE = "order/confirm_order"
+STAFF_CONFIRM_ORDER_TEMPLATE = "order/staff_confirm_order"
CONFIRM_FULFILLMENT_TEMPLATE = "order/confirm_fulfillment"
UPDATE_FULFILLMENT_TEMPLATE = "order/update_fulfillment"
CONFIRM_PAYMENT_TEMPLATE = "order/payment/confirm_payment"
@@ -43,6 +45,37 @@ def collect_data_for_email(order_pk, template):
}
+def collect_staff_order_notification_data(order_pk, template):
+ """Collect the required data for sending emails.
+
+ Args:
+ order_pk (int): order primary key
+ template (str): email template path
+
+ """
+ order = Order.objects.get(pk=order_pk)
+ staff_notifications = StaffNotificationRecipient.objects.filter(
+ active=True, user__is_active=True, user__is_staff=True
+ )
+ recipient_emails = [
+ notification.get_email() for notification in staff_notifications
+ ]
+ send_kwargs, email_context = get_email_context()
+ email_context["order_details_url"] = build_absolute_uri(
+ reverse("order:details", kwargs={"token": order.token})
+ )
+ email_context["order"] = order
+ email_markup = get_order_confirmation_markup(order)
+ email_context["schema_markup"] = email_markup
+
+ return {
+ "recipient_list": recipient_emails,
+ "template_name": template,
+ "context": email_context,
+ **send_kwargs,
+ }
+
+
def collect_data_for_fullfillment_email(order_pk, template, fulfillment_pk):
fulfillment = Fulfillment.objects.get(pk=fulfillment_pk)
email_data = collect_data_for_email(order_pk, template)
@@ -73,6 +106,16 @@ def send_order_confirmation(order_pk, user_pk=None):
)
+def send_staff_order_confirmation(order_pk):
+ """Send order confirmation email."""
+ staff_email_data = collect_staff_order_notification_data(
+ order_pk, STAFF_CONFIRM_ORDER_TEMPLATE
+ )
+ if staff_email_data["recipient_list"]:
+ send_templated_mail(**staff_email_data)
+
+
@app.task
def send_fulfillment_confirmation(order_pk, fulfillment_pk):
email_data = collect_data_for_fullfillment_email(
diff --git a/templates/templated_email/order/staff_confirm_order.email b/templates/templated_email/order/staff_confirm_order.email
new file mode 100644
index 0000000000..0d9dc01fda
--- /dev/null
+++ b/templates/templated_email/order/staff_confirm_order.email
@@ -0,0 +1,35 @@
+{% load i18n %}
+{% load price from taxed_prices %}
+{% load voucher %}
+
+{% block subject %}
+ {% trans "Order details" context "Order confirmation e-mail subject" %}
+{% endblock %}
+
+{% block plain %}
+{% include 'templated_email/shared/_header.email' %}
+{% blocktrans context "Order confirmation staff e-mail text" %}
+Below is the list of ordered products. To see payment details please visit:
+{{ order_details_url }}{% endblocktrans %}
+{% for line in order %}
+{{ line.quantity }} x {{ line }}, {% price line.get_total display_gross=order.display_gross_prices html=False %}
+{% endfor %}
+{% trans "Order summary" context "Order confirmation e-mail table header" %}:
+{% trans "Subtotal" context "Order confirmation e-mail table header" %}: {% price order.get_subtotal display_gross=order.display_gross_prices html=False %}
+{% trans "Shipping" context "Order confirmation e-mail table header" %}: {% price order.shipping_price display_gross=order.display_gross_prices html=False %}
+{% if order.display_gross_prices %}{% trans "Taxes (included)" context "Order confirmation e-mail table header" %}{% else %}{% trans "Taxes" context "Order confirmation e-mail table header" %}{% endif %}: {% price order.total.tax html=False %}
+{% if order.discount_amount %}{% trans "Discount:" context "Order confirmation e-mail table header" %} {% discount_as_negative order.discount %}{% endif %}
+{% trans "Total" context "Order confirmation e-mail table header" %}: {% price order.total.gross html=False %}
+
+{% trans "Billing address" context "Order confirmation e-mail billing address" %}
+{% if order.billing_address %}{{ order.billing_address }}{% else %}{% trans "No billing address" context "Order confirmation e-mail text" %}{% endif %}
+
+{% trans "Shipping address" context "Order confirmation e-mail shipping address" %}
+{% if order.shipping_address %}{{ order.shipping_address }}{% else %}{% trans "No shipping required" context "Order confirmation e-mail text" %}{% endif %}
+
+{% include 'templated_email/shared/_footer.email' %}
+{% endblock %}
+
+{% block html %}
+{% include 'templated_email/compiled/staff_confirm_order.html' %}
+{% endblock %}
diff --git a/templates/templated_email/source/staff_confirm_order.mjml b/templates/templated_email/source/staff_confirm_order.mjml
new file mode 100644
index 0000000000..1c527c850f
--- /dev/null
+++ b/templates/templated_email/source/staff_confirm_order.mjml
@@ -0,0 +1,56 @@
+<mjml>
+ <mj-head>
+ <mj-include path="./shared/styles.mjml" />
+ </mj-head>
+ <mj-body>
+ <mj-raw>
+ {% load i18n %}
+ {% load i18n_address_tags %}
+ </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 trimmed context "Order confirmation staff e-mail text" %}
+ Someone placed a new order in your store. To see order details please visit: <a href="{{ order_details_url }}">{{ order_details_url }}</a>
+ {% endblocktrans %}
+ </mj-text>
+ </mj-column>
+ </mj-section>
+ <mj-include path="./partials/_order_lines.mjml" />
+ <mj-section>
+ <mj-column>
+ <mj-table>
+ <thead class="table-header-row">
+ <tr>
+ <th>{% trans "Billing address" context "Order confirmation e-mail billing address" %}</th>
+ <th>{% trans "Shipping address" context "Order confirmation e-mail shipping address" %}</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td class="address">
+ {% if order.billing_address %}
+ {% format_address order.billing_address %}
+ {% else %}
+ {% trans "No billing address" context "Order confirmation e-mail text" %}
+ {% endif %}
+ </td>
+ <td css-class="address">
+ {% if order.shipping_address %}
+ {% format_address order.shipping_address %}
+ {% else %}
+ {% trans "No shipping required" context "Order confirmation e-mail text" %}
+ {% endif %}
+ </td>
+ </tr>
+ </tbody>
+ </mj-table>
+ </mj-column>
+ </mj-section>
+ <mj-include path="./shared/footer.mjml" />
+ </mj-body>
+</mjml>
diff --git a/tests/api/test_shop.py b/tests/api/test_shop.py
index f62f3271a0..24e8af6e82 100644
--- a/tests/api/test_shop.py
+++ b/tests/api/test_shop.py
@@ -830,3 +830,293 @@ def test_mutation_update_company_address_remove_address_without_address(
site_settings.refresh_from_db()
assert not site_settings.company_address
+
+
+def test_staff_notification_query(
+ staff_api_client,
+ staff_user,
+ permission_manage_settings,
+ staff_notification_recipient,
+):
+ query = """
+ {
+ shop {
+ staffNotificationRecipients {
+ active
+ email
+ user {
+ firstName
+ lastName
+ email
+ }
+ }
+ }
+ }
+ """
+
+ response = staff_api_client.post_graphql(
+ query, permissions=[permission_manage_settings]
+ )
+ content = get_graphql_content(response)
+
+ assert content["data"]["shop"]["staffNotificationRecipients"] == [
+ {
+ "active": True,
+ "email": staff_user.email,
+ "user": {
+ "firstName": staff_user.first_name,
+ "lastName": staff_user.last_name,
+ "email": staff_user.email,
+ },
+ }
+ ]
+
+
+MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE = """
+ mutation StaffNotificationRecipient ($input: StaffNotificationRecipientInput!) {
+ staffNotificationRecipientCreate(input: $input) {
+ staffNotificationRecipient {
+ active
+ email
+ user {
+ id
+ firstName
+ lastName
+ email
+ }
+ }
+ shopErrors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
+def test_staff_notification_create_mutation(
+ staff_api_client, staff_user, permission_manage_settings
+):
+ user_id = graphene.Node.to_global_id("User", staff_user.id)
+ variables = {"input": {"user": user_id}}
+ response = staff_api_client.post_graphql(
+ MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+ content = get_graphql_content(response)
+
+ assert content["data"]["staffNotificationRecipientCreate"] == {
+ "staffNotificationRecipient": {
+ "active": True,
+ "email": staff_user.email,
+ "user": {
+ "id": user_id,
+ "firstName": staff_user.first_name,
+ "lastName": staff_user.last_name,
+ "email": staff_user.email,
+ },
+ },
+ "shopErrors": [],
+ }
+
+
+def test_staff_notification_create_mutation_with_staffs_email(
+ staff_api_client, staff_user, permission_manage_settings
+):
+ user_id = graphene.Node.to_global_id("User", staff_user.id)
+ variables = {"input": {"email": staff_user.email}}
+ response = staff_api_client.post_graphql(
+ MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+ content = get_graphql_content(response)
+
+ assert content["data"]["staffNotificationRecipientCreate"] == {
+ "staffNotificationRecipient": {
+ "active": True,
+ "email": staff_user.email,
+ "user": {
+ "id": user_id,
+ "firstName": staff_user.first_name,
+ "lastName": staff_user.last_name,
+ "email": staff_user.email,
+ },
+ },
+ "shopErrors": [],
+ }
+
+
+def test_staff_notification_create_mutation_with_customer_user(
+ staff_api_client, customer_user, permission_manage_settings
+):
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variables = {"input": {"user": user_id}}
+ response = staff_api_client.post_graphql(
+ MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+ content = get_graphql_content(response)
+
+ assert content["data"]["staffNotificationRecipientCreate"] == {
+ "staffNotificationRecipient": None,
+ "shopErrors": [
+ {"code": "INVALID", "field": "user", "message": "User has to be staff user"}
+ ],
+ }
+
+
+def test_staff_notification_create_mutation_with_email(
+ staff_api_client, permission_manage_settings
+):
+ staff_email = "[email protected]"
+ variables = {"input": {"email": staff_email}}
+ response = staff_api_client.post_graphql(
+ MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+ content = get_graphql_content(response)
+
+ assert content["data"]["staffNotificationRecipientCreate"] == {
+ "staffNotificationRecipient": {
+ "active": True,
+ "email": staff_email,
+ "user": None,
+ },
+ "shopErrors": [],
+ }
+
+
+def test_staff_notification_create_mutation_with_empty_email(
+ staff_api_client, permission_manage_settings
+):
+ staff_email = ""
+ variables = {"input": {"email": staff_email}}
+ response = staff_api_client.post_graphql(
+ MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+ content = get_graphql_content(response)
+
+ assert content["data"]["staffNotificationRecipientCreate"] == {
+ "staffNotificationRecipient": None,
+ "shopErrors": [
+ {
+ "code": "INVALID",
+ "field": "staffNotification",
+ "message": "User and email cannot be set empty",
+ }
+ ],
+ }
+
+
+MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE = """
+ mutation StaffNotificationRecipient (
+ $id: ID!,
+ $input: StaffNotificationRecipientInput!
+ ) {
+ staffNotificationRecipientUpdate(id: $id, input: $input) {
+ staffNotificationRecipient {
+ active
+ email
+ user {
+ firstName
+ lastName
+ email
+ }
+ }
+ shopErrors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
+def test_staff_notification_update_mutation(
+ staff_api_client,
+ staff_user,
+ permission_manage_settings,
+ staff_notification_recipient,
+):
+ old_email = staff_notification_recipient.get_email()
+ assert staff_notification_recipient.active
+ staff_notification_recipient_id = graphene.Node.to_global_id(
+ "StaffNotificationRecipient", staff_notification_recipient.id
+ )
+ variables = {"id": staff_notification_recipient_id, "input": {"active": False}}
+ staff_api_client.post_graphql(
+ MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+ staff_notification_recipient.refresh_from_db()
+ assert not staff_notification_recipient.active
+ assert staff_notification_recipient.get_email() == old_email
+
+
+def test_staff_notification_update_mutation_with_empty_user(
+ staff_api_client,
+ staff_user,
+ permission_manage_settings,
+ staff_notification_recipient,
+):
+ staff_notification_recipient_id = graphene.Node.to_global_id(
+ "StaffNotificationRecipient", staff_notification_recipient.id
+ )
+ variables = {"id": staff_notification_recipient_id, "input": {"user": ""}}
+ response = staff_api_client.post_graphql(
+ MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+ content = get_graphql_content(response)
+
+ staff_notification_recipient.refresh_from_db()
+ assert content["data"]["staffNotificationRecipientUpdate"] == {
+ "staffNotificationRecipient": None,
+ "shopErrors": [
+ {
+ "code": "INVALID",
+ "field": "staffNotification",
+ "message": "User and email cannot be set empty",
+ }
+ ],
+ }
+
+
+def test_staff_notification_update_mutation_with_empty_email(
+ staff_api_client,
+ staff_user,
+ permission_manage_settings,
+ staff_notification_recipient,
+):
+ staff_notification_recipient_id = graphene.Node.to_global_id(
+ "StaffNotificationRecipient", staff_notification_recipient.id
+ )
+ variables = {"id": staff_notification_recipient_id, "input": {"email": ""}}
+ response = staff_api_client.post_graphql(
+ MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+ content = get_graphql_content(response)
+
+ staff_notification_recipient.refresh_from_db()
+ assert content["data"]["staffNotificationRecipientUpdate"] == {
+ "staffNotificationRecipient": None,
+ "shopErrors": [
+ {
+ "code": "INVALID",
+ "field": "staffNotification",
+ "message": "User and email cannot be set empty",
+ }
+ ],
+ }
diff --git a/tests/conftest.py b/tests/conftest.py
index 4008cc394a..0c71c862d1 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -22,7 +22,12 @@ from PIL import Image
from prices import Money, TaxedMoney
from saleor.account.backends import BaseBackend
-from saleor.account.models import Address, ServiceAccount, User
+from saleor.account.models import (
+ Address,
+ ServiceAccount,
+ User,
+ StaffNotificationRecipient,
+)
from saleor.checkout import utils
from saleor.checkout.models import Checkout
from saleor.checkout.utils import add_variant_to_checkout
@@ -1743,3 +1748,8 @@ def mock_get_manager(mocker, fake_payment_interface):
)
yield fake_payment_interface
mgr.assert_called_once()
+
+
+def staff_notification_recipient(db, staff_user):
+ return StaffNotificationRecipient.objects.create(active=True, user=staff_user)
diff --git a/tests/test_checkout.py b/tests/test_checkout.py
index 616c96dc11..b279e55e30 100644
--- a/tests/test_checkout.py
+++ b/tests/test_checkout.py
@@ -662,6 +662,8 @@ def test_create_order_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)
+
def test_create_order_insufficient_stock(
request_checkout, customer_user, product_without_shipping
diff --git a/tests/test_emails.py b/tests/test_emails.py
index 51e542e765..1f93f8e0b1 100644
--- a/tests/test_emails.py
+++ b/tests/test_emails.py
@@ -95,6 +95,40 @@ def test_send_emails(
email_connection.get_email_message(to=recipients, **expected_call_kwargs)
[email protected]("saleor.order.emails.send_templated_mail")
+def test_send_staff_emails_without_notification_recipient(
+ mocked_templated_email, order, site_settings
+):
+ emails.send_staff_order_confirmation(order.pk)
+ mocked_templated_email.assert_not_called()
+
+
[email protected]("saleor.order.emails.send_templated_mail")
+def test_send_staff_emails(
+ mocked_templated_email, order, site_settings, staff_notification_recipient
+):
+ emails.send_staff_order_confirmation(order.pk)
+ email_data = emails.collect_staff_order_notification_data(
+ order.pk, emails.STAFF_CONFIRM_ORDER_TEMPLATE
+ )
+
+ recipients = [staff_notification_recipient.get_email()]
+
+ expected_call_kwargs = {
+ "context": email_data["context"],
+ "from_email": site_settings.default_from_email,
+ "template_name": emails.STAFF_CONFIRM_ORDER_TEMPLATE,
+ }
+
+ mocked_templated_email.assert_called_once_with(
+ recipient_list=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)
+
+
@pytest.mark.parametrize(
"send_email,template",
[