Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix draft order complete with unavailable variants (#7204)
Damian Wysocki9357c3cdd863
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 1322eda4f6..4fdfe68713 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -1,9 +1,11 @@+import datetimefrom typing import TYPE_CHECKING, Iterable, List, Optional, Tupleimport graphenefrom django.conf import settingsfrom django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.db import transaction+from django.db.models import Qfrom ...channel.exceptions import ChannelNotDefinedfrom ...channel.models import Channel@@ -35,6 +37,7 @@ from ...core.exceptions import InsufficientStock, PermissionDenied, ProductNotPufrom ...core.transactions import transaction_with_commit_on_errorsfrom ...order import models as order_modelsfrom ...product import models as product_models+from ...product.models import ProductChannelListingfrom ...shipping import models as shipping_modelsfrom ...warehouse.availability import check_stock_quantity_bulkfrom ..account.i18n import I18nMixin@@ -43,6 +46,7 @@ from ..core.enums import LanguageCodeEnumfrom ..core.mutations import BaseMutation, ModelMutationfrom ..core.types.common import CheckoutErrorfrom ..core.utils import from_global_id_or_error+from ..core.validators import validate_variants_available_in_channelfrom ..order.types import Orderfrom ..product.types import ProductVariantfrom ..shipping.types import ShippingMethod@@ -145,56 +149,34 @@ def check_lines_quantity(variants, quantities, country, channel_slug):raise ValidationError({"quantity": errors})-def validate_variants_available_for_purchase(variants, channel_id):- not_available_variants = []- for variant in variants:- product_channel_listing = variant.product.channel_listings.filter(- channel_id=channel_id- ).first()- if not (- product_channel_listing- and product_channel_listing.is_available_for_purchase()- ):- not_available_variants.append(variant.pk)-+def validate_variants_available_for_purchase(variants_id: set, channel_id: int):+ today = datetime.date.today()+ is_available_for_purchase = Q(+ available_for_purchase__lte=today,+ product__variants__id__in=variants_id,+ channel_id=channel_id,+ )+ available_variants = ProductChannelListing.objects.filter(+ is_available_for_purchase+ ).values_list("product__variants__id", flat=True)+ not_available_variants = variants_id.difference(set(available_variants))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_PURCHASEraise ValidationError({"lines": ValidationError("Cannot add lines for unavailable for purchase variants.",- code=CheckoutErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE,+ code=error_code, # type: ignoreparams={"variants": variant_ids},)})-def validate_variants_available_in_channel(variants, channel_id):- variants_id = {variant.id for variant in variants}- available_variants = product_models.ProductVariantChannelListing.objects.filter(- variant__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)- 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=CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL,- params={"variants": not_available_variants_ids},- )- }- )--class CheckoutLineInput(graphene.InputObjectType):quantity = graphene.Int(required=True, description="The number of items purchased.")variant_id = graphene.ID(required=True, description="ID of the product variant.")@@ -263,8 +245,11 @@ class CheckoutCreate(ModelMutation, I18nMixin):)quantities = [line["quantity"] for line in lines]- validate_variants_available_for_purchase(variants, channel.id)- validate_variants_available_in_channel(variants, channel.id)+ 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+ )check_lines_quantity(variants, quantities, country, channel.slug)return variants, quantities@@ -468,8 +453,13 @@ class CheckoutLinesAdd(BaseMutation):check_lines_quantity(variants, quantities, checkout.get_country(), checkout_info.channel.slug)- validate_variants_available_for_purchase(variants, checkout.channel_id)- validate_variants_available_in_channel(variants, checkout.channel_id)+ variants_db_ids = {variant.id for variant in variants}+ validate_variants_available_for_purchase(variants_db_ids, checkout.channel_id)+ validate_variants_available_in_channel(+ variants_db_ids,+ checkout.channel_id,+ CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL,+ )if variants and quantities:for variant, quantity in zip(variants, quantities):@@ -952,8 +942,12 @@ class CheckoutComplete(BaseMutation):manager = info.context.pluginslines = fetch_checkout_lines(checkout)- variants = [line.variant for line in lines]- validate_variants_available_in_channel(variants, checkout.channel)+ variants_id = {line.variant.id for line in lines}+ validate_variants_available_in_channel(+ variants_id,+ checkout.channel,+ CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL,+ )checkout_info = fetch_checkout_info(checkout, lines, info.context.discounts, manager)diff --git a/saleor/graphql/core/validators.py b/saleor/graphql/core/validators.pyindex 73958ef288..566ad88f8c 100644--- a/saleor/graphql/core/validators.py+++ b/saleor/graphql/core/validators.py@@ -1,9 +1,12 @@from typing import TYPE_CHECKING, Optional+import graphenefrom django.core.exceptions import ValidationErrorfrom django_prices.utils.formatting import get_currency_fractionfrom graphql.error import GraphQLError+from ...product.models import ProductVariantChannelListing+if TYPE_CHECKING:from decimal import Decimal@@ -42,3 +45,30 @@ def validate_price_precision(value: Optional["Decimal"], currency: str):raise ValidationError(f"Value cannot have more than {currency_fraction} decimal places.")+++def validate_variants_available_in_channel(+ variants_id,+ channel_id,+ error_code,+):+ """Validate available variants in specific channel."""++ 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)+ 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},+ )+ }+ )diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.pyindex 5f736fc766..91f660f109 100644--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@ -154,14 +154,8 @@ class DraftOrderCreate(ModelMutation, I18nMixin):if lines:variant_ids = [line.get("variant_id") for line in lines]variants = cls.get_nodes_or_error(variant_ids, "variants", ProductVariant)- try:- validate_product_is_published_in_channel(variants, channel)- validate_variant_channel_listings(variants, channel)- except ValidationError as error:- field_name = "lines"- if error.code == OrderErrorCode.REQUIRED:- field_name = "channel"- raise ValidationError({field_name: error})+ validate_product_is_published_in_channel(variants, channel)+ validate_variant_channel_listings(variants, channel)quantities = [line.get("quantity") for line in lines]if not all(quantity > 0 for quantity in quantities):raise ValidationError(diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex 1328810273..d3a7433046 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -648,6 +648,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):permissions = (OrderPermissions.MANAGE_ORDERS,)error_type_class = OrderErrorerror_type_field = "order_errors"+ errors_mapping = {"lines": "input", "channel": "input"}@classmethoddef validate_lines(cls, info, data):@@ -675,14 +676,15 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):)return lines_to_add- @staticmethod- def validate_variants(order, variants):+ @classmethod+ def validate_variants(cls, order, variants):try:channel = order.channelvalidate_product_is_published_in_channel(variants, channel)validate_variant_channel_listings(variants, channel)except ValidationError as error:- raise ValidationError({"input": error})+ cls.remap_error_fields(error, cls._meta.errors_mapping)+ raise ValidationError(error)@staticmethoddef add_lines_to_order(order, lines_to_add, user, manager):diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.pyindex 6c0df22018..031cfe5c07 100644--- a/saleor/graphql/order/tests/test_order.py+++ b/saleor/graphql/order/tests/test_order.py@@ -2462,6 +2462,7 @@ DRAFT_ORDER_COMPLETE_MUTATION = """orderErrors {fieldcode+ variants}order {status@@ -2536,6 +2537,32 @@ def test_draft_order_complete_with_inactive_channel(assert data["orderErrors"][0]["field"] == "channel"+def test_draft_order_complete_with_unavailable_variant(+ staff_api_client,+ permission_manage_orders,+ staff_user,+ draft_order,+):+ order = draft_order+ variant = order.lines.first().variant+ variant.channel_listings.filter(channel=order.channel).delete()++ order_id = graphene.Node.to_global_id("Order", order.id)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)++ variables = {"id": order_id}+ response = staff_api_client.post_graphql(+ DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ data = content["data"]["draftOrderComplete"]+ assert (+ data["orderErrors"][0]["code"] == OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.name+ )+ assert data["orderErrors"][0]["field"] == "lines"+ assert data["orderErrors"][0]["variants"] == [variant_id]++def test_draft_order_complete_channel_without_shipping_zones(staff_api_client,permission_manage_orders,diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.pyindex 9d42b4ce4b..a4ca5ee2b7 100644--- a/saleor/graphql/order/utils.py+++ b/saleor/graphql/order/utils.py@@ -3,8 +3,9 @@ from django.core.exceptions import ValidationErrorfrom ...core.exceptions import InsufficientStockfrom ...order.error_codes import OrderErrorCode-from ...product.models import Product, ProductVariant, ProductVariantChannelListing+from ...product.models import Product, ProductVariantfrom ...warehouse.availability import check_stock_quantity+from ..core.validators import validate_variants_available_in_channeldef validate_total_quantity(order):@@ -97,10 +98,15 @@ def validate_order_lines(order, country):raise ValidationError({"lines": errors})+def validate_variants_is_available(order):+ variants_ids = {line.variant_id for line in order.lines.all()}+ validate_variants_available_in_channel(+ variants_ids, order.channel_id, OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL+ )++def validate_product_is_published(order):- variant_ids = []- for line in order.lines.all():- variant_ids.append(line.variant_id)+ variant_ids = [line.variant_id for line in order.lines.all()]unpublished_product = Product.objects.filter(variants__id__in=variant_ids).not_published(order.channel.slug)@@ -118,8 +124,12 @@ def validate_product_is_published(order):def validate_product_is_published_in_channel(variants, channel):if not channel:raise ValidationError(- "Can't add product variant for draft order without channel",- code=OrderErrorCode.REQUIRED,+ {+ "channel": ValidationError(+ "Can't add product variant for draft order without channel",+ code=OrderErrorCode.REQUIRED,+ )+ })variant_ids = [variant.id for variant in variants]unpublished_product = list(@@ -134,41 +144,32 @@ def validate_product_is_published_in_channel(variants, channel):for unpublished_variant in unpublished_variants]raise ValidationError(- "Can't add product variant that are not published in "- "the channel associated with this draft order.",- code=OrderErrorCode.PRODUCT_NOT_PUBLISHED,- params={"variants": unpublished_variants_global_ids},+ {+ "lines": ValidationError(+ "Can't add product variant that are not published in "+ "the channel associated with this draft order.",+ code=OrderErrorCode.PRODUCT_NOT_PUBLISHED,+ params={"variants": unpublished_variants_global_ids},+ )+ })def validate_variant_channel_listings(variants, channel):if not channel:raise ValidationError(- "Can't add product variant for draft order without channel",- code=OrderErrorCode.REQUIRED,+ {+ "channel": ValidationError(+ "Can't add product variant for draft order without channel",+ code=OrderErrorCode.REQUIRED,+ )+ })- variant_ids = set([variant.id for variant in variants])- variant_channel_listings = ProductVariantChannelListing.objects.filter(- channel=channel, variant_id__in=variant_ids, price_amount__isnull=False- )- variant_ids_in_channel = set(- [- variant_channel_listing.variant_id- for variant_channel_listing in 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)- missing_variant_ids_in_channel = variant_ids - variant_ids_in_channel- if missing_variant_ids_in_channel:- missing_variant_global_ids = [- graphene.Node.to_global_id("ProductVariant", missing_variant_id_in_channel)- for missing_variant_id_in_channel in missing_variant_ids_in_channel- ]- raise ValidationError(- "Can't add product variant that are don't have price in"- "the channel associated with this draft order.",- code=OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL,- params={"variants": missing_variant_global_ids},- )def validate_product_is_available_for_purchase(order):@@ -219,9 +220,10 @@ def validate_draft_order(order, country):validate_shipping_method(order)validate_total_quantity(order)validate_order_lines(order, country)+ validate_channel_is_active(order.channel)validate_product_is_published(order)validate_product_is_available_for_purchase(order)- validate_channel_is_active(order.channel)+ validate_variants_is_available(order)def prepare_insufficient_stock_order_validation_errors(exc):