Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Drop product channel listings when removing last available variant (#9232)
Iga Karbowiakb92d3b686b3a
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.pyindex f7b3601a1c..88931425b2 100644--- a/saleor/graphql/product/bulk_mutations/products.py+++ b/saleor/graphql/product/bulk_mutations/products.py@@ -1,9 +1,12 @@from collections import defaultdict+from typing import Iterableimport graphenefrom django.core.exceptions import ValidationErrorfrom django.db import transaction-from django.db.models import Q+from django.db.models import Exists, OuterRef, Q, Subquery+from django.db.models.fields import IntegerField+from django.db.models.functions import Coalescefrom graphene.types import InputObjectTypefrom ....attribute import AttributeInputType@@ -605,6 +608,7 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):)cls.delete_assigned_attribute_values(pks)+ cls.delete_product_channel_listings_without_available_variants(product_pks, pks)response = super().perform_mutation(_root, info, ids, **data)transaction.on_commit(@@ -650,6 +654,38 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,).delete()+ @staticmethod+ def delete_product_channel_listings_without_available_variants(+ product_pks: Iterable[int], variant_pks: Iterable[int]+ ):+ """Delete invalid channel listings.++ Delete product channel listings for product and channel for which+ the last available variant has been deleted.+ """+ variants = models.ProductVariant.objects.filter(+ product_id__in=product_pks+ ).exclude(id__in=variant_pks)++ variant_subquery = Subquery(+ queryset=variants.filter(id=OuterRef("variant_id")).values("product_id"),+ output_field=IntegerField(),+ )+ variant_channel_listings = models.ProductVariantChannelListing.objects.annotate(+ product_id=Coalesce(variant_subquery, 0)+ )++ invalid_product_channel_listings = models.ProductChannelListing.objects.filter(+ product_id__in=product_pks+ ).exclude(+ Exists(+ variant_channel_listings.filter(+ channel_id=OuterRef("channel_id"), product_id=OuterRef("product_id")+ )+ )+ )+ invalid_product_channel_listings.delete()+class ProductVariantStocksCreate(BaseMutation):product_variant = graphene.Field(diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex 47b56e974d..3df37a0aa7 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -5,7 +5,7 @@ from typing import List, Tupleimport graphenefrom django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.db import transaction-from django.db.models import Q+from django.db.models import Exists, OuterRef, Qfrom django.utils.text import slugifyfrom ....attribute import AttributeInputType, AttributeType@@ -1146,6 +1146,7 @@ class ProductVariantDelete(ModelDeleteMutation):).get(id=instance.id)cls.delete_assigned_attribute_values(variant)+ cls.delete_product_channel_listings_without_available_variants(variant)response = super().perform_mutation(_root, info, **data)# delete order lines for deleted variant@@ -1177,6 +1178,35 @@ class ProductVariantDelete(ModelDeleteMutation):attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,).delete()+ @staticmethod+ def delete_product_channel_listings_without_available_variants(instance):+ """Delete invalid product channel listings.++ Delete product channel listings for channels for which the deleted variant+ was the last available variant.+ """+ channel_ids = set(+ instance.channel_listings.values_list("channel_id", flat=True)+ )+ product_id = instance.product_id+ variants = (+ models.ProductVariant.objects.filter(product_id=product_id)+ .exclude(id=instance.id)+ .values("id")+ )+ available_channel_ids = set(+ models.ProductVariantChannelListing.objects.filter(+ Exists(+ variants.filter(id=OuterRef("variant_id")),+ channel_id__in=channel_ids,+ )+ ).values_list("channel_id", flat=True)+ )+ not_available_channel_ids = channel_ids - available_channel_ids+ models.ProductChannelListing.objects.filter(+ product_id=product_id, channel_id__in=not_available_channel_ids+ ).delete()+class ProductTypeInput(graphene.InputObjectType):name = graphene.String(description="Name of the product type.")diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.pyindex 335ed810e9..7e01665dc6 100644--- a/saleor/graphql/product/tests/test_bulk_delete.py+++ b/saleor/graphql/product/tests/test_bulk_delete.py@@ -1343,3 +1343,64 @@ def test_delete_product_variants_from_different_products(assert product_1.default_variant is Noneassert product_2.default_variant.pk == product_2_second_variant.pkmocked_recalculate_orders_task.assert_not_called()+++@patch("saleor.order.tasks.recalculate_orders_task.delay")+def test_delete_variants_delete_product_channel_listing_without_available_channel(+ mocked_recalculate_orders_task,+ staff_api_client,+ product,+ product_with_two_variants,+ permission_manage_products,+):+ """Ensure that when the last available variant for channel is removed,+ the corresponging product channel listings will be removed too, and when+ any available variant for channel exist the product channel listing will+ be not removed."""+ # given+ query = PRODUCT_VARIANT_BULK_DELETE_MUTATION++ product_1 = product+ product_2 = product_with_two_variants++ product_1_default_variant = product_1.variants.first()+ product_2_default_variant = product_2.variants.first()++ product_1.default_variant = product_1_default_variant+ product_2.default_variant = product_2_default_variant++ Product.objects.bulk_update([product_1, product_2], ["default_variant"])++ product_2_second_variant = product_2.variants.last()++ assert product_1.channel_listings.count() > 0+ product_2_channel_listings_count = product_2.channel_listings.count()++ variables = {+ "ids": [+ graphene.Node.to_global_id("ProductVariant", product_1_default_variant.id),+ graphene.Node.to_global_id("ProductVariant", product_2_default_variant.id),+ ]+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)++ assert content["data"]["productVariantBulkDelete"]["count"] == 2+ assert not ProductVariant.objects.filter(+ id__in=[product_1_default_variant.id, product_2_default_variant.id]+ ).exists()++ product_1.refresh_from_db()+ product_2.refresh_from_db()++ assert product_1.default_variant is None+ assert product_2.default_variant.pk == product_2_second_variant.pk+ assert product_1.channel_listings.count() == 0+ assert product_2.channel_listings.count() == product_2_channel_listings_count+ mocked_recalculate_orders_task.assert_not_called()diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.pyindex 168a7e687a..17dbfee96e 100644--- a/saleor/graphql/product/tests/test_variant.py+++ b/saleor/graphql/product/tests/test_variant.py@@ -3650,6 +3650,92 @@ def test_delete_default_all_product_variant_left_product_default_variant_unset(mocked_recalculate_orders_task.assert_not_called()+@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")+@patch("saleor.order.tasks.recalculate_orders_task.delay")+def test_delete_variant_delete_product_channel_listing_without_available_channel(+ mocked_recalculate_orders_task,+ product_variant_deleted_webhook_mock,+ staff_api_client,+ product,+ permission_manage_products,+):+ """Ensure that when the last available variant for channel is removed,+ the corresponging product channel listings will be removed too."""+ # given+ query = DELETE_VARIANT_MUTATION+ variant = product.variants.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ variant_sku = variant.sku+ variables = {"id": variant_id}++ # second variant not available+ ProductVariant.objects.create(product=product, sku="not-available-variant")++ assert product.channel_listings.count() == 1++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ flush_post_commit_hooks()+ data = content["data"]["productVariantDelete"]++ product_variant_deleted_webhook_mock.assert_called_once_with(variant)+ assert data["productVariant"]["sku"] == variant_sku+ with pytest.raises(variant._meta.model.DoesNotExist):+ variant.refresh_from_db()+ mocked_recalculate_orders_task.assert_not_called()+ product.refresh_from_db()+ assert product.search_document+ assert variant_sku not in product.search_document+ assert product.channel_listings.count() == 0+++@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")+@patch("saleor.order.tasks.recalculate_orders_task.delay")+def test_delete_variant_delete_product_channel_listing_not_deleted(+ mocked_recalculate_orders_task,+ product_variant_deleted_webhook_mock,+ staff_api_client,+ product_with_two_variants,+ permission_manage_products,+):+ """Ensure that any other available variant for channel exist,+ the corresponging product channel listings will be not removed."""+ # given+ query = DELETE_VARIANT_MUTATION+ product = product_with_two_variants+ variant = product.variants.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ variant_sku = variant.sku+ variables = {"id": variant_id}++ product_channel_listing_count = product.channel_listings.count()++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ flush_post_commit_hooks()+ data = content["data"]["productVariantDelete"]++ product_variant_deleted_webhook_mock.assert_called_once_with(variant)+ assert data["productVariant"]["sku"] == variant_sku+ with pytest.raises(variant._meta.model.DoesNotExist):+ variant.refresh_from_db()+ mocked_recalculate_orders_task.assert_not_called()+ product.refresh_from_db()+ assert product.search_document+ assert variant_sku not in product.search_document+ assert product.channel_listings.count() == product_channel_listing_count++def _fetch_all_variants(client, variables={}, permissions=None):query = """query fetchAllVariants($channel: String) {