Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add mutation to create checkout from order (#12628)
Maciej Korycinski4cbc8e3e5f61
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0b2cb304f2..83306e99fc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,6 +28,7 @@ All notable, unreleased changes to this project will be documented in this file.- `staffUpdate`- `accountUpdate`- `customerBulkUpdate`+- Add mutation to create checkout from order - #12628 by @korycins- Allow setting metadata during invoice creating and updating - #12641 by @IKarbowiak- Introduce channel permissions - #10423 by @IKarbowiak- Limit staff users to access only certain channels. Granted permissions only apply to channels that the user has already been given access to.diff --git a/saleor/checkout/error_codes.py b/saleor/checkout/error_codes.pyindex eb729b481b..b5e6daebea 100644--- a/saleor/checkout/error_codes.py+++ b/saleor/checkout/error_codes.py@@ -47,3 +47,20 @@ class OrderCreateFromCheckoutErrorCode(Enum):NO_LINES = "no_lines"EMAIL_NOT_SET = "email_not_set"UNAVAILABLE_VARIANT_IN_CHANNEL = "unavailable_variant_in_channel"+++class CheckoutCreateFromOrderErrorCode(Enum):+ GRAPHQL_ERROR = "graphql_error"+ INVALID = "invalid"+ ORDER_NOT_FOUND = "order_not_found"+ CHANNEL_INACTIVE = "channel_inactive"+ TAX_ERROR = "tax_error"+++class CheckoutCreateFromOrderUnavailableVariantErrorCode(Enum):+ NOT_FOUND = "not_found"+ PRODUCT_UNAVAILABLE_FOR_PURCHASE = "product_unavailable_for_purchase"+ UNAVAILABLE_VARIANT_IN_CHANNEL = "unavailable_variant_in_channel"+ PRODUCT_NOT_PUBLISHED = "product_not_published"+ QUANTITY_GREATER_THAN_LIMIT = "quantity_greater_than_limit"+ INSUFFICIENT_STOCK = "insufficient_stock"diff --git a/saleor/graphql/checkout/enums.py b/saleor/graphql/checkout/enums.pyindex dca8d8418f..6a43356faf 100644--- a/saleor/graphql/checkout/enums.py+++ b/saleor/graphql/checkout/enums.py@@ -18,3 +18,13 @@ CheckoutAuthorizeStatusEnum = to_enum(CheckoutAuthorizeStatus, description=CheckoutAuthorizeStatus.__doc__)CheckoutAuthorizeStatusEnum.doc_category = DOC_CATEGORY_CHECKOUT++CheckoutCreateFromOrderErrorCode = graphene.Enum.from_enum(+ error_codes.CheckoutCreateFromOrderErrorCode+)+CheckoutCreateFromOrderErrorCode.doc_category = DOC_CATEGORY_CHECKOUT++CheckoutCreateFromOrderUnavailableVariantErrorCode = graphene.Enum.from_enum(+ error_codes.CheckoutCreateFromOrderUnavailableVariantErrorCode+)+CheckoutCreateFromOrderUnavailableVariantErrorCode.doc_category = DOC_CATEGORY_CHECKOUTdiff --git a/saleor/graphql/checkout/mutations/__init__.py b/saleor/graphql/checkout/mutations/__init__.pyindex 7718967b32..218dd238c9 100644--- a/saleor/graphql/checkout/mutations/__init__.py+++ b/saleor/graphql/checkout/mutations/__init__.py@@ -2,6 +2,7 @@ from .checkout_add_promo_code import CheckoutAddPromoCodefrom .checkout_billing_address_update import CheckoutBillingAddressUpdatefrom .checkout_complete import CheckoutCompletefrom .checkout_create import CheckoutCreate+from .checkout_create_from_order import CheckoutCreateFromOrderfrom .checkout_customer_attach import CheckoutCustomerAttachfrom .checkout_customer_detach import CheckoutCustomerDetachfrom .checkout_delivery_method_update import CheckoutDeliveryMethodUpdate@@ -21,6 +22,7 @@ __all__ = ["CheckoutBillingAddressUpdate","CheckoutComplete","CheckoutCreate",+ "CheckoutCreateFromOrder","CheckoutCustomerAttach","CheckoutCustomerDetach","CheckoutDeliveryMethodUpdate",diff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.pyindex 360ca27f0a..bd8347b463 100644--- a/saleor/graphql/checkout/mutations/checkout_create.py+++ b/saleor/graphql/checkout/mutations/checkout_create.py@@ -208,7 +208,9 @@ class CheckoutCreate(ModelMutation, I18nMixin):variant_db_ids = {variant.id for variant in variants}validate_variants_available_for_purchase(variant_db_ids, channel.id)validate_variants_available_in_channel(- variant_db_ids, channel.id, CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL+ variant_db_ids,+ channel.id,+ CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.value,)validate_variants_are_published(variant_db_ids, channel.id)diff --git a/saleor/graphql/checkout/mutations/checkout_create_from_order.py b/saleor/graphql/checkout/mutations/checkout_create_from_order.pynew file mode 100644index 0000000000..732d79e140--- /dev/null+++ b/saleor/graphql/checkout/mutations/checkout_create_from_order.py@@ -0,0 +1,425 @@+from typing import Any, Optional, cast++import graphene+from django.contrib.sites.models import Site++from ....checkout import models as checkout_models+from ....checkout.utils import add_variants_to_checkout+from ....core.exceptions import InsufficientStock+from ....order import models as order_models+from ....product import models as product_models+from ....product.models import ProductVariant+from ....warehouse.availability import check_stock_and_preorder_quantity_bulk+from ....warehouse.reservations import get_reservation_length, is_reservation_enabled+from ...core import ResolveInfo+from ...core.descriptions import ADDED_IN_314, PREVIEW_FEATURE+from ...core.doc_category import DOC_CATEGORY_CHECKOUT+from ...core.mutations import BaseMutation+from ...core.types import BaseObjectType, Error, common+from ...core.validators import get_not_available_variants_in_channel+from ...order.types import Order+from ...site.dataloaders import get_site_promise+from ..enums import (+ CheckoutCreateFromOrderErrorCode,+ CheckoutCreateFromOrderUnavailableVariantErrorCode,+)+from ..types import Checkout+from .utils import (+ CheckoutLineData,+ get_not_available_variants_for_purchase,+ get_not_published_variants,+ get_variants_and_total_quantities,+)+++class CheckoutCreateFromOrderUnavailableVariant(BaseObjectType):+ message = graphene.String(description="The error message.", required=True)+ code = CheckoutCreateFromOrderUnavailableVariantErrorCode(+ description="The error code.", required=True+ )+ variant_id = graphene.ID(+ description="Variant ID that is unavailable.", required=True+ )+ line_id = graphene.ID(+ description="Order line ID that is unavailable.", required=True+ )++ class Meta:+ doc_category = DOC_CATEGORY_CHECKOUT+++class CheckoutCreateFromOrderError(Error):+ code = CheckoutCreateFromOrderErrorCode(+ description="The error code.", required=True+ )++ class Meta:+ doc_category = DOC_CATEGORY_CHECKOUT+++class CheckoutCreateFromOrder(BaseMutation):+ unavailable_variants = common.NonNullList(+ CheckoutCreateFromOrderUnavailableVariant,+ description="Variants that were not attached to the checkout.",+ )+ checkout = graphene.Field(Checkout, description="Created checkout.")++ class Arguments:+ id = graphene.ID(+ required=True,+ description="ID of a order that will be used to create the checkout.",+ )++ class Meta:+ description = (+ "Create new checkout from existing order." + ADDED_IN_314 + PREVIEW_FEATURE+ )+ doc_category = DOC_CATEGORY_CHECKOUT+ error_type_class = CheckoutCreateFromOrderError++ @classmethod+ def _create_variant_errors(+ cls, error_code: str, msg: str, order_lines: list[order_models.OrderLine]+ ) -> list[dict[str, Any]]:+ return [+ {+ "message": msg,+ "code": error_code,+ "variant_id": line.product_variant_id,+ "line_id": graphene.Node.to_global_id("OrderLine", line.pk),+ }+ for line in order_lines+ ]++ @classmethod+ def handle_not_available_variants_in_channel(+ cls,+ variant_ids_set: set[int],+ channel_id: int,+ order_lines: list[order_models.OrderLine],+ variant_errors: list[dict[str, Any]],+ ) -> set[int]:+ (+ not_available_in_channel,+ not_available_in_channel_graphql_ids,+ ) = get_not_available_variants_in_channel(variant_ids_set, channel_id)+ variant_ids_set = variant_ids_set - not_available_in_channel++ if not_available_in_channel:+ error_codes = CheckoutCreateFromOrderUnavailableVariantErrorCode+ variant_errors.extend(+ cls._create_variant_errors(+ error_code=error_codes.UNAVAILABLE_VARIANT_IN_CHANNEL.value,+ msg="Cannot add lines with unavailable variants.",+ order_lines=[+ line+ for line in order_lines+ if line.variant_id in not_available_in_channel+ ],+ )+ )+ return variant_ids_set++ @classmethod+ def handle_not_found_variants(+ cls,+ order_lines: list[order_models.OrderLine],+ variant_errors: list[dict[str, Any]],+ ):+ error_codes = CheckoutCreateFromOrderUnavailableVariantErrorCode+ lines_with_not_found_variants = (+ [line for line in order_lines if not line.variant_id],+ )+ if lines_with_not_found_variants:+ variant_errors.extend(+ cls._create_variant_errors(+ error_code=error_codes.NOT_FOUND.value,+ msg="Product variant not found",+ order_lines=[line for line in order_lines if not line.variant_id],+ )+ )++ @classmethod+ def handle_not_published_variants(+ cls,+ variant_ids_set: set[int],+ channel_id: int,+ order_lines: list[order_models.OrderLine],+ variant_errors: list[dict[str, Any]],+ ) -> set[int]:+ not_published_ids, not_published_graphql_ids = get_not_published_variants(+ variant_ids_set, channel_id+ )+ variant_ids_set = variant_ids_set - not_published_ids++ if not_published_ids:+ error_codes = CheckoutCreateFromOrderUnavailableVariantErrorCode+ variant_errors.extend(+ cls._create_variant_errors(+ error_code=error_codes.PRODUCT_NOT_PUBLISHED.value,+ msg="Cannot add lines for unpublished variants.",+ order_lines=[+ line+ for line in order_lines+ if line.variant_id in not_published_ids+ ],+ )+ )+ return variant_ids_set++ @classmethod+ def handle_not_available_variants_for_purchase(+ cls,+ variant_ids_set: set[int],+ channel_id: int,+ order_lines: list[order_models.OrderLine],+ variant_errors: list[dict[str, Any]],+ ) -> set[int]:+ (+ not_available_for_purchase,+ not_available_for_purchase_graphql_ids,+ ) = get_not_available_variants_for_purchase(variant_ids_set, channel_id)+ variant_ids_set = variant_ids_set - not_available_for_purchase+ if not_available_for_purchase:+ error_codes = CheckoutCreateFromOrderUnavailableVariantErrorCode+ variant_errors.extend(+ cls._create_variant_errors(+ error_code=error_codes.PRODUCT_UNAVAILABLE_FOR_PURCHASE.value,+ msg="Cannot add lines for unavailable for purchase variants.",+ order_lines=[+ line+ for line in order_lines+ if line.variant_id in not_available_for_purchase+ ],+ )+ )+ return variant_ids_set++ @classmethod+ def handle_variants_exceeding_quantity_limit(+ cls,+ variant_ids_set: set[int],+ order_lines: list[order_models.OrderLine],+ variant_errors: list[dict[str, Any]],+ global_quantity_limit: Optional[int],+ ) -> set[int]:+ variant_ids_to_exclude = []+ error_codes = CheckoutCreateFromOrderUnavailableVariantErrorCode+ for line in order_lines:+ variant = line.variant+ variant = cast(ProductVariant, variant)+ quantity_limit = (+ variant.quantity_limit_per_customer or global_quantity_limit+ )+ if quantity_limit is not None and line.quantity > quantity_limit:+ msg = f"Cannot add more than {quantity_limit} "+ f"times this item: {line.variant}."+ variant_errors.append(+ {+ "message": msg,+ "code": error_codes.QUANTITY_GREATER_THAN_LIMIT.value,+ "variant_id": line.product_variant_id,+ "line_id": graphene.Node.to_global_id("OrderLine", line.pk),+ }+ )+ variant_ids_to_exclude.append(line.variant_id)+ return variant_ids_set - set(variant_ids_to_exclude)++ @classmethod+ def exclude_lines_unavailable_to_purchase(+ cls,+ order: order_models.Order,+ order_lines: list[order_models.OrderLine],+ global_quantity_limit: Optional[int],+ ) -> tuple[set[int], list[order_models.OrderLine], list[dict[str, Any]]]:+ variant_errors: list[dict[str, Any]] = []+ variant_ids_set = set(+ [line.variant_id for line in order_lines if line.variant_id]+ )+ channel_id = (order.channel_id,)+ channel_id = cast(int, channel_id)++ cls.handle_not_found_variants(+ order_lines=order_lines, variant_errors=variant_errors+ )++ order_lines = [line for line in order_lines if line.variant_id]++ variant_ids_set = cls.handle_not_available_variants_in_channel(+ variant_ids_set=variant_ids_set,+ channel_id=channel_id,+ order_lines=order_lines,+ variant_errors=variant_errors,+ )++ order_lines = [+ line for line in order_lines if line.variant_id in variant_ids_set+ ]++ variant_ids_set = cls.handle_not_published_variants(+ variant_ids_set=variant_ids_set,+ channel_id=channel_id,+ order_lines=order_lines,+ variant_errors=variant_errors,+ )++ order_lines = [+ line for line in order_lines if line.variant_id in variant_ids_set+ ]+ variant_ids_set = cls.handle_not_available_variants_for_purchase(+ variant_ids_set=variant_ids_set,+ channel_id=channel_id,+ order_lines=order_lines,+ variant_errors=variant_errors,+ )++ order_lines = [+ line for line in order_lines if line.variant_id in variant_ids_set+ ]+ variant_ids_set = cls.handle_variants_exceeding_quantity_limit(+ variant_ids_set, order_lines, variant_errors, global_quantity_limit+ )++ order_lines = [+ line for line in order_lines if line.variant_id in variant_ids_set+ ]+ return variant_ids_set, order_lines, variant_errors++ @classmethod+ def clean_order_lines(+ cls,+ order: order_models.Order,+ order_lines: list[order_models.OrderLine],+ site: Site,+ ):+ (+ variant_ids_set,+ available_order_lines,+ variant_errors,+ ) = cls.exclude_lines_unavailable_to_purchase(+ order=order,+ order_lines=order_lines,+ global_quantity_limit=site.settings.limit_quantity_per_checkout,+ )++ variants = list(+ product_models.ProductVariant.objects.select_related(+ "product__product_type"+ ).filter(id__in=variant_ids_set)+ )++ variants, quantities = get_variants_and_total_quantities(+ variants,+ [+ CheckoutLineData(+ variant_id=str(line.variant_id), quantity=line.quantity+ )+ for line in order_lines+ ],+ )+ valid_order_lines: list[order_models.OrderLine] = []+ if order.shipping_address:+ country = order.shipping_address.country.code+ else:+ country = order.channel.default_country+ try:+ check_stock_and_preorder_quantity_bulk(+ variants,+ country,+ quantities,+ order.channel.slug,+ site.settings.limit_quantity_per_checkout,+ check_reservations=is_reservation_enabled(site.settings),+ )+ valid_order_lines = available_order_lines+ except InsufficientStock as e:+ variants_with_insufficient_stock = {+ item.variant.pk: item for item in e.items if item.variant+ }+ variant_ids_set = variant_ids_set - set(+ list(variants_with_insufficient_stock.keys())+ )+ error_codes = CheckoutCreateFromOrderUnavailableVariantErrorCode+ for line in available_order_lines:+ variant_id = cast(int, line.variant_id)+ variant_with_insufficient_stock = variants_with_insufficient_stock.get(+ variant_id+ )+ if not variant_with_insufficient_stock:+ valid_order_lines.append(line)+ continue+ msg = (+ f"Could not add items {variant_with_insufficient_stock.variant}. "+ f"Only {max(variant_with_insufficient_stock.available_quantity, 0)}"+ f" remaining in stock.",+ )+ variant_errors.append(+ {+ "message": msg,+ "code": error_codes.INSUFFICIENT_STOCK.value,+ "variant_id": line.product_variant_id,+ "line_id": graphene.Node.to_global_id("OrderLine", line.pk),+ }+ )+ variants = product_models.ProductVariant.objects.filter(id__in=variant_ids_set)+ return variants, valid_order_lines, variant_errors++ @classmethod+ def create_checkout(+ cls,+ info: ResolveInfo,+ order: order_models.Order,+ ):+ user = info.context.user+ checkout = checkout_models.Checkout(+ channel_id=order.channel_id,+ currency=order.currency,+ )+ if user:+ checkout.user = user+ checkout.email = user.email+ checkout.save()+ return checkout++ @classmethod+ def perform_mutation( # type: ignore[override]+ cls,+ _root,+ info: ResolveInfo,+ /,+ *,+ id,+ ):+ site = get_site_promise(info.context).get()+ order = cls.get_node_or_error(+ info,+ id,+ field="id",+ only_type=Order,+ code=CheckoutCreateFromOrderErrorCode.ORDER_NOT_FOUND.value,+ )+ order_lines = order.lines.prefetch_related("variant").all()+ checkout = cls.create_checkout(info, order)+ variants, valid_order_lines, variant_errors = cls.clean_order_lines(+ order, order_lines, site+ )++ if variants and valid_order_lines:+ checkout = add_variants_to_checkout(+ checkout,+ variants,+ [+ CheckoutLineData(+ variant_id=str(line.variant_id), quantity=line.quantity+ )+ for line in valid_order_lines+ ],+ order.channel,+ site.settings.limit_quantity_per_checkout,+ reservation_length=get_reservation_length(+ site=site, user=info.context.user+ ),+ )+ return CheckoutCreateFromOrder(+ checkout=checkout, unavailable_variants=variant_errors+ )diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.pyindex edbf7ea4f8..df7227af85 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py@@ -135,7 +135,7 @@ class CheckoutLinesAdd(BaseMutation):validate_variants_available_in_channel(variants_ids_to_validate,checkout.channel_id,- CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL,+ CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.value,)validate_variants_are_published(variants_ids_to_validate, checkout.channel_iddiff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.pyindex 349cbcd02a..ef6f645741 100644--- a/saleor/graphql/checkout/mutations/utils.py+++ b/saleor/graphql/checkout/mutations/utils.py@@ -196,7 +196,9 @@ def check_lines_quantity(raise ValidationError({"quantity": errors})-def validate_variants_available_for_purchase(variants_id: set, channel_id: int):+def get_not_available_variants_for_purchase(+ variants_id: set, channel_id: int+) -> tuple[set[int], set[str]]:today = datetime.datetime.now(pytz.UTC)is_available_for_purchase = Q(available_for_purchase_at__lte=today,@@ -207,40 +209,62 @@ def validate_variants_available_for_purchase(variants_id: set, channel_id: int):is_available_for_purchase).values_list("product__variants__id", flat=True)not_available_variants = variants_id.difference(set(available_variants))+ not_available_graphql_ids = {+ graphene.Node.to_global_id("ProductVariant", pk)+ for pk in not_available_variants+ }+ return not_available_variants, not_available_graphql_ids+++def validate_variants_available_for_purchase(+ variants_id: set,+ channel_id: int,+ error_code: str = CheckoutErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE.value,+):+ (+ not_available_variants,+ not_available_graphql_ids,+ ) = get_not_available_variants_for_purchase(variants_id, channel_id)if not_available_variants:- variant_ids = [- graphene.Node.to_global_id("ProductVariant", pk)- for pk in not_available_variants- ]- error_code = CheckoutErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE.valueraise ValidationError({"lines": ValidationError("Cannot add lines for unavailable for purchase variants.",code=error_code,- params={"variants": variant_ids},+ params={"variants": not_available_graphql_ids},)})-def validate_variants_are_published(variants_id: set, channel_id: int):+def get_not_published_variants(+ variants_id: set, channel_id: int+) -> tuple[set[int], set[str]]:published_variants = product_models.ProductChannelListing.objects.filter(channel_id=channel_id, product__variants__id__in=variants_id, is_published=True).values_list("product__variants__id", flat=True)- not_published_variants = variants_id.difference(set(published_variants))- if not_published_variants:- variant_ids = [- graphene.Node.to_global_id("ProductVariant", pk)- for pk in not_published_variants- ]- error_code = CheckoutErrorCode.PRODUCT_NOT_PUBLISHED.value+ not_published_ids = variants_id.difference(set(published_variants))+ not_published_graphql_ids = {+ graphene.Node.to_global_id("ProductVariant", pk) for pk in not_published_ids+ }+ return not_published_ids, not_published_graphql_ids+++def validate_variants_are_published(+ variants_id: set,+ channel_id: int,+ error_code: str = CheckoutErrorCode.PRODUCT_NOT_PUBLISHED.value,+):+ not_published_ids, not_published_graphql_ids = get_not_published_variants(+ variants_id, channel_id+ )+ if not_published_ids:raise ValidationError({"lines": ValidationError("Cannot add lines for unpublished variants.",code=error_code,- params={"variants": variant_ids},+ params={"variants": not_published_graphql_ids},)})diff --git a/saleor/graphql/checkout/schema.py b/saleor/graphql/checkout/schema.pyindex 837b7dfe3a..55dbdce324 100644--- a/saleor/graphql/checkout/schema.py+++ b/saleor/graphql/checkout/schema.py@@ -19,6 +19,7 @@ from .mutations import (CheckoutBillingAddressUpdate,CheckoutComplete,CheckoutCreate,+ CheckoutCreateFromOrder,CheckoutCustomerAttach,CheckoutCustomerDetach,CheckoutDeliveryMethodUpdate,@@ -105,6 +106,7 @@ class CheckoutMutations(graphene.ObjectType):checkout_billing_address_update = CheckoutBillingAddressUpdate.Field()checkout_complete = CheckoutComplete.Field()checkout_create = CheckoutCreate.Field()+ checkout_create_from_order = CheckoutCreateFromOrder.Field()checkout_customer_attach = CheckoutCustomerAttach.Field()checkout_customer_detach = CheckoutCustomerDetach.Field()checkout_email_update = CheckoutEmailUpdate.Field()diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 40a34d665d..039f6a0d33 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -1353,3 +1353,47 @@ def test_complete_checkout_preorder(response = get_graphql_content(api_client.post_graphql(query, variables))assert not response["data"]["checkoutComplete"]["errors"]+++MUTATION_CHECKOUT_CREATE_FROM_ORDER = (+ FRAGMENT_CHECKOUT+ + """+mutation CheckoutCreateFromOrder($id: ID!) {+ checkoutCreateFromOrder(id:$id){+ errors{+ field+ message+ code+ }+ unavailableVariants{+ message+ code+ variantId+ lineId+ }+ checkout{+ ...Checkout+ }+ }+}+"""+)++[email protected]_queries(autouse=False)+def test_checkout_create_from_order(user_api_client, order_with_lines):+ # given+ order_with_lines.user = user_api_client.user+ order_with_lines.save()+ Stock.objects.update(quantity=10)++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["checkoutCreateFromOrder"]["errors"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.pynew file mode 100644index 0000000000..2e64701fa1--- /dev/null+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.py@@ -0,0 +1,725 @@+from datetime import datetime, timedelta++import graphene+import pytz++from .....checkout.error_codes import CheckoutCreateFromOrderUnavailableVariantErrorCode+from .....checkout.models import Checkout+from .....warehouse.models import Stock+from ....tests.utils import get_graphql_content+from ...enums import CheckoutCreateFromOrderErrorCode++MUTATION_CHECKOUT_CREATE_FROM_ORDER = """+mutation CheckoutCreateFromOrder($id: ID!) {+ checkoutCreateFromOrder(id:$id){+ errors{+ field+ message+ code+ }+ unavailableVariants{+ message+ code+ variantId+ lineId+ }+ checkout{+ id+ lines{+ quantity+ variant{+ id+ }+ }+ }+ }+}+"""+++def _assert_checkout_lines(+ order_lines_map, checkout_lines, checkout_lines_from_response_map+):+ for line in checkout_lines:+ order_line = order_lines_map.get(line.variant.pk)+ assert line.quantity == order_line.quantity+ assert line.variant_id == order_line.variant_id+ variant_global_id = graphene.Node.to_global_id(+ "ProductVariant", line.variant.pk+ )+ line_from_response = checkout_lines_from_response_map.get(variant_global_id)+ assert line.quantity == line_from_response["quantity"]+ assert variant_global_id == line_from_response["variant"]["id"]+++def test_checkout_create_from_order_with_same_user(user_api_client, order_with_lines):+ # given+ order_with_lines.user = user_api_client.user+ order_with_lines.save()+ Stock.objects.update(quantity=10)++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then+ order_lines_map = {line.variant.pk: line for line in order_with_lines.lines.all()}++ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ checkout = Checkout.objects.get()+ checkout_lines = checkout.lines.all()+ assert checkout.user == order_with_lines.user+ assert checkout.email == order_with_lines.user_email+ checkout_lines_from_response = data["checkout"]["lines"]+ assert len(checkout_lines_from_response) == checkout_lines.count()+ checkout_lines_from_response_map = {+ line["variant"]["id"]: line for line in checkout_lines_from_response+ }+ assert not data["unavailableVariants"]+ assert data["checkout"]["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ _assert_checkout_lines(+ order_lines_map, checkout_lines, checkout_lines_from_response_map+ )+++def test_checkout_create_from_order_with_different_user(+ user_api_client, order_with_lines, customer_user2+):+ # given+ order_with_lines.user = customer_user2+ order_with_lines.save()+ assert user_api_client.user != customer_user2+ Stock.objects.update(quantity=10)++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then+ order_lines_map = {line.variant.pk: line for line in order_with_lines.lines.all()}++ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ checkout = Checkout.objects.get()+ checkout_lines = checkout.lines.all()+ assert checkout.user == user_api_client.user+ assert checkout.email == user_api_client.user.email+ checkout_lines_from_response = data["checkout"]["lines"]+ assert len(checkout_lines_from_response) == checkout_lines.count()+ checkout_lines_from_response_map = {+ line["variant"]["id"]: line for line in checkout_lines_from_response+ }+ assert not data["unavailableVariants"]+ assert data["checkout"]["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ _assert_checkout_lines(+ order_lines_map, checkout_lines, checkout_lines_from_response_map+ )+++def test_checkout_create_from_order_with_anonymous_user(api_client, order_with_lines):+ # given+ Stock.objects.update(quantity=10)+ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ # when+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables)++ # then+ order_lines_map = {line.variant.pk: line for line in order_with_lines.lines.all()}++ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ checkout = Checkout.objects.get()+ checkout_lines = checkout.lines.all()+ assert not checkout.user+ assert not checkout.email+ checkout_lines_from_response = data["checkout"]["lines"]+ assert len(checkout_lines_from_response) == checkout_lines.count()+ checkout_lines_from_response_map = {+ line["variant"]["id"]: line for line in checkout_lines_from_response+ }+ assert not data["unavailableVariants"]+ assert data["checkout"]["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ _assert_checkout_lines(+ order_lines_map, checkout_lines, checkout_lines_from_response_map+ )+++def test_checkout_create_from_anonymous_order_and_logged_in_user(+ user_api_client,+ order_with_lines,+):+ # given+ order_with_lines.user = None+ order_with_lines.save()+ Stock.objects.update(quantity=10)++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then+ order_lines_map = {line.variant.pk: line for line in order_with_lines.lines.all()}++ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ checkout = Checkout.objects.get()+ checkout_lines = checkout.lines.all()+ assert checkout.user == user_api_client.user+ assert checkout.email == user_api_client.user.email+ checkout_lines_from_response = data["checkout"]["lines"]+ assert len(checkout_lines_from_response) == checkout_lines.count()+ checkout_lines_from_response_map = {+ line["variant"]["id"]: line for line in checkout_lines_from_response+ }+ assert not data["unavailableVariants"]+ assert data["checkout"]["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ _assert_checkout_lines(+ order_lines_map, checkout_lines, checkout_lines_from_response_map+ )+++def test_checkout_create_from_order_when_order_not_found(+ user_api_client,+ order_with_lines,+):+ # given+ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ order_with_lines.delete()+ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["checkoutCreateFromOrder"]["errors"]+ assert len(errors) == 1+ error = errors[0]+ assert error["field"] == "id"+ assert error["code"] == CheckoutCreateFromOrderErrorCode.ORDER_NOT_FOUND.name+++def test_checkout_create_from_order_variant_not_found(+ user_api_client, order_with_lines+):+ # given+ order_with_lines.user = user_api_client.user+ order_with_lines.save()+ Stock.objects.update(quantity=10)+ first_line = order_with_lines.lines.first()+ first_line.variant.delete()++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then+ order_lines_map = {+ line.variant.pk: line for line in order_with_lines.lines.all() if line.variant+ }++ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ checkout = Checkout.objects.get()+ checkout_lines = checkout.lines.all()+ assert checkout.user == order_with_lines.user+ assert checkout.email == order_with_lines.user_email+ checkout_lines_from_response = data["checkout"]["lines"]+ assert (+ len(checkout_lines_from_response)+ == checkout_lines.count()+ == len(order_lines_map)+ )+ checkout_lines_from_response_map = {+ line["variant"]["id"]: line for line in checkout_lines_from_response+ }++ assert data["checkout"]["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ _assert_checkout_lines(+ order_lines_map, checkout_lines, checkout_lines_from_response_map+ )++ error_codes = CheckoutCreateFromOrderUnavailableVariantErrorCode+ assert len(data["unavailableVariants"]) == 1+ unavailable_variant = data["unavailableVariants"][0]+ assert unavailable_variant["code"] == error_codes.NOT_FOUND.name+ assert unavailable_variant["lineId"] == graphene.Node.to_global_id(+ "OrderLine", first_line.pk+ )+ assert unavailable_variant["variantId"] == first_line.product_variant_id+++def test_checkout_create_from_order_variant_not_available_in_channel(+ user_api_client, order_with_lines+):+ # given+ order_with_lines.user = user_api_client.user+ order_with_lines.save()+ Stock.objects.update(quantity=10)+ first_line = order_with_lines.lines.first()+ first_line.variant.channel_listings.all().delete()++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then+ order_lines_map = {line.variant.pk: line for line in order_with_lines.lines.all()}++ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ checkout = Checkout.objects.get()+ checkout_lines = checkout.lines.all()+ assert checkout.user == order_with_lines.user+ assert checkout.email == order_with_lines.user_email+ checkout_lines_from_response = data["checkout"]["lines"]+ assert (+ len(checkout_lines_from_response)+ == checkout_lines.count()+ == len(order_lines_map) - 1+ )+ checkout_lines_from_response_map = {+ line["variant"]["id"]: line for line in checkout_lines_from_response+ }++ assert data["checkout"]["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ _assert_checkout_lines(+ order_lines_map, checkout_lines, checkout_lines_from_response_map+ )++ error_codes = CheckoutCreateFromOrderUnavailableVariantErrorCode+ assert len(data["unavailableVariants"]) == 1+ unavailable_variant = data["unavailableVariants"][0]+ assert (+ unavailable_variant["code"] == error_codes.UNAVAILABLE_VARIANT_IN_CHANNEL.name+ )+ assert unavailable_variant["lineId"] == graphene.Node.to_global_id(+ "OrderLine", first_line.pk+ )+ assert unavailable_variant["variantId"] == first_line.product_variant_id+++def test_checkout_create_from_order_variant_not_published(+ user_api_client, order_with_lines+):+ # given+ order_with_lines.user = user_api_client.user+ order_with_lines.save()+ Stock.objects.update(quantity=10)+ first_line = order_with_lines.lines.first()+ first_line.variant.product.channel_listings.all().update(is_published=False)++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then+ order_lines_map = {line.variant.pk: line for line in order_with_lines.lines.all()}++ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ checkout = Checkout.objects.get()+ checkout_lines = checkout.lines.all()+ assert checkout.user == order_with_lines.user+ assert checkout.email == order_with_lines.user_email+ checkout_lines_from_response = data["checkout"]["lines"]+ assert (+ len(checkout_lines_from_response)+ == checkout_lines.count()+ == len(order_lines_map) - 1+ )+ checkout_lines_from_response_map = {+ line["variant"]["id"]: line for line in checkout_lines_from_response+ }++ assert data["checkout"]["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ _assert_checkout_lines(+ order_lines_map, checkout_lines, checkout_lines_from_response_map+ )++ error_codes = CheckoutCreateFromOrderUnavailableVariantErrorCode+ assert len(data["unavailableVariants"]) == 1+ unavailable_variant = data["unavailableVariants"][0]+ assert unavailable_variant["code"] == error_codes.PRODUCT_NOT_PUBLISHED.name+ assert unavailable_variant["lineId"] == graphene.Node.to_global_id(+ "OrderLine", first_line.pk+ )+ assert unavailable_variant["variantId"] == first_line.product_variant_id+++def test_checkout_create_from_order_variant_exceed_variant_quantity_limit(+ user_api_client, order_with_lines+):+ # given+ order_with_lines.user = user_api_client.user+ order_with_lines.save()+ Stock.objects.update(quantity=10)+ first_line = order_with_lines.lines.first()+ variant = first_line.variant+ variant.quantity_limit_per_customer = first_line.quantity - 1+ variant.save()++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then+ order_lines_map = {line.variant.pk: line for line in order_with_lines.lines.all()}++ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ checkout = Checkout.objects.get()+ checkout_lines = checkout.lines.all()+ assert checkout.user == order_with_lines.user+ assert checkout.email == order_with_lines.user_email+ checkout_lines_from_response = data["checkout"]["lines"]+ assert (+ len(checkout_lines_from_response)+ == checkout_lines.count()+ == len(order_lines_map) - 1+ )+ checkout_lines_from_response_map = {+ line["variant"]["id"]: line for line in checkout_lines_from_response+ }++ assert data["checkout"]["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ _assert_checkout_lines(+ order_lines_map, checkout_lines, checkout_lines_from_response_map+ )++ error_codes = CheckoutCreateFromOrderUnavailableVariantErrorCode+ assert len(data["unavailableVariants"]) == 1+ unavailable_variant = data["unavailableVariants"][0]+ assert unavailable_variant["code"] == error_codes.QUANTITY_GREATER_THAN_LIMIT.name+ assert unavailable_variant["lineId"] == graphene.Node.to_global_id(+ "OrderLine", first_line.pk+ )+ assert unavailable_variant["variantId"] == first_line.product_variant_id+++def test_checkout_create_from_order_variant_exceed_global_quantity_limit(+ user_api_client, order_with_lines, site_settings+):+ # given+ order_with_lines.user = user_api_client.user+ order_with_lines.save()+ Stock.objects.update(quantity=10)+ first_line = order_with_lines.lines.first()+ first_line.quantity = 25+ first_line.save()++ site_settings.limit_quantity_per_checkout = 20+ site_settings.save()++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then+ order_lines_map = {line.variant.pk: line for line in order_with_lines.lines.all()}++ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ checkout = Checkout.objects.get()+ checkout_lines = checkout.lines.all()+ assert checkout.user == order_with_lines.user+ assert checkout.email == order_with_lines.user_email+ checkout_lines_from_response = data["checkout"]["lines"]+ assert (+ len(checkout_lines_from_response)+ == checkout_lines.count()+ == len(order_lines_map) - 1+ )+ checkout_lines_from_response_map = {+ line["variant"]["id"]: line for line in checkout_lines_from_response+ }++ assert data["checkout"]["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ _assert_checkout_lines(+ order_lines_map, checkout_lines, checkout_lines_from_response_map+ )++ error_codes = CheckoutCreateFromOrderUnavailableVariantErrorCode+ assert len(data["unavailableVariants"]) == 1+ unavailable_variant = data["unavailableVariants"][0]+ assert unavailable_variant["code"] == error_codes.QUANTITY_GREATER_THAN_LIMIT.name+ assert unavailable_variant["lineId"] == graphene.Node.to_global_id(+ "OrderLine", first_line.pk+ )+ assert unavailable_variant["variantId"] == first_line.product_variant_id+++def test_checkout_create_from_order_variant_not_available_for_purchase(+ user_api_client, order_with_lines+):+ # given+ available_at = datetime.now(pytz.UTC) + timedelta(days=2)+ order_with_lines.user = user_api_client.user+ order_with_lines.save()+ Stock.objects.update(quantity=10)+ first_line = order_with_lines.lines.first()+ first_line.variant.product.channel_listings.all().update(+ available_for_purchase_at=available_at+ )++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then+ order_lines_map = {line.variant.pk: line for line in order_with_lines.lines.all()}++ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ checkout = Checkout.objects.get()+ checkout_lines = checkout.lines.all()+ assert checkout.user == order_with_lines.user+ assert checkout.email == order_with_lines.user_email+ checkout_lines_from_response = data["checkout"]["lines"]+ assert (+ len(checkout_lines_from_response)+ == checkout_lines.count()+ == len(order_lines_map) - 1+ )+ checkout_lines_from_response_map = {+ line["variant"]["id"]: line for line in checkout_lines_from_response+ }++ assert data["checkout"]["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ _assert_checkout_lines(+ order_lines_map, checkout_lines, checkout_lines_from_response_map+ )++ error_codes = CheckoutCreateFromOrderUnavailableVariantErrorCode+ assert len(data["unavailableVariants"]) == 1+ unavailable_variant = data["unavailableVariants"][0]+ assert (+ unavailable_variant["code"] == error_codes.PRODUCT_UNAVAILABLE_FOR_PURCHASE.name+ )+ assert unavailable_variant["lineId"] == graphene.Node.to_global_id(+ "OrderLine", first_line.pk+ )+ assert unavailable_variant["variantId"] == first_line.product_variant_id+++def test_checkout_create_from_order_variant_out_of_stock(+ user_api_client, order_with_lines+):+ # given+ order_with_lines.user = user_api_client.user+ order_with_lines.save()+ first_line = order_with_lines.lines.first()+ Stock.objects.exclude(product_variant=first_line.variant).update(quantity=10)++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then+ order_lines_map = {line.variant.pk: line for line in order_with_lines.lines.all()}++ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ checkout = Checkout.objects.get()+ checkout_lines = checkout.lines.all()+ assert checkout.user == order_with_lines.user+ assert checkout.email == order_with_lines.user_email+ checkout_lines_from_response = data["checkout"]["lines"]+ assert (+ len(checkout_lines_from_response)+ == checkout_lines.count()+ == len(order_lines_map) - 1+ )+ checkout_lines_from_response_map = {+ line["variant"]["id"]: line for line in checkout_lines_from_response+ }++ assert data["checkout"]["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ _assert_checkout_lines(+ order_lines_map, checkout_lines, checkout_lines_from_response_map+ )++ error_codes = CheckoutCreateFromOrderUnavailableVariantErrorCode+ assert len(data["unavailableVariants"]) == 1+ unavailable_variant = data["unavailableVariants"][0]+ assert unavailable_variant["code"] == error_codes.INSUFFICIENT_STOCK.name+ assert unavailable_variant["lineId"] == graphene.Node.to_global_id(+ "OrderLine", first_line.pk+ )+ assert unavailable_variant["variantId"] == first_line.product_variant_id+++def test_checkout_create_from_order_variant_not_enough_stock(+ user_api_client, order_with_lines+):+ # given+ order_with_lines.user = user_api_client.user+ order_with_lines.save()+ first_line = order_with_lines.lines.first()+ Stock.objects.exclude(product_variant=first_line.variant).update(quantity=10)+ Stock.objects.filter(product_variant=first_line.variant).update(+ quantity=first_line.quantity - 1+ )++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then+ order_lines_map = {line.variant.pk: line for line in order_with_lines.lines.all()}++ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ checkout = Checkout.objects.get()+ checkout_lines = checkout.lines.all()+ assert checkout.user == order_with_lines.user+ assert checkout.email == order_with_lines.user_email+ checkout_lines_from_response = data["checkout"]["lines"]+ assert (+ len(checkout_lines_from_response)+ == checkout_lines.count()+ == len(order_lines_map) - 1+ )+ checkout_lines_from_response_map = {+ line["variant"]["id"]: line for line in checkout_lines_from_response+ }++ assert data["checkout"]["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ _assert_checkout_lines(+ order_lines_map, checkout_lines, checkout_lines_from_response_map+ )++ error_codes = CheckoutCreateFromOrderUnavailableVariantErrorCode+ assert len(data["unavailableVariants"]) == 1+ unavailable_variant = data["unavailableVariants"][0]+ assert unavailable_variant["code"] == error_codes.INSUFFICIENT_STOCK.name+ assert unavailable_variant["lineId"] == graphene.Node.to_global_id(+ "OrderLine", first_line.pk+ )+ assert unavailable_variant["variantId"] == first_line.product_variant_id+++def test_checkout_create_from_order_multiple_unavailable_variants(+ user_api_client, order_with_lines, order_line+):+ # given+ order_with_lines.user = user_api_client.user+ order_with_lines.save()+ order_line.order_id = order_with_lines.pk+ order_line.save()+ first_line = order_with_lines.lines.first()++ Stock.objects.exclude(product_variant=first_line.variant).update(quantity=10)+ order_line.variant.channel_listings.all().delete()++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then+ order_lines_map = {line.variant.pk: line for line in order_with_lines.lines.all()}++ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ checkout = Checkout.objects.get()+ checkout_lines = checkout.lines.all()+ assert checkout.user == order_with_lines.user+ assert checkout.email == order_with_lines.user_email+ checkout_lines_from_response = data["checkout"]["lines"]+ assert (+ len(checkout_lines_from_response)+ == checkout_lines.count()+ == len(order_lines_map) - 2+ )+ checkout_lines_from_response_map = {+ line["variant"]["id"]: line for line in checkout_lines_from_response+ }++ assert data["checkout"]["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ _assert_checkout_lines(+ order_lines_map, checkout_lines, checkout_lines_from_response_map+ )++ error_codes = CheckoutCreateFromOrderUnavailableVariantErrorCode+ assert len(data["unavailableVariants"]) == 2++ unavailable_variants = data["unavailableVariants"]+ errors = {variant_data["code"] for variant_data in unavailable_variants}+ line_ids = {variant_data["lineId"] for variant_data in unavailable_variants}+ variant_ids = {variant_data["variantId"] for variant_data in unavailable_variants}+ assert errors == {+ error_codes.INSUFFICIENT_STOCK.name,+ error_codes.UNAVAILABLE_VARIANT_IN_CHANNEL.name,+ }+ assert line_ids == {+ graphene.Node.to_global_id("OrderLine", first_line.pk),+ graphene.Node.to_global_id("OrderLine", order_line.pk),+ }+ assert variant_ids == {first_line.product_variant_id, order_line.product_variant_id}+++def test_checkout_create_from_order_with_the_same_variant_in_multiple_lines(+ user_api_client, order_with_lines+):+ # given+ order_with_lines.user = user_api_client.user+ order_with_lines.save()+ Stock.objects.update(quantity=10)+ first_line = order_with_lines.lines.first()+ first_line.pk = None+ first_line.save()++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then+ order_lines_map = {line.variant.pk: line for line in order_with_lines.lines.all()}++ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ checkout = Checkout.objects.get()+ checkout_lines = checkout.lines.all()+ assert checkout.user == order_with_lines.user+ assert checkout.email == order_with_lines.user_email+ checkout_lines_from_response = data["checkout"]["lines"]+ assert (+ len(checkout_lines_from_response)+ == checkout_lines.count()+ == order_with_lines.lines.count()+ )+ checkout_lines_from_response_map = {+ line["variant"]["id"]: line for line in checkout_lines_from_response+ }+ assert not data["unavailableVariants"]+ assert data["checkout"]["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ _assert_checkout_lines(+ order_lines_map, checkout_lines, checkout_lines_from_response_map+ )diff --git a/saleor/graphql/core/validators/__init__.py b/saleor/graphql/core/validators/__init__.pyindex ced850c155..26512a0d62 100644--- a/saleor/graphql/core/validators/__init__.py+++ b/saleor/graphql/core/validators/__init__.py@@ -94,30 +94,39 @@ def validate_decimal_max_value(value: "Decimal", max_value=10**9):raise ValidationError(f"Value must be lower than {max_value}.")-def validate_variants_available_in_channel(- variants_id,- channel_id,- error_code,-):- """Validate available variants in specific channel."""-+def get_not_available_variants_in_channel(+ variants_id: set, channel_id: int+) -> tuple[set[int], set[str]]:available_variants = ProductVariantChannelListing.objects.filter(variant__id__in=variants_id,channel_id=channel_id,price_amount__isnull=False,).values_list("variant_id", flat=True)not_available_variants = variants_id - set(available_variants)+ not_available_graphql_ids = {+ graphene.Node.to_global_id("ProductVariant", pk)+ for pk in not_available_variants+ }+ return not_available_variants, not_available_graphql_ids+++def validate_variants_available_in_channel(+ variants_id: set,+ channel_id: int,+ error_code: str,+):+ """Validate available variants in specific channel."""+ (+ not_available_variants,+ not_available_graphql_ids,+ ) = get_not_available_variants_in_channel(variants_id, channel_id)if not_available_variants:- not_available_variants_ids = {- graphene.Node.to_global_id("ProductVariant", pk)- for pk in not_available_variants- }raise ValidationError({"lines": ValidationError("Cannot add lines with unavailable variants.",code=error_code,- params={"variants": not_available_variants_ids},+ params={"variants": not_available_graphql_ids},)})diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.pyindex df58f77f8a..72b573d3e4 100644--- a/saleor/graphql/order/utils.py+++ b/saleor/graphql/order/utils.py@@ -152,7 +152,9 @@ def validate_variants_is_available(order: "Order", errors: T_ERRORS):variants_ids = {line.variant_id for line in order.lines.all()}try:validate_variants_available_in_channel(- variants_ids, order.channel_id, OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL+ variants_ids,+ order.channel_id,+ OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.value,)except ValidationError as e:errors["lines"].extend(e.error_dict["lines"])@@ -223,7 +225,7 @@ def validate_variant_channel_listings(variant_ids = {variant.id for variant in variants}validate_variants_available_in_channel(- variant_ids, channel.id, OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL+ variant_ids, channel.id, OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.value)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex e5ceb04436..d802136836 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -15693,6 +15693,18 @@ type Mutation {input: CheckoutCreateInput!): CheckoutCreate @doc(category: "Checkout")+ """+ Create new checkout from existing order.++ Added in Saleor 3.14.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ checkoutCreateFromOrder(+ """ID of a order that will be used to create the checkout."""+ id: ID!+ ): CheckoutCreateFromOrder @doc(category: "Checkout")+"""Sets the customer as the owner of the checkout.@@ -23847,6 +23859,68 @@ input CheckoutValidationRules @doc(category: "Checkout") {billingAddress: CheckoutAddressValidationRules}+"""+Create new checkout from existing order.++Added in Saleor 3.14.++Note: this API is currently in Feature Preview and can be subject to changes at later point.+"""+type CheckoutCreateFromOrder @doc(category: "Checkout") {+ """Variants that were not attached to the checkout."""+ unavailableVariants: [CheckoutCreateFromOrderUnavailableVariant!]++ """Created checkout."""+ checkout: Checkout+ errors: [CheckoutCreateFromOrderError!]!+}++type CheckoutCreateFromOrderUnavailableVariant @doc(category: "Checkout") {+ """The error message."""+ message: String!++ """The error code."""+ code: CheckoutCreateFromOrderUnavailableVariantErrorCode!++ """Variant ID that is unavailable."""+ variantId: ID!++ """Order line ID that is unavailable."""+ lineId: ID!+}++"""An enumeration."""+enum CheckoutCreateFromOrderUnavailableVariantErrorCode @doc(category: "Checkout") {+ NOT_FOUND+ PRODUCT_UNAVAILABLE_FOR_PURCHASE+ UNAVAILABLE_VARIANT_IN_CHANNEL+ PRODUCT_NOT_PUBLISHED+ QUANTITY_GREATER_THAN_LIMIT+ INSUFFICIENT_STOCK+}++type CheckoutCreateFromOrderError @doc(category: "Checkout") {+ """+ 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: CheckoutCreateFromOrderErrorCode!+}++"""An enumeration."""+enum CheckoutCreateFromOrderErrorCode @doc(category: "Checkout") {+ GRAPHQL_ERROR+ INVALID+ ORDER_NOT_FOUND+ CHANNEL_INACTIVE+ TAX_ERROR+}+"""Sets the customer as the owner of the checkout.