Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Prevent creating checkout with unpublished product
Damian W1ce497b1ba62
diff --git a/saleor/checkout/error_codes.py b/saleor/checkout/error_codes.pyindex 3fbdefef44..4792af1245 100644--- a/saleor/checkout/error_codes.py+++ b/saleor/checkout/error_codes.py@@ -5,6 +5,7 @@ class CheckoutErrorCode(Enum):BILLING_ADDRESS_NOT_SET = "billing_address_not_set"CHECKOUT_NOT_FULLY_PAID = "checkout_not_fully_paid"GRAPHQL_ERROR = "graphql_error"+ PRODUCT_NOT_PUBLISHED = "product_not_published"INSUFFICIENT_STOCK = "insufficient_stock"INVALID = "invalid"INVALID_SHIPPING_METHOD = "invalid_shipping_method"diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex e8e9d1709f..ce8c68839a 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -15,6 +15,7 @@ from ..account.models import Userfrom ..account.utils import store_user_addressfrom ..checkout import calculationsfrom ..checkout.error_codes import CheckoutErrorCode+from ..core.exceptions import ProductNotPublishedfrom ..core.taxes import quantize_price, zero_taxed_moneyfrom ..core.utils.promo_code import (InvalidPromoCode,@@ -129,6 +130,8 @@ def add_variant_to_checkout(If `replace` is truthy then any previous quantity is discarded insteadof added to."""+ if not variant.product.is_published:+ raise ProductNotPublished()new_quantity, line = check_variant_in_stock(checkout,diff --git a/saleor/core/exceptions.py b/saleor/core/exceptions.pyindex 2269677488..532304bb06 100644--- a/saleor/core/exceptions.py+++ b/saleor/core/exceptions.py@@ -24,3 +24,10 @@ class ReadOnlyException(Exception):if msg is None:msg = "API runs in read-only mode"super().__init__(msg)+++class ProductNotPublished(Exception):+ def __init__(self, context=None):+ super().__init__(f"Can't create checkout with unpublished product.")+ self.context = context+ self.code = CheckoutErrorCode.PRODUCT_NOT_PUBLISHEDdiff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex b1d94dbe10..41b18c41ae 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -24,7 +24,7 @@ from ...checkout.utils import (remove_promo_code_from_checkout,)from ...core import analytics-from ...core.exceptions import InsufficientStock+from ...core.exceptions import InsufficientStock, ProductNotPublishedfrom ...core.permissions import OrderPermissionsfrom ...core.taxes import TaxErrorfrom ...core.utils.url import validate_storefront_url@@ -283,7 +283,11 @@ class CheckoutCreate(ModelMutation, I18nMixin):raise ValidationError(f"Insufficient product stock: {exc.item}", code=exc.code)-+ except ProductNotPublished as exc:+ raise ValidationError(+ f"Can't create checkout with unpublished product.",+ code=exc.code,+ )# Save provided addresses and associate them to the checkoutcls.save_addresses(instance, cleaned_input)@@ -354,6 +358,11 @@ class CheckoutLinesAdd(BaseMutation):raise ValidationError(f"Insufficient product stock: {exc.item}", code=exc.code)+ except ProductNotPublished as exc:+ raise ValidationError(+ f"Can't create checkout with unpublished product.",+ code=exc.code,+ )lines = list(checkout)diff --git a/saleor/graphql/core/fields.py b/saleor/graphql/core/fields.pyindex e612d01d25..10fe26325d 100644--- a/saleor/graphql/core/fields.py+++ b/saleor/graphql/core/fields.py@@ -192,7 +192,6 @@ class FilterInputConnectionField(PrefetchingConnectionField):on_resolve = partial(cls.resolve_connection, connection, args)filter_input = args.get(filters_name)-if filter_input and filterset_class:instance = filterset_class(data=dict(filter_input), queryset=iterable, request=info.contextdiff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 4332a68854..887cde4e93 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -867,6 +867,7 @@ enum CheckoutErrorCode {BILLING_ADDRESS_NOT_SETCHECKOUT_NOT_FULLY_PAIDGRAPHQL_ERROR+ PRODUCT_NOT_PUBLISHEDINSUFFICIENT_STOCKINVALIDINVALID_SHIPPING_METHODdiff --git a/tests/api/benchmark/test_checkout_mutations.py b/tests/api/benchmark/test_checkout_mutations.pyindex 2f06ba736c..768a651e05 100644--- a/tests/api/benchmark/test_checkout_mutations.py+++ b/tests/api/benchmark/test_checkout_mutations.py@@ -228,6 +228,50 @@ def test_create_checkout(assert checkout_counts + 1 == Checkout.objects.count()[email protected]_queries(autouse=False)+def test_create_checkout_with_unpublished_product(+ api_client, graphql_address_data, stock, count_queries,+):+ stock.product_variant.product.is_published = False+ stock.product_variant.product.save()+ query = (+ FRAGMENT_CHECKOUT+ + """+ mutation CreateCheckout($checkoutInput: CheckoutCreateInput!) {+ checkoutCreate(input: $checkoutInput) {+ errors {+ field+ message+ }+ checkout {+ ...Checkout+ }+ }+ }+ """+ )++ variables = {+ "checkoutInput": {+ "email": "[email protected]",+ "shippingAddress": graphql_address_data,+ "lines": [+ {+ "quantity": 1,+ "variantId": Node.to_global_id(+ "ProductVariant", stock.product_variant.pk+ ),+ },+ ],+ }+ }+ response = get_graphql_content(api_client.post_graphql(query, variables))++ error = response["data"]["checkoutCreate"]["errors"][0]+ assert error["message"] == "Can't create checkout with unpublished product."++@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)def test_add_shipping_to_checkout(diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.pyindex 9daf0b4613..c6404899d6 100644--- a/tests/api/test_checkout.py+++ b/tests/api/test_checkout.py@@ -754,6 +754,28 @@ def test_checkout_lines_add()+def test_checkout_lines_add_with_unpublished_product(+ user_api_client, checkout_with_item, stock+):+ variant = stock.product_variant+ stock.product_variant.product.is_published = False+ stock.product_variant.product.save()++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)++ variables = {+ "checkoutId": checkout_id,+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }++ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)++ content = get_graphql_content(response)+ error = content["data"]["checkoutLinesAdd"]["errors"][0]+ assert error["message"] == "Can't create checkout with unpublished product."++def test_checkout_lines_add_too_many(user_api_client, checkout_with_item, stock):variant = stock.product_variantvariant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)@@ -909,6 +931,28 @@ def test_checkout_lines_update()+def test_checkout_lines_update_with_unpublished_product(+ user_api_client, checkout_with_item+):+ checkout = checkout_with_item+ line = checkout.lines.first()+ variant = line.variant+ variant.product.is_published = False+ variant.product.save()++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)++ variables = {+ "checkoutId": checkout_id,+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)++ error = get_graphql_content(response)["data"]["checkoutLinesUpdate"]["errors"][0]+ assert error["message"] == "Can't create checkout with unpublished product."++def test_checkout_lines_update_invalid_checkout_id(user_api_client):variables = {"checkoutId": "test", "lines": []}response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)diff --git a/tests/conftest.py b/tests/conftest.pyindex 08c126a1c7..1969c1c450 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -928,7 +928,7 @@ def product_list(product_type, category, warehouse):price=Money(20, "USD"),category=category,product_type=product_type,- is_published=False,+ is_published=True,),Product(pk=1489,diff --git a/tests/test_product_availability.py b/tests/test_product_availability.pyindex fdb6579325..0432bd8639 100644--- a/tests/test_product_availability.py+++ b/tests/test_product_availability.py@@ -160,6 +160,10 @@ def test_availability(stock, monkeypatch, settings):def test_available_products_only_published(product_list):+ product = product_list[0]+ product.is_published = False+ product.save()+available_products = models.Product.objects.published()assert available_products.count() == 2assert all([product.is_published for product in available_products])@@ -171,5 +175,5 @@ def test_available_products_only_available(product_list):product.publication_date = date_tomorrowproduct.save()available_products = models.Product.objects.published()- assert available_products.count() == 1+ assert available_products.count() == 2assert all([product.is_visible for product in available_products])