Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix products export with filters (#18768) (#18775)
Iga Karbowiake7175003a542
diff --git a/saleor/csv/tests/export/test_export.py b/saleor/csv/tests/export/test_export.pyindex 3227cec0c7..76d43f126c 100644--- a/saleor/csv/tests/export/test_export.py+++ b/saleor/csv/tests/export/test_export.py@@ -15,8 +15,10 @@ from ....core import JobStatusfrom ....discount.models import VoucherCodefrom ....giftcard.models import GiftCardfrom ....graphql.csv.enums import ProductFieldEnum+from ....graphql.product.enums import StockAvailabilityfrom ....graphql.product.filters.product import ProductFilterfrom ....product.models import Product, ProductChannelListing+from ....warehouse.models import Allocationfrom ... import FileTypesfrom ...utils.export import (append_to_file,@@ -558,6 +560,35 @@ def get_product_queryset_filter(product_list):assert queryset.count() == len(product_list) - 1+def test_get_product_queryset_filter_stock_availability(+ product_list,+ order_line,+ channel_USD,+):+ # given+ # Allocate stock only for one product+ out_of_stock_product = product_list[0]+ stock = out_of_stock_product.variants.first().stocks.first()+ Allocation.objects.create(+ order_line=order_line, stock=stock, quantity_allocated=stock.quantity+ )++ # when+ queryset = get_queryset(+ Product,+ ProductFilter,+ {+ "filter": {+ "stock_availability": StockAvailability.OUT_OF_STOCK.name,+ "channel": channel_USD.slug,+ }+ },+ )++ # then+ assert queryset.count() == 1++def test_create_file_with_headers_csv(user_export_file, tmpdir, media_root):# givenfile_headers = ["id", "name", "collections"]diff --git a/saleor/graphql/csv/mutations/export_products.py b/saleor/graphql/csv/mutations/export_products.pyindex a082da58bd..24c877a3d6 100644--- a/saleor/graphql/csv/mutations/export_products.py+++ b/saleor/graphql/csv/mutations/export_products.py@@ -1,5 +1,9 @@+from typing import cast+import graphene+from django.core.exceptions import ValidationError+from ....channel import models as channel_modelsfrom ....csv import models as csv_modelsfrom ....csv.events import export_started_eventfrom ....csv.tasks import export_products_task@@ -10,6 +14,7 @@ from ...attribute.types import Attributefrom ...channel.types import Channelfrom ...core import ResolveInfofrom ...core.doc_category import DOC_CATEGORY_PRODUCTS+from ...core.enums import ExportErrorCodefrom ...core.types import BaseInputObjectType, ExportError, NonNullListfrom ...core.utils import WebhookEventInfofrom ...product.filters.product import ProductFilterInput@@ -18,6 +23,20 @@ from ...warehouse.types import Warehousefrom ..enums import ExportScope, FileTypeEnum, ProductFieldEnumfrom .base_export import BaseExportMutation+# Filters that require a channel to work properly+CHANNEL_REQUIRED_FILTERS = frozenset(+ [+ "is_published",+ "published_from",+ "is_available",+ "available_from",+ "is_visible_in_listing",+ "price",+ "minimal_price",+ "stock_availability",+ ]+)+class ExportInfoInput(BaseInputObjectType):attributes = NonNullList(@@ -91,9 +110,16 @@ class ExportProducts(BaseExportMutation):cls, _root, info: ResolveInfo, /, input):scope = cls.get_scope(input, Product)- export_info = cls.get_export_info(input["export_info"])+ export_info_input = input.get("export_info") or {}+ export_info = cls.get_export_info(export_info_input)file_type = input["file_type"]+ if "filter" in scope:+ scope = cast(dict[str, dict], scope)+ scope = cls.add_channel_to_filter_scope(+ scope, input.get("filter", {}), export_info+ )+app = get_app_promise(info.context).get()export_file = csv_models.ExportFile.objects.create(@@ -105,6 +131,49 @@ class ExportProducts(BaseExportMutation):export_file.refresh_from_db()return cls(export_file=export_file)+ @classmethod+ def add_channel_to_filter_scope(+ cls, scope: dict, filter_input: dict, export_info: dict+ ) -> dict:+ """Add channel slug to filter scope if channel-dependent filters are used.++ When filter contains fields that require a channel (like stock_availability,+ is_published, price, etc.), exactly one channel must be provided in+ export_info.channels. The channel slug is then injected into the filter.+ """+ used_channel_filters = set(filter_input.keys()) & CHANNEL_REQUIRED_FILTERS+ if not used_channel_filters:+ return scope++ channel_pks = export_info.get("channels") or []+ if len(channel_pks) != 1:+ raise ValidationError(+ {+ "channels": ValidationError(+ "Exactly one channel must be provided in export_info.channels "+ f"when using channel-dependent filters: "+ f"{', '.join(sorted(used_channel_filters))}.",+ code=ExportErrorCode.REQUIRED.value,+ )+ }+ )++ channel_pk = channel_pks[0]+ channel = channel_models.Channel.objects.filter(pk=channel_pk).first()+ if not channel:+ raise ValidationError(+ {+ "channels": ValidationError(+ "Channel not found.",+ code=ExportErrorCode.NOT_FOUND.value,+ )+ }+ )++ # Inject channel slug into the filter+ updated_filter = {**scope["filter"], "channel": channel.slug}+ return {"filter": updated_filter}+@classmethoddef get_export_info(cls, export_info_input):export_info = {}diff --git a/saleor/graphql/csv/tests/mutations/test_export_products.py b/saleor/graphql/csv/tests/mutations/test_export_products.pyindex 1abcf55596..25027051a5 100644--- a/saleor/graphql/csv/tests/mutations/test_export_products.py+++ b/saleor/graphql/csv/tests/mutations/test_export_products.py@@ -60,42 +60,72 @@ EXPORT_PRODUCTS_BY_APP_MUTATION = """"""- ("input", "called_data"),- [- (- {- "scope": ExportScope.ALL.name,- "exportInfo": {},- "fileType": FileTypeEnum.CSV.name,- },- {"all": ""},- ),- (- {- "scope": ExportScope.FILTER.name,- "filter": {"isPublished": True},- "exportInfo": {},- "fileType": FileTypeEnum.CSV.name,- },- {"filter": {"is_published": True}},- ),- ],-)@patch("saleor.graphql.csv.mutations.export_products.export_products_task.delay")-def test_export_products_mutation(+def test_export_products_mutation_all_scope(export_products_mock,staff_api_client,product_list,permission_manage_products,permission_manage_apps,- input,- called_data,):# givenquery = EXPORT_PRODUCTS_MUTATIONuser = staff_api_client.user- variables = {"input": input}+ variables = {+ "input": {+ "scope": ExportScope.ALL.name,+ "exportInfo": {},+ "fileType": FileTypeEnum.CSV.name,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables=variables,+ permissions=[permission_manage_products, permission_manage_apps],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["exportProducts"]+ export_file_data = data["exportFile"]++ export_products_mock.assert_called_once_with(+ ANY, {"all": ""}, {}, FileTypeEnum.CSV.value+ )++ assert not data["errors"]+ assert data["exportFile"]["id"]+ assert export_file_data["createdAt"]+ assert export_file_data["user"]["email"] == staff_api_client.user.email+ assert export_file_data["app"] is None+ assert ExportEvent.objects.filter(+ user=user, app=None, type=ExportEvents.EXPORT_PENDING+ ).exists()+++@patch("saleor.graphql.csv.mutations.export_products.export_products_task.delay")+def test_export_products_mutation_filter_scope_with_channel(+ export_products_mock,+ staff_api_client,+ product_list,+ channel_USD,+ permission_manage_products,+ permission_manage_apps,+):+ # given+ query = EXPORT_PRODUCTS_MUTATION+ user = staff_api_client.user+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)+ variables = {+ "input": {+ "scope": ExportScope.FILTER.name,+ "filter": {"isPublished": True},+ "exportInfo": {"channels": [channel_id]},+ "fileType": FileTypeEnum.CSV.name,+ }+ }# whenresponse = staff_api_client.post_graphql(@@ -110,7 +140,10 @@ def test_export_products_mutation(export_file_data = data["exportFile"]export_products_mock.assert_called_once_with(- ANY, called_data, {}, FileTypeEnum.CSV.value+ ANY,+ {"filter": {"is_published": True, "channel": channel_USD.slug}},+ {"channels": [str(channel_USD.pk)]},+ FileTypeEnum.CSV.value,)assert not data["errors"]@@ -635,3 +668,236 @@ def test_export_products_webhooks(assert not data["errors"]product_export_completed_mock.assert_called_once()+++ "filter_input",+ [+ {"stockAvailability": "OUT_OF_STOCK"},+ {"isPublished": True},+ {"isAvailable": True},+ {"isVisibleInListing": True},+ {"price": {"gte": 10, "lte": 100}},+ {"minimalPrice": {"gte": 10, "lte": 100}},+ ],+)+@patch("saleor.graphql.csv.mutations.export_products.export_products_task.delay")+def test_export_products_with_channel_dependent_filter_requires_channel(+ export_products_mock,+ staff_api_client,+ product_list,+ channel_USD,+ permission_manage_products,+ permission_manage_apps,+ filter_input,+):+ """Test that channel-dependent filters require exactly one channel in exportInfo."""+ # given+ query = EXPORT_PRODUCTS_MUTATION+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)+ variables = {+ "input": {+ "scope": ExportScope.FILTER.name,+ "filter": filter_input,+ "exportInfo": {"channels": [channel_id]},+ "fileType": FileTypeEnum.CSV.name,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables=variables,+ permissions=[permission_manage_products, permission_manage_apps],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["exportProducts"]+ assert not data["errors"]+ assert data["exportFile"]["id"]++ # Verify channel slug was injected into the filter+ export_products_mock.assert_called_once()+ call_args = export_products_mock.call_args[0]+ scope = call_args[1]+ assert "filter" in scope+ assert scope["filter"]["channel"] == channel_USD.slug+++ "filter_input",+ [+ {"stockAvailability": "OUT_OF_STOCK"},+ {"isPublished": True},+ {"isAvailable": True},+ {"isVisibleInListing": True},+ {"price": {"gte": 10, "lte": 100}},+ {"minimalPrice": {"gte": 10, "lte": 100}},+ ],+)+@patch("saleor.graphql.csv.mutations.export_products.export_products_task.delay")+def test_export_products_with_channel_dependent_filter_no_channel_returns_error(+ export_products_mock,+ staff_api_client,+ product_list,+ permission_manage_products,+ permission_manage_apps,+ filter_input,+):+ """Test that channel-dependent filters fail when no channel is provided."""+ # given+ query = EXPORT_PRODUCTS_MUTATION+ variables = {+ "input": {+ "scope": ExportScope.FILTER.name,+ "filter": filter_input,+ "exportInfo": {},+ "fileType": FileTypeEnum.CSV.name,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables=variables,+ permissions=[permission_manage_products, permission_manage_apps],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["exportProducts"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "channels"+ assert errors[0]["code"] == ExportErrorCode.REQUIRED.name+ assert not data["exportFile"]++ export_products_mock.assert_not_called()+++@patch("saleor.graphql.csv.mutations.export_products.export_products_task.delay")+def test_export_products_with_channel_dependent_filter_multiple_channels_returns_error(+ export_products_mock,+ staff_api_client,+ product_list,+ channel_USD,+ channel_PLN,+ permission_manage_products,+ permission_manage_apps,+):+ """Test that channel-dependent filters fail when multiple channels are provided."""+ # given+ query = EXPORT_PRODUCTS_MUTATION+ channel_ids = [+ graphene.Node.to_global_id("Channel", channel_USD.pk),+ graphene.Node.to_global_id("Channel", channel_PLN.pk),+ ]+ variables = {+ "input": {+ "scope": ExportScope.FILTER.name,+ "filter": {"stockAvailability": "OUT_OF_STOCK"},+ "exportInfo": {"channels": channel_ids},+ "fileType": FileTypeEnum.CSV.name,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables=variables,+ permissions=[permission_manage_products, permission_manage_apps],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["exportProducts"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "channels"+ assert errors[0]["code"] == ExportErrorCode.REQUIRED.name+ assert not data["exportFile"]++ export_products_mock.assert_not_called()+++@patch("saleor.graphql.csv.mutations.export_products.export_products_task.delay")+def test_export_products_with_non_channel_filter_does_not_require_channel(+ export_products_mock,+ staff_api_client,+ product_list,+ collection,+ permission_manage_products,+ permission_manage_apps,+):+ """Test that non-channel-dependent filters work without providing a channel."""+ # given+ query = EXPORT_PRODUCTS_MUTATION+ collection_id = graphene.Node.to_global_id("Collection", collection.pk)+ variables = {+ "input": {+ "scope": ExportScope.FILTER.name,+ "filter": {"collections": [collection_id]},+ "exportInfo": {},+ "fileType": FileTypeEnum.CSV.name,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables=variables,+ permissions=[permission_manage_products, permission_manage_apps],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["exportProducts"]+ assert not data["errors"]+ assert data["exportFile"]["id"]++ export_products_mock.assert_called_once()+ call_args = export_products_mock.call_args[0]+ scope = call_args[1]+ # Channel should not be in the filter since we used a non-channel filter+ assert "channel" not in scope.get("filter", {})+++@patch("saleor.graphql.csv.mutations.export_products.export_products_task.delay")+def test_export_products_with_channel_dependent_filter_invalid_channel_returns_error(+ export_products_mock,+ staff_api_client,+ product_list,+ permission_manage_products,+ permission_manage_apps,+):+ """Test that channel-dependent filters fail when invalid channel ID is provided."""+ # given+ query = EXPORT_PRODUCTS_MUTATION+ invalid_channel_id = graphene.Node.to_global_id("Channel", 99999)+ variables = {+ "input": {+ "scope": ExportScope.FILTER.name,+ "filter": {"stockAvailability": "IN_STOCK"},+ "exportInfo": {"channels": [invalid_channel_id]},+ "fileType": FileTypeEnum.CSV.name,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables=variables,+ permissions=[permission_manage_products, permission_manage_apps],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["exportProducts"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "channels"+ assert errors[0]["code"] == ExportErrorCode.NOT_FOUND.name+ assert not data["exportFile"]++ export_products_mock.assert_not_called()diff --git a/saleor/graphql/product/filters/product_helpers.py b/saleor/graphql/product/filters/product_helpers.pyindex 7584efa171..cc56915ab9 100644--- a/saleor/graphql/product/filters/product_helpers.py+++ b/saleor/graphql/product/filters/product_helpers.py@@ -136,9 +136,9 @@ def filter_products_by_stock_availability(qs, stock_availability, channel_slug):.filter(Exists(stocks.filter(product_variant_id=OuterRef("pk")))).values("product_id"))- if stock_availability == StockAvailability.IN_STOCK:+ if stock_availability == StockAvailability.IN_STOCK.value: # type: ignore[attr-defined]qs = qs.filter(Exists(variants.filter(product_id=OuterRef("pk"))))- if stock_availability == StockAvailability.OUT_OF_STOCK:+ if stock_availability == StockAvailability.OUT_OF_STOCK.value: # type: ignore[attr-defined]qs = qs.filter(~Exists(variants.filter(product_id=OuterRef("pk"))))return qs