Skip to content

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

Mutation for creating an order from checkout (#9343)

Maciej Korycinskief22676fbfb6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e8798b4923..0317f9bfdc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,7 +16,7 @@ All notable, unreleased changes to this project will be documented in this file.
### Other changes
- Fix failing `checkoutCustomerAttach` mutation - #9401 by @IKarbowiak
-
+- Add new mutation `orderCreateFromCheckout` - #9343 by @korycins
# 3.1.7
diff --git a/saleor/checkout/checkout_cleaner.py b/saleor/checkout/checkout_cleaner.py
index b7bfeaf0aa..6aa96612c8 100644
--- a/saleor/checkout/checkout_cleaner.py
+++ b/saleor/checkout/checkout_cleaner.py
@@ -1,13 +1,20 @@
-from typing import TYPE_CHECKING, Iterable, Optional, Type, Union
+from datetime import date
+from typing import TYPE_CHECKING, Iterable, List, Optional, Type, Union
+import graphene
from django.core.exceptions import ValidationError
+from ..core.exceptions import GiftCardNotApplicable
+from ..core.taxes import TaxError
from ..discount import DiscountInfo
+from ..giftcard.models import GiftCard
from ..payment import gateway
from ..payment import models as payment_models
from ..payment.error_codes import PaymentErrorCode
from ..plugins.manager import PluginsManager
-from .error_codes import CheckoutErrorCode
+from . import models
+from .error_codes import CheckoutErrorCode, OrderCreateFromCheckoutErrorCode
+from .models import Checkout
from .utils import clear_delivery_method, is_fully_paid, is_shipping_required
if TYPE_CHECKING:
@@ -17,7 +24,11 @@ if TYPE_CHECKING:
def clean_checkout_shipping(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
- error_code: Union[Type[CheckoutErrorCode], Type[PaymentErrorCode]],
+ error_code: Union[
+ Type[CheckoutErrorCode],
+ Type[PaymentErrorCode],
+ Type[OrderCreateFromCheckoutErrorCode],
+ ],
):
delivery_method_info = checkout_info.delivery_method_info
@@ -54,7 +65,11 @@ def clean_checkout_shipping(
def clean_billing_address(
checkout_info: "CheckoutInfo",
- error_code: Union[Type[CheckoutErrorCode], Type[PaymentErrorCode]],
+ error_code: Union[
+ Type[CheckoutErrorCode],
+ Type[PaymentErrorCode],
+ Type[OrderCreateFromCheckoutErrorCode],
+ ],
):
if not checkout_info.billing_address:
raise ValidationError(
@@ -84,3 +99,91 @@ def clean_checkout_payment(
"Provided payment methods can not cover the checkout's total amount",
code=error_code.CHECKOUT_NOT_FULLY_PAID.value,
)
+
+
+def validate_checkout_email(checkout: models.Checkout):
+ if not checkout.email:
+ raise ValidationError(
+ "Checkout email must be set.",
+ code=CheckoutErrorCode.EMAIL_NOT_SET.value,
+ )
+
+
+def _validate_gift_cards(checkout: Checkout):
+ """Check if all gift cards assigned to checkout are available."""
+ today = date.today()
+ all_gift_cards = GiftCard.objects.filter(checkouts=checkout.token).count()
+ active_gift_cards = (
+ GiftCard.objects.active(date=today).filter(checkouts=checkout.token).count()
+ )
+ if not all_gift_cards == active_gift_cards:
+ msg = "Gift card has expired. Order placement cancelled."
+ raise GiftCardNotApplicable(msg)
+
+
+def validate_checkout(
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ unavailable_variant_pks: Iterable[int],
+ discounts: List["DiscountInfo"],
+ manager: "PluginsManager",
+):
+ """Validate all required data for converting checkout into order."""
+ if not checkout_info.channel.is_active:
+ raise ValidationError(
+ {
+ "channel": ValidationError(
+ "Cannot complete checkout with inactive channel.",
+ code=OrderCreateFromCheckoutErrorCode.CHANNEL_INACTIVE.value,
+ )
+ }
+ )
+ if unavailable_variant_pks:
+ not_available_variants_ids = {
+ graphene.Node.to_global_id("ProductVariant", pk)
+ for pk in unavailable_variant_pks
+ }
+ code = OrderCreateFromCheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.value
+ raise ValidationError(
+ {
+ "lines": ValidationError(
+ "Some of the checkout lines variants are unavailable.",
+ code=code,
+ params={"variants": not_available_variants_ids},
+ )
+ }
+ )
+ if not lines:
+ raise ValidationError(
+ {
+ "lines": ValidationError(
+ "Cannot complete checkout without lines",
+ code=OrderCreateFromCheckoutErrorCode.NO_LINES.value,
+ )
+ }
+ )
+
+ if checkout_info.checkout.voucher_code and not checkout_info.voucher:
+ raise ValidationError(
+ {
+ "voucher_code": ValidationError(
+ "Voucher not applicable",
+ code=OrderCreateFromCheckoutErrorCode.VOUCHER_NOT_APPLICABLE.value,
+ )
+ }
+ )
+ validate_checkout_email(checkout_info.checkout)
+
+ clean_billing_address(checkout_info, OrderCreateFromCheckoutErrorCode)
+ clean_checkout_shipping(checkout_info, lines, OrderCreateFromCheckoutErrorCode)
+ _validate_gift_cards(checkout_info.checkout)
+
+ # call plugin's hooks to validate if we are able to create an order
+ # can raise TaxError
+ try:
+ manager.preprocess_order_creation(checkout_info, discounts, lines)
+ except TaxError as tax_error:
+ raise ValidationError(
+ "Unable to calculate taxes - %s" % str(tax_error),
+ code=OrderCreateFromCheckoutErrorCode.TAX_ERROR.value,
+ )
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index a73d2a1bb9..f9ca8732ca 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -1,5 +1,15 @@
-from datetime import date
-from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, cast
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Dict,
+ Iterable,
+ List,
+ Optional,
+ Tuple,
+ Union,
+ cast,
+)
+from uuid import UUID
import graphene
from django.contrib.sites.models import Site
@@ -8,23 +18,22 @@ from django.db import transaction
from prices import TaxedMoney
from ..account.error_codes import AccountErrorCode
-from ..account.models import User
+from ..account.models import Address, User
from ..account.utils import store_user_address
from ..checkout import calculations
from ..checkout.error_codes import CheckoutErrorCode
-from ..core.exceptions import InsufficientStock
+from ..core.exceptions import GiftCardNotApplicable, InsufficientStock
from ..core.taxes import TaxError, zero_taxed_money
from ..core.tracing import traced_atomic_transaction
from ..core.utils.url import validate_storefront_url
from ..discount import DiscountInfo, DiscountValueType, OrderDiscountType, VoucherType
-from ..discount.models import NotApplicable
+from ..discount.models import NotApplicable, Voucher
from ..discount.utils import (
add_voucher_usage_by_customer,
get_sale_id_applied_as_a_discount,
increase_voucher_usage,
release_voucher_usage,
)
-from ..giftcard.models import GiftCard
from ..giftcard.utils import fulfill_non_shippable_gift_cards
from ..graphql.checkout.utils import (
prepare_insufficient_stock_checkout_validation_error,
@@ -43,7 +52,12 @@ from ..warehouse.availability import check_stock_and_preorder_quantity_bulk
from ..warehouse.management import allocate_preorders, allocate_stocks
from ..warehouse.reservations import is_reservation_enabled
from . import AddressType
-from .checkout_cleaner import clean_checkout_payment, clean_checkout_shipping
+from .checkout_cleaner import (
+ _validate_gift_cards,
+ clean_checkout_payment,
+ clean_checkout_shipping,
+)
+from .fetch import CheckoutInfo, CheckoutLineInfo
from .models import Checkout
from .utils import get_voucher_for_checkout_info
@@ -51,7 +65,6 @@ if TYPE_CHECKING:
from ..app.models import App
from ..plugins.manager import PluginsManager
from ..site.models import SiteSettings
- from .fetch import CheckoutInfo, CheckoutLineInfo
def _process_voucher_data_for_order(checkout_info: "CheckoutInfo") -> dict:
@@ -129,18 +142,6 @@ def _process_user_data_for_order(checkout_info: "CheckoutInfo", manager):
}
-def _validate_gift_cards(checkout: Checkout):
- """Check if all gift cards assigned to checkout are available."""
- today = date.today()
- all_gift_cards = GiftCard.objects.filter(checkouts=checkout.token).count()
- active_gift_cards = (
- GiftCard.objects.active(date=today).filter(checkouts=checkout.token).count()
- )
- if not all_gift_cards == active_gift_cards:
- msg = "Gift card has expired. Order placement cancelled."
- raise NotApplicable(msg)
-
-
def _create_line_for_order(
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
@@ -410,7 +411,7 @@ def _prepare_order_data(
try:
manager.preprocess_order_creation(checkout_info, discounts, lines)
except TaxError:
- release_voucher_usage(order_data)
+ release_voucher_usage(order_data.get("voucher"), order_data.get("user_email"))
raise
return order_data
@@ -629,6 +630,8 @@ def _get_order_data(
"Voucher not applicable",
code=CheckoutErrorCode.VOUCHER_NOT_APPLICABLE.value,
)
+ except GiftCardNotApplicable as e:
+ raise ValidationError(e.message, code=e.code)
except TaxError as tax_error:
raise ValidationError(
"Unable to calculate taxes - %s" % str(tax_error),
@@ -669,7 +672,7 @@ def _process_payment(
if not txn.is_success:
raise PaymentError(txn.error)
except PaymentError as e:
- release_voucher_usage(order_data)
+ release_voucher_usage(order_data.get("voucher"), order_data.get("user_email"))
raise ValidationError(str(e), code=CheckoutErrorCode.PAYMENT_ERROR.value)
return txn
@@ -740,7 +743,9 @@ def complete_checkout(
action_required = txn.action_required
if action_required:
action_data = txn.action_required_data
- release_voucher_usage(order_data)
+ release_voucher_usage(
+ order_data.get("voucher"), order_data.get("user_email")
+ )
order = None
if not action_required:
@@ -757,13 +762,352 @@ def complete_checkout(
# remove checkout after order is successfully created
checkout.delete()
except InsufficientStock as e:
- release_voucher_usage(order_data)
+ release_voucher_usage(
+ order_data.get("voucher"), order_data.get("user_email")
+ )
gateway.payment_refund_or_void(payment, manager, channel_slug=channel_slug)
error = prepare_insufficient_stock_checkout_validation_error(e)
raise error
+ except GiftCardNotApplicable as e:
+ release_voucher_usage(
+ order_data.get("voucher"), order_data.get("user_email")
+ )
+ gateway.payment_refund_or_void(payment, manager, channel_slug=channel_slug)
+ raise ValidationError(code=e.code, message=e.message)
# if the order total value is 0 it is paid from the definition
if order.total.net.amount == 0:
mark_order_as_paid(order, user, app, manager)
return order, action_required, action_data
+
+
+def _get_order_total(
+ checkout_info: CheckoutInfo,
+ lines: List[CheckoutLineInfo],
+ discounts: List["DiscountInfo"],
+ manager: "PluginsManager",
+ address: Optional["Address"],
+) -> TaxedMoney:
+ """Calculate a taxed total for order."""
+ taxed_total = calculations.checkout_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=address,
+ discounts=discounts,
+ )
+ cards_total = checkout_info.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_info.checkout.currency))
+ return taxed_total
+
+
+def _increase_voucher_usage(checkout_info: "CheckoutInfo"):
+ """Increase a voucher usage applied to the checkout."""
+ voucher = get_voucher_for_checkout_info(checkout_info, with_lock=True)
+ if not voucher:
+ return None
+
+ if voucher.apply_once_per_customer:
+ customer_email = cast(str, checkout_info.get_customer_email())
+ add_voucher_usage_by_customer(voucher, customer_email)
+
+ if voucher.usage_limit:
+ increase_voucher_usage(voucher)
+
+
+def _create_order_lines_from_checkout_lines(
+ checkout_info: CheckoutInfo,
+ lines: List[CheckoutLineInfo],
+ discounts: List["DiscountInfo"],
+ manager: "PluginsManager",
+ order_pk: Union[str, UUID],
+ reservation_enabled: bool,
+ taxes_included_in_prices: bool,
+) -> List[OrderLineInfo]:
+ order_lines_info = _create_lines_for_order(
+ manager,
+ checkout_info,
+ lines,
+ discounts,
+ reservation_enabled,
+ taxes_included_in_prices,
+ )
+ order_lines = []
+ for line_info in order_lines_info:
+ line = line_info.line
+ line.order_id = order_pk
+ order_lines.append(line)
+
+ OrderLine.objects.bulk_create(order_lines)
+ return list(order_lines_info)
+
+
+def _handle_allocations_of_order_lines(
+ checkout_info: CheckoutInfo,
+ checkout_lines: List[CheckoutLineInfo],
+ order_lines_info: List[OrderLineInfo],
+ manager: "PluginsManager",
+ reservation_enabled: bool,
+):
+ country_code = checkout_info.get_country()
+ additional_warehouse_lookup = (
+ checkout_info.delivery_method_info.get_warehouse_filter_lookup()
+ )
+ allocate_stocks(
+ order_lines_info,
+ country_code,
+ checkout_info.channel.slug,
+ manager,
+ additional_warehouse_lookup,
+ check_reservations=reservation_enabled,
+ checkout_lines=[line.line for line in checkout_lines],
+ )
+ allocate_preorders(
+ order_lines_info,
+ checkout_info.channel.slug,
+ check_reservations=reservation_enabled,
+ checkout_lines=[line.line for line in checkout_lines],
+ )
+
+
+def _handle_checkout_discount(
+ order: "Order", checkout: "Checkout", voucher: Optional["Voucher"]
+):
+ if checkout.discount:
+ # store voucher as a fixed value as it this the simplest solution for now.
+ # This will be solved when we refactor the voucher logic to use .discounts
+ # relations
+
+ # When we have a voucher for specific products we track it directly in the
+ # Orderline. Voucher with 'apply_once_per_order' is handled in the same way
+ # as we apply it only for single quantity of the cheapest line.
+ if not voucher or (
+ voucher.type != VoucherType.SPECIFIC_PRODUCT
+ and not voucher.apply_once_per_order
+ ):
+ order.discounts.create(
+ type=OrderDiscountType.VOUCHER,
+ value_type=DiscountValueType.FIXED,
+ value=checkout.discount.amount,
+ name=checkout.discount_name,
+ translated_name=checkout.translated_discount_name,
+ currency=checkout.currency,
+ amount_value=checkout.discount_amount,
+ )
+
+
+def _post_create_order_actions(
+ order: "Order",
+ checkout_info: "CheckoutInfo",
+ order_lines_info: List["OrderLineInfo"],
+ manager: "PluginsManager",
+ user: User,
+ app: Optional["App"],
+ site_settings: "SiteSettings",
+):
+ order_info = OrderInfo(
+ order=order,
+ customer_email=order.user_email,
+ channel=checkout_info.channel,
+ payment=order.get_last_payment(),
+ lines_data=order_lines_info,
+ )
+
+ transaction.on_commit(
+ lambda: order_created(
+ order_info=order_info, user=user, app=app, manager=manager
+ )
+ )
+
+ # Send the order confirmation email
+ transaction.on_commit(
+ lambda: send_order_confirmation(
+ order_info, checkout_info.checkout.redirect_url, manager
+ )
+ )
+
+ order_lines = [line.line for line in order_lines_info]
+ if site_settings.automatically_fulfill_non_shippable_gift_card:
+ fulfill_non_shippable_gift_cards(
+ order, order_lines, site_settings, user, app, manager
+ )
+
+
+def _create_order_from_checkout(
+ checkout_info: CheckoutInfo,
+ checkout_lines_info: List[CheckoutLineInfo],
+ discounts: List["DiscountInfo"],
+ manager: "PluginsManager",
+ user: User,
+ app: Optional["App"],
+ tracking_code: Optional[str] = None,
+):
+ from ..order.utils import add_gift_cards_to_order
+
+ site_settings = Site.objects.get_current().settings
+
+ address = checkout_info.shipping_address or checkout_info.billing_address
+
+ reservation_enabled = is_reservation_enabled(site_settings)
+ taxes_included_in_prices = site_settings.include_taxes_in_prices
+
+ # total
+ taxed_total = _get_order_total(
+ checkout_info,
+ checkout_lines_info,
+ discounts,
+ manager,
+ address,
+ )
+ undiscounted_total = taxed_total + checkout_info.checkout.discount
+
+ # voucher
+ voucher = checkout_info.voucher
+
+ # shipping
+ shipping_total = manager.calculate_checkout_shipping(
+ checkout_info, checkout_lines_info, address, discounts
+ )
+ shipping_tax_rate = manager.get_checkout_shipping_tax_rate(
+ checkout_info, checkout_lines_info, address, discounts, shipping_total
+ )
+
+ # status
+ status = (
+ OrderStatus.UNFULFILLED
+ if site_settings.automatically_confirm_all_new_orders
+ else OrderStatus.UNCONFIRMED
+ )
+
+ # order
+ order = Order.objects.create(
+ status=status,
+ language_code=checkout_info.checkout.language_code,
+ tracking_client_id=tracking_code or "",
+ total=taxed_total,
+ undiscounted_total=undiscounted_total,
+ shipping_tax_rate=shipping_tax_rate,
+ voucher=voucher,
+ checkout_token=checkout_info.checkout.token,
+ origin=OrderOrigin.CHECKOUT,
+ channel=checkout_info.channel,
+ metadata=checkout_info.checkout.metadata,
+ private_metadata=checkout_info.checkout.private_metadata,
+ redirect_url=checkout_info.checkout.redirect_url,
+ **_process_shipping_data_for_order(
+ checkout_info, shipping_total, manager, checkout_lines_info
+ ),
+ **_process_user_data_for_order(checkout_info, manager),
+ )
+
+ # checkout discount
+ _handle_checkout_discount(order, checkout_info.checkout, voucher)
+
+ # lines
+ order_lines_info = _create_order_lines_from_checkout_lines(
+ checkout_info=checkout_info,
+ lines=checkout_lines_info,
+ discounts=discounts,
+ manager=manager,
+ order_pk=order.pk,
+ reservation_enabled=reservation_enabled,
+ taxes_included_in_prices=taxes_included_in_prices,
+ )
+
+ # allocations
+ _handle_allocations_of_order_lines(
+ checkout_info=checkout_info,
+ checkout_lines=checkout_lines_info,
+ order_lines_info=order_lines_info,
+ manager=manager,
+ reservation_enabled=reservation_enabled,
+ )
+
+ # giftcards
+ currency = checkout_info.checkout.currency
+ subtotal_list = [line.line.total_price for line in order_lines_info]
+ subtotal = sum(subtotal_list, zero_taxed_money(currency))
+ total_without_giftcard = subtotal + shipping_total - checkout_info.checkout.discount
+ add_gift_cards_to_order(
+ checkout_info, order, total_without_giftcard.gross, user, app
+ )
+
+ # payments
+ checkout_info.checkout.payments.update(order=order, checkout_id=None)
+
+ # order search
+ order.search_document = prepare_order_search_document_value(order)
+ order.save()
+
+ # post create actions
+ _post_create_order_actions(
+ order=order,
+ checkout_info=checkout_info,
+ order_lines_info=order_lines_info,
+ manager=manager,
+ user=user,
+ app=app,
+ site_settings=site_settings,
+ )
+ return order
+
+
+def create_order_from_checkout(
+ checkout_info: CheckoutInfo,
+ checkout_lines: Iterable["CheckoutLineInfo"],
+ discounts: List["DiscountInfo"],
+ manager: "PluginsManager",
+ user: User,
+ app: Optional["App"],
+ tracking_code: str,
+ delete_checkout: bool = True,
+) -> Order:
+ """Crate order from checkout.
+
+ If checkout doesn't have all required data, the function will raise ValidationError.
+
+ 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.
+
+ Checkout can be deleted by setting flag `delete_checkout` to True
+
+ :raises: InsufficientStock, GiftCardNotApplicable
+ """
+
+ if checkout_info.voucher:
+ with transaction.atomic():
+ _increase_voucher_usage(checkout_info=checkout_info)
+
+ with transaction.atomic():
+ try:
+ order = _create_order_from_checkout(
+ checkout_info=checkout_info,
+ checkout_lines_info=list(checkout_lines),
+ discounts=discounts,
+ manager=manager,
+ user=user,
+ app=app,
+ tracking_code=tracking_code,
+ )
+ if delete_checkout:
+ checkout_info.checkout.delete()
+ return order
+ except InsufficientStock:
+ release_voucher_usage(
+ checkout_info.voucher, checkout_info.checkout.get_customer_email()
+ )
+ raise
+ except GiftCardNotApplicable:
+ release_voucher_usage(
+ checkout_info.voucher, checkout_info.checkout.get_customer_email()
+ )
+ raise
diff --git a/saleor/checkout/error_codes.py b/saleor/checkout/error_codes.py
index ab461c48e5..8b41503af9 100644
--- a/saleor/checkout/error_codes.py
+++ b/saleor/checkout/error_codes.py
@@ -29,3 +29,20 @@ class CheckoutErrorCode(Enum):
UNAVAILABLE_VARIANT_IN_CHANNEL = "unavailable_variant_in_channel"
EMAIL_NOT_SET = "email_not_set"
NO_LINES = "no_lines"
+
+
+class OrderCreateFromCheckoutErrorCode(Enum):
+ GRAPHQL_ERROR = "graphql_error"
+ NOT_FOUND = "not_found"
+ CHANNEL_INACTIVE = "channel_inactive"
+ INSUFFICIENT_STOCK = "insufficient_stock"
+ VOUCHER_NOT_APPLICABLE = "voucher_not_applicable"
+ GIFT_CARD_NOT_APPLICABLE = "gift_card_not_applicable"
+ TAX_ERROR = "tax_error"
+ SHIPPING_METHOD_NOT_SET = "shipping_method_not_set"
+ BILLING_ADDRESS_NOT_SET = "billing_address_not_set"
+ SHIPPING_ADDRESS_NOT_SET = "shipping_address_not_set"
+ INVALID_SHIPPING_METHOD = "invalid_shipping_method"
+ NO_LINES = "no_lines"
+ EMAIL_NOT_SET = "email_not_set"
+ UNAVAILABLE_VARIANT_IN_CHANNEL = "unavailable_variant_in_channel"
diff --git a/saleor/checkout/tests/test_order_from_checkout.py b/saleor/checkout/tests/test_order_from_checkout.py
new file mode 100644
index 0000000000..d77c1d3fee
--- /dev/null
+++ b/saleor/checkout/tests/test_order_from_checkout.py
@@ -0,0 +1,480 @@
+from unittest import mock
+
+import pytest
+from django.contrib.auth.models import AnonymousUser
+from django.test import override_settings
+
+from ...core.exceptions import InsufficientStock
+from ...core.taxes import zero_money, zero_taxed_money
+from ...giftcard import GiftCardEvents
+from ...giftcard.models import GiftCard, GiftCardEvent
+from ...plugins.manager import get_plugins_manager
+from ...product.models import ProductTranslation, ProductVariantTranslation
+from ...tests.utils import flush_post_commit_hooks
+from .. import calculations
+from ..complete_checkout import create_order_from_checkout
+from ..fetch import fetch_checkout_info, fetch_checkout_lines
+from ..utils import add_variant_to_checkout
+
+
+def test_create_order_insufficient_stock(
+ checkout, customer_user, product_without_shipping, app
+):
+ variant = product_without_shipping.variants.get()
+ manager = get_plugins_manager()
+ checkout_info = fetch_checkout_info(checkout, [], [], manager)
+
+ add_variant_to_checkout(checkout_info, 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()
+
+ checkout_lines, unavailable_variant_pks = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, checkout_lines, [], manager)
+ lines, _ = fetch_checkout_lines(checkout)
+ with pytest.raises(InsufficientStock):
+ create_order_from_checkout(
+ checkout_info=checkout_info,
+ checkout_lines=checkout_lines,
+ discounts=[],
+ manager=manager,
+ user=AnonymousUser(),
+ app=app,
+ tracking_code="tracking_code",
+ )
+
+
[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, app
+):
+ 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()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ subtotal = calculations.checkout_subtotal(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout.shipping_address,
+ )
+ shipping_price = calculations.checkout_shipping_price(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout.shipping_address,
+ )
+ total_gross_without_gift_cards = (
+ subtotal.gross + shipping_price.gross - checkout.discount
+ )
+ gift_cards_balance = checkout.get_total_gift_cards_balance()
+
+ order = create_order_from_checkout(
+ checkout_info=checkout_info,
+ checkout_lines=lines,
+ discounts=[],
+ manager=manager,
+ user=AnonymousUser(),
+ app=app,
+ tracking_code="tracking_code",
+ )
+
+ assert order.gift_cards.count() == 1
+ gift_card = order.gift_cards.first()
+ assert gift_card.current_balance.amount == 0
+ assert order.total.gross == (total_gross_without_gift_cards - gift_cards_balance)
+ assert GiftCardEvent.objects.filter(
+ gift_card=gift_card, type=GiftCardEvents.USED_IN_ORDER
+ )
+
+
+def test_create_order_with_gift_card_partial_use(
+ checkout_with_item, gift_card_used, customer_user, shipping_method, app
+):
+ 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()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ price_without_gift_card = calculations.checkout_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout.shipping_address,
+ )
+ gift_card_balance_before_order = gift_card_used.current_balance_amount
+
+ checkout.gift_cards.add(gift_card_used)
+ checkout.save()
+
+ checkout_lines, unavailable_variant_pks = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, checkout_lines, [], manager)
+
+ order = create_order_from_checkout(
+ checkout_info=checkout_info,
+ checkout_lines=checkout_lines,
+ discounts=[],
+ manager=manager,
+ user=AnonymousUser(),
+ app=app,
+ tracking_code="tracking_code",
+ )
+
+ 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(order.currency)
+ assert gift_card_balance_before_order == expected_old_balance
+ assert GiftCardEvent.objects.filter(
+ gift_card=gift_card_used, type=GiftCardEvents.USED_IN_ORDER
+ )
+
+
+def test_create_order_with_many_gift_cards(
+ checkout_with_item,
+ gift_card_created_by_staff,
+ gift_card,
+ customer_user,
+ shipping_method,
+ app,
+):
+ 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()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ price_without_gift_card = calculations.checkout_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout.shipping_address,
+ )
+ 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()
+
+ checkout_lines, unavailable_variant_pks = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, checkout_lines, [], manager)
+
+ order = create_order_from_checkout(
+ checkout_info=checkout_info,
+ checkout_lines=checkout_lines,
+ discounts=[],
+ manager=manager,
+ user=AnonymousUser,
+ app=app,
+ tracking_code="tracking_code",
+ )
+
+ gift_card_created_by_staff.refresh_from_db()
+ gift_card.refresh_from_db()
+ zero_price = zero_money(gift_card.currency)
+ 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
+ )
+ assert GiftCardEvent.objects.filter(
+ gift_card=gift_card_created_by_staff, type=GiftCardEvents.USED_IN_ORDER
+ )
+ assert GiftCardEvent.objects.filter(
+ gift_card=gift_card, type=GiftCardEvents.USED_IN_ORDER
+ )
+
+
[email protected]("saleor.giftcard.utils.send_gift_card_notification")
[email protected]("is_anonymous_user", (True, False))
+def test_create_order_gift_card_bought(
+ send_notification_mock,
+ checkout_with_gift_card_items,
+ customer_user,
+ shipping_method,
+ is_anonymous_user,
+ non_shippable_gift_card_product,
+ app,
+):
+ checkout_user = None if is_anonymous_user else customer_user
+ checkout = checkout_with_gift_card_items
+ 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()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ subtotal = calculations.checkout_subtotal(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout.shipping_address,
+ )
+ shipping_price = calculations.checkout_shipping_price(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout.shipping_address,
+ )
+ total_gross = subtotal.gross + shipping_price.gross - checkout.discount
+
+ order = create_order_from_checkout(
+ checkout_info=checkout_info,
+ checkout_lines=lines,
+ discounts=[],
+ manager=manager,
+ user=AnonymousUser(),
+ app=app,
+ tracking_code="tracking_code",
+ )
+
+ flush_post_commit_hooks()
+ assert order.total.gross == total_gross
+ flush_post_commit_hooks()
+ gift_card = GiftCard.objects.get()
+ assert (
+ gift_card.initial_balance
+ == order.lines.get(
+ variant=non_shippable_gift_card_product.variants.first()
+ ).unit_price_gross
+ )
+ assert GiftCardEvent.objects.filter(gift_card=gift_card, type=GiftCardEvents.BOUGHT)
+ send_notification_mock.assert_called_once_with(
+ None,
+ app,
+ checkout_user,
+ order.user_email,
+ gift_card,
+ manager,
+ order.channel.slug,
+ resending=False,
+ )
+
+
[email protected]("saleor.giftcard.utils.send_gift_card_notification")
[email protected]("is_anonymous_user", (True, False))
+def test_create_order_gift_card_bought_only_shippable_gift_card(
+ send_notification_mock,
+ checkout,
+ shippable_gift_card_product,
+ customer_user,
+ shipping_method,
+ is_anonymous_user,
+ app,
+):
+ checkout_user = None if is_anonymous_user else customer_user
+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
+ shippable_variant = shippable_gift_card_product.variants.get()
+ add_variant_to_checkout(checkout_info, shippable_variant, 2)
+
+ 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()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ subtotal = calculations.checkout_subtotal(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout.shipping_address,
+ )
+ shipping_price = calculations.checkout_shipping_price(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout.shipping_address,
+ )
+ total_gross = subtotal.gross + shipping_price.gross - checkout.discount
+
+ order = create_order_from_checkout(
+ checkout_info=checkout_info,
+ checkout_lines=lines,
+ discounts=[],
+ manager=manager,
+ user=AnonymousUser(),
+ app=app,
+ tracking_code="tracking_code",
+ )
+
+ assert order.total.gross == total_gross
+ assert not GiftCard.objects.all()
+ send_notification_mock.assert_not_called()
+
+
[email protected]("is_anonymous_user", (True, False))
+def test_create_order_gift_card_bought_do_not_fulfill_gift_cards_automatically(
+ site_settings,
+ checkout_with_gift_card_items,
+ customer_user,
+ shipping_method,
+ is_anonymous_user,
+ non_shippable_gift_card_product,
+ app,
+):
+ site_settings.automatically_fulfill_non_shippable_gift_card = False
+ site_settings.save(update_fields=["automatically_fulfill_non_shippable_gift_card"])
+
+ checkout_user = None if is_anonymous_user else customer_user
+ checkout = checkout_with_gift_card_items
+ 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()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ subtotal = calculations.checkout_subtotal(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout.shipping_address,
+ )
+ shipping_price = calculations.checkout_shipping_price(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout.shipping_address,
+ )
+ total_gross = subtotal.gross + shipping_price.gross - checkout.discount
+
+ order = create_order_from_checkout(
+ checkout_info=checkout_info,
+ checkout_lines=lines,
+ discounts=[],
+ manager=manager,
+ user=AnonymousUser(),
+ app=app,
+ tracking_code="tracking_code",
+ )
+
+ assert order.total.gross == total_gross
+ assert not GiftCard.objects.all()
+
+
+def test_note_in_created_order(
+ checkout_with_item, address, customer_user, shipping_method, app
+):
+ checkout_with_item.shipping_address = address
+ checkout_with_item.billing_address = address
+ checkout_with_item.shipping_method = shipping_method
+ 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()
+ manager = get_plugins_manager()
+
+ checkout_lines, unavailable_variant_pks = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(checkout_with_item, checkout_lines, [], manager)
+
+ order = create_order_from_checkout(
+ checkout_info=checkout_info,
+ checkout_lines=checkout_lines,
+ discounts=[],
+ manager=manager,
+ user=AnonymousUser(),
+ app=app,
+ tracking_code="tracking_code",
+ )
+ assert order.customer_note == checkout_with_item.note
+
+
+@override_settings(LANGUAGE_CODE="fr")
+def test_create_order_use_translations(
+ checkout_with_item, customer_user, shipping_method, app
+):
+ translated_product_name = "French name"
+ translated_variant_name = "French variant name"
+
+ 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.language_code = "fr"
+ checkout.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)
+ variant = lines[0].variant
+ product = lines[0].product
+
+ ProductTranslation.objects.create(
+ language_code="fr",
+ product=product,
+ name=translated_product_name,
+ )
+ ProductVariantTranslation.objects.create(
+ language_code="fr",
+ product_variant=variant,
+ name=translated_variant_name,
+ )
+
+ order = create_order_from_checkout(
+ checkout_info=checkout_info,
+ checkout_lines=lines,
+ discounts=[],
+ manager=manager,
+ user=AnonymousUser(),
+ app=app,
+ tracking_code="tracking_code",
+ )
+ order_line = order.lines.first()
+
+ assert order_line.translated_product_name == translated_product_name
+ assert order_line.translated_variant_name == translated_variant_name
diff --git a/saleor/core/exceptions.py b/saleor/core/exceptions.py
index 040689cb09..a2585e1734 100644
--- a/saleor/core/exceptions.py
+++ b/saleor/core/exceptions.py
@@ -66,3 +66,10 @@ class PermissionDenied(Exception):
message = "You do not have permission to perform this action"
super().__init__(message)
self.permissions = permissions
+
+
+class GiftCardNotApplicable(Exception):
+ def __init__(self, message: str):
+ super().__init__(message)
+ self.message = message
+ self.code = CheckoutErrorCode.GIFT_CARD_NOT_APPLICABLE.value
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 47b3d917e6..ba24a1bb46 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -64,14 +64,13 @@ def remove_voucher_usage_by_customer(voucher: "Voucher", customer_email: str) ->
voucher_customer.delete()
-def release_voucher_usage(order_data: dict):
- voucher = order_data.get("voucher")
+def release_voucher_usage(voucher: Optional["Voucher"], user_email: Optional[str]):
if not voucher:
return
if voucher.usage_limit:
decrease_voucher_usage(voucher)
- if "user_email" in order_data:
- remove_voucher_usage_by_customer(voucher, order_data["user_email"])
+ if user_email:
+ remove_voucher_usage_by_customer(voucher, user_email)
def get_product_discount_on_sale(
diff --git a/saleor/giftcard/tests/test_utils.py b/saleor/giftcard/tests/test_utils.py
index 0b8d9b20cf..a048b12f4d 100644
--- a/saleor/giftcard/tests/test_utils.py
+++ b/saleor/giftcard/tests/test_utils.py
@@ -3,10 +3,10 @@ from unittest.mock import patch
import pytest
from dateutil.relativedelta import relativedelta
-from django.core.exceptions import ValidationError
from django.utils import timezone
from ...core import TimePeriodType
+from ...core.exceptions import GiftCardNotApplicable
from ...core.utils.promo_code import InvalidPromoCode
from ...order.models import OrderLine
from ...plugins.manager import get_plugins_manager
@@ -621,7 +621,7 @@ def test_fulfill_gift_card_lines_lack_of_stock(
)
# when
- with pytest.raises(ValidationError):
+ with pytest.raises(GiftCardNotApplicable):
fulfill_gift_card_lines(lines, staff_user, None, order, site_settings, manager)
diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.py
index be4e49281c..31ff2654b2 100644
--- a/saleor/giftcard/utils.py
+++ b/saleor/giftcard/utils.py
@@ -3,13 +3,12 @@ from datetime import date
from typing import TYPE_CHECKING, Iterable, Optional
from dateutil.relativedelta import relativedelta
-from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models.expressions import Exists, OuterRef
from django.utils import timezone
-from ..checkout.error_codes import CheckoutErrorCode
from ..checkout.models import Checkout
+from ..core.exceptions import GiftCardNotApplicable
from ..core.tracing import traced_atomic_transaction
from ..core.utils.promo_code import InvalidPromoCode, generate_promo_code
from ..core.utils.validators import user_is_valid
@@ -133,9 +132,8 @@ def fulfill_gift_card_lines(
else:
stock = line.variant.stocks.for_channel(channel_slug).first()
if not stock:
- raise ValidationError(
- "Lack of gift card stock for checkout channel.",
- code=CheckoutErrorCode.GIFT_CARD_NOT_APPLICABLE.value,
+ raise GiftCardNotApplicable(
+ message="Lack of gift card stock for checkout channel.",
)
warehouse_pk = str(stock.warehouse_id)
lines_for_warehouses[warehouse_pk].append(
diff --git a/saleor/graphql/checkout/enums.py b/saleor/graphql/checkout/enums.py
new file mode 100644
index 0000000000..4328996405
--- /dev/null
+++ b/saleor/graphql/checkout/enums.py
@@ -0,0 +1,7 @@
+import graphene
+
+from ...checkout import error_codes
+
+OrderCreateFromCheckoutErrorCode = graphene.Enum.from_enum(
+ error_codes.OrderCreateFromCheckoutErrorCode
+)
diff --git a/saleor/graphql/checkout/mutations/__init__.py b/saleor/graphql/checkout/mutations/__init__.py
index 5229dc88b5..7718967b32 100644
--- a/saleor/graphql/checkout/mutations/__init__.py
+++ b/saleor/graphql/checkout/mutations/__init__.py
@@ -14,6 +14,7 @@ from .checkout_lines_update import CheckoutLinesUpdate
from .checkout_remove_promo_code import CheckoutRemovePromoCode
from .checkout_shipping_address_update import CheckoutShippingAddressUpdate
from .checkout_shipping_method_update import CheckoutShippingMethodUpdate
+from .order_create_from_checkout import OrderCreateFromCheckout
__all__ = [
"CheckoutAddPromoCode",
@@ -32,4 +33,5 @@ __all__ = [
"CheckoutRemovePromoCode",
"CheckoutShippingAddressUpdate",
"CheckoutShippingMethodUpdate",
+ "OrderCreateFromCheckout",
]
diff --git a/saleor/graphql/checkout/mutations/checkout_add_promo_code.py b/saleor/graphql/checkout/mutations/checkout_add_promo_code.py
index ad0d0fda50..541fccec10 100644
--- a/saleor/graphql/checkout/mutations/checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/mutations/checkout_add_promo_code.py
@@ -1,6 +1,7 @@
import graphene
from django.core.exceptions import ValidationError
+from ....checkout.checkout_cleaner import validate_checkout_email
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import (
fetch_checkout_info,
@@ -14,11 +15,7 @@ from ...core.scalars import UUID
from ...core.types import CheckoutError
from ...core.validators import validate_one_of_args_is_in_mutation
from ..types import Checkout
-from .utils import (
- get_checkout_by_token,
- update_checkout_shipping_method_if_invalid,
- validate_checkout_email,
-)
+from .utils import get_checkout_by_token, update_checkout_shipping_method_if_invalid
class CheckoutAddPromoCode(BaseMutation):
diff --git a/saleor/graphql/checkout/mutations/checkout_complete.py b/saleor/graphql/checkout/mutations/checkout_complete.py
index 4f8cbde57c..d5d9983494 100644
--- a/saleor/graphql/checkout/mutations/checkout_complete.py
+++ b/saleor/graphql/checkout/mutations/checkout_complete.py
@@ -2,6 +2,7 @@ import graphene
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ValidationError
+from ....checkout.checkout_cleaner import validate_checkout_email
from ....checkout.complete_checkout import complete_checkout
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
@@ -18,7 +19,7 @@ from ...core.validators import validate_one_of_args_is_in_mutation
from ...order.types import Order
from ...utils import get_user_or_app_from_context
from ..types import Checkout
-from .utils import get_checkout_by_token, validate_checkout_email
+from .utils import get_checkout_by_token
class CheckoutComplete(BaseMutation):
diff --git a/saleor/graphql/checkout/mutations/order_create_from_checkout.py b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
new file mode 100644
index 0000000000..9a00cbc099
--- /dev/null
+++ b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
@@ -0,0 +1,119 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....checkout.checkout_cleaner import validate_checkout
+from ....checkout.complete_checkout import create_order_from_checkout
+from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ....core import analytics
+from ....core.exceptions import GiftCardNotApplicable, InsufficientStock
+from ....core.permissions import CheckoutPermissions
+from ....discount.models import NotApplicable
+from ...core.descriptions import ADDED_IN_32, PREVIEW_FEATURE
+from ...core.mutations import BaseMutation
+from ...core.types import Error
+from ...order.types import Order
+from ..enums import OrderCreateFromCheckoutErrorCode
+from ..types import Checkout
+from ..utils import prepare_insufficient_stock_checkout_validation_error
+
+
+class OrderCreateFromCheckoutError(Error):
+ code = OrderCreateFromCheckoutErrorCode(
+ description="The error code.", required=True
+ )
+ variants = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of variant IDs which causes the error.",
+ required=False,
+ )
+ lines = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of line Ids which cause the error.",
+ required=False,
+ )
+
+
+class OrderCreateFromCheckout(BaseMutation):
+ order = graphene.Field(Order, description="Placed order.")
+
+ class Arguments:
+ id = graphene.ID(
+ required=True,
+ description="ID of a checkout that will be converted to an order.",
+ )
+ remove_checkout = graphene.Boolean(
+ description=(
+ "Determines if checkout should be removed after creating an order. "
+ "Default true."
+ ),
+ default_value=True,
+ )
+
+ class Meta:
+ description = (
+ f"{ADDED_IN_32} Create new order from existing checkout. {PREVIEW_FEATURE}"
+ )
+ object_type = Order
+ permissions = (CheckoutPermissions.HANDLE_CHECKOUTS,)
+ error_type_class = OrderCreateFromCheckoutError
+
+ @classmethod
+ def check_permissions(cls, context, permissions=None):
+ """Determine whether app has rights to perform this mutation."""
+ permissions = permissions or cls._meta.permissions
+ app = getattr(context, "app", None)
+ if app:
+ return app.has_perms(permissions)
+ return False
+
+ @classmethod
+ def perform_mutation(cls, root, info, **data):
+ checkout_id = data.get("id")
+ checkout = cls.get_node_or_error(
+ info, checkout_id, field="id", only_type=Checkout
+ )
+ tracking_code = analytics.get_client_id(info.context)
+
+ discounts = info.context.discounts
+ manager = info.context.plugins
+ checkout_lines, unavailable_variant_pks = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, checkout_lines, discounts, manager
+ )
+
+ validate_checkout(
+ checkout_info=checkout_info,
+ lines=checkout_lines,
+ unavailable_variant_pks=unavailable_variant_pks,
+ discounts=discounts,
+ manager=manager,
+ )
+
+ try:
+ order = create_order_from_checkout(
+ checkout_info=checkout_info,
+ checkout_lines=checkout_lines,
+ discounts=info.context.discounts,
+ manager=info.context.plugins,
+ user=info.context.user,
+ app=info.context.app,
+ tracking_code=tracking_code,
+ delete_checkout=data["remove_checkout"],
+ )
+ except NotApplicable:
+ code = OrderCreateFromCheckoutErrorCode.VOUCHER_NOT_APPLICABLE.value
+ raise ValidationError(
+ {
+ "voucher_code": ValidationError(
+ "Voucher not applicable",
+ code=code,
+ )
+ }
+ )
+ except InsufficientStock as e:
+ error = prepare_insufficient_stock_checkout_validation_error(e)
+ raise error
+ except GiftCardNotApplicable as e:
+ raise ValidationError({"gift_cards": e})
+
+ return OrderCreateFromCheckout(order=order)
diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.py
index 9c611f6196..01c4d978fa 100644
--- a/saleor/graphql/checkout/mutations/utils.py
+++ b/saleor/graphql/checkout/mutations/utils.py
@@ -220,11 +220,3 @@ def group_quantity_by_variants(lines: List[Dict[str, Any]]) -> List[int]:
variant_quantity_map[variant_id] += quantity
return list(variant_quantity_map.values())
-
-
-def validate_checkout_email(checkout: models.Checkout):
- if not checkout.email:
- raise ValidationError(
- "Checkout email must be set.",
- code=CheckoutErrorCode.EMAIL_NOT_SET.value,
- )
diff --git a/saleor/graphql/checkout/schema.py b/saleor/graphql/checkout/schema.py
index 33be9c2ecc..4778ef255c 100644
--- a/saleor/graphql/checkout/schema.py
+++ b/saleor/graphql/checkout/schema.py
@@ -25,6 +25,7 @@ from .mutations import (
CheckoutRemovePromoCode,
CheckoutShippingAddressUpdate,
CheckoutShippingMethodUpdate,
+ OrderCreateFromCheckout,
)
from .resolvers import resolve_checkout, resolve_checkout_lines, resolve_checkouts
from .sorters import CheckoutSortingInput
@@ -101,3 +102,5 @@ class CheckoutMutations(graphene.ObjectType):
)
checkout_delivery_method_update = CheckoutDeliveryMethodUpdate.Field()
checkout_language_code_update = CheckoutLanguageCodeUpdate.Field()
+
+ order_create_from_checkout = OrderCreateFromCheckout.Field()
diff --git a/saleor/graphql/checkout/tests/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/test_order_create_from_checkout.py
new file mode 100644
index 0000000000..25b0ee823e
--- /dev/null
+++ b/saleor/graphql/checkout/tests/test_order_create_from_checkout.py
@@ -0,0 +1,1460 @@
+from datetime import date, timedelta
+from decimal import Decimal
+from unittest.mock import ANY, patch
+
+import graphene
+import pytest
+from django.db.models.aggregates import Sum
+from django.utils import timezone
+from prices import Money
+
+from ....checkout import calculations
+from ....checkout.error_codes import OrderCreateFromCheckoutErrorCode
+from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ....checkout.models import Checkout
+from ....core.taxes import TaxError, zero_money, zero_taxed_money
+from ....giftcard import GiftCardEvents
+from ....giftcard.models import GiftCard, GiftCardEvent
+from ....order import OrderOrigin, OrderStatus
+from ....order.models import Fulfillment, Order
+from ....plugins.manager import PluginsManager, get_plugins_manager
+from ....tests.utils import flush_post_commit_hooks
+from ....warehouse.models import Reservation, Stock, WarehouseClickAndCollectOption
+from ....warehouse.tests.utils import get_available_quantity_for_stock
+from ...tests.utils import assert_no_permission, get_graphql_content
+
+MUTATION_ORDER_CREATE_FROM_CHECKOUT = """
+mutation orderCreateFromCheckout($id: ID!){
+ orderCreateFromCheckout(id: $id){
+ order{
+ id,
+ token
+ original
+ origin
+ }
+ errors{
+ field
+ message
+ code
+ variants
+ }
+ }
+}
+"""
+
+
+def test_order_from_checkout_with_inactive_channel(
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_with_gift_card,
+ gift_card,
+ address,
+ shipping_method,
+):
+ assert not gift_card.last_used_on
+
+ checkout = checkout_with_gift_card
+ channel = checkout.channel
+ channel.is_active = False
+ channel.save()
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.save()
+
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert (
+ data["errors"][0]["code"]
+ == OrderCreateFromCheckoutErrorCode.CHANNEL_INACTIVE.name
+ )
+ assert data["errors"][0]["field"] == "channel"
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_confirmed")
+def test_order_from_checkout(
+ order_confirmed_mock,
+ app_api_client,
+ permission_handle_checkouts,
+ site_settings,
+ checkout_with_gift_card,
+ gift_card,
+ address,
+ shipping_method,
+):
+
+ assert not gift_card.last_used_on
+
+ checkout = checkout_with_gift_card
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.save()
+
+ checkout_line = checkout.lines.first()
+ checkout_line_quantity = checkout_line.quantity
+ checkout_line_variant = checkout_line.variant
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+ site_settings.automatically_confirm_all_new_orders = True
+ site_settings.save()
+
+ orders_count = Order.objects.count()
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert not data["errors"]
+
+ order_token = data["order"]["token"]
+ assert Order.objects.count() == orders_count + 1
+ order = Order.objects.first()
+ assert order.status == OrderStatus.UNFULFILLED
+ assert order.origin == OrderOrigin.CHECKOUT
+ assert not order.original
+ assert str(order.pk) == order_token
+ assert order.total.gross == total.gross
+ assert order.metadata == checkout.metadata
+ assert order.private_metadata == checkout.private_metadata
+
+ order_line = order.lines.first()
+ 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.search_document
+
+ gift_card.refresh_from_db()
+ assert gift_card.current_balance == zero_money(gift_card.currency)
+ assert gift_card.last_used_on
+ assert GiftCardEvent.objects.filter(
+ gift_card=gift_card, type=GiftCardEvents.USED_IN_ORDER
+ )
+
+ order_confirmed_mock.assert_called_once_with(order)
+
+
+def test_order_from_checkout_by_app_with_missing_permission(
+ app_api_client,
+ checkout_with_item,
+ customer_user,
+ address,
+ shipping_method,
+):
+ checkout = checkout_with_item
+ checkout.user = customer_user
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ )
+
+ assert_no_permission(response)
+
+
+@patch("saleor.giftcard.utils.send_gift_card_notification")
+@patch("saleor.plugins.manager.PluginsManager.order_confirmed")
+def test_order_from_checkout_gift_card_bought(
+ order_confirmed_mock,
+ send_notification_mock,
+ site_settings,
+ customer_user,
+ app_api_client,
+ app,
+ permission_handle_checkouts,
+ checkout_with_gift_card_items,
+ address,
+ shipping_method,
+):
+ checkout = checkout_with_gift_card_items
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.user = customer_user
+ checkout.save()
+
+ site_settings.automatically_confirm_all_new_orders = True
+ site_settings.automatically_fulfill_non_shippable_gift_card = True
+ site_settings.save()
+
+ orders_count = Order.objects.count()
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert not data["errors"]
+
+ assert Order.objects.count() == orders_count + 1
+ order = Order.objects.first()
+ assert order.status == OrderStatus.PARTIALLY_FULFILLED
+
+ flush_post_commit_hooks()
+ gift_card = GiftCard.objects.get()
+ assert GiftCardEvent.objects.filter(gift_card=gift_card, type=GiftCardEvents.BOUGHT)
+ send_notification_mock.assert_called_once_with(
+ None,
+ app,
+ customer_user,
+ customer_user.email,
+ gift_card,
+ ANY,
+ checkout.channel.slug,
+ resending=False,
+ )
+ order_confirmed_mock.assert_called_once_with(order)
+ assert Fulfillment.objects.count() == 1
+
+
+def test_order_from_checkout_no_checkout_email(
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_with_gift_card,
+ address,
+ shipping_method,
+):
+ checkout = checkout_with_gift_card
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.email = None
+ checkout.save()
+
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert len(data["errors"]) == 1
+ assert (
+ data["errors"][0]["code"] == OrderCreateFromCheckoutErrorCode.EMAIL_NOT_SET.name
+ )
+
+
+def test_order_from_checkout_with_variant_without_sku(
+ site_settings,
+ app_api_client,
+ checkout_with_item,
+ gift_card,
+ permission_handle_checkouts,
+ address,
+ shipping_method,
+):
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ checkout_line = checkout.lines.first()
+ checkout_line_variant = checkout_line.variant
+ checkout_line_variant.sku = None
+ checkout_line_variant.save()
+
+ site_settings.automatically_confirm_all_new_orders = True
+ site_settings.save()
+
+ orders_count = Order.objects.count()
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert not data["errors"]
+
+ order_token = data["order"]["token"]
+ assert Order.objects.count() == orders_count + 1
+ order = Order.objects.get(pk=order_token)
+ assert order.status == OrderStatus.UNFULFILLED
+ assert order.origin == OrderOrigin.CHECKOUT
+
+ order_line = order.lines.first()
+ assert order_line.product_sku is None
+ assert order_line.product_variant_id == order_line.variant.get_global_id()
+
+
+def test_order_from_checkout_with_variant_without_price(
+ site_settings,
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_with_item,
+ gift_card,
+ address,
+ shipping_method,
+):
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ checkout_line = checkout.lines.first()
+ checkout_line_variant = checkout_line.variant
+ checkout_line_variant.channel_listings.filter(channel=checkout.channel).update(
+ price_amount=None
+ )
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", checkout_line_variant.pk)
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ content = get_graphql_content(response)
+ errors = content["data"]["orderCreateFromCheckout"]["errors"]
+ assert (
+ errors[0]["code"]
+ == OrderCreateFromCheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name
+ )
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["variants"] == [variant_id]
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_confirmed")
+def test_order_from_checkout_requires_confirmation(
+ order_confirmed_mock,
+ app_api_client,
+ permission_handle_checkouts,
+ site_settings,
+ checkout_ready_to_complete,
+):
+ site_settings.automatically_confirm_all_new_orders = False
+ site_settings.save()
+
+ variables = {
+ "id": graphene.Node.to_global_id("Checkout", checkout_ready_to_complete.pk),
+ }
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+ content = get_graphql_content(response)
+
+ order_id = graphene.Node.from_global_id(
+ content["data"]["orderCreateFromCheckout"]["order"]["id"]
+ )[1]
+ order = Order.objects.get(pk=order_id)
+ assert order.is_unconfirmed()
+ order_confirmed_mock.assert_not_called()
+
+
+def test_order_from_checkout_with_voucher(
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_with_voucher_percentage,
+ voucher_percentage,
+ address,
+ shipping_method,
+):
+ voucher_used_count = voucher_percentage.used
+ voucher_percentage.usage_limit = voucher_used_count + 1
+ voucher_percentage.save(update_fields=["usage_limit"])
+
+ checkout = checkout_with_voucher_percentage
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.save()
+
+ checkout_line = checkout.lines.first()
+ checkout_line_quantity = checkout_line.quantity
+ checkout_line_variant = checkout_line.variant
+
+ orders_count = Order.objects.count()
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert not data["errors"]
+
+ order_token = data["order"]["token"]
+ assert Order.objects.count() == orders_count + 1
+ order = Order.objects.first()
+ assert str(order.pk) == order_token
+ assert order.metadata == checkout.metadata
+ assert order.private_metadata == checkout.private_metadata
+
+ order_line = order.lines.first()
+ 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
+
+ voucher_percentage.refresh_from_db()
+ assert voucher_percentage.used == voucher_used_count + 1
+
+
[email protected](PluginsManager, "preprocess_order_creation")
+def test_order_from_checkout_voucher_not_increase_uses_on_preprocess_creation_failure(
+ mocked_preprocess_order_creation,
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_with_voucher_percentage,
+ voucher_percentage,
+ address,
+ shipping_method,
+):
+ mocked_preprocess_order_creation.side_effect = TaxError("tax error!")
+ voucher_percentage.used = 0
+ voucher_percentage.usage_limit = 1
+ voucher_percentage.save(update_fields=["used", "usage_limit"])
+
+ checkout = checkout_with_voucher_percentage
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+
+ assert data["errors"][0]["code"] == OrderCreateFromCheckoutErrorCode.TAX_ERROR.name
+
+ voucher_percentage.refresh_from_db()
+ assert voucher_percentage.used == 0
+
+
+def test_order_from_checkout_without_inventory_tracking(
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_with_variant_without_inventory_tracking,
+ address,
+ shipping_method,
+):
+ checkout = checkout_with_variant_without_inventory_tracking
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.save()
+
+ checkout_line = checkout.lines.first()
+ checkout_line_quantity = checkout_line.quantity
+ checkout_line_variant = checkout_line.variant
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.checkout_total(
+ manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ )
+
+ orders_count = Order.objects.count()
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert not data["errors"]
+
+ order_token = data["order"]["token"]
+ assert Order.objects.count() == orders_count + 1
+ order = Order.objects.first()
+ assert str(order.pk) == order_token
+ assert order.total.gross == total.gross
+ assert order.metadata == checkout.metadata
+ assert order.private_metadata == checkout.private_metadata
+
+ order_line = order.lines.first()
+ assert checkout_line_quantity == order_line.quantity
+ assert checkout_line_variant == order_line.variant
+ assert not order_line.allocations.all()
+ assert order.shipping_address == address
+ assert order.shipping_method == checkout.shipping_method
+
+
+def test_order_from_checkout_checkout_without_lines(
+ site_settings,
+ app_api_client,
+ permission_handle_checkouts,
+ checkout,
+ address,
+ shipping_method,
+):
+ checkout = checkout
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.save()
+
+ lines, _ = fetch_checkout_lines(checkout)
+ assert not lines
+
+ site_settings.automatically_confirm_all_new_orders = True
+ site_settings.save()
+
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["code"] == OrderCreateFromCheckoutErrorCode.NO_LINES.name
+
+
+def test_order_from_checkout_insufficient_stock(
+ app,
+ app_api_client,
+ checkout_with_item,
+ address,
+ shipping_method,
+ permission_handle_checkouts,
+):
+ checkout = checkout_with_item
+ checkout_line = checkout.lines.first()
+ stock = Stock.objects.get(product_variant=checkout_line.variant)
+ quantity_available = get_available_quantity_for_stock(stock)
+ checkout_line.quantity = quantity_available + 1
+ checkout_line.save()
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ orders_count = Order.objects.count()
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert data["errors"][0]["message"] == "Insufficient product stock: 123"
+ assert orders_count == Order.objects.count()
+
+
+def test_order_from_checkout_insufficient_stock_reserved_by_other_user(
+ site_settings_with_reservations,
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_with_item,
+ address,
+ shipping_method,
+ channel_USD,
+):
+ checkout = checkout_with_item
+ checkout_line = checkout.lines.first()
+ stock = Stock.objects.get(product_variant=checkout_line.variant)
+ quantity_available = get_available_quantity_for_stock(stock)
+
+ other_checkout = Checkout.objects.create(channel=channel_USD, currency="USD")
+ other_checkout_line = other_checkout.lines.create(
+ variant=checkout_line.variant,
+ quantity=quantity_available,
+ )
+ Reservation.objects.create(
+ checkout_line=other_checkout_line,
+ stock=stock,
+ quantity_reserved=quantity_available,
+ reserved_until=timezone.now() + timedelta(minutes=5),
+ )
+
+ checkout_line.quantity = 1
+ checkout_line.save()
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ variables = {
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ }
+ orders_count = Order.objects.count()
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert data["errors"][0]["message"] == "Insufficient product stock: 123"
+ assert orders_count == Order.objects.count()
+
+
+def test_order_from_checkout_own_reservation(
+ site_settings_with_reservations,
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_with_item,
+ address,
+ shipping_method,
+ channel_USD,
+):
+ checkout = checkout_with_item
+ checkout_line = checkout.lines.first()
+ stock = Stock.objects.get(product_variant=checkout_line.variant)
+ quantity_available = get_available_quantity_for_stock(stock)
+
+ checkout_line.quantity = quantity_available
+ checkout_line.save()
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ reservation = Reservation.objects.create(
+ checkout_line=checkout_line,
+ stock=stock,
+ quantity_reserved=quantity_available,
+ reserved_until=timezone.now() + timedelta(minutes=5),
+ )
+
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+
+ orders_count = Order.objects.count()
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert not data["errors"]
+
+ order_token = data["order"]["token"]
+ assert Order.objects.count() == orders_count + 1
+ order = Order.objects.first()
+ assert str(order.pk) == order_token
+
+ order_line = order.lines.first()
+ assert order_line.quantity == quantity_available
+ assert order_line.variant == checkout_line.variant
+
+ # Reservation associated with checkout has been deleted
+ with pytest.raises(Reservation.DoesNotExist):
+ reservation.refresh_from_db()
+
+
+def test_order_from_checkout_with_digital(
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_with_digital_item,
+ address,
+):
+ """Ensure it is possible to complete a digital checkout without shipping."""
+
+ order_count = Order.objects.count()
+ checkout = checkout_with_digital_item
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+
+ # Set a billing address
+ checkout.billing_address = address
+ checkout.save(update_fields=["billing_address"])
+
+ # Send the creation request
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+ content = get_graphql_content(response)["data"]["orderCreateFromCheckout"]
+ assert not content["errors"]
+
+ # Ensure the order was actually created
+ assert (
+ Order.objects.count() == order_count + 1
+ ), "The order should have been created"
+
+
+def test_order_from_checkout_0_total_value(
+ app_api_client,
+ checkout_with_item,
+ gift_card,
+ permission_handle_checkouts,
+ address,
+ shipping_method,
+):
+
+ assert not gift_card.last_used_on
+
+ checkout = checkout_with_item
+ checkout.billing_address = address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.save()
+
+ checkout_line = checkout.lines.first()
+ checkout_line_quantity = checkout_line.quantity
+ checkout_line_variant = checkout_line.variant
+
+ product_type = checkout_line_variant.product.product_type
+ product_type.is_shipping_required = False
+ product_type.save(update_fields=["is_shipping_required"])
+
+ checkout_line_variant.cost_price_amount = Decimal(0)
+ checkout_line_variant.price_amount = Decimal(0)
+ checkout_line_variant.save()
+
+ checkout.refresh_from_db()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.checkout_total(
+ manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ )
+
+ orders_count = Order.objects.count()
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert not data["errors"]
+
+ order_token = data["order"]["token"]
+ assert Order.objects.count() == orders_count + 1
+ order = Order.objects.first()
+ assert str(order.pk) == order_token
+ assert order.total.gross == total.gross
+ assert order.metadata == checkout.metadata
+ assert order.private_metadata == checkout.private_metadata
+
+ order_line = order.lines.first()
+ assert checkout_line_quantity == order_line.quantity
+ assert checkout_line_variant == order_line.variant
+ assert order.shipping_address is None
+ assert order.shipping_method is None
+
+ assert not Checkout.objects.filter(
+ pk=checkout.pk
+ ).exists(), "Checkout should have been deleted"
+
+
+def test_order_from_checkout_for_click_and_collect(
+ app_api_client,
+ checkout_with_item_for_cc,
+ address,
+ warehouse_for_cc,
+ permission_handle_checkouts,
+):
+ order_count = Order.objects.count()
+ checkout = checkout_with_item_for_cc
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+
+ checkout.billing_address = address
+ checkout.collection_point = warehouse_for_cc
+
+ checkout.save(
+ update_fields=["shipping_address", "billing_address", "collection_point"]
+ )
+
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+ content = get_graphql_content(response)["data"]["orderCreateFromCheckout"]
+
+ assert not content["errors"]
+ assert Order.objects.count() == order_count + 1
+
+ order = Order.objects.first()
+
+ assert order.collection_point == warehouse_for_cc
+ assert order.shipping_method is None
+ assert order.shipping_address == warehouse_for_cc.address
+ assert order.shipping_price == zero_taxed_money(order.currency)
+
+
+def test_order_from_checkout_raises_error_for_local_stock(
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_with_item_for_cc,
+ address,
+ warehouse_for_cc,
+):
+ initial_order_count = Order.objects.count()
+ checkout = checkout_with_item_for_cc
+ checkout_line = checkout.lines.first()
+ stock = Stock.objects.get(product_variant=checkout_line.variant)
+ quantity_available = get_available_quantity_for_stock(stock)
+ checkout_line.quantity = quantity_available + 1
+ checkout_line.save()
+
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+
+ checkout.collection_point = warehouse_for_cc
+ checkout.billing_address = address
+ checkout.save(
+ update_fields=["collection_point", "shipping_address", "billing_address"]
+ )
+
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ content = get_graphql_content(response)["data"]["orderCreateFromCheckout"]
+ assert (
+ content["errors"][0]["code"]
+ == OrderCreateFromCheckoutErrorCode.INSUFFICIENT_STOCK.name
+ )
+ assert Order.objects.count() == initial_order_count
+
+
+def test_order_from_checkout_for_all_warehouse_even_if_not_available_locally(
+ stocks_for_cc,
+ warehouse_for_cc,
+ checkout_with_item_for_cc,
+ address,
+ app_api_client,
+ permission_handle_checkouts,
+):
+ initial_order_count = Order.objects.count()
+ checkout = checkout_with_item_for_cc
+ checkout_line = checkout.lines.first()
+ stock = Stock.objects.get(
+ product_variant=checkout_line.variant, warehouse=warehouse_for_cc
+ )
+ quantity_available = get_available_quantity_for_stock(stock)
+ checkout_line.quantity = quantity_available + 1
+ checkout_line.save()
+
+ warehouse_for_cc.click_and_collect_option = (
+ WarehouseClickAndCollectOption.ALL_WAREHOUSES
+ )
+ warehouse_for_cc.save()
+
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+
+ checkout.collection_point = warehouse_for_cc
+ checkout.save(update_fields=["collection_point"])
+
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+ content = get_graphql_content(response)["data"]["orderCreateFromCheckout"]
+ assert not content["errors"]
+ assert Order.objects.count() == initial_order_count + 1
+
+
+def test_checkout_from_order_raises_insufficient_stock_when_quantity_above_stock_sum(
+ stocks_for_cc,
+ warehouse_for_cc,
+ checkout_with_item_for_cc,
+ address,
+ app_api_client,
+ permission_handle_checkouts,
+):
+ initial_order_count = Order.objects.count()
+ checkout = checkout_with_item_for_cc
+ checkout_line = checkout.lines.first()
+ overall_stock_quantity = (
+ Stock.objects.filter(product_variant=checkout_line.variant).aggregate(
+ Sum("quantity")
+ )
+ ).pop("quantity__sum")
+ checkout_line.quantity = overall_stock_quantity + 1
+ checkout_line.save()
+ warehouse_for_cc.click_and_collect_option = (
+ WarehouseClickAndCollectOption.ALL_WAREHOUSES
+ )
+ warehouse_for_cc.save()
+
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+
+ checkout.collection_point = warehouse_for_cc
+ checkout.billing_address = address
+ checkout.save(update_fields=["collection_point", "billing_address"])
+
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+ content = get_graphql_content(response)["data"]["orderCreateFromCheckout"]
+ assert (
+ content["errors"][0]["code"]
+ == OrderCreateFromCheckoutErrorCode.INSUFFICIENT_STOCK.name
+ )
+ assert Order.objects.count() == initial_order_count
+
+
+def test_order_from_checkout_raises_invalid_shipping_method_when_warehouse_disabled(
+ warehouse_for_cc,
+ checkout_with_item_for_cc,
+ address,
+ app_api_client,
+ permission_handle_checkouts,
+):
+ initial_order_count = Order.objects.count()
+ checkout = checkout_with_item_for_cc
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+
+ checkout.billing_address = address
+ checkout.collection_point = warehouse_for_cc
+
+ checkout.save(
+ update_fields=["shipping_address", "billing_address", "collection_point"]
+ )
+
+ warehouse_for_cc.click_and_collect_option = WarehouseClickAndCollectOption.DISABLED
+ warehouse_for_cc.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ assert not checkout_info.valid_pick_up_points
+ assert not checkout_info.delivery_method_info.is_method_in_valid_methods(
+ checkout_info
+ )
+
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+ content = get_graphql_content(response)["data"]["orderCreateFromCheckout"]
+
+ assert (
+ content["errors"][0]["code"]
+ == OrderCreateFromCheckoutErrorCode.INVALID_SHIPPING_METHOD.name
+ )
+ assert Order.objects.count() == initial_order_count
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_confirmed")
+def test_order_from_draft_create_with_preorder_variant(
+ order_confirmed_mock,
+ site_settings,
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_with_item_and_preorder_item,
+ address,
+ shipping_method,
+):
+ checkout = checkout_with_item_and_preorder_item
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ variants_and_quantities = {line.variant_id: line.quantity for line in checkout}
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+ site_settings.automatically_confirm_all_new_orders = True
+ site_settings.save()
+
+ orders_count = Order.objects.count()
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert not data["errors"]
+
+ order_token = data["order"]["token"]
+ assert Order.objects.count() == orders_count + 1
+ order = Order.objects.first()
+ assert order.status == OrderStatus.UNFULFILLED
+ assert order.origin == OrderOrigin.CHECKOUT
+ assert not order.original
+ assert str(order.pk) == order_token
+ assert order.total.gross == total.gross
+
+ assert order.lines.count() == len(variants_and_quantities)
+ for variant_id, quantity in variants_and_quantities.items():
+ order.lines.get(variant_id=variant_id).quantity == quantity
+ assert order.shipping_address == address
+ assert order.shipping_method == checkout.shipping_method
+
+ preorder_line = order.lines.filter(variant__is_preorder=True).first()
+ assert not preorder_line.allocations.exists()
+ preorder_allocation = preorder_line.preorder_allocations.get()
+ assert preorder_allocation.quantity == quantity
+
+ stock_line = order.lines.filter(variant__is_preorder=False).first()
+ assert stock_line.allocations.exists()
+ assert not stock_line.preorder_allocations.exists()
+
+ assert not Checkout.objects.filter(
+ pk=checkout.pk
+ ).exists(), "Checkout should have been deleted"
+ order_confirmed_mock.assert_called_once_with(order)
+
+
+def test_order_from_draft_create_click_collect_preorder_fails_for_disabled_warehouse(
+ warehouse_for_cc,
+ checkout_with_items_for_cc,
+ address,
+ app_api_client,
+ permission_handle_checkouts,
+):
+ initial_order_count = Order.objects.count()
+ checkout = checkout_with_items_for_cc
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+
+ checkout.billing_address = address
+ checkout.collection_point = warehouse_for_cc
+
+ checkout_line = checkout.lines.first()
+ checkout_line.variant.is_preorder = True
+ checkout_line.variant.preorder_global_threshold = 100
+ checkout_line.variant.save()
+
+ for line in checkout.lines.all():
+ if line.variant.channel_listings.filter(channel=checkout.channel).exists():
+ continue
+
+ line.variant.channel_listings.create(
+ channel=checkout.channel,
+ price_amount=Decimal(15),
+ currency=checkout.currency,
+ )
+
+ checkout.save(
+ update_fields=["shipping_address", "billing_address", "collection_point"]
+ )
+
+ warehouse_for_cc.click_and_collect_option = WarehouseClickAndCollectOption.DISABLED
+ warehouse_for_cc.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ assert not checkout_info.valid_pick_up_points
+ assert not checkout_info.delivery_method_info.is_method_in_valid_methods(
+ checkout_info
+ )
+
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+ content = get_graphql_content(response)["data"]["orderCreateFromCheckout"]
+
+ assert (
+ content["errors"][0]["code"]
+ == OrderCreateFromCheckoutErrorCode.INVALID_SHIPPING_METHOD.name
+ )
+ assert Order.objects.count() == initial_order_count
+
+
+def test_order_from_draft_create_variant_channel_listing_does_not_exist(
+ checkout_with_items,
+ address,
+ shipping_method,
+ app_api_client,
+ permission_handle_checkouts,
+):
+
+ # given
+ checkout = checkout_with_items
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.save()
+
+ checkout_line = checkout.lines.first()
+ checkout_line_variant = checkout_line.variant
+ checkout_line_variant.channel_listings.get(channel__id=checkout.channel_id).delete()
+
+ lines, _ = fetch_checkout_lines(checkout)
+
+ orders_count = Order.objects.count()
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert (
+ errors[0]["code"]
+ == OrderCreateFromCheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name
+ )
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["variants"] == [
+ graphene.Node.to_global_id("ProductVariant", checkout_line_variant.pk)
+ ]
+
+ assert Order.objects.count() == orders_count
+ assert Checkout.objects.filter(pk=checkout.pk).exists()
+
+
+def test_order_from_draft_create_variant_channel_listing_no_price(
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_with_items,
+ address,
+ shipping_method,
+):
+ # given
+ checkout = checkout_with_items
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.save()
+
+ variants = []
+ for line in checkout.lines.all()[:2]:
+ checkout_line_variant = line.variant
+ variants.append(checkout_line_variant)
+ variant_channel_listing = checkout_line_variant.channel_listings.get(
+ channel__id=checkout.channel_id
+ )
+ variant_channel_listing.price_amount = None
+ variant_channel_listing.save(update_fields=["price_amount"])
+
+ orders_count = Order.objects.count()
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert (
+ errors[0]["code"]
+ == OrderCreateFromCheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name
+ )
+ assert errors[0]["field"] == "lines"
+ assert set(errors[0]["variants"]) == {
+ graphene.Node.to_global_id("ProductVariant", variant.pk) for variant in variants
+ }
+
+ assert Order.objects.count() == orders_count
+ assert Checkout.objects.filter(pk=checkout.pk).exists()
+
+
+def test_order_from_draft_create_product_channel_listing_does_not_exist(
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_with_items,
+ address,
+ shipping_method,
+):
+ # given
+ checkout = checkout_with_items
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.save()
+
+ checkout_line = checkout.lines.first()
+ checkout_line_variant = checkout_line.variant
+ checkout_line_variant.product.channel_listings.get(
+ channel__id=checkout.channel_id
+ ).delete()
+
+ orders_count = Order.objects.count()
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert (
+ errors[0]["code"]
+ == OrderCreateFromCheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name
+ )
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["variants"] == [
+ graphene.Node.to_global_id("ProductVariant", checkout_line_variant.pk)
+ ]
+
+ assert Order.objects.count() == orders_count
+ assert Checkout.objects.filter(pk=checkout.pk).exists()
+
+
+ "available_for_purchase", [None, date.today() + timedelta(days=1)]
+)
+def test_order_from_draft_create_product_channel_listing_not_available_for_purchase(
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_with_items,
+ address,
+ shipping_method,
+ available_for_purchase,
+):
+ # given
+ checkout = checkout_with_items
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.save()
+
+ checkout_line = checkout.lines.first()
+ checkout_line_variant = checkout_line.variant
+ product_channel_listings = checkout_line_variant.product.channel_listings.get(
+ channel__id=checkout.channel_id
+ )
+ product_channel_listings.available_for_purchase = available_for_purchase
+ product_channel_listings.save(update_fields=["available_for_purchase"])
+
+ orders_count = Order.objects.count()
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert (
+ errors[0]["code"]
+ == OrderCreateFromCheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name
+ )
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["variants"] == [
+ graphene.Node.to_global_id("ProductVariant", checkout_line_variant.pk)
+ ]
+
+ assert Order.objects.count() == orders_count
+ assert Checkout.objects.filter(pk=checkout.pk).exists()
+
+
+def test_order_from_draft_create_0_total_value_from_voucher(
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_without_shipping_required,
+ shipping_method,
+ address,
+ voucher,
+):
+ checkout = checkout_without_shipping_required
+ checkout.billing_address = address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.voucher_code = voucher.code
+ checkout.discount = Money("10.00", "USD")
+
+ checkout.save()
+
+ checkout_line = checkout.lines.first()
+ checkout_line_quantity = checkout_line.quantity
+ checkout_line_variant = checkout_line.variant
+
+ checkout.refresh_from_db()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ )
+ orders_count = Order.objects.count()
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert not data["errors"]
+
+ order_token = data["order"]["token"]
+ assert Order.objects.count() == orders_count + 1
+ order = Order.objects.first()
+ assert str(order.pk) == order_token
+ assert order.total.gross == total.gross
+ assert order.metadata == checkout.metadata
+ assert order.private_metadata == checkout.private_metadata
+
+ order_line = order.lines.first()
+ assert checkout_line_quantity == order_line.quantity
+ assert checkout_line_variant == order_line.variant
+ assert order.shipping_address is None
+ assert order.shipping_method is None
+
+ assert not Checkout.objects.filter(
+ pk=checkout.pk
+ ).exists(), "Checkout should have been deleted"
+
+
+def test_order_from_draft_create_0_total_value_from_giftcard(
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_without_shipping_required,
+ address,
+ gift_card,
+):
+ checkout = checkout_without_shipping_required
+ checkout.billing_address = address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.gift_cards.add(gift_card)
+ checkout.save()
+
+ checkout_line = checkout.lines.first()
+ checkout_line_quantity = checkout_line.quantity
+ checkout_line_variant = checkout_line.variant
+
+ checkout.refresh_from_db()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ )
+ orders_count = Order.objects.count()
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert not data["errors"]
+
+ order_token = data["order"]["token"]
+ assert Order.objects.count() == orders_count + 1
+ order = Order.objects.first()
+ assert str(order.pk) == order_token
+ assert order.total.gross == total.gross
+ assert order.metadata == checkout.metadata
+ assert order.private_metadata == checkout.private_metadata
+
+ order_line = order.lines.first()
+ assert checkout_line_quantity == order_line.quantity
+ assert checkout_line_variant == order_line.variant
+ assert order.shipping_address is None
+ assert order.shipping_method is None
+
+ assert not Checkout.objects.filter(
+ pk=checkout.pk
+ ).exists(), "Checkout should have been deleted"
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index fe8f48dd28..b401b36ac9 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -104,6 +104,7 @@ AppErrorCode = graphene.Enum.from_enum(app_error_codes.AppErrorCode)
AttributeErrorCode = graphene.Enum.from_enum(attribute_error_codes.AttributeErrorCode)
ChannelErrorCode = graphene.Enum.from_enum(channel_error_codes.ChannelErrorCode)
CheckoutErrorCode = graphene.Enum.from_enum(checkout_error_codes.CheckoutErrorCode)
+
ExternalNotificationTriggerErrorCode = graphene.Enum.from_enum(
external_notifications_error_codes.ExternalNotificationErrorCodes
)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 595b26b275..e41b636170 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -9901,6 +9901,19 @@ type Mutation {
token: UUID
): CheckoutLanguageCodeUpdate
+ """
+ New in Saleor 3.2. Create new order from existing checkout. Note: this feature is in a preview state and can be subject to changes at later point. Requires one of the following permissions: HANDLE_CHECKOUTS.
+ """
+ orderCreateFromCheckout(
+ """ID of a checkout that will be converted to an order."""
+ id: ID!
+
+ """
+ Determines if checkout should be removed after creating an order. Default true.
+ """
+ removeCheckout: Boolean = true
+ ): OrderCreateFromCheckout
+
"""
Creates new channel. Requires one of the following permissions: MANAGE_CHANNELS.
"""
@@ -15022,6 +15035,52 @@ type CheckoutLanguageCodeUpdate {
errors: [CheckoutError!]!
}
+"""
+New in Saleor 3.2. Create new order from existing checkout. Note: this feature is in a preview state and can be subject to changes at later point. Requires one of the following permissions: HANDLE_CHECKOUTS.
+"""
+type OrderCreateFromCheckout {
+ """Placed order."""
+ order: Order
+ errors: [OrderCreateFromCheckoutError!]!
+}
+
+type OrderCreateFromCheckoutError {
+ """
+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.
+ """
+ field: String
+
+ """The error message."""
+ message: String
+
+ """The error code."""
+ code: OrderCreateFromCheckoutErrorCode!
+
+ """List of variant IDs which causes the error."""
+ variants: [ID!]
+
+ """List of line Ids which cause the error."""
+ lines: [ID!]
+}
+
+"""An enumeration."""
+enum OrderCreateFromCheckoutErrorCode {
+ GRAPHQL_ERROR
+ NOT_FOUND
+ CHANNEL_INACTIVE
+ INSUFFICIENT_STOCK
+ VOUCHER_NOT_APPLICABLE
+ GIFT_CARD_NOT_APPLICABLE
+ TAX_ERROR
+ SHIPPING_METHOD_NOT_SET
+ BILLING_ADDRESS_NOT_SET
+ SHIPPING_ADDRESS_NOT_SET
+ INVALID_SHIPPING_METHOD
+ NO_LINES
+ EMAIL_NOT_SET
+ UNAVAILABLE_VARIANT_IN_CHANNEL
+}
+
"""
Creates new channel. Requires one of the following permissions: MANAGE_CHANNELS.
"""
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index a460688e0e..0ee83fefbd 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -1739,6 +1739,11 @@ def permission_manage_checkouts():
return Permission.objects.get(codename="manage_checkouts")
+def permission_handle_checkouts():
+ return Permission.objects.get(codename="handle_checkouts")
+
+
@pytest.fixture
def permission_manage_plugins():
return Permission.objects.get(codename="manage_plugins")