Skip to content

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

Add order post-create actions in API

Marcin Gębala14af37baf486
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index fefa0c6d80..711edde857 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -176,10 +176,12 @@ def get_or_create_user_cart(user: User, cart_queryset=Cart.objects.all()):
'shipping_address': user.default_shipping_address,
'billing_address': user.default_billing_address}
+ created = False
cart = cart_queryset.filter(user=user).first()
if cart is None:
cart = Cart.objects.create(user=user, **defaults)
- return cart
+ created = True
+ return cart, created
def get_anonymous_cart_from_token(token, cart_queryset=Cart.objects.all()):
@@ -195,7 +197,7 @@ def get_user_cart(user, cart_queryset=Cart.objects.all()):
def get_or_create_cart_from_request(request, cart_queryset=Cart.objects.all()):
"""Fetch cart from database or create a new one based on cookie."""
if request.user.is_authenticated:
- return get_or_create_user_cart(request.user, cart_queryset)
+ return get_or_create_user_cart(request.user, cart_queryset)[0]
token = request.get_signed_cookie(COOKIE_NAME, default=None)
return get_or_create_anonymous_cart_from_token(token, cart_queryset)
@@ -834,26 +836,12 @@ def _process_user_data_for_order(cart):
return {
'user': cart.user,
'user_email': cart.user.email if cart.user else cart.email,
- 'billing_address': billing_address}
-
-
-def _fill_order_with_cart_data(order, cart, discounts, taxes):
- """Fill an order with data (variants, note) from cart."""
- from ..order.utils import add_variant_to_order
-
- for line in cart:
- add_variant_to_order(
- order, line.variant, line.quantity, discounts, taxes)
-
- cart.payments.update(order=order)
-
- if cart.note:
- order.customer_note = cart.note
- order.save(update_fields=['customer_note'])
+ 'billing_address': billing_address,
+ 'customer_note': cart.note}
@transaction.atomic
-def create_order(cart, tracking_code, discounts, taxes):
+def create_order(cart: Cart, tracking_code: str, discounts, taxes):
"""Create an order from the cart.
Each order will get a private copy of both the billing and the shipping
@@ -865,16 +853,14 @@ def create_order(cart, tracking_code, discounts, taxes):
Current user's language is saved in the order so we can later determine
which language to use when sending email.
"""
+ from ..order.utils import add_variant_to_order
+
order = Order.objects.filter(checkout_token=cart.token).first()
if order is not None:
return order
- # FIXME: save locale along with the language
- try:
- order_data = _process_voucher_data_for_order(cart)
- except NotApplicable:
- return None
-
+ order_data: dict = {}
+ order_data.update(_process_voucher_data_for_order(cart))
order_data.update(_process_shipping_data_for_order(cart, taxes))
order_data.update(_process_user_data_for_order(cart))
order_data.update({
@@ -883,7 +869,14 @@ def create_order(cart, tracking_code, discounts, taxes):
'total': cart.get_total(discounts, taxes)})
order = Order.objects.create(**order_data, checkout_token=cart.token)
- _fill_order_with_cart_data(order, cart, discounts, taxes)
+
+ # create order lines from cart lines
+ for line in cart:
+ add_variant_to_order(
+ order, line.variant, line.quantity, discounts, taxes)
+
+ # assign cart payments to the order
+ cart.payments.update(order=order)
return order
diff --git a/saleor/checkout/views/summary.py b/saleor/checkout/views/summary.py
index 8dde0a839b..d9e70e31d6 100644
--- a/saleor/checkout/views/summary.py
+++ b/saleor/checkout/views/summary.py
@@ -6,6 +6,7 @@ from django.utils.translation import pgettext
from ...account.models import Address
from ...core import analytics
from ...core.exceptions import InsufficientStock
+from ...discount.models import NotApplicable
from ...order import OrderEvents, OrderEventsEmails
from ...order.emails import send_order_confirmation
from ..forms import CartNoteForm
@@ -18,7 +19,9 @@ from ..utils import (
def handle_order_placement(request, cart):
"""Try to create an order and redirect the user as necessary.
- This is a helper function.
+ This function creates an order from cart and performs post-create actions
+ such as removing the checkout instance, sending order notification email
+ and creating order history events.
"""
try:
order = create_order(
@@ -28,13 +31,13 @@ def handle_order_placement(request, cart):
taxes=get_taxes_for_cart(cart, request.taxes))
except InsufficientStock:
return redirect('cart:index')
-
- # happens when a voucher is now invalid
- if not order:
- msg = pgettext('Checkout warning', 'Please review your checkout.')
- messages.warning(request, msg)
+ except NotApplicable:
+ messages.warning(
+ request, pgettext(
+ 'Checkout warning', 'Please review your checkout.'))
return redirect('checkout:summary')
+ # remove cart after checkout is created
cart.delete()
order.events.create(type=OrderEvents.PLACED.value)
send_order_confirmation.delay(order.pk)
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 0d62755444..59f8607ecb 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -13,6 +13,8 @@ from ...core import analytics
from ...core.exceptions import InsufficientStock
from ...core.utils.taxes import get_taxes_for_address
from ...discount import models as voucher_model
+from ...order import OrderEvents, OrderEventsEmails
+from ...order.emails import send_order_confirmation
from ...payment import PaymentError
from ...payment.utils import gateway_process_payment
from ...shipping.models import ShippingMethod as ShippingMethodModel
@@ -521,8 +523,23 @@ class CheckoutComplete(BaseMutation):
field=None, message='Insufficient product stock.',
errors=errors)
return CheckoutComplete(errors=errors)
+ except voucher_model.NotApplicable:
+ cls.add_error(
+ field=None, message='Voucher not applicable', errors=errors)
+ return CheckoutComplete(errors=errors)
payment = checkout.get_last_active_payment()
+
+ # remove cart after checkout is created
+ checkout.delete()
+ order.events.create(type=OrderEvents.PLACED.value)
+ send_order_confirmation.delay(order.pk)
+ order.events.create(
+ type=OrderEvents.EMAIL_SENT.value,
+ parameters={
+ 'email': order.get_user_current_email(),
+ 'email_type': OrderEventsEmails.ORDER.value})
+
try:
gateway_process_payment(
payment=payment, payment_token=payment.token)
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index eb645a1d0c..dd0ec03118 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -796,6 +796,11 @@ def test_checkout_complete(
checkout.shipping_address = address
checkout.shipping_method = shipping_method
checkout.save()
+
+ checkout_line = checkout.lines.first()
+ checkout_line_quantity = checkout_line.quantity
+ checkout_line_variant = checkout_line.variant
+
total = checkout.get_total()
payment = payment_dummy
payment.is_active = True
@@ -804,24 +809,26 @@ def test_checkout_complete(
payment.currency = total.gross.currency
payment.checkout = checkout
payment.save()
- checkout_id = graphene.Node.to_global_id('Checkout', checkout.pk)
assert not payment.transactions.exists()
- variables = {'checkoutId': checkout_id}
+
orders_count = Order.objects.count()
+ checkout_id = graphene.Node.to_global_id('Checkout', checkout.pk)
+ variables = {'checkoutId': checkout_id}
response = user_api_client.post_graphql(
MUTATION_CHECKOUT_COMPLETE, variables)
content = get_graphql_content(response)
data = content['data']['checkoutComplete']
assert not data['errors']
+
order_token = data['order']['token']
assert Order.objects.count() == orders_count + 1
order = Order.objects.first()
assert order.token == order_token
assert order.total.gross == total.gross
- checkout_line = checkout.lines.first()
+
order_line = order.lines.first()
- assert checkout_line.quantity == order_line.quantity
- assert checkout_line.variant == order_line.variant
+ assert checkout_line_quantity == order_line.quantity
+ assert checkout_line_variant == order_line.variant
assert order.shipping_address == address
assert order.shipping_method == checkout.shipping_method
assert order.payments.exists()
@@ -829,6 +836,10 @@ def test_checkout_complete(
assert order_payment == payment
assert payment.transactions.count() == 2
+ # assert that the cart has been delated after checkout
+ with pytest.raises(Cart.DoesNotExist):
+ checkout.refresh_from_db()
+
def test_checkout_complete_invalid_checkout_id(user_api_client):
checkout_id = 'invalidId'
diff --git a/tests/test_cart.py b/tests/test_cart.py
index a9f400363e..d98ebbaa3e 100644
--- a/tests/test_cart.py
+++ b/tests/test_cart.py
@@ -79,7 +79,7 @@ def test_get_or_create_anonymous_cart_from_token(anonymous_cart, user_cart):
def test_get_or_create_user_cart(
customer_user, anonymous_cart, user_cart, admin_user):
- cart = utils.get_or_create_user_cart(customer_user)
+ cart = utils.get_or_create_user_cart(customer_user)[0]
assert Cart.objects.all().count() == 2
assert cart == user_cart
@@ -87,7 +87,7 @@ def test_get_or_create_user_cart(
Cart.objects.create(user=admin_user)
queryset = Cart.objects.all()
carts = list(queryset)
- cart = utils.get_or_create_user_cart(admin_user)
+ cart = utils.get_or_create_user_cart(admin_user)[0]
assert Cart.objects.all().count() == 3
assert cart in carts
assert cart.user == admin_user
@@ -122,7 +122,7 @@ def test_get_or_create_cart_from_request(
request = cart_request_factory(user=customer_user, token=token)
user_cart = Cart(user=customer_user)
anonymous_cart = Cart()
- mock_get_for_user = Mock(return_value=user_cart)
+ mock_get_for_user = Mock(return_value=(user_cart, False))
mock_get_for_anonymous = Mock(return_value=anonymous_cart)
monkeypatch.setattr(
'saleor.checkout.utils.get_or_create_user_cart', mock_get_for_user)
diff --git a/tests/test_checkout.py b/tests/test_checkout.py
index eb4607bd4e..c8353b8d0a 100644
--- a/tests/test_checkout.py
+++ b/tests/test_checkout.py
@@ -260,6 +260,9 @@ def test_view_checkout_summary(
assert response.request['PATH_INFO'] == redirect_url
mock_send_confirmation.delay.assert_called_once_with(order.pk)
+ # cart should be deleted after order is created
+ assert request_cart_with_item.pk is None
+
@patch('saleor.checkout.views.summary.send_order_confirmation')
def test_view_checkout_summary_authorized_user(