Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix remove channel without orders (#6600)
Filip Owczarek45b9ac977847
diff --git a/saleor/channel/error_codes.py b/saleor/channel/error_codes.pyindex 0413aa88d4..33d0a77830 100644--- a/saleor/channel/error_codes.py+++ b/saleor/channel/error_codes.py@@ -10,3 +10,4 @@ class ChannelErrorCode(Enum):UNIQUE = "unique"CHANNEL_TARGET_ID_MUST_BE_DIFFERENT = "channel_target_id_must_be_different"CHANNELS_CURRENCY_MUST_BE_THE_SAME = "channels_currency_must_be_the_same"+ CHANNEL_WITH_ORDERS = "channel_with_orders"diff --git a/saleor/graphql/channel/dataloaders.py b/saleor/graphql/channel/dataloaders.pyindex 15c053715c..a14111fc27 100644--- a/saleor/graphql/channel/dataloaders.py+++ b/saleor/graphql/channel/dataloaders.py@@ -1,4 +1,7 @@+from django.db.models import Exists, OuterRef+from ...channel.models import Channel+from ...order.models import Orderfrom ..checkout.dataloaders import CheckoutByIdLoader, CheckoutLineByIdLoaderfrom ..core.dataloaders import DataLoaderfrom ..order.dataloaders import OrderByIdLoader, OrderLineByIdLoader@@ -62,3 +65,12 @@ class ChannelByOrderLineIdLoader(DataLoader):)return OrderLineByIdLoader(self.context).load_many(keys).then(channel_by_lines)+++class ChannelWithHasOrdersByIdLoader(DataLoader):+ context_key = "channel_with_has_orders_by_id"++ def batch_load(self, keys):+ orders = Order.objects.filter(channel=OuterRef("pk"))+ channels = Channel.objects.annotate(has_orders=Exists(orders)).in_bulk(keys)+ return [channels.get(channel_id) for channel_id in keys]diff --git a/saleor/graphql/channel/mutations.py b/saleor/graphql/channel/mutations.pyindex 1b713b46fd..36352ba465 100644--- a/saleor/graphql/channel/mutations.py+++ b/saleor/graphql/channel/mutations.py@@ -95,9 +95,7 @@ class ChannelDeleteInput(graphene.InputObjectType):class ChannelDelete(ModelDeleteMutation):class Arguments:id = graphene.ID(required=True, description="ID of a channel to delete.")- input = ChannelDeleteInput(- required=True, description="Fields required to delete a channel."- )+ input = ChannelDeleteInput(description="Fields required to delete a channel.")class Meta:description = (@@ -137,32 +135,51 @@ class ChannelDelete(ModelDeleteMutation):)@classmethod- def perform_delete(cls, origin_channel, target_channel):+ def migrate_orders_to_target_channel(cls, origin_channel_id, target_channel_id):+ Order.objects.select_for_update().filter(channel_id=origin_channel_id).update(+ channel=target_channel_id+ )++ @classmethod+ def delete_checkouts(cls, origin_channel_id):+ Checkout.objects.select_for_update().filter(+ channel_id=origin_channel_id+ ).delete()++ @classmethod+ def perform_delete_with_order_migration(cls, origin_channel, target_channel):cls.validate_input(origin_channel, target_channel)with transaction.atomic():origin_channel_id = origin_channel.id- cls.migrate_orders_to_target_channel(origin_channel_id, target_channel.id)cls.delete_checkouts(origin_channel_id)+ cls.migrate_orders_to_target_channel(origin_channel_id, target_channel.id)@classmethod- def migrate_orders_to_target_channel(cls, origin_channel, target_channel):- Order.objects.select_for_update().filter(channel_id=origin_channel).update(- channel=target_channel- )-- @classmethod- def delete_checkouts(cls, origin_channel):- Checkout.objects.select_for_update().filter(channel_id=origin_channel).delete()+ def perform_delete_channel_without_order(cls, origin_channel):+ if Order.objects.filter(channel=origin_channel).exists():+ raise ValidationError(+ {+ "id": ValidationError(+ "Cannot remove channel with orders. Try to migrate orders to "+ "another channel by passing `targetChannel` param.",+ code=ChannelErrorCode.CHANNEL_WITH_ORDERS,+ )+ }+ )+ cls.delete_checkouts(origin_channel.id)@classmethoddef perform_mutation(cls, _root, info, **data):origin_channel = cls.get_node_or_error(info, data["id"], only_type=Channel)- target_channel = cls.get_node_or_error(- info, data["input"]["target_channel"], only_type=Channel- )-- cls.perform_delete(origin_channel, target_channel)+ target_channel_global_id = data.get("input", {}).get("target_channel")+ if target_channel_global_id:+ target_channel = cls.get_node_or_error(+ info, target_channel_global_id, only_type=Channel+ )+ cls.perform_delete_with_order_migration(origin_channel, target_channel)+ else:+ cls.perform_delete_channel_without_order(origin_channel)return super().perform_mutation(_root, info, **data)diff --git a/saleor/graphql/channel/tests/test_channel_delete_mutations.py b/saleor/graphql/channel/tests/test_channel_delete_mutations.pyindex 817fd6aa7f..71c35cd3db 100644--- a/saleor/graphql/channel/tests/test_channel_delete_mutations.py+++ b/saleor/graphql/channel/tests/test_channel_delete_mutations.py@@ -1,11 +1,13 @@import graphenefrom ....channel.error_codes import ChannelErrorCode+from ....channel.models import Channelfrom ....checkout.models import Checkout+from ....order.models import Orderfrom ...tests.utils import assert_no_permission, get_graphql_contentCHANNEL_DELETE_MUTATION = """- mutation deleteChannel($id: ID!,$input: ChannelDeleteInput!){+ mutation deleteChannel($id: ID!, $input: ChannelDeleteInput){channelDelete(id: $id, input: $input){channel{id@@ -52,6 +54,7 @@ def test_channel_delete_mutation_as_staff_user(assert order.channel == other_channel_USDassert Checkout.objects.first() is None+ assert not Channel.objects.filter(slug=channel_USD.slug).exists()def test_channel_delete_mutation_with_the_same_channel_and_target_channel_id(@@ -74,6 +77,55 @@ def test_channel_delete_mutation_with_the_same_channel_and_target_channel_id(assert error["code"] == ChannelErrorCode.CHANNEL_TARGET_ID_MUST_BE_DIFFERENT.name+def test_channel_delete_mutation_without_migration_channel_with_orders(+ permission_manage_channels, staff_api_client, channel_USD, checkout, order_list,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {"id": channel_id}+ checkout = Checkout.objects.first()+ assert checkout.channel == channel_USD+ assert Order.objects.filter(channel=channel_USD).exists()++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_DELETE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["channelDelete"]["channelErrors"][0]+ assert error["field"] == "id"+ assert error["code"] == ChannelErrorCode.CHANNEL_WITH_ORDERS.name+ assert Channel.objects.filter(slug=channel_USD.slug).exists()+++def test_channel_delete_mutation_without_orders_in_channel(+ permission_manage_channels, staff_api_client, channel_USD, checkout,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {"id": channel_id}+ checkout = Checkout.objects.first()+ assert checkout.channel == channel_USD+ assert Order.objects.first() is None++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_DELETE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["channelDelete"]["channelErrors"]+ assert Checkout.objects.first() is None+ assert not Channel.objects.filter(slug=channel_USD.slug).exists()++def test_channel_delete_mutation_with_different_currency(permission_manage_channels, staff_api_client, channel_USD, channel_PLN):@@ -125,6 +177,7 @@ def test_channel_delete_mutation_as_app(# thenassert order.channel == other_channel_USDassert Checkout.objects.first() is None+ assert not Channel.objects.filter(slug=channel_USD.slug).exists()def test_channel_delete_mutation_as_customer(@@ -142,6 +195,7 @@ def test_channel_delete_mutation_as_customer(# thenassert_no_permission(response)+ assert Channel.objects.filter(slug=channel_USD.slug).exists()def test_channel_delete_mutation_as_anonymous(@@ -159,3 +213,4 @@ def test_channel_delete_mutation_as_anonymous(# thenassert_no_permission(response)+ assert Channel.objects.filter(slug=channel_USD.slug).exists()diff --git a/saleor/graphql/channel/tests/test_channel_queries.py b/saleor/graphql/channel/tests/test_channel_queries.pyindex ed5de515e5..0b03d8ba5b 100644--- a/saleor/graphql/channel/tests/test_channel_queries.py+++ b/saleor/graphql/channel/tests/test_channel_queries.py@@ -77,6 +77,58 @@ def test_query_channels_as_anonymous(api_client, channel_USD, channel_PLN):assert_no_permission(response)+QUERY_CHANNELS_WITH_HAS_ORDERS = """+query {+ channels {+ name+ slug+ currencyCode+ hasOrders+ }+}+"""+++def test_query_channels_with_has_orders_order(+ staff_api_client, permission_manage_channels, channel_USD, channel_PLN, order_list+):+ # given++ # when+ response = staff_api_client.post_graphql(+ QUERY_CHANNELS_WITH_HAS_ORDERS, {}, permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ channels = content["data"]["channels"]+ assert len(channels) == 2+ assert {+ "slug": channel_PLN.slug,+ "name": channel_PLN.name,+ "currencyCode": channel_PLN.currency_code,+ "hasOrders": False,+ } in channels+ assert {+ "slug": channel_USD.slug,+ "name": channel_USD.name,+ "currencyCode": channel_USD.currency_code,+ "hasOrders": True,+ } in channels+++def test_query_channels_with_has_orders_without_permission(+ staff_api_client, channel_USD, channel_PLN+):+ # given++ # when+ response = staff_api_client.post_graphql(QUERY_CHANNELS_WITH_HAS_ORDERS, {})++ # then+ assert_no_permission(response)++QUERY_CHANNEL = """query getChannel($id: ID!){channel(id: $id){diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.pyindex cc18e8e53d..ec9febe973 100644--- a/saleor/graphql/channel/types.py+++ b/saleor/graphql/channel/types.py@@ -1,12 +1,15 @@-from graphene import relay+import graphenefrom graphene.types.resolver import get_default_resolverfrom graphene_django import DjangoObjectTypefrom ...channel import models+from ...core.permissions import ChannelPermissionsfrom ..core.connection import CountableDjangoObjectType+from ..decorators import permission_requiredfrom ..meta.types import ObjectWithMetadatafrom ..translations.resolvers import resolve_translationfrom . import ChannelContext+from .dataloaders import ChannelWithHasOrdersByIdLoaderclass ChannelContextType(DjangoObjectType):@@ -58,8 +61,21 @@ class ChannelContextTypeWithMetadata(ChannelContextType):class Channel(CountableDjangoObjectType):+ has_orders = graphene.Boolean(+ required=True, description="Whether a channel has associated orders."+ )+class Meta:description = "Represents channel."model = models.Channel- interfaces = [relay.Node]+ interfaces = [graphene.relay.Node]only_fields = ["id", "name", "slug", "currency_code", "is_active"]++ @staticmethod+ @permission_required(ChannelPermissions.MANAGE_CHANNELS)+ def resolve_has_orders(root: models.Channel, info):+ return (+ ChannelWithHasOrdersByIdLoader(info.context)+ .load(root.id)+ .then(lambda channel: channel.has_orders)+ )diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex bff317611e..61dcd6cf4c 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -797,6 +797,7 @@ type Channel implements Node {isActive: Boolean!slug: String!currencyCode: String!+ hasOrders: Boolean!}type ChannelActivate {@@ -849,6 +850,7 @@ enum ChannelErrorCode {UNIQUECHANNEL_TARGET_ID_MUST_BE_DIFFERENTCHANNELS_CURRENCY_MUST_BE_THE_SAME+ CHANNEL_WITH_ORDERS}type ChannelUpdate {@@ -2728,7 +2730,7 @@ type Mutation {checkoutShippingMethodUpdate(checkoutId: ID, shippingMethodId: ID!): CheckoutShippingMethodUpdatechannelCreate(input: ChannelCreateInput!): ChannelCreatechannelUpdate(id: ID!, input: ChannelUpdateInput!): ChannelUpdate- channelDelete(id: ID!, input: ChannelDeleteInput!): ChannelDelete+ channelDelete(id: ID!, input: ChannelDeleteInput): ChannelDeletechannelActivate(id: ID!): ChannelActivatechannelDeactivate(id: ID!): ChannelDeactivateattributeCreate(input: AttributeCreateInput!): AttributeCreate