Skip to content

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

Implement customer order placement event

NyanKiyoshi05456d5c0b19
diff --git a/saleor/account/events.py b/saleor/account/events.py
new file mode 100644
index 0000000000..0aa038c4d7
--- /dev/null
+++ b/saleor/account/events.py
@@ -0,0 +1,22 @@
+from typing import Optional
+
+from django.contrib.auth.base_user import AbstractBaseUser
+
+from ..order.models import Order
+from . import CustomerEvents
+from .models import CustomerEvent
+
+UserType = AbstractBaseUser
+
+
+def _new_customer_event(**data) -> CustomerEvent:
+ return CustomerEvent.objects.create(**data)
+
+
+def customer_placed_order_event(
+ *, user: UserType, order: Order
+) -> Optional[CustomerEvent]:
+ if user.is_anonymous:
+ return None
+
+ return _new_customer_event(user=user, order=order, type=CustomerEvents.PLACED_ORDER)
diff --git a/saleor/account/models.py b/saleor/account/models.py
index f892fa9d36..7cb1c449ae 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -11,7 +11,6 @@ from django.db import models
from django.db.models import Q, Value
from django.forms.models import model_to_dict
from django.utils import timezone
-from django.utils.timezone import now
from django.utils.translation import pgettext_lazy
from django_countries.fields import Country, CountryField
from phonenumber_field.modelfields import PhoneNumber, PhoneNumberField
@@ -207,7 +206,7 @@ class CustomerNote(models.Model):
class CustomerEvent(models.Model):
"""Model used to store events that happened during the customer lifecycle."""
- date = models.DateTimeField(default=now, editable=False)
+ date = models.DateTimeField(default=timezone.now, editable=False)
type = models.CharField(
max_length=255,
choices=[
diff --git a/saleor/order/events.py b/saleor/order/events.py
index 87539a3fc3..ed282fb5a6 100644
--- a/saleor/order/events.py
+++ b/saleor/order/events.py
@@ -3,6 +3,7 @@ from typing import Dict, List, Optional, Tuple, Union
from django.contrib.auth.base_user import AbstractBaseUser
+from ..account.events import customer_placed_order_event
from ..account.models import Address
from ..order.models import Fulfillment, FulfillmentLine, Order, OrderLine
from ..payment.models import Payment
@@ -89,7 +90,11 @@ def draft_order_removed_products_event(
def order_created_event(*, order: Order, user: UserType, from_draft=False):
- event_type = OrderEvents.PLACED_FROM_DRAFT if from_draft else OrderEvents.PLACED
+ if from_draft:
+ event_type = OrderEvents.PLACED_FROM_DRAFT
+ else:
+ event_type = OrderEvents.PLACED
+ customer_placed_order_event(user=user, order=order)
if user.is_anonymous:
user = None
diff --git a/tests/test_checkout.py b/tests/test_checkout.py
index 74c371fd91..da0ceed3e5 100644
--- a/tests/test_checkout.py
+++ b/tests/test_checkout.py
@@ -2,12 +2,14 @@ import datetime
from unittest.mock import Mock, patch
import pytest
+from django.contrib.auth.models import AnonymousUser
from django.urls import reverse
from django_countries.fields import Country
from freezegun import freeze_time
from prices import Money, TaxedMoney, TaxedMoneyRange
-from saleor.account.models import Address
+from saleor.account import CustomerEvents
+from saleor.account.models import Address, CustomerEvent
from saleor.checkout import views
from saleor.checkout.forms import CheckoutVoucherForm, CountryForm
from saleor.checkout.utils import (
@@ -30,6 +32,8 @@ from saleor.core.exceptions import InsufficientStock
from saleor.core.utils.taxes import ZERO_MONEY, ZERO_TAXED_MONEY, get_taxes_for_country
from saleor.discount import DiscountValueType, VoucherType
from saleor.discount.models import NotApplicable, Voucher
+from saleor.order import OrderEvents, OrderEventsEmails
+from saleor.order.models import OrderEvent
from saleor.product.models import Category
from saleor.shipping.models import ShippingZone
@@ -551,6 +555,67 @@ def test_view_checkout_summary_remove_voucher(
assert not response.context["checkout"].voucher_code
[email protected]("is_anonymous_user", (True, False))
+def test_create_order_creates_expected_events(
+ request_checkout_with_item, customer_user, shipping_method, is_anonymous_user
+):
+ checkout = request_checkout_with_item
+ checkout_user = None if is_anonymous_user else customer_user
+
+ # Ensure not events are existing prior
+ assert not OrderEvent.objects.exists()
+ assert not CustomerEvent.objects.exists()
+
+ # Prepare valid checkout
+ checkout.user = checkout_user
+ checkout.billing_address = customer_user.default_billing_address
+ checkout.shipping_address = customer_user.default_shipping_address
+ checkout.shipping_method = shipping_method
+ checkout.save()
+
+ # Place checkout
+ order = create_order(
+ checkout,
+ "tracking_code",
+ discounts=None,
+ taxes=None,
+ user=customer_user if not is_anonymous_user else AnonymousUser(),
+ )
+
+ # Ensure only two events were created, and retrieve them
+ placement_event, email_sent_event = order.events.all() # type: OrderEvent
+
+ # Ensure the correct order event was created
+ assert placement_event.type == OrderEvents.PLACED # is the event the expected type
+ assert placement_event.user == checkout_user # is the user anonymous/ the customer
+ assert placement_event.order is order # is the associated backref order valid
+ assert placement_event.date # ensure a date was set
+ assert not placement_event.parameters # should not have any additional parameters
+
+ # Ensure the correct email sent event was created
+ assert email_sent_event.type == OrderEvents.EMAIL_SENT # should be email sent event
+ assert email_sent_event.user == checkout_user # ensure the user is none or valid
+ assert email_sent_event.order is order # ensure the mail event is related to order
+ assert email_sent_event.date # ensure a date was set
+ assert email_sent_event.parameters == { # ensure the correct parameters were set
+ "email": order.get_user_current_email(),
+ "email_type": OrderEventsEmails.ORDER,
+ }
+
+ # Check no event was created if the user was anonymous
+ if is_anonymous_user:
+ assert not CustomerEvent.objects.exists() # should not have created any event
+ return # we are done testing as the user is anonymous
+
+ # Ensure the correct customer event was created if the user was not anonymous
+ placement_event = customer_user.events.get() # type: CustomerEvent
+ assert placement_event.type == CustomerEvents.PLACED_ORDER # check the event type
+ assert placement_event.user == customer_user # check the backref is valid
+ assert placement_event.order == order # check the associated order is valid
+ assert placement_event.date # ensure a date was set
+ assert not placement_event.parameters # should not have any additional parameters
+
+
def test_create_order_insufficient_stock(
request_checkout, customer_user, product_without_shipping
):