Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Move all checkout complete logic to checkout_complete file.
Maciej Korycinskia3abc5f58884
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 7c1ccdb86f..0c2db651e6 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -1,29 +1,293 @@-from typing import List, Optional, Tuple+from datetime import date+from decimal import Decimal+from typing import Iterable, List, Optional, Tuplefrom django.core.exceptions import ValidationErrorfrom django.db import transaction+from django.utils.encoding import smart_text+from django.utils.translation import get_language+from prices import TaxedMoneyfrom ..account.error_codes import AccountErrorCodefrom ..account.models import User+from ..account.utils import store_user_address+from ..checkout import calculations+from ..checkout.error_codes import CheckoutErrorCodefrom ..core.exceptions import InsufficientStock-from ..core.taxes import TaxError+from ..core.prices import quantize_price+from ..core.taxes import TaxError, zero_taxed_moneyfrom ..core.utils.url import validate_storefront_urlfrom ..discount import DiscountInfofrom ..discount.models import NotApplicable-from ..order import models as order_models-from ..order.models import Order+from ..discount.utils import (+ add_voucher_usage_by_customer,+ decrease_voucher_usage,+ increase_voucher_usage,+ remove_voucher_usage_by_customer,+)+from ..order.actions import order_created+from ..order.emails import send_order_confirmation, send_staff_order_confirmation+from ..order.models import Order, OrderLinefrom ..payment import PaymentError, gatewayfrom ..payment.models import Payment, Transactionfrom ..payment.utils import store_customer_id-from . import models+from ..plugins.manager import get_plugins_manager+from ..warehouse.availability import check_stock_quantity+from ..warehouse.management import allocate_stock+from . import AddressType, modelsfrom .checkout_cleaner import clean_checkout_payment, clean_checkout_shipping-from .error_codes import CheckoutErrorCode-from .utils import abort_order_data, create_order, prepare_order_data+from .models import Checkout, CheckoutLine+from .utils import get_voucher_for_checkout-def prepare_checkout(+def _get_voucher_data_for_order(checkout: Checkout) -> dict:+ """Fetch, process and return voucher/discount data from checkout.++ Careful! It should be called inside a transaction.++ :raises NotApplicable: When the voucher is not applicable in the current checkout.+ """+ voucher = get_voucher_for_checkout(checkout, with_lock=True)++ if checkout.voucher_code and not voucher:+ msg = "Voucher expired in meantime. Order placement aborted."+ raise NotApplicable(msg)++ if not voucher:+ return {}++ increase_voucher_usage(voucher)+ if voucher.apply_once_per_customer:+ add_voucher_usage_by_customer(voucher, checkout.get_customer_email())+ return {+ "voucher": voucher,+ "discount": checkout.discount,+ "discount_name": checkout.discount_name,+ "translated_discount_name": checkout.translated_discount_name,+ }+++def _process_shipping_data_for_order(+ checkout: Checkout, shipping_price: TaxedMoney+) -> dict:+ """Fetch, process and return shipping data from checkout."""+ if not checkout.is_shipping_required():+ return {}++ shipping_address = checkout.shipping_address++ if checkout.user:+ store_user_address(checkout.user, shipping_address, AddressType.SHIPPING)+ if (+ shipping_address+ and checkout.user.addresses.filter(pk=shipping_address.pk).exists()+ ):+ shipping_address = shipping_address.get_copy()++ return {+ "shipping_address": shipping_address,+ "shipping_method": checkout.shipping_method,+ "shipping_method_name": smart_text(checkout.shipping_method),+ "shipping_price": shipping_price,+ "weight": checkout.get_total_weight(),+ }+++def _process_user_data_for_order(checkout: Checkout):+ """Fetch, process and return shipping data from checkout."""+ billing_address = checkout.billing_address++ if checkout.user:+ store_user_address(checkout.user, billing_address, AddressType.BILLING)+ if (+ billing_address+ and checkout.user.addresses.filter(pk=billing_address.pk).exists()+ ):+ billing_address = billing_address.get_copy()++ return {+ "user": checkout.user,+ "user_email": checkout.get_customer_email(),+ "billing_address": billing_address,+ "customer_note": checkout.note,+ }+++def _validate_gift_cards(checkout: Checkout):+ """Check if all gift cards assigned to checkout are available."""+ if (+ not checkout.gift_cards.count()+ == checkout.gift_cards.active(date=date.today()).count()+ ):+ msg = "Gift card has expired. Order placement cancelled."+ raise NotApplicable(msg)+++def _create_line_for_order(checkout_line: "CheckoutLine", discounts) -> OrderLine:+ """Create a line for the given order.++ :raises InsufficientStock: when there is not enough items in stock for this variant.+ """++ quantity = checkout_line.quantity+ variant = checkout_line.variant+ product = variant.product+ country = checkout_line.checkout.get_country()+ check_stock_quantity(variant, country, quantity)++ product_name = str(product)+ variant_name = str(variant)++ translated_product_name = str(product.translated)+ translated_variant_name = str(variant.translated)++ if translated_product_name == product_name:+ translated_product_name = ""++ if translated_variant_name == variant_name:+ translated_variant_name = ""++ manager = get_plugins_manager()+ total_line_price = manager.calculate_checkout_line_total(checkout_line, discounts)+ unit_price = quantize_price(+ total_line_price / checkout_line.quantity, total_line_price.currency+ )+ tax_rate = Decimal("0.0")+ # The condition will return False when unit_price.gross is 0.0+ if not isinstance(unit_price, Decimal) and unit_price.gross:+ tax_rate = unit_price.tax / unit_price.net++ line = OrderLine(+ product_name=product_name,+ variant_name=variant_name,+ translated_product_name=translated_product_name,+ translated_variant_name=translated_variant_name,+ product_sku=variant.sku,+ is_shipping_required=variant.is_shipping_required(),+ quantity=quantity,+ variant=variant,+ unit_price=unit_price, # type: ignore+ tax_rate=tax_rate,+ )++ return line+++def _prepare_order_data(+ *, checkout: Checkout, lines: Iterable[CheckoutLine], discounts+) -> dict:+ """Run checks and return all the data from a given checkout to create an order.++ :raises NotApplicable InsufficientStock:+ """+ order_data = {}++ manager = get_plugins_manager()+ taxed_total = calculations.checkout_total(+ checkout=checkout, lines=lines, discounts=discounts+ )+ cards_total = checkout.get_total_gift_cards_balance()+ taxed_total.gross -= cards_total+ taxed_total.net -= cards_total++ taxed_total = max(taxed_total, zero_taxed_money(checkout.currency))++ shipping_total = manager.calculate_checkout_shipping(checkout, lines, discounts)+ order_data.update(_process_shipping_data_for_order(checkout, shipping_total))+ order_data.update(_process_user_data_for_order(checkout))+ order_data.update(+ {+ "language_code": get_language(),+ "tracking_client_id": checkout.tracking_code or "",+ "total": taxed_total,+ }+ )++ order_data["lines"] = [+ _create_line_for_order(checkout_line=line, discounts=discounts)+ for line in lines+ ]++ # validate checkout gift cards+ _validate_gift_cards(checkout)++ # Get voucher data (last) as they require a transaction+ order_data.update(_get_voucher_data_for_order(checkout))++ # assign gift cards to the order++ order_data["total_price_left"] = (+ manager.calculate_checkout_subtotal(checkout, lines, discounts)+ + shipping_total+ - checkout.discount+ ).gross++ manager.preprocess_order_creation(checkout, discounts)+ return order_data+++def _create_order(*, checkout: Checkout, order_data: dict, user: User) -> Order:+ """Create an order from the checkout.++ Each order will get a private copy of both the billing and the shipping+ address (if shipping).++ If any of the addresses is new and the user is logged in the address+ will also get saved to that user's address book.++ 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_gift_card_to_order++ order = Order.objects.filter(checkout_token=checkout.token).first()+ if order is not None:+ return order++ total_price_left = order_data.pop("total_price_left")+ order_lines = order_data.pop("lines")++ order = Order.objects.create(**order_data, checkout_token=checkout.token)+ for line in order_lines:+ line.order_id = order.pk+ order_lines = OrderLine.objects.bulk_create(order_lines)++ # allocate stocks from the lines+ for line in order_lines: # type: OrderLine+ variant = line.variant+ if variant and variant.track_inventory:+ allocate_stock(line, checkout.get_country(), line.quantity)++ # Add gift cards to the order+ for gift_card in checkout.gift_cards.select_for_update():+ total_price_left = add_gift_card_to_order(order, gift_card, total_price_left)++ # assign checkout payments to the order+ checkout.payments.update(order=order)++ # copy metadata from the checkout into the new order+ order.metadata = checkout.metadata+ order.private_metadata = checkout.private_metadata+ order.save()++ order_created(order=order, user=user)++ # Send the order confirmation email+ transaction.on_commit(+ lambda: send_order_confirmation.delay(order.pk, checkout.redirect_url, user.pk)+ )+ transaction.on_commit(+ lambda: send_staff_order_confirmation.delay(order.pk, checkout.redirect_url)+ )++ return order+++def _prepare_checkout(checkout: models.Checkout, discounts, tracking_code, redirect_url, payment):+ """Prepare checkout object to complete the checkout process."""lines = list(checkout)clean_checkout_shipping(checkout, lines, discounts, CheckoutErrorCode)@@ -53,23 +317,20 @@ def prepare_checkout(checkout.save(update_fields=to_update)-def convert_checkout_to_order(- checkout: models.Checkout, order_data: dict, user: Optional[User]-) -> order_models.Order:- order = create_order(- checkout=checkout, order_data=order_data, user=user, # type: ignore- )- # remove checkout after order is successfully created- checkout.delete()- return order+def abort_order_data(order_data: dict):+ if "voucher" in order_data:+ voucher = order_data["voucher"]+ decrease_voucher_usage(voucher)+ if "user_email" in order_data:+ remove_voucher_usage_by_customer(voucher, order_data["user_email"])-def get_order_data(checkout: models.Checkout, discounts: List[DiscountInfo]) -> dict:+def _get_order_data(checkout: models.Checkout, discounts: List[DiscountInfo]) -> dict:+ """Prepare data that will be converted to order and its lines."""try:- with transaction.atomic():- order_data = prepare_order_data(- checkout=checkout, lines=list(checkout), discounts=discounts,- )+ order_data = _prepare_order_data(+ checkout=checkout, lines=list(checkout), discounts=discounts,+ )except InsufficientStock as e:raise ValidationError(f"Insufficient product stock: {e.item}", code=e.code)except NotApplicable:@@ -85,12 +346,13 @@ def get_order_data(checkout: models.Checkout, discounts: List[DiscountInfo]) ->return order_data-def process_payment(+def _process_payment(payment: Payment,store_source: bool,payment_data: Optional[dict],order_data: dict,) -> Transaction:+ """Process the payment assigned to checkout."""try:if payment.to_confirm:txn = gateway.confirm(payment, additional_data=payment_data)@@ -121,11 +383,12 @@ def complete_checkout() -> Tuple[Optional[Order], bool, dict]:"""Logic required to finalize the checkout and convert it to order.- Should be used with transaction_with_commit_on_errors. As there is a possibility+ Should be used with transaction_with_commit_on_errors, as there is a possibilityfor thread race.+ :raises ValidationError"""payment = checkout.get_last_active_payment()- prepare_checkout(+ _prepare_checkout(checkout=checkout,discounts=discounts,tracking_code=tracking_code,@@ -134,12 +397,12 @@ def complete_checkout()try:- order_data = get_order_data(checkout, discounts)+ order_data = _get_order_data(checkout, discounts)except ValidationError as error:gateway.payment_refund_or_void(payment)raise error- txn = process_payment(+ txn = _process_payment(payment=payment, # type: ignorestore_source=store_source,payment_data=payment_data,@@ -155,9 +418,11 @@ def complete_checkout(order = Noneif not action_required:try:- order = convert_checkout_to_order(- checkout=checkout, order_data=order_data, user=user+ order = _create_order(+ checkout=checkout, order_data=order_data, user=user, # type: ignore)+ # remove checkout after order is successfully created+ checkout.delete()except InsufficientStock as e:abort_order_data(order_data)gateway.payment_refund_or_void(payment)diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.pyindex d31e468b20..0563e7c549 100644--- a/saleor/checkout/tests/test_checkout.py+++ b/saleor/checkout/tests/test_checkout.py@@ -3,40 +3,31 @@ from unittest.mock import Mock, patchimport pytestimport pytz-from django.contrib.auth.models import AnonymousUserfrom django.utils import timezonefrom django_countries.fields import Countryfrom freezegun import freeze_timefrom prices import Money, TaxedMoney-from ...account import CustomerEvents-from ...account.models import Address, CustomerEvent, User+from ...account.models import Address, Userfrom ...account.utils import store_user_address-from ...core.exceptions import InsufficientStock-from ...core.taxes import zero_money, zero_taxed_money+from ...core.taxes import zero_moneyfrom ...discount import DiscountValueType, VoucherTypefrom ...discount.models import NotApplicable, Voucher-from ...order import OrderEvents, OrderEventsEmails-from ...order.models import OrderEventfrom ...payment.models import Paymentfrom ...plugins.manager import get_plugins_managerfrom ...shipping.models import ShippingZone-from ...tests.utils import flush_post_commit_hooksfrom .. import AddressType, calculationsfrom ..models import Checkoutfrom ..utils import (- add_variant_to_checkout,add_voucher_to_checkout,cancel_active_payments,change_billing_address_in_checkout,change_shipping_address_in_checkout,clear_shipping_method,- create_order,get_voucher_discount_for_checkout,get_voucher_for_checkout,is_fully_paid,is_valid_shipping_method,- prepare_order_data,recalculate_checkout_discount,remove_voucher_from_checkout,)@@ -89,597 +80,6 @@ def test_last_change_update_foregin_key(checkout, shipping_method):assert checkout.last_change == pytz.utc.localize(frozen_datetime())-def test_create_order_captured_payment_creates_expected_events(- checkout_with_item, customer_user, shipping_method, payment_txn_captured,-):- checkout = checkout_with_item- checkout_user = 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.payments.add(payment_txn_captured)- checkout.tracking_code = "tracking_code"- checkout.redirect_url = "https://www.example.com"- checkout.save()-- # Place checkout- order = create_order(- checkout=checkout,- order_data=prepare_order_data(- checkout=checkout, lines=list(checkout), discounts=None,- ),- user=customer_user,- )- flush_post_commit_hooks()-- # Ensure only two events were created, and retrieve them- order_events = order.events.all()-- (- order_placed_event,- payment_captured_event,- order_fully_paid_event,- payment_email_sent_event,- order_placed_email_sent_event,- ) = order_events # type: OrderEvent-- # Ensure the correct order event was created- # is the event the expected type- assert order_placed_event.type == OrderEvents.PLACED- # is the user anonymous/ the customer- assert order_placed_event.user == checkout_user- # is the associated backref order valid- assert order_placed_event.order is order- # ensure a date was set- assert order_placed_event.date- # should not have any additional parameters- assert not order_placed_event.parameters-- # Ensure the correct order event was created- # is the event the expected type- assert payment_captured_event.type == OrderEvents.PAYMENT_CAPTURED- # is the user anonymous/ the customer- assert payment_captured_event.user == checkout_user- # is the associated backref order valid- assert payment_captured_event.order is order- # ensure a date was set- assert payment_captured_event.date- # should not have any additional parameters- assert "amount" in payment_captured_event.parameters.keys()- assert "payment_id" in payment_captured_event.parameters.keys()- assert "payment_gateway" in payment_captured_event.parameters.keys()-- # Ensure the correct order event was created- # is the event the expected type- assert order_fully_paid_event.type == OrderEvents.ORDER_FULLY_PAID- # is the user anonymous/ the customer- assert order_fully_paid_event.user == checkout_user- # is the associated backref order valid- assert order_fully_paid_event.order is order- # ensure a date was set- assert order_fully_paid_event.date- # should not have any additional parameters- assert not order_fully_paid_event.parameters-- # Ensure the correct email sent event was created- # should be email sent event- assert payment_email_sent_event.type == OrderEvents.EMAIL_SENT- # ensure the user is none or valid- assert payment_email_sent_event.user == checkout_user- # ensure the mail event is related to order- assert payment_email_sent_event.order is order- # ensure a date was set- assert payment_email_sent_event.date- # ensure the correct parameters were set- assert payment_email_sent_event.parameters == {- "email": order.get_customer_email(),- "email_type": OrderEventsEmails.PAYMENT,- }-- # Ensure the correct email sent event was created- # should be email sent event- assert order_placed_email_sent_event.type == OrderEvents.EMAIL_SENT- # ensure the user is none or valid- assert order_placed_email_sent_event.user == checkout_user- # ensure the mail event is related to order- assert order_placed_email_sent_event.order is order- # ensure a date was set- assert order_placed_email_sent_event.date- # ensure the correct parameters were set- assert order_placed_email_sent_event.parameters == {- "email": order.get_customer_email(),- "email_type": OrderEventsEmails.ORDER_CONFIRMATION,- }-- # 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-- # mock_send_staff_order_confirmation.assert_called_once_with(order.pk)---def test_create_order_captured_payment_creates_expected_events_anonymous_user(- checkout_with_item, customer_user, shipping_method, payment_txn_captured,-):- checkout = checkout_with_item- checkout_user = None-- # Ensure not events are existing prior- assert not OrderEvent.objects.exists()- assert not CustomerEvent.objects.exists()-- # Prepare valid checkout- checkout.user = checkout_user- checkout.email = "[email protected]"- checkout.billing_address = customer_user.default_billing_address- checkout.shipping_address = customer_user.default_shipping_address- checkout.shipping_method = shipping_method- checkout.payments.add(payment_txn_captured)- checkout.tracking_code = "tracking_code"- checkout.redirect_url = "https://www.example.com"- checkout.save()-- # Place checkout- order = create_order(- checkout=checkout,- order_data=prepare_order_data(- checkout=checkout, lines=list(checkout), discounts=None,- ),- user=AnonymousUser(),- )- flush_post_commit_hooks()-- # Ensure only two events were created, and retrieve them- order_events = order.events.all()-- (- order_placed_event,- payment_captured_event,- order_fully_paid_event,- payment_email_sent_event,- order_placed_email_sent_event,- ) = order_events # type: OrderEvent-- # Ensure the correct order event was created- # is the event the expected type- assert order_placed_event.type == OrderEvents.PLACED- # is the user anonymous/ the customer- assert order_placed_event.user == checkout_user- # is the associated backref order valid- assert order_placed_event.order is order- # ensure a date was set- assert order_placed_event.date- # should not have any additional parameters- assert not order_placed_event.parameters-- # Ensure the correct order event was created- # is the event the expected type- assert payment_captured_event.type == OrderEvents.PAYMENT_CAPTURED- # is the user anonymous/ the customer- assert payment_captured_event.user == checkout_user- # is the associated backref order valid- assert payment_captured_event.order is order- # ensure a date was set- assert payment_captured_event.date- # should not have any additional parameters- assert "amount" in payment_captured_event.parameters.keys()- assert "payment_id" in payment_captured_event.parameters.keys()- assert "payment_gateway" in payment_captured_event.parameters.keys()-- # Ensure the correct order event was created- # is the event the expected type- assert order_fully_paid_event.type == OrderEvents.ORDER_FULLY_PAID- # is the user anonymous/ the customer- assert order_fully_paid_event.user == checkout_user- # is the associated backref order valid- assert order_fully_paid_event.order is order- # ensure a date was set- assert order_fully_paid_event.date- # should not have any additional parameters- assert not order_fully_paid_event.parameters-- # Ensure the correct email sent event was created- # should be email sent event- assert payment_email_sent_event.type == OrderEvents.EMAIL_SENT- # ensure the user is none or valid- assert payment_email_sent_event.user == checkout_user- # ensure the mail event is related to order- assert payment_email_sent_event.order is order- # ensure a date was set- assert payment_email_sent_event.date- # ensure the correct parameters were set- assert payment_email_sent_event.parameters == {- "email": order.get_customer_email(),- "email_type": OrderEventsEmails.PAYMENT,- }-- # Ensure the correct email sent event was created- # should be email sent event- assert order_placed_email_sent_event.type == OrderEvents.EMAIL_SENT- # ensure the user is none or valid- assert order_placed_email_sent_event.user == checkout_user- # ensure the mail event is related to order- assert order_placed_email_sent_event.order is order- # ensure a date was set- assert order_placed_email_sent_event.date- # ensure the correct parameters were set- assert order_placed_email_sent_event.parameters == {- "email": order.get_customer_email(),- "email_type": OrderEventsEmails.ORDER_CONFIRMATION,- }-- # Check no event was created if the user was anonymous- assert not CustomerEvent.objects.exists() # should not have created any event---def test_create_order_preauth_payment_creates_expected_events(- checkout_with_item, customer_user, shipping_method, payment_txn_preauth,-):- checkout = checkout_with_item- checkout_user = 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.payments.add(payment_txn_preauth)- checkout.tracking_code = "tracking_code"- checkout.redirect_url = "https://www.example.com"- checkout.save()-- # Place checkout- order = create_order(- checkout=checkout,- order_data=prepare_order_data(- checkout=checkout, lines=list(checkout), discounts=None,- ),- user=customer_user,- )- flush_post_commit_hooks()-- # Ensure only two events were created, and retrieve them- order_events = order.events.all()-- (- order_placed_event,- payment_authorized_event,- order_placed_email_sent_event,- ) = order_events # type: OrderEvent-- # Ensure the correct order event was created- # is the event the expected type- assert order_placed_event.type == OrderEvents.PLACED- # is the user anonymous/ the customer- assert order_placed_event.user == checkout_user- # is the associated backref order valid- assert order_placed_event.order is order- # ensure a date was set- assert order_placed_event.date- # should not have any additional parameters- assert not order_placed_event.parameters-- # Ensure the correct order event was created- # is the event the expected type- assert payment_authorized_event.type == OrderEvents.PAYMENT_AUTHORIZED- # is the user anonymous/ the customer- assert payment_authorized_event.user == checkout_user- # is the associated backref order valid- assert payment_authorized_event.order is order- # ensure a date was set- assert payment_authorized_event.date- # should not have any additional parameters- assert "amount" in payment_authorized_event.parameters.keys()- assert "payment_id" in payment_authorized_event.parameters.keys()- assert "payment_gateway" in payment_authorized_event.parameters.keys()-- # Ensure the correct email sent event was created- # should be email sent event- assert order_placed_email_sent_event.type == OrderEvents.EMAIL_SENT- # ensure the user is none or valid- assert order_placed_email_sent_event.user == checkout_user- # ensure the mail event is related to order- assert order_placed_email_sent_event.order is order- # ensure a date was set- assert order_placed_email_sent_event.date- # ensure the correct parameters were set- assert order_placed_email_sent_event.parameters == {- "email": order.get_customer_email(),- "email_type": OrderEventsEmails.ORDER_CONFIRMATION,- }-- # 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-- # mock_send_staff_order_confirmation.assert_called_once_with(order.pk)---def test_create_order_preauth_payment_creates_expected_events_anonymous_user(- checkout_with_item, customer_user, shipping_method, payment_txn_preauth,-):- checkout = checkout_with_item- checkout_user = None-- # Ensure not events are existing prior- assert not OrderEvent.objects.exists()- assert not CustomerEvent.objects.exists()-- # Prepare valid checkout- checkout.user = checkout_user- checkout.email = "[email protected]"- checkout.billing_address = customer_user.default_billing_address- checkout.shipping_address = customer_user.default_shipping_address- checkout.shipping_method = shipping_method- checkout.payments.add(payment_txn_preauth)- checkout.tracking_code = "tracking_code"- checkout.redirect_url = "https://www.example.com"- checkout.save()-- # Place checkout- order = create_order(- checkout=checkout,- order_data=prepare_order_data(- checkout=checkout, lines=list(checkout), discounts=None,- ),- user=AnonymousUser(),- )- flush_post_commit_hooks()-- # Ensure only two events were created, and retrieve them- order_events = order.events.all()-- (- order_placed_event,- payment_captured_event,- order_placed_email_sent_event,- ) = order_events # type: OrderEvent-- # Ensure the correct order event was created- # is the event the expected type- assert order_placed_event.type == OrderEvents.PLACED- # is the user anonymous/ the customer- assert order_placed_event.user == checkout_user- # is the associated backref order valid- assert order_placed_event.order is order- # ensure a date was set- assert order_placed_event.date- # should not have any additional parameters- assert not order_placed_event.parameters-- # Ensure the correct order event was created- # is the event the expected type- assert payment_captured_event.type == OrderEvents.PAYMENT_AUTHORIZED- # is the user anonymous/ the customer- assert payment_captured_event.user == checkout_user- # is the associated backref order valid- assert payment_captured_event.order is order- # ensure a date was set- assert payment_captured_event.date- # should not have any additional parameters- assert "amount" in payment_captured_event.parameters.keys()- assert "payment_id" in payment_captured_event.parameters.keys()- assert "payment_gateway" in payment_captured_event.parameters.keys()-- # Ensure the correct email sent event was created- # should be email sent event- assert order_placed_email_sent_event.type == OrderEvents.EMAIL_SENT- # ensure the user is none or valid- assert order_placed_email_sent_event.user == checkout_user- # ensure the mail event is related to order- assert order_placed_email_sent_event.order is order- # ensure a date was set- assert order_placed_email_sent_event.date- # ensure the correct parameters were set- assert order_placed_email_sent_event.parameters == {- "email": order.get_customer_email(),- "email_type": OrderEventsEmails.ORDER_CONFIRMATION,- }-- # Check no event was created if the user was anonymous- assert not CustomerEvent.objects.exists() # should not have created any event---def test_create_order_insufficient_stock(- checkout, customer_user, product_without_shipping-):- variant = product_without_shipping.variants.get()- add_variant_to_checkout(checkout, variant, 10, check_quantity=False)- checkout.user = customer_user- checkout.billing_address = customer_user.default_billing_address- checkout.shipping_address = customer_user.default_billing_address- checkout.tracking_code = "tracking_code"- checkout.save()-- with pytest.raises(InsufficientStock):- prepare_order_data(- checkout=checkout, lines=list(checkout), discounts=None,- )---def test_create_order_doesnt_duplicate_order(- checkout_with_item, customer_user, shipping_method-):- checkout = checkout_with_item- checkout.user = customer_user- checkout.billing_address = customer_user.default_billing_address- checkout.shipping_address = customer_user.default_billing_address- checkout.shipping_method = shipping_method- checkout.tracking_code = ""- checkout.redirect_url = "https://www.example.com"- checkout.save()-- order_data = prepare_order_data(- checkout=checkout, lines=list(checkout), discounts=None- )-- order_1 = create_order(- checkout=checkout, order_data=order_data, user=customer_user,- )- assert order_1.checkout_token == checkout.token-- order_2 = create_order(- checkout=checkout, order_data=order_data, user=customer_user,- )- assert order_1.pk == order_2.pk--[email protected]("is_anonymous_user", (True, False))-def test_create_order_with_gift_card(- checkout_with_gift_card, customer_user, shipping_method, is_anonymous_user-):- checkout_user = None if is_anonymous_user else customer_user- checkout = checkout_with_gift_card- checkout.user = checkout_user- checkout.billing_address = customer_user.default_billing_address- checkout.shipping_address = customer_user.default_billing_address- checkout.shipping_method = shipping_method- checkout.tracking_code = "tracking_code"- checkout.redirect_url = "https://www.example.com"- checkout.save()-- lines = list(checkout)- subtotal = calculations.checkout_subtotal(checkout=checkout, lines=lines)- shipping_price = calculations.checkout_shipping_price(- checkout=checkout, lines=lines- )- total_gross_without_gift_cards = (- subtotal.gross + shipping_price.gross - checkout.discount- )- gift_cards_balance = checkout.get_total_gift_cards_balance()-- order = create_order(- checkout=checkout,- order_data=prepare_order_data(checkout=checkout, lines=lines, discounts=None,),- user=customer_user if not is_anonymous_user else AnonymousUser(),- )-- assert order.gift_cards.count() == 1- assert order.gift_cards.first().current_balance.amount == 0- assert order.total.gross == (total_gross_without_gift_cards - gift_cards_balance)---def test_create_order_with_gift_card_partial_use(- checkout_with_item, gift_card_used, customer_user, shipping_method-):- checkout = checkout_with_item- checkout.user = customer_user- checkout.billing_address = customer_user.default_billing_address- checkout.shipping_address = customer_user.default_billing_address- checkout.shipping_method = shipping_method- checkout.tracking_code = "tracking_code"- checkout.redirect_url = "https://www.example.com"- checkout.save()-- price_without_gift_card = calculations.checkout_total(- checkout=checkout, lines=list(checkout)- )- gift_card_balance_before_order = gift_card_used.current_balance_amount-- checkout.gift_cards.add(gift_card_used)- checkout.save()-- order = create_order(- checkout=checkout,- order_data=prepare_order_data(- checkout=checkout, lines=list(checkout), discounts=None,- ),- user=customer_user,- )-- gift_card_used.refresh_from_db()-- expected_old_balance = (- price_without_gift_card.gross.amount + gift_card_used.current_balance_amount- )-- assert order.gift_cards.count() > 0- assert order.total == zero_taxed_money()- assert gift_card_balance_before_order == expected_old_balance---def test_create_order_with_many_gift_cards(- checkout_with_item,- gift_card_created_by_staff,- gift_card,- customer_user,- shipping_method,-):- checkout = checkout_with_item- checkout.user = customer_user- checkout.billing_address = customer_user.default_billing_address- checkout.shipping_address = customer_user.default_billing_address- checkout.shipping_method = shipping_method- checkout.tracking_code = "tracking_code"- checkout.redirect_url = "https://www.example.com"- checkout.save()-- price_without_gift_card = calculations.checkout_total(- checkout=checkout, lines=list(checkout)- )- gift_cards_balance_before_order = (- gift_card_created_by_staff.current_balance.amount- + gift_card.current_balance.amount- )-- checkout.gift_cards.add(gift_card_created_by_staff)- checkout.gift_cards.add(gift_card)- checkout.save()-- order = create_order(- checkout=checkout,- order_data=prepare_order_data(- checkout=checkout, lines=list(checkout), discounts=None,- ),- user=customer_user,- )-- gift_card_created_by_staff.refresh_from_db()- gift_card.refresh_from_db()- zero_price = zero_money()- assert order.gift_cards.count() > 0- assert gift_card_created_by_staff.current_balance == zero_price- assert gift_card.current_balance == zero_price- assert price_without_gift_card.gross.amount == (- gift_cards_balance_before_order + order.total.gross.amount- )---def test_note_in_created_order(checkout_with_item, address, customer_user):- checkout_with_item.shipping_address = address- checkout_with_item.note = "test_note"- checkout_with_item.tracking_code = "tracking_code"- checkout_with_item.redirect_url = "https://www.example.com"- checkout_with_item.save()- order = create_order(- checkout=checkout_with_item,- order_data=prepare_order_data(- checkout=checkout_with_item, lines=list(checkout_with_item), discounts=None,- ),- user=customer_user,- )- assert order.customer_note == checkout_with_item.note--@pytest.mark.parametrize("total, min_spent_amount, total_quantity, min_checkout_items_quantity, ""discount_value, discount_value_type, expected_value",@@ -1467,25 +867,3 @@ def test_cancel_active_payments(checkout_with_payments):# thenassert checkout.payments.filter(is_active=True).count() == 0---def test_create_order_with_variant_tracking_false(- checkout, customer_user, variant_without_inventory_tracking-):- variant = variant_without_inventory_tracking- checkout.user = customer_user- checkout.billing_address = customer_user.default_billing_address- checkout.shipping_address = customer_user.default_billing_address- checkout.tracking_code = ""- checkout.redirect_url = "https://www.example.com"- checkout.save()- add_variant_to_checkout(checkout, variant, 10, check_quantity=False)-- order_data = prepare_order_data(- checkout=checkout, lines=list(checkout), discounts=None- )-- order_1 = create_order(- checkout=checkout, order_data=order_data, user=customer_user,- )- assert order_1.checkout_token == checkout.tokendiff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.pynew file mode 100644index 0000000000..a7c7e152aa--- /dev/null+++ b/saleor/checkout/tests/test_checkout_complete.py@@ -0,0 +1,626 @@+import pytest+from django.contrib.auth.models import AnonymousUser++from ...account import CustomerEvents+from ...account.models import CustomerEvent+from ...core.exceptions import InsufficientStock+from ...core.taxes import zero_money, zero_taxed_money+from ...order import OrderEvents, OrderEventsEmails+from ...order.models import OrderEvent+from ...tests.utils import flush_post_commit_hooks+from .. import calculations+from ..complete_checkout import _create_order, _prepare_order_data+from ..utils import add_variant_to_checkout+++def test_create_order_captured_payment_creates_expected_events(+ checkout_with_item, customer_user, shipping_method, payment_txn_captured,+):+ checkout = checkout_with_item+ checkout_user = 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.payments.add(payment_txn_captured)+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"+ checkout.save()++ # Place checkout+ order = _create_order(+ checkout=checkout,+ order_data=_prepare_order_data(+ checkout=checkout, lines=list(checkout), discounts=None,+ ),+ user=customer_user,+ )+ flush_post_commit_hooks()++ # Ensure only two events were created, and retrieve them+ order_events = order.events.all()++ (+ order_placed_event,+ payment_captured_event,+ order_fully_paid_event,+ payment_email_sent_event,+ order_placed_email_sent_event,+ ) = order_events # type: OrderEvent++ # Ensure the correct order event was created+ # is the event the expected type+ assert order_placed_event.type == OrderEvents.PLACED+ # is the user anonymous/ the customer+ assert order_placed_event.user == checkout_user+ # is the associated backref order valid+ assert order_placed_event.order is order+ # ensure a date was set+ assert order_placed_event.date+ # should not have any additional parameters+ assert not order_placed_event.parameters++ # Ensure the correct order event was created+ # is the event the expected type+ assert payment_captured_event.type == OrderEvents.PAYMENT_CAPTURED+ # is the user anonymous/ the customer+ assert payment_captured_event.user == checkout_user+ # is the associated backref order valid+ assert payment_captured_event.order is order+ # ensure a date was set+ assert payment_captured_event.date+ # should not have any additional parameters+ assert "amount" in payment_captured_event.parameters.keys()+ assert "payment_id" in payment_captured_event.parameters.keys()+ assert "payment_gateway" in payment_captured_event.parameters.keys()++ # Ensure the correct order event was created+ # is the event the expected type+ assert order_fully_paid_event.type == OrderEvents.ORDER_FULLY_PAID+ # is the user anonymous/ the customer+ assert order_fully_paid_event.user == checkout_user+ # is the associated backref order valid+ assert order_fully_paid_event.order is order+ # ensure a date was set+ assert order_fully_paid_event.date+ # should not have any additional parameters+ assert not order_fully_paid_event.parameters++ # Ensure the correct email sent event was created+ # should be email sent event+ assert payment_email_sent_event.type == OrderEvents.EMAIL_SENT+ # ensure the user is none or valid+ assert payment_email_sent_event.user == checkout_user+ # ensure the mail event is related to order+ assert payment_email_sent_event.order is order+ # ensure a date was set+ assert payment_email_sent_event.date+ # ensure the correct parameters were set+ assert payment_email_sent_event.parameters == {+ "email": order.get_customer_email(),+ "email_type": OrderEventsEmails.PAYMENT,+ }++ # Ensure the correct email sent event was created+ # should be email sent event+ assert order_placed_email_sent_event.type == OrderEvents.EMAIL_SENT+ # ensure the user is none or valid+ assert order_placed_email_sent_event.user == checkout_user+ # ensure the mail event is related to order+ assert order_placed_email_sent_event.order is order+ # ensure a date was set+ assert order_placed_email_sent_event.date+ # ensure the correct parameters were set+ assert order_placed_email_sent_event.parameters == {+ "email": order.get_customer_email(),+ "email_type": OrderEventsEmails.ORDER_CONFIRMATION,+ }++ # 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++ # mock_send_staff_order_confirmation.assert_called_once_with(order.pk)+++def test_create_order_captured_payment_creates_expected_events_anonymous_user(+ checkout_with_item, customer_user, shipping_method, payment_txn_captured,+):+ checkout = checkout_with_item+ checkout_user = None++ # Ensure not events are existing prior+ assert not OrderEvent.objects.exists()+ assert not CustomerEvent.objects.exists()++ # Prepare valid checkout+ checkout.user = checkout_user+ checkout.email = "[email protected]"+ checkout.billing_address = customer_user.default_billing_address+ checkout.shipping_address = customer_user.default_shipping_address+ checkout.shipping_method = shipping_method+ checkout.payments.add(payment_txn_captured)+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"+ checkout.save()++ # Place checkout+ order = _create_order(+ checkout=checkout,+ order_data=_prepare_order_data(+ checkout=checkout, lines=list(checkout), discounts=None,+ ),+ user=AnonymousUser(),+ )+ flush_post_commit_hooks()++ # Ensure only two events were created, and retrieve them+ order_events = order.events.all()++ (+ order_placed_event,+ payment_captured_event,+ order_fully_paid_event,+ payment_email_sent_event,+ order_placed_email_sent_event,+ ) = order_events # type: OrderEvent++ # Ensure the correct order event was created+ # is the event the expected type+ assert order_placed_event.type == OrderEvents.PLACED+ # is the user anonymous/ the customer+ assert order_placed_event.user == checkout_user+ # is the associated backref order valid+ assert order_placed_event.order is order+ # ensure a date was set+ assert order_placed_event.date+ # should not have any additional parameters+ assert not order_placed_event.parameters++ # Ensure the correct order event was created+ # is the event the expected type+ assert payment_captured_event.type == OrderEvents.PAYMENT_CAPTURED+ # is the user anonymous/ the customer+ assert payment_captured_event.user == checkout_user+ # is the associated backref order valid+ assert payment_captured_event.order is order+ # ensure a date was set+ assert payment_captured_event.date+ # should not have any additional parameters+ assert "amount" in payment_captured_event.parameters.keys()+ assert "payment_id" in payment_captured_event.parameters.keys()+ assert "payment_gateway" in payment_captured_event.parameters.keys()++ # Ensure the correct order event was created+ # is the event the expected type+ assert order_fully_paid_event.type == OrderEvents.ORDER_FULLY_PAID+ # is the user anonymous/ the customer+ assert order_fully_paid_event.user == checkout_user+ # is the associated backref order valid+ assert order_fully_paid_event.order is order+ # ensure a date was set+ assert order_fully_paid_event.date+ # should not have any additional parameters+ assert not order_fully_paid_event.parameters++ # Ensure the correct email sent event was created+ # should be email sent event+ assert payment_email_sent_event.type == OrderEvents.EMAIL_SENT+ # ensure the user is none or valid+ assert payment_email_sent_event.user == checkout_user+ # ensure the mail event is related to order+ assert payment_email_sent_event.order is order+ # ensure a date was set+ assert payment_email_sent_event.date+ # ensure the correct parameters were set+ assert payment_email_sent_event.parameters == {+ "email": order.get_customer_email(),+ "email_type": OrderEventsEmails.PAYMENT,+ }++ # Ensure the correct email sent event was created+ # should be email sent event+ assert order_placed_email_sent_event.type == OrderEvents.EMAIL_SENT+ # ensure the user is none or valid+ assert order_placed_email_sent_event.user == checkout_user+ # ensure the mail event is related to order+ assert order_placed_email_sent_event.order is order+ # ensure a date was set+ assert order_placed_email_sent_event.date+ # ensure the correct parameters were set+ assert order_placed_email_sent_event.parameters == {+ "email": order.get_customer_email(),+ "email_type": OrderEventsEmails.ORDER_CONFIRMATION,+ }++ # Check no event was created if the user was anonymous+ assert not CustomerEvent.objects.exists() # should not have created any event+++def test_create_order_preauth_payment_creates_expected_events(+ checkout_with_item, customer_user, shipping_method, payment_txn_preauth,+):+ checkout = checkout_with_item+ checkout_user = 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.payments.add(payment_txn_preauth)+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"+ checkout.save()++ # Place checkout+ order = _create_order(+ checkout=checkout,+ order_data=_prepare_order_data(+ checkout=checkout, lines=list(checkout), discounts=None,+ ),+ user=customer_user,+ )+ flush_post_commit_hooks()++ # Ensure only two events were created, and retrieve them+ order_events = order.events.all()++ (+ order_placed_event,+ payment_authorized_event,+ order_placed_email_sent_event,+ ) = order_events # type: OrderEvent++ # Ensure the correct order event was created+ # is the event the expected type+ assert order_placed_event.type == OrderEvents.PLACED+ # is the user anonymous/ the customer+ assert order_placed_event.user == checkout_user+ # is the associated backref order valid+ assert order_placed_event.order is order+ # ensure a date was set+ assert order_placed_event.date+ # should not have any additional parameters+ assert not order_placed_event.parameters++ # Ensure the correct order event was created+ # is the event the expected type+ assert payment_authorized_event.type == OrderEvents.PAYMENT_AUTHORIZED+ # is the user anonymous/ the customer+ assert payment_authorized_event.user == checkout_user+ # is the associated backref order valid+ assert payment_authorized_event.order is order+ # ensure a date was set+ assert payment_authorized_event.date+ # should not have any additional parameters+ assert "amount" in payment_authorized_event.parameters.keys()+ assert "payment_id" in payment_authorized_event.parameters.keys()+ assert "payment_gateway" in payment_authorized_event.parameters.keys()++ # Ensure the correct email sent event was created+ # should be email sent event+ assert order_placed_email_sent_event.type == OrderEvents.EMAIL_SENT+ # ensure the user is none or valid+ assert order_placed_email_sent_event.user == checkout_user+ # ensure the mail event is related to order+ assert order_placed_email_sent_event.order is order+ # ensure a date was set+ assert order_placed_email_sent_event.date+ # ensure the correct parameters were set+ assert order_placed_email_sent_event.parameters == {+ "email": order.get_customer_email(),+ "email_type": OrderEventsEmails.ORDER_CONFIRMATION,+ }++ # 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++ # mock_send_staff_order_confirmation.assert_called_once_with(order.pk)+++def test_create_order_preauth_payment_creates_expected_events_anonymous_user(+ checkout_with_item, customer_user, shipping_method, payment_txn_preauth,+):+ checkout = checkout_with_item+ checkout_user = None++ # Ensure not events are existing prior+ assert not OrderEvent.objects.exists()+ assert not CustomerEvent.objects.exists()++ # Prepare valid checkout+ checkout.user = checkout_user+ checkout.email = "[email protected]"+ checkout.billing_address = customer_user.default_billing_address+ checkout.shipping_address = customer_user.default_shipping_address+ checkout.shipping_method = shipping_method+ checkout.payments.add(payment_txn_preauth)+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"+ checkout.save()++ # Place checkout+ order = _create_order(+ checkout=checkout,+ order_data=_prepare_order_data(+ checkout=checkout, lines=list(checkout), discounts=None,+ ),+ user=AnonymousUser(),+ )+ flush_post_commit_hooks()++ # Ensure only two events were created, and retrieve them+ order_events = order.events.all()++ (+ order_placed_event,+ payment_captured_event,+ order_placed_email_sent_event,+ ) = order_events # type: OrderEvent++ # Ensure the correct order event was created+ # is the event the expected type+ assert order_placed_event.type == OrderEvents.PLACED+ # is the user anonymous/ the customer+ assert order_placed_event.user == checkout_user+ # is the associated backref order valid+ assert order_placed_event.order is order+ # ensure a date was set+ assert order_placed_event.date+ # should not have any additional parameters+ assert not order_placed_event.parameters++ # Ensure the correct order event was created+ # is the event the expected type+ assert payment_captured_event.type == OrderEvents.PAYMENT_AUTHORIZED+ # is the user anonymous/ the customer+ assert payment_captured_event.user == checkout_user+ # is the associated backref order valid+ assert payment_captured_event.order is order+ # ensure a date was set+ assert payment_captured_event.date+ # should not have any additional parameters+ assert "amount" in payment_captured_event.parameters.keys()+ assert "payment_id" in payment_captured_event.parameters.keys()+ assert "payment_gateway" in payment_captured_event.parameters.keys()++ # Ensure the correct email sent event was created+ # should be email sent event+ assert order_placed_email_sent_event.type == OrderEvents.EMAIL_SENT+ # ensure the user is none or valid+ assert order_placed_email_sent_event.user == checkout_user+ # ensure the mail event is related to order+ assert order_placed_email_sent_event.order is order+ # ensure a date was set+ assert order_placed_email_sent_event.date+ # ensure the correct parameters were set+ assert order_placed_email_sent_event.parameters == {+ "email": order.get_customer_email(),+ "email_type": OrderEventsEmails.ORDER_CONFIRMATION,+ }++ # Check no event was created if the user was anonymous+ assert not CustomerEvent.objects.exists() # should not have created any event+++def test_create_order_insufficient_stock(+ checkout, customer_user, product_without_shipping+):+ variant = product_without_shipping.variants.get()+ add_variant_to_checkout(checkout, variant, 10, check_quantity=False)+ checkout.user = customer_user+ checkout.billing_address = customer_user.default_billing_address+ checkout.shipping_address = customer_user.default_billing_address+ checkout.tracking_code = "tracking_code"+ checkout.save()++ with pytest.raises(InsufficientStock):+ _prepare_order_data(+ checkout=checkout, lines=list(checkout), discounts=None,+ )+++def test_create_order_doesnt_duplicate_order(+ checkout_with_item, customer_user, shipping_method+):+ checkout = checkout_with_item+ checkout.user = customer_user+ checkout.billing_address = customer_user.default_billing_address+ checkout.shipping_address = customer_user.default_billing_address+ checkout.shipping_method = shipping_method+ checkout.tracking_code = ""+ checkout.redirect_url = "https://www.example.com"+ checkout.save()++ order_data = _prepare_order_data(+ checkout=checkout, lines=list(checkout), discounts=None+ )++ order_1 = _create_order(+ checkout=checkout, order_data=order_data, user=customer_user,+ )+ assert order_1.checkout_token == checkout.token++ order_2 = _create_order(+ checkout=checkout, order_data=order_data, user=customer_user,+ )+ assert order_1.pk == order_2.pk++[email protected]("is_anonymous_user", (True, False))+def test_create_order_with_gift_card(+ checkout_with_gift_card, customer_user, shipping_method, is_anonymous_user+):+ checkout_user = None if is_anonymous_user else customer_user+ checkout = checkout_with_gift_card+ checkout.user = checkout_user+ checkout.billing_address = customer_user.default_billing_address+ checkout.shipping_address = customer_user.default_billing_address+ checkout.shipping_method = shipping_method+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"+ checkout.save()++ lines = list(checkout)+ subtotal = calculations.checkout_subtotal(checkout=checkout, lines=lines)+ shipping_price = calculations.checkout_shipping_price(+ checkout=checkout, lines=lines+ )+ total_gross_without_gift_cards = (+ subtotal.gross + shipping_price.gross - checkout.discount+ )+ gift_cards_balance = checkout.get_total_gift_cards_balance()++ order = _create_order(+ checkout=checkout,+ order_data=_prepare_order_data(checkout=checkout, lines=lines, discounts=None,),+ user=customer_user if not is_anonymous_user else AnonymousUser(),+ )++ assert order.gift_cards.count() == 1+ assert order.gift_cards.first().current_balance.amount == 0+ assert order.total.gross == (total_gross_without_gift_cards - gift_cards_balance)+++def test_create_order_with_gift_card_partial_use(+ checkout_with_item, gift_card_used, customer_user, shipping_method+):+ checkout = checkout_with_item+ checkout.user = customer_user+ checkout.billing_address = customer_user.default_billing_address+ checkout.shipping_address = customer_user.default_billing_address+ checkout.shipping_method = shipping_method+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"+ checkout.save()++ price_without_gift_card = calculations.checkout_total(+ checkout=checkout, lines=list(checkout)+ )+ gift_card_balance_before_order = gift_card_used.current_balance_amount++ checkout.gift_cards.add(gift_card_used)+ checkout.save()++ order = _create_order(+ checkout=checkout,+ order_data=_prepare_order_data(+ checkout=checkout, lines=list(checkout), discounts=None,+ ),+ user=customer_user,+ )++ gift_card_used.refresh_from_db()++ expected_old_balance = (+ price_without_gift_card.gross.amount + gift_card_used.current_balance_amount+ )++ assert order.gift_cards.count() > 0+ assert order.total == zero_taxed_money()+ assert gift_card_balance_before_order == expected_old_balance+++def test_create_order_with_many_gift_cards(+ checkout_with_item,+ gift_card_created_by_staff,+ gift_card,+ customer_user,+ shipping_method,+):+ checkout = checkout_with_item+ checkout.user = customer_user+ checkout.billing_address = customer_user.default_billing_address+ checkout.shipping_address = customer_user.default_billing_address+ checkout.shipping_method = shipping_method+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"+ checkout.save()++ price_without_gift_card = calculations.checkout_total(+ checkout=checkout, lines=list(checkout)+ )+ gift_cards_balance_before_order = (+ gift_card_created_by_staff.current_balance.amount+ + gift_card.current_balance.amount+ )++ checkout.gift_cards.add(gift_card_created_by_staff)+ checkout.gift_cards.add(gift_card)+ checkout.save()++ order = _create_order(+ checkout=checkout,+ order_data=_prepare_order_data(+ checkout=checkout, lines=list(checkout), discounts=None,+ ),+ user=customer_user,+ )++ gift_card_created_by_staff.refresh_from_db()+ gift_card.refresh_from_db()+ zero_price = zero_money()+ assert order.gift_cards.count() > 0+ assert gift_card_created_by_staff.current_balance == zero_price+ assert gift_card.current_balance == zero_price+ assert price_without_gift_card.gross.amount == (+ gift_cards_balance_before_order + order.total.gross.amount+ )+++def test_note_in_created_order(checkout_with_item, address, customer_user):+ checkout_with_item.shipping_address = address+ checkout_with_item.note = "test_note"+ checkout_with_item.tracking_code = "tracking_code"+ checkout_with_item.redirect_url = "https://www.example.com"+ checkout_with_item.save()+ order = _create_order(+ checkout=checkout_with_item,+ order_data=_prepare_order_data(+ checkout=checkout_with_item, lines=list(checkout_with_item), discounts=None,+ ),+ user=customer_user,+ )+ assert order.customer_note == checkout_with_item.note+++def test_create_order_with_variant_tracking_false(+ checkout, customer_user, variant_without_inventory_tracking+):+ variant = variant_without_inventory_tracking+ checkout.user = customer_user+ checkout.billing_address = customer_user.default_billing_address+ checkout.shipping_address = customer_user.default_billing_address+ checkout.tracking_code = ""+ checkout.redirect_url = "https://www.example.com"+ checkout.save()+ add_variant_to_checkout(checkout, variant, 10, check_quantity=False)++ order_data = _prepare_order_data(+ checkout=checkout, lines=list(checkout), discounts=None+ )++ order_1 = _create_order(+ checkout=checkout, order_data=order_data, user=customer_user,+ )+ assert order_1.checkout_token == checkout.tokendiff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex de374f034f..0e0c43514b 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -1,18 +1,12 @@"""Checkout-related utility functions."""-from datetime import date-from decimal import Decimalfrom typing import Iterable, List, Optional, Tuplefrom django.core.exceptions import ValidationError-from django.db import transactionfrom django.db.models import Max, Min, Sumfrom django.utils import timezone-from django.utils.encoding import smart_text-from django.utils.translation import get_language-from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange+from prices import Money, MoneyRange, TaxedMoneyRangefrom ..account.models import User-from ..account.utils import store_user_addressfrom ..checkout import calculationsfrom ..checkout.error_codes import CheckoutErrorCodefrom ..core.exceptions import ProductNotPublished@@ -26,25 +20,17 @@ from ..core.utils.promo_code import (from ..discount import DiscountInfo, VoucherTypefrom ..discount.models import NotApplicable, Voucherfrom ..discount.utils import (- add_voucher_usage_by_customer,- decrease_voucher_usage,get_discounted_lines,get_products_voucher_discount,- increase_voucher_usage,- remove_voucher_usage_by_customer,validate_voucher_for_checkout,)from ..giftcard.utils import (add_gift_card_code_to_checkout,remove_gift_card_code_from_checkout,)-from ..order.actions import order_created-from ..order.emails import send_order_confirmation, send_staff_order_confirmation-from ..order.models import Order, OrderLinefrom ..plugins.manager import get_plugins_managerfrom ..shipping.models import ShippingMethodfrom ..warehouse.availability import check_stock_quantity-from ..warehouse.management import allocate_stockfrom . import AddressTypefrom .models import Checkout, CheckoutLine@@ -502,257 +488,6 @@ def clear_shipping_method(checkout: Checkout):checkout.save(update_fields=["shipping_method", "last_change"])-def _get_voucher_data_for_order(checkout: Checkout) -> dict:- """Fetch, process and return voucher/discount data from checkout.-- Careful! It should be called inside a transaction.-- :raises NotApplicable: When the voucher is not applicable in the current checkout.- """- voucher = get_voucher_for_checkout(checkout, with_lock=True)-- if checkout.voucher_code and not voucher:- msg = "Voucher expired in meantime. Order placement aborted."- raise NotApplicable(msg)-- if not voucher:- return {}-- increase_voucher_usage(voucher)- if voucher.apply_once_per_customer:- add_voucher_usage_by_customer(voucher, checkout.get_customer_email())- return {- "voucher": voucher,- "discount": checkout.discount,- "discount_name": checkout.discount_name,- "translated_discount_name": checkout.translated_discount_name,- }---def _process_shipping_data_for_order(- checkout: Checkout, shipping_price: TaxedMoney-) -> dict:- """Fetch, process and return shipping data from checkout."""- if not checkout.is_shipping_required():- return {}-- shipping_address = checkout.shipping_address-- if checkout.user:- store_user_address(checkout.user, shipping_address, AddressType.SHIPPING)- if (- shipping_address- and checkout.user.addresses.filter(pk=shipping_address.pk).exists()- ):- shipping_address = shipping_address.get_copy()-- return {- "shipping_address": shipping_address,- "shipping_method": checkout.shipping_method,- "shipping_method_name": smart_text(checkout.shipping_method),- "shipping_price": shipping_price,- "weight": checkout.get_total_weight(),- }---def _process_user_data_for_order(checkout: Checkout):- """Fetch, process and return shipping data from checkout."""- billing_address = checkout.billing_address-- if checkout.user:- store_user_address(checkout.user, billing_address, AddressType.BILLING)- if (- billing_address- and checkout.user.addresses.filter(pk=billing_address.pk).exists()- ):- billing_address = billing_address.get_copy()-- return {- "user": checkout.user,- "user_email": checkout.get_customer_email(),- "billing_address": billing_address,- "customer_note": checkout.note,- }---def validate_gift_cards(checkout: Checkout):- """Check if all gift cards assigned to checkout are available."""- if (- not checkout.gift_cards.count()- == checkout.gift_cards.active(date=date.today()).count()- ):- msg = "Gift card has expired. Order placement cancelled."- raise NotApplicable(msg)---def create_line_for_order(checkout_line: "CheckoutLine", discounts) -> OrderLine:- """Create a line for the given order.-- :raises InsufficientStock: when there is not enough items in stock for this variant.- """-- quantity = checkout_line.quantity- variant = checkout_line.variant- product = variant.product- country = checkout_line.checkout.get_country()- check_stock_quantity(variant, country, quantity)-- product_name = str(product)- variant_name = str(variant)-- translated_product_name = str(product.translated)- translated_variant_name = str(variant.translated)-- if translated_product_name == product_name:- translated_product_name = ""-- if translated_variant_name == variant_name:- translated_variant_name = ""-- manager = get_plugins_manager()- total_line_price = manager.calculate_checkout_line_total(checkout_line, discounts)- unit_price = quantize_price(- total_line_price / checkout_line.quantity, total_line_price.currency- )- tax_rate = Decimal("0.0")- # The condition will return False when unit_price.gross is 0.0- if not isinstance(unit_price, Decimal) and unit_price.gross:- tax_rate = unit_price.tax / unit_price.net-- line = OrderLine(- product_name=product_name,- variant_name=variant_name,- translated_product_name=translated_product_name,- translated_variant_name=translated_variant_name,- product_sku=variant.sku,- is_shipping_required=variant.is_shipping_required(),- quantity=quantity,- variant=variant,- unit_price=unit_price, # type: ignore- tax_rate=tax_rate,- )-- return line---def prepare_order_data(- *, checkout: Checkout, lines: Iterable[CheckoutLine], discounts-) -> dict:- """Run checks and return all the data from a given checkout to create an order.-- :raises NotApplicable InsufficientStock:- """- order_data = {}-- manager = get_plugins_manager()- taxed_total = calculations.checkout_total(- checkout=checkout, lines=lines, discounts=discounts- )- cards_total = checkout.get_total_gift_cards_balance()- taxed_total.gross -= cards_total- taxed_total.net -= cards_total-- taxed_total = max(taxed_total, zero_taxed_money(checkout.currency))-- shipping_total = manager.calculate_checkout_shipping(checkout, lines, discounts)- order_data.update(_process_shipping_data_for_order(checkout, shipping_total))- order_data.update(_process_user_data_for_order(checkout))- order_data.update(- {- "language_code": get_language(),- "tracking_client_id": checkout.tracking_code or "",- "total": taxed_total,- }- )-- order_data["lines"] = [- create_line_for_order(checkout_line=line, discounts=discounts) for line in lines- ]-- # validate checkout gift cards- validate_gift_cards(checkout)-- # Get voucher data (last) as they require a transaction- order_data.update(_get_voucher_data_for_order(checkout))-- # assign gift cards to the order-- order_data["total_price_left"] = (- manager.calculate_checkout_subtotal(checkout, lines, discounts)- + shipping_total- - checkout.discount- ).gross-- manager.preprocess_order_creation(checkout, discounts)- return order_data---def abort_order_data(order_data: dict):- if "voucher" in order_data:- voucher = order_data["voucher"]- decrease_voucher_usage(voucher)- if "user_email" in order_data:- remove_voucher_usage_by_customer(voucher, order_data["user_email"])---def create_order(*, checkout: Checkout, order_data: dict, user: User) -> Order:- """Create an order from the checkout.-- Each order will get a private copy of both the billing and the shipping- address (if shipping).-- If any of the addresses is new and the user is logged in the address- will also get saved to that user's address book.-- 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_gift_card_to_order-- order = Order.objects.filter(checkout_token=checkout.token).first()- if order is not None:- return order-- total_price_left = order_data.pop("total_price_left")- order_lines = order_data.pop("lines")-- order = Order.objects.create(**order_data, checkout_token=checkout.token)- for line in order_lines:- line.order_id = order.pk- order_lines = OrderLine.objects.bulk_create(order_lines)-- # allocate stocks from the lines- for line in order_lines: # type: OrderLine- variant = line.variant- if variant and variant.track_inventory:- allocate_stock(line, checkout.get_country(), line.quantity)-- # Add gift cards to the order- for gift_card in checkout.gift_cards.select_for_update():- total_price_left = add_gift_card_to_order(order, gift_card, total_price_left)-- # assign checkout payments to the order- checkout.payments.update(order=order)-- # copy metadata from the checkout into the new order- order.metadata = checkout.metadata- order.private_metadata = checkout.private_metadata- order.save()-- order_created(order=order, user=user)-- # Send the order confirmation email- transaction.on_commit(- lambda: send_order_confirmation.delay(order.pk, checkout.redirect_url, user.pk)- )- transaction.on_commit(- lambda: send_staff_order_confirmation.delay(order.pk, checkout.redirect_url)- )-- return order--def is_fully_paid(checkout: Checkout, lines: Iterable[CheckoutLine], discounts: Iterable[DiscountInfo]):diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 1fbff94c85..097f830d30 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -794,11 +794,7 @@ class CheckoutComplete(BaseMutation):checkout_id, Checkout, field="checkout_id")- order = (- order_models.Order.objects.confirmed()- .filter(checkout_token=checkout_token)- .first()- )+ order = order_models.Order.objects.get_by_checkout_token(checkout_token)if order:# The order is already created. We return it as a success# checkoutComplete response. Order is anonymized for not logged indiff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.pyindex d77fb5bb9e..9872115647 100644--- a/saleor/graphql/checkout/tests/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py@@ -793,7 +793,7 @@ def test_order_already_exists(assert Checkout.objects.count() == 0-@patch("saleor.checkout.complete_checkout.create_order")+@patch("saleor.checkout.complete_checkout._create_order")def test_create_order_raises_insufficient_stock(mocked_create_order, user_api_client, checkout_ready_to_complete, payment_dummy):diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 69cbd319ba..14904fae21 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -29,6 +29,10 @@ from . import FulfillmentStatus, OrderEvents, OrderStatusclass OrderQueryset(models.QuerySet):+ def get_by_checkout_token(self, token):+ """Return non-draft order with matched checkout token."""+ return self.confirmed().filter(checkout_token=token).first()+def confirmed(self):"""Return non-draft orders."""return self.exclude(status=OrderStatus.DRAFT)