Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Remove deprecated exportGiftCards and exportVoucherCodes mutations (#19583)
Lukasz Ostrowski2c48391b652c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d3739fd3d7..30b7ec1943 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,8 @@ All notable, unreleased changes to this project will be documented in this file.- Removed the deprecated `orderSettingsUpdate` mutation. Use the `channelUpdate` mutation with the `orderSettings` input to update order settings per channel instead.- Removed the deprecated `orderSettings` query field. Use the `channel` query and read its `orderSettings` field instead.- Removed the deprecated `orderAddNote` mutation, along with the `OrderAddNote` type and `OrderAddNoteInput` input. Use the `orderNoteAdd` mutation instead.+- Removed the deprecated `exportGiftCards` and `exportVoucherCodes` mutations, along with the `ExportGiftCards`, `ExportGiftCardsInput`, `ExportVoucherCodes` and `ExportVoucherCodesInput` types. Fetch the data with the `giftCards` and `voucher` queries and format it in your app instead.+- Removed the `GIFT_CARD_EXPORT_COMPLETED` and `VOUCHER_CODE_EXPORT_COMPLETED` webhook event types, along with the `GiftCardExportCompleted` and `VoucherCodeExportCompleted` subscription types. They were emitted only by the removed `exportGiftCards` and `exportVoucherCodes` mutations. Existing webhook subscriptions to these events are deleted by a migration; a webhook left with no other events will stop being triggered.- Removed the `DIGITAL_LINKS` value from the `OrderEventsEmailsEnum` enum and the `DIGITAL_LINK_DOWNLOADED` value from the `CustomerEventsEnum` enum. Events with these types were deleted in 3.23, along with the legacy digital content feature that emitted them.- Removed the always-empty `digital_lines` key from the fulfillment confirmation notification payload. Use `physical_lines`, which holds every line of the fulfillment.- Attribute value and bulk attribute mutations now require the permission matching the attribute's type: `MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES` for `PRODUCT_TYPE` attributes, `MANAGE_PAGE_TYPES_AND_ATTRIBUTES` for `PAGE_TYPE` attributes, and `MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES` for `CUSTOMER_TYPE` attributes. Previously each mutation required a single fixed permission regardless of the attribute's type, which let a requestor modify attributes of a type they were not authorized for.diff --git a/saleor/csv/notifications.py b/saleor/csv/notifications.pyindex 159999b5f7..03bbcb9d71 100644--- a/saleor/csv/notifications.py+++ b/saleor/csv/notifications.py@@ -42,12 +42,8 @@ def send_export_download_link_notification(export_file: "ExportFile", data_type:manager = get_plugins_manager(allow_replica=True)handler = NotifyHandler(_generate_payload)manager.notify(NotifyEventType.CSV_EXPORT_SUCCESS, payload_func=handler.payload)- if data_type == "gift cards":- manager.gift_card_export_completed(export_file)if data_type == "products":manager.product_export_completed(export_file)- if data_type == "voucher codes":- manager.voucher_code_export_completed(export_file)def send_export_failed_info(export_file: "ExportFile", data_type: str):@@ -65,9 +61,5 @@ def send_export_failed_info(export_file: "ExportFile", data_type: str):manager = get_plugins_manager(allow_replica=True)handler = NotifyHandler(_generate_payload)manager.notify(NotifyEventType.CSV_EXPORT_FAILED, payload_func=handler.payload)- if data_type == "gift cards":- manager.gift_card_export_completed(export_file)if data_type == "products":manager.product_export_completed(export_file)- if data_type == "voucher codes":- manager.voucher_code_export_completed(export_file)diff --git a/saleor/csv/tasks.py b/saleor/csv/tasks.pyindex 505af5628d..5ea53ba16a 100644--- a/saleor/csv/tasks.py+++ b/saleor/csv/tasks.py@@ -12,7 +12,7 @@ from ..core.tasks import RestrictWriterDBTaskfrom . import eventsfrom .models import ExportEvent, ExportFilefrom .notifications import send_export_failed_info-from .utils.export import export_gift_cards, export_products, export_voucher_codes+from .utils.export import export_productstask_logger = get_task_logger(__name__)@@ -21,8 +21,6 @@ class ExportTask(RestrictWriterDBTask):# should be updated when new export task is addedTASK_NAME_TO_DATA_TYPE_MAPPING = {"export-products": "products",- "export-gift-cards": "gift cards",- "export-voucher-codes": "voucher codes",}def on_failure(self, exc, task_id, args, kwargs, einfo):@@ -74,38 +72,6 @@ def export_products_task(export_products(export_file, scope, export_info, file_type, delimiter)[email protected](name="export-gift-cards", base=ExportTask)-def export_gift_cards_task(- export_file_id: int,- scope: dict[str, str | dict],- file_type: str,- delimiter: str = ",",-):- with allow_writer():- # Read the ExportFile instance from the writer instead of replica as it might- # not be replicated yet.- export_file = ExportFile.objects.select_related("app", "user").get(- pk=export_file_id- )- export_gift_cards(export_file, scope, file_type, delimiter)--[email protected](name="export-voucher-codes", base=ExportTask)-def export_voucher_codes_task(- export_file_id: int,- file_type: str,- voucher_id: int | None,- ids: list[int],-):- with allow_writer():- # Read the ExportFile instance from the writer instead of replica as it might- # not be replicated yet.- export_file = ExportFile.objects.select_related("app", "user").get(- pk=export_file_id- )- export_voucher_codes(export_file, file_type, voucher_id, ids)--@app.task@allow_writer()def delete_old_export_files():diff --git a/saleor/csv/tests/export/test_export.py b/saleor/csv/tests/export/test_export.pyindex 76d43f126c..a14c4ee25d 100644--- a/saleor/csv/tests/export/test_export.py+++ b/saleor/csv/tests/export/test_export.py@@ -12,8 +12,6 @@ from django.core.files import Filefrom freezegun import freeze_timefrom ....core import JobStatus-from ....discount.models import VoucherCode-from ....giftcard.models import GiftCardfrom ....graphql.csv.enums import ProductFieldEnumfrom ....graphql.product.enums import StockAvailabilityfrom ....graphql.product.filters.product import ProductFilter@@ -23,12 +21,8 @@ from ... import FileTypesfrom ...utils.export import (append_to_file,create_file_with_headers,- export_gift_cards,- export_gift_cards_in_batches,export_products,export_products_in_batches,- export_voucher_codes,- export_voucher_codes_in_batches,get_filename,get_queryset,parse_input,@@ -319,208 +313,6 @@ def test_export_products_webhook(mocked_product_export_completed.assert_called_once_with(user_export_file)-@patch("saleor.csv.utils.export.create_file_with_headers")-@patch("saleor.csv.utils.export.export_gift_cards_in_batches")-@patch("saleor.csv.utils.export.send_export_download_link_notification")-@patch("saleor.csv.utils.export.save_csv_file_in_export_file")-def test_export_gift_cards(- save_file_mock,- send_email_mock,- export_in_batches_mock,- create_file_with_headers_mock,- user_export_file,- gift_card,- gift_card_expiry_date,- gift_card_used,-):- # given- file_type = FileTypes.CSV-- mock_file = MagicMock(spec=File)- create_file_with_headers_mock.return_value = mock_file-- # when- export_gift_cards(user_export_file, {"all": ""}, file_type)-- # then- create_file_with_headers_mock.assert_called_once_with(["code"], ",", file_type)-- assert export_in_batches_mock.call_count == 1- args, kwargs = export_in_batches_mock.call_args- assert set(args[0].values_list("pk", flat=True)) == set(- GiftCard.objects.exclude(id=gift_card_used.id).values_list("pk", flat=True)- )- assert args[1:] == (- ["code"],- ",",- mock_file,- file_type,- )-- send_email_mock.assert_called_once_with(user_export_file, "gift cards")-- save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)---@patch("saleor.csv.utils.export.create_file_with_headers")-@patch("saleor.csv.utils.export.export_gift_cards_in_batches")-@patch("saleor.csv.utils.export.send_export_download_link_notification")-@patch("saleor.csv.utils.export.save_csv_file_in_export_file")-def test_export_gift_cards_by_app(- save_file_mock,- send_email_mock,- export_in_batches_mock,- create_file_with_headers_mock,- app_export_file,- gift_card,- gift_card_expiry_date,- gift_card_used,-):- file_type = FileTypes.CSV-- mock_file = MagicMock(spec=File)- create_file_with_headers_mock.return_value = mock_file-- # when- export_gift_cards(app_export_file, {"all": ""}, file_type)-- # then- create_file_with_headers_mock.assert_called_once_with(["code"], ",", file_type)-- assert export_in_batches_mock.call_count == 1- args, kwargs = export_in_batches_mock.call_args- assert set(args[0].values_list("pk", flat=True)) == set(- GiftCard.objects.exclude(id=gift_card_used.id).values_list("pk", flat=True)- )- assert args[1:] == (- ["code"],- ",",- mock_file,- file_type,- )-- send_email_mock.assert_called_once_with(app_export_file, "gift cards")-- save_file_mock.assert_called_once_with(app_export_file, mock_file, ANY)---@patch("saleor.csv.utils.export.create_file_with_headers")-@patch("saleor.csv.utils.export.export_gift_cards_in_batches")-@patch("saleor.csv.utils.export.send_export_download_link_notification")-@patch("saleor.csv.utils.export.save_csv_file_in_export_file")-def test_export_gift_cards_ids(- save_file_mock,- send_email_mock,- export_in_batches_mock,- create_file_with_headers_mock,- user_export_file,- gift_card,- gift_card_expiry_date,- gift_card_used,-):- file_type = FileTypes.CSV-- mock_file = MagicMock(spec=File)- create_file_with_headers_mock.return_value = mock_file- pks = [gift_card.pk]-- # when- export_gift_cards(user_export_file, {"ids": pks}, file_type)-- # then- create_file_with_headers_mock.assert_called_once_with(["code"], ",", file_type)-- assert export_in_batches_mock.call_count == 1- args, kwargs = export_in_batches_mock.call_args- assert set(args[0].values_list("pk", flat=True)) == set(pks)- assert args[1:] == (- ["code"],- ",",- mock_file,- file_type,- )-- send_email_mock.assert_called_once_with(user_export_file, "gift cards")-- save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)---@patch("saleor.csv.utils.export.create_file_with_headers")-@patch("saleor.csv.utils.export.export_gift_cards_in_batches")-@patch("saleor.csv.utils.export.send_export_download_link_notification")-@patch("saleor.csv.utils.export.save_csv_file_in_export_file")-def test_export_gift_cards_with_filter(- save_file_mock,- send_email_mock,- export_in_batches_mock,- create_file_with_headers_mock,- user_export_file,- gift_card,- gift_card_expiry_date,- gift_card_used,- shippable_gift_card_product,-):- file_type = FileTypes.CSV-- mock_file = MagicMock(spec=File)- create_file_with_headers_mock.return_value = mock_file-- gift_card_expiry_date.product = shippable_gift_card_product- gift_card_used.product = shippable_gift_card_product- GiftCard.objects.bulk_update([gift_card_expiry_date, gift_card_used], ["product"])-- # when- export_gift_cards(- user_export_file,- {- "filter": {- "products": [- graphene.Node.to_global_id(- "Product", shippable_gift_card_product.pk- )- ]- }- },- file_type,- )-- # then- create_file_with_headers_mock.assert_called_once_with(["code"], ",", file_type)-- assert export_in_batches_mock.call_count == 1- args, kwargs = export_in_batches_mock.call_args- assert set(args[0].values_list("pk", flat=True)) == {gift_card_expiry_date.pk}- assert args[1:] == (- ["code"],- ",",- mock_file,- file_type,- )-- send_email_mock.assert_called_once_with(user_export_file, "gift cards")-- save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)---@patch("saleor.plugins.manager.PluginsManager.gift_card_export_completed")-def test_export_gift_cards_webhook(- mocked_gift_card_export_completed,- user_export_file,- gift_card,- gift_card_expiry_date,- gift_card_used,- media_root,-):- # given- file_type = FileTypes.CSV-- # when- export_gift_cards(user_export_file, {"all": ""}, file_type)-- # then- mocked_gift_card_export_completed.assert_called_once_with(user_export_file)--def test_get_filename_csv():with freeze_time("2000-02-09 03:21:34"):file_name = get_filename("test", FileTypes.CSV)@@ -854,85 +646,6 @@ def test_export_products_in_batches_for_xlsx(shutil.rmtree(tmpdir)-@patch("saleor.csv.utils.export.BATCH_SIZE", 1)-def test_export_gift_cards_in_batches_to_csv(- gift_card,- gift_card_expiry_date,- gift_card_used,- tmpdir,-):- # given- gift_cards = GiftCard.objects.exclude(id=gift_card_used.id).order_by("pk")-- table = etl.wrap([["code"]])- temp_file = NamedTemporaryFile()- etl.tocsv(table, temp_file.name, delimiter=",")-- # when- export_gift_cards_in_batches(- gift_cards,- ["code"],- ",",- temp_file,- "csv",- )-- # then- file_content = temp_file.read().decode().split("\r\n")-- # ensure headers are in the file- assert "code" in file_content-- for card in gift_cards:- assert card.code in file_content-- shutil.rmtree(tmpdir)---@patch("saleor.csv.utils.export.BATCH_SIZE", 1)-def test_export_gift_cards_in_batches_to_xlsx(- gift_card,- gift_card_expiry_date,- gift_card_used,- tmpdir,-):- # given- gift_cards = GiftCard.objects.exclude(id=gift_card_used.id).order_by("pk")-- table = etl.wrap([["code"]])- temp_file = NamedTemporaryFile(suffix=".xlsx")- etl.io.xlsx.toxlsx(table, temp_file.name)-- # when- export_gift_cards_in_batches(- gift_cards,- ["code"],- ",",- temp_file,- "xlsx",- )-- # then- wb_obj = openpyxl.load_workbook(temp_file)-- sheet_obj = wb_obj.active- max_col = sheet_obj.max_column- max_row = sheet_obj.max_row- headers = [sheet_obj.cell(row=1, column=i).value for i in range(1, max_col + 1)]- data = []- for i in range(2, max_row + 1):- row = []- for j in range(1, max_col + 1):- row.append(sheet_obj.cell(row=i, column=j).value)- data.append(row)-- assert headers == ["code"]- for card in gift_cards:- assert [card.code] in data-- shutil.rmtree(tmpdir)--def test_parse_input():data = {"collections": None,@@ -970,218 +683,3 @@ def test_parse_input():parsed_data = parse_input(data)assert data == parsed_data---@patch("saleor.csv.utils.export.create_file_with_headers")-@patch("saleor.csv.utils.export.export_voucher_codes_in_batches")-@patch("saleor.csv.utils.export.send_export_download_link_notification")-@patch("saleor.csv.utils.export.save_csv_file_in_export_file")-def test_export_voucher_codes_by_voucher_id(- save_file_mock,- send_email_mock,- export_in_batches_mock,- create_file_with_headers_mock,- user_export_file,- voucher_with_many_codes,- voucher_percentage,-):- mock_file = MagicMock(spec=File)- create_file_with_headers_mock.return_value = mock_file- file_type = FileTypes.CSV- voucher = voucher_with_many_codes-- # when- export_voucher_codes(user_export_file, file_type, voucher_id=voucher.id)-- # then- create_file_with_headers_mock.assert_called_once_with(["code"], ",", file_type)-- assert export_in_batches_mock.call_count == 1- args, kwargs = export_in_batches_mock.call_args- assert set(args[0].values_list("pk", flat=True)) == set(- VoucherCode.objects.filter(voucher_id=voucher.id).values_list("pk", flat=True)- )- assert args[1:] == (- ["code"],- ",",- mock_file,- file_type,- )-- send_email_mock.assert_called_once_with(user_export_file, "voucher codes")-- save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)---@patch("saleor.csv.utils.export.create_file_with_headers")-@patch("saleor.csv.utils.export.export_voucher_codes_in_batches")-@patch("saleor.csv.utils.export.send_export_download_link_notification")-@patch("saleor.csv.utils.export.save_csv_file_in_export_file")-def test_export_voucher_codes_by_ids(- save_file_mock,- send_email_mock,- export_in_batches_mock,- create_file_with_headers_mock,- user_export_file,- voucher_with_many_codes,- voucher_percentage,-):- mock_file = MagicMock(spec=File)- create_file_with_headers_mock.return_value = mock_file- file_type = FileTypes.CSV- voucher = voucher_with_many_codes- code_ids = [code.id for code in voucher.codes.all()]-- # when- export_voucher_codes(user_export_file, file_type, ids=code_ids)-- # then- create_file_with_headers_mock.assert_called_once_with(["code"], ",", file_type)-- assert export_in_batches_mock.call_count == 1- args, kwargs = export_in_batches_mock.call_args- assert set(args[0].values_list("pk", flat=True)) == set(- VoucherCode.objects.filter(id__in=code_ids).values_list("pk", flat=True)- )- assert args[1:] == (- ["code"],- ",",- mock_file,- file_type,- )-- send_email_mock.assert_called_once_with(user_export_file, "voucher codes")-- save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)---@patch("saleor.csv.utils.export.create_file_with_headers")-@patch("saleor.csv.utils.export.export_voucher_codes_in_batches")-@patch("saleor.csv.utils.export.send_export_download_link_notification")-@patch("saleor.csv.utils.export.save_csv_file_in_export_file")-def test_export_voucher_codes_by_app(- save_file_mock,- send_email_mock,- export_in_batches_mock,- create_file_with_headers_mock,- app_export_file,- voucher_with_many_codes,-):- mock_file = MagicMock(spec=File)- create_file_with_headers_mock.return_value = mock_file- file_type = FileTypes.CSV- voucher = voucher_with_many_codes-- # when- export_voucher_codes(app_export_file, file_type, voucher_id=voucher.id)-- # then- create_file_with_headers_mock.assert_called_once_with(["code"], ",", file_type)-- assert export_in_batches_mock.call_count == 1- args, kwargs = export_in_batches_mock.call_args- assert set(args[0].values_list("pk", flat=True)) == set(- VoucherCode.objects.filter(voucher_id=voucher.id).values_list("pk", flat=True)- )- assert args[1:] == (- ["code"],- ",",- mock_file,- file_type,- )-- send_email_mock.assert_called_once_with(app_export_file, "voucher codes")-- save_file_mock.assert_called_once_with(app_export_file, mock_file, ANY)---@patch("saleor.plugins.manager.PluginsManager.voucher_code_export_completed")-def test_export_voucher_codes_webhooks(- mocked_voucher_code_export_completed,- user_export_file,- voucher_with_many_codes,- media_root,-):- file_type = FileTypes.CSV- voucher = voucher_with_many_codes-- # when- export_voucher_codes(user_export_file, file_type, voucher_id=voucher.id)-- # then- mocked_voucher_code_export_completed.assert_called_once()---@patch("saleor.csv.utils.export.BATCH_SIZE", 1)-def test_export_voucher_codes_in_batches_to_csv(- voucher_with_many_codes,- tmpdir,-):- # given- voucher_codes = voucher_with_many_codes.codes.all()-- table = etl.wrap([["code"]])- temp_file = NamedTemporaryFile()- etl.tocsv(table, temp_file.name, delimiter=",")-- # when- export_voucher_codes_in_batches(- voucher_codes,- ["code"],- ",",- temp_file,- "csv",- )-- # then- file_content = temp_file.read().decode().split("\r\n")-- # ensure headers are in the file- assert "code" in file_content-- for voucher_code in voucher_codes:- assert voucher_code.code in file_content-- shutil.rmtree(tmpdir)---@patch("saleor.csv.utils.export.BATCH_SIZE", 1)-def test_export_voucher_codes_in_batches_to_xlsx(- voucher_with_many_codes,- tmpdir,-):- # given- voucher_codes = voucher_with_many_codes.codes.all()-- table = etl.wrap([["code"]])- temp_file = NamedTemporaryFile(suffix=".xlsx")- etl.io.xlsx.toxlsx(table, temp_file.name)-- # when- export_voucher_codes_in_batches(- voucher_codes,- ["code"],- ",",- temp_file,- "xlsx",- )-- # then- wb_obj = openpyxl.load_workbook(temp_file)-- sheet_obj = wb_obj.active- max_col = sheet_obj.max_column- max_row = sheet_obj.max_row- headers = [sheet_obj.cell(row=1, column=i).value for i in range(1, max_col + 1)]- data = []- for i in range(2, max_row + 1):- row = []- for j in range(1, max_col + 1):- row.append(sheet_obj.cell(row=i, column=j).value)- data.append(row)-- assert headers == ["code"]- for voucher_code in voucher_codes:- assert [voucher_code.code] in data-- shutil.rmtree(tmpdir)diff --git a/saleor/csv/tests/test_notifications.py b/saleor/csv/tests/test_notifications.pyindex b393268a5a..5d867701d9 100644--- a/saleor/csv/tests/test_notifications.py+++ b/saleor/csv/tests/test_notifications.py@@ -11,13 +11,11 @@ from ..notifications import get_default_export_payload@freeze_time("2018-05-31 12:00:01")[email protected]("saleor.plugins.manager.PluginsManager.gift_card_export_completed")@mock.patch("saleor.plugins.manager.PluginsManager.product_export_completed")@mock.patch("saleor.plugins.manager.PluginsManager.notify")def test_send_export_download_link_notification(mocked_notify,mocked_product_export_completed,- mocked_gift_card_export_completed,site_settings,user_export_file,tmpdir,@@ -51,18 +49,15 @@ def test_send_export_download_link_notification(assert len(called_kwargs) == 1assert called_kwargs["payload_func"]() == expected_payload- mocked_gift_card_export_completed.assert_not_called()- mocked_product_export_completed.assert_called_with(user_export_file)+ mocked_product_export_completed.assert_called_once_with(user_export_file)@freeze_time("2018-05-31 12:00:01")[email protected]("saleor.plugins.manager.PluginsManager.gift_card_export_completed")@mock.patch("saleor.plugins.manager.PluginsManager.product_export_completed")@mock.patch("saleor.plugins.manager.PluginsManager.notify")def test_send_export_failed_info(mocked_notify,mocked_product_export_completed,- mocked_gift_card_export_completed,site_settings,user_export_file,tmpdir,@@ -71,7 +66,7 @@ def test_send_export_failed_info(# givenfile_mock = mock.MagicMock(spec=File)file_mock.name = "temp_file.csv"- data_type = "gift cards"+ data_type = "products"user_export_file.content_file = file_mockuser_export_file.save()@@ -95,5 +90,4 @@ def test_send_export_failed_info(assert len(called_kwargs) == 1assert called_kwargs["payload_func"]() == expected_payload- mocked_gift_card_export_completed.assert_called_once_with(user_export_file)- mocked_product_export_completed.assert_not_called()+ mocked_product_export_completed.assert_called_once_with(user_export_file)diff --git a/saleor/csv/tests/test_tasks.py b/saleor/csv/tests/test_tasks.pyindex 339e59778a..0e6e90ab79 100644--- a/saleor/csv/tests/test_tasks.py+++ b/saleor/csv/tests/test_tasks.py@@ -9,12 +9,7 @@ from freezegun import freeze_timefrom ...core import JobStatusfrom .. import ExportEvents, FileTypesfrom ..models import ExportEvent, ExportFile-from ..tasks import (- ExportTask,- delete_old_export_files,- export_gift_cards_task,- export_products_task,-)+from ..tasks import ExportTask, delete_old_export_files, export_products_task@patch("saleor.csv.tasks.export_products")@@ -57,42 +52,6 @@ def test_export_products_task_failed(send_export_failed_info_mock.assert_called_once_with(user_export_file, "products")-@patch("saleor.csv.tasks.export_gift_cards")-def test_export_gift_cards_task(export_gift_cards_mock, user_export_file):- # given- scope = {"all": ""}- file_type = FileTypes.CSV- delimiter = ";"-- # when- export_gift_cards_task(user_export_file.id, scope, file_type, delimiter)-- # then- export_gift_cards_mock.assert_called_once_with(- user_export_file, scope, file_type, delimiter- )---@patch("saleor.csv.tasks.send_export_failed_info")-@patch("saleor.csv.tasks.export_gift_cards")-def test_export_gift_cards_task_failed(- export_gift_cards_mock, send_export_failed_info_mock, user_export_file-):- # given- scope = {"all": ""}- file_type = FileTypes.CSV- delimiter = ";"-- exc_message = "Test error"- export_gift_cards_mock.side_effect = Exception(exc_message)-- # when- export_gift_cards_task.delay(user_export_file.id, scope, file_type, delimiter)-- # then- send_export_failed_info_mock.assert_called_once_with(user_export_file, "gift cards")--@patch("saleor.csv.tasks.send_export_failed_info")def test_on_task_failure(send_export_failed_info_mock, user_export_file):# givendiff --git a/saleor/csv/utils/export.py b/saleor/csv/utils/export.pyindex cf6d276269..fe633a50b8 100644--- a/saleor/csv/utils/export.py+++ b/saleor/csv/utils/export.py@@ -9,8 +9,6 @@ from django.utils import timezonefrom ...core.db.connection import allow_writerfrom ...core.utils.batches import queryset_in_batches-from ...discount.models import VoucherCode-from ...giftcard.models import GiftCardfrom ...product.models import Productfrom .. import FileTypesfrom ..notifications import send_export_download_link_notification@@ -61,71 +59,6 @@ def export_products(send_export_download_link_notification(export_file, "products")-def export_gift_cards(- export_file: "ExportFile",- scope: dict[str, str | dict],- file_type: str,- delimiter: str = ",",-):- from ...graphql.giftcard.filters import GiftCardFilter-- file_name = get_filename("gift_card", file_type)-- queryset = get_queryset(GiftCard, GiftCardFilter, scope)- # only unused gift cards codes can be exported- queryset = queryset.filter(used_by_email__isnull=True)-- export_fields = ["code"]- temporary_file = create_file_with_headers(export_fields, delimiter, file_type)-- export_gift_cards_in_batches(- queryset,- export_fields,- delimiter,- temporary_file,- file_type,- )-- save_csv_file_in_export_file(export_file, temporary_file, file_name)- temporary_file.close()- send_export_download_link_notification(export_file, "gift cards")---def export_voucher_codes(- export_file: "ExportFile",- file_type: str,- voucher_id: int | None = None,- ids: list[int] | None = None,- delimiter: str = ",",-):- file_name = get_filename("voucher_code", file_type)-- qs = VoucherCode.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME).all()- if voucher_id:- qs = VoucherCode.objects.using(- settings.DATABASE_CONNECTION_REPLICA_NAME- ).filter(voucher_id=voucher_id)- if ids:- qs = VoucherCode.objects.using(- settings.DATABASE_CONNECTION_REPLICA_NAME- ).filter(id__in=ids)-- export_fields = ["code"]- temporary_file = create_file_with_headers(export_fields, delimiter, file_type)-- export_voucher_codes_in_batches(- qs,- export_fields,- delimiter,- temporary_file,- file_type,- )-- save_csv_file_in_export_file(export_file, temporary_file, file_name)- temporary_file.close()- send_export_download_link_notification(export_file, "voucher codes")--def get_filename(model_name: str, file_type: str) -> str:hash = uuid.uuid4()return "{}_data_{}_{}.{}".format(@@ -222,40 +155,6 @@ def export_products_in_batches(append_to_file(export_data, headers, temporary_file, file_type, delimiter)-def export_gift_cards_in_batches(- queryset: "QuerySet",- export_fields: list[str],- delimiter: str,- temporary_file: Any,- file_type: str,-):- for batch_pks in queryset_in_batches(queryset, BATCH_SIZE):- gift_card_batch = GiftCard.objects.using(- settings.DATABASE_CONNECTION_REPLICA_NAME- ).filter(pk__in=batch_pks)-- export_data = list(gift_card_batch.values(*export_fields))-- append_to_file(export_data, export_fields, temporary_file, file_type, delimiter)---def export_voucher_codes_in_batches(- queryset: "QuerySet",- export_fields: list[str],- delimiter: str,- temporary_file: Any,- file_type: str,-):- for batch_pks in queryset_in_batches(queryset, BATCH_SIZE):- voucher_codes_batch = VoucherCode.objects.using(- settings.DATABASE_CONNECTION_REPLICA_NAME- ).filter(pk__in=batch_pks)-- export_data = list(voucher_codes_batch.values(*export_fields))-- append_to_file(export_data, export_fields, temporary_file, file_type, delimiter)--def append_to_file(export_data: list[dict[str, str | bool]],headers: list[str],diff --git a/saleor/graphql/csv/mutations/__init__.py b/saleor/graphql/csv/mutations/__init__.pyindex c81c41da2d..33468e54cf 100644--- a/saleor/graphql/csv/mutations/__init__.py+++ b/saleor/graphql/csv/mutations/__init__.py@@ -1,5 +1,3 @@-from .export_gift_cards import ExportGiftCardsfrom .export_products import ExportProducts-from .export_voucher_codes import ExportVoucherCodes-__all__ = ["ExportGiftCards", "ExportProducts", "ExportVoucherCodes"]+__all__ = ["ExportProducts"]diff --git a/saleor/graphql/csv/mutations/export_gift_cards.py b/saleor/graphql/csv/mutations/export_gift_cards.pydeleted file mode 100644index 784603ceed..0000000000--- a/saleor/graphql/csv/mutations/export_gift_cards.py+++ /dev/null@@ -1,75 +0,0 @@-import graphene--from ....csv import models as csv_models-from ....csv.events import export_started_event-from ....csv.tasks import export_gift_cards_task-from ....permission.enums import GiftcardPermissions-from ....webhook.event_types import WebhookEventAsyncType-from ...app.dataloaders import get_app_promise-from ...core import ResolveInfo-from ...core.doc_category import DOC_CATEGORY_GIFT_CARDS-from ...core.types import BaseInputObjectType, ExportError, NonNullList-from ...core.utils import WebhookEventInfo-from ...giftcard.filters import GiftCardFilterInput-from ...giftcard.types import GiftCard-from ..enums import ExportScope, FileTypeEnum-from .base_export import BaseExportMutation---class ExportGiftCardsInput(BaseInputObjectType):- scope = ExportScope(- description="Determine which gift cards should be exported.", required=True- )- filter = GiftCardFilterInput(- description="Filtering options for gift cards.", required=False- )- ids = NonNullList(- graphene.ID,- description="List of gift cards IDs to export.",- required=False,- )- file_type = FileTypeEnum(description="Type of exported file.", required=True)-- class Meta:- doc_category = DOC_CATEGORY_GIFT_CARDS---class ExportGiftCards(BaseExportMutation):- class Arguments:- input = ExportGiftCardsInput(- required=True, description="Fields required to export gift cards data."- )-- class Meta:- description = "Export gift cards to csv file."- doc_category = DOC_CATEGORY_GIFT_CARDS- permissions = (GiftcardPermissions.MANAGE_GIFT_CARD,)- error_type_class = ExportError- webhook_events_info = [- WebhookEventInfo(- type=WebhookEventAsyncType.NOTIFY_USER,- description="A notification for the exported file.",- ),- WebhookEventInfo(- type=WebhookEventAsyncType.GIFT_CARD_EXPORT_COMPLETED,- description="A notification for the exported file.",- ),- ]-- @classmethod- def perform_mutation( # type: ignore[override]- cls, _root, info: ResolveInfo, /, *, input- ):- scope = cls.get_scope(input, GiftCard)- file_type = input["file_type"]-- app = get_app_promise(info.context).get()-- export_file = csv_models.ExportFile.objects.create(- app=app, user=info.context.user- )- export_started_event(export_file=export_file, app=app, user=info.context.user)- export_gift_cards_task.delay(export_file.pk, scope, file_type)-- export_file.refresh_from_db()- return cls(export_file=export_file)diff --git a/saleor/graphql/csv/mutations/export_voucher_codes.py b/saleor/graphql/csv/mutations/export_voucher_codes.pydeleted file mode 100644index c4c9921d4b..0000000000--- a/saleor/graphql/csv/mutations/export_voucher_codes.py+++ /dev/null@@ -1,108 +0,0 @@-import graphene-from django.core.exceptions import ValidationError--from ....csv import models as csv_models-from ....csv.error_codes import ExportErrorCode-from ....csv.events import export_started_event-from ....csv.tasks import export_voucher_codes_task-from ....permission.enums import DiscountPermissions-from ....webhook.event_types import WebhookEventAsyncType-from ...app.dataloaders import get_app_promise-from ...core import ResolveInfo-from ...core.doc_category import DOC_CATEGORY_DISCOUNTS-from ...core.types import BaseInputObjectType, ExportError, NonNullList-from ...core.utils import WebhookEventInfo, raise_validation_error-from ...core.validators import validate_one_of_args_is_in_mutation-from ..enums import FileTypeEnum-from .base_export import BaseExportMutation---class ExportVoucherCodesInput(BaseInputObjectType):- voucher_id = graphene.GlobalID(- required=False,- description=(- "The ID of the voucher. "- "If provided, exports all codes belonging to the voucher."- ),- )- ids = NonNullList(- graphene.ID,- description="List of voucher code IDs to export.",- required=False,- )- file_type = FileTypeEnum(description="Type of exported file.", required=True)-- class Meta:- doc_category = DOC_CATEGORY_DISCOUNTS---class ExportVoucherCodes(BaseExportMutation):- class Arguments:- input = ExportVoucherCodesInput(- required=True, description="Fields required to export voucher codes."- )-- class Meta:- description = "Export voucher codes to csv/xlsx file."- doc_category = DOC_CATEGORY_DISCOUNTS- permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)- error_type_class = ExportError- webhook_events_info = [- WebhookEventInfo(- type=WebhookEventAsyncType.VOUCHER_CODE_EXPORT_COMPLETED,- description="A notification for the exported file.",- ),- ]-- @classmethod- def clean_input(cls, input):- voucher_id = input.get("voucher_id")- ids = input.get("ids") or []- validate_one_of_args_is_in_mutation("voucher_id", voucher_id, "ids", ids)-- if voucher_id:- try:- input["voucher_id"] = cls.get_global_id_or_error(- id=voucher_id, only_type="Voucher"- )- except ValidationError:- raise_validation_error(- field="voucherId",- message="Invalid voucher ID.",- code=ExportErrorCode.INVALID,- )-- if ids:- try:- input["ids"] = cls.get_global_ids_or_error(- ids=ids, only_type="VoucherCode"- )- except ValidationError:- raise_validation_error(- field="ids",- message="Invalid voucher code IDs.",- code=ExportErrorCode.INVALID,- )- return input-- @classmethod- def perform_mutation( # type: ignore[override]- cls, _root, info: ResolveInfo, /, *, input- ):- cls.clean_input(input)- file_type = input["file_type"]- ids = input.get("ids") or []- voucher_id = input.get("voucher_id")-- app = get_app_promise(info.context).get()-- export_file = csv_models.ExportFile.objects.create(- app=app, user=info.context.user- )- export_started_event(export_file=export_file, app=app, user=info.context.user)- export_voucher_codes_task.delay(- export_file.pk, file_type, voucher_id=voucher_id, ids=ids- )-- export_file.refresh_from_db()- return cls(export_file=export_file)diff --git a/saleor/graphql/csv/schema.py b/saleor/graphql/csv/schema.pyindex e8e93d3f98..7aff4391e3 100644--- a/saleor/graphql/csv/schema.py+++ b/saleor/graphql/csv/schema.py@@ -7,7 +7,7 @@ from ..core.descriptions import DEPRECATED_EXPORT_MUTATIONSfrom ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.utils import from_global_id_or_errorfrom .filters import ExportFileFilterInput-from .mutations import ExportGiftCards, ExportProducts, ExportVoucherCodes+from .mutations import ExportProductsfrom .resolvers import resolve_export_file, resolve_export_filesfrom .sorters import ExportFileSortingInputfrom .types import ExportFile, ExportFileCountableConnection@@ -46,9 +46,3 @@ class CsvMutations(graphene.ObjectType):export_products = ExportProducts.Field(deprecation_reason=DEPRECATED_EXPORT_MUTATIONS)- export_gift_cards = ExportGiftCards.Field(- deprecation_reason=DEPRECATED_EXPORT_MUTATIONS- )- export_voucher_codes = ExportVoucherCodes.Field(- deprecation_reason=DEPRECATED_EXPORT_MUTATIONS- )diff --git a/saleor/graphql/csv/tests/mutations/test_export_gift_cards.py b/saleor/graphql/csv/tests/mutations/test_export_gift_cards.pydeleted file mode 100644index c7feffc194..0000000000--- a/saleor/graphql/csv/tests/mutations/test_export_gift_cards.py+++ /dev/null@@ -1,380 +0,0 @@-from unittest.mock import ANY, patch--import graphene-import pytest--from .....csv import ExportEvents-from .....csv.error_codes import ExportErrorCode-from .....csv.models import ExportEvent-from ....tests.utils import get_graphql_content-from ...enums import ExportScope, FileTypeEnum--EXPORT_GIFT_CARDS_MUTATION = """- mutation ExportGiftCards($input: ExportGiftCardsInput!){- exportGiftCards(input: $input){- exportFile {- id- status- createdAt- updatedAt- url- user {- }- app {- name- }- }- errors {- field- code- message- }- }- }-"""--- ("input", "called_data"),- [- (- {- "scope": ExportScope.ALL.name,- "fileType": FileTypeEnum.CSV.name,- },- {"all": ""},- ),- (- {- "scope": ExportScope.FILTER.name,- "filter": {"tags": ["abc"]},- "fileType": FileTypeEnum.CSV.name,- },- {"filter": {"tags": ["abc"]}},- ),- ],-)-@patch("saleor.graphql.csv.mutations.export_gift_cards.export_gift_cards_task.delay")-def test_export_gift_cards_mutation(- export_gift_cards_mock,- input,- called_data,- staff_api_client,- gift_card,- gift_card_expiry_date,- permission_manage_gift_card,- permission_manage_apps,-):- # given- query = EXPORT_GIFT_CARDS_MUTATION- user = staff_api_client.user- variables = {"input": input}-- # when- response = staff_api_client.post_graphql(- query,- variables=variables,- permissions=[permission_manage_gift_card, permission_manage_apps],- )- content = get_graphql_content(response)-- # then- data = content["data"]["exportGiftCards"]- export_file_data = data["exportFile"]-- export_gift_cards_mock.assert_called_once_with(- ANY, called_data, 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_gift_cards.export_gift_cards_task.delay")-def test_export_gift_cards_mutation_ids_scope(- export_gift_cards_mock,- staff_api_client,- gift_card,- gift_card_expiry_date,- gift_card_used,- permission_manage_gift_card,- permission_manage_apps,- permission_manage_staff,-):- # given- query = EXPORT_GIFT_CARDS_MUTATION- user = staff_api_client.user-- gift_cards = [gift_card_expiry_date, gift_card_used]-- ids = [graphene.Node.to_global_id("GiftCard", card.pk) for card in gift_cards]-- variables = {- "input": {- "scope": ExportScope.IDS.name,- "ids": ids,- "fileType": FileTypeEnum.XLSX.name,- }- }-- # when- response = staff_api_client.post_graphql(- query,- variables=variables,- permissions=[- permission_manage_gift_card,- permission_manage_apps,- permission_manage_staff,- ],- )- content = get_graphql_content(response)-- # then- data = content["data"]["exportGiftCards"]- export_file_data = data["exportFile"]-- export_gift_cards_mock.assert_called_once()- (- call_args,- call_kwargs,- ) = export_gift_cards_mock.call_args-- assert set(call_args[1]["ids"]) == {str(card.pk) for card in gift_cards}- assert call_args[2] == FileTypeEnum.XLSX.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_gift_cards.export_gift_cards_task.delay")-def test_export_gift_cards_mutation_ids_scope_invalid_object_type(- export_gift_cards_mock,- staff_api_client,- gift_card,- gift_card_expiry_date,- gift_card_used,- permission_manage_gift_card,- permission_manage_apps,- permission_manage_staff,-):- # given- query = EXPORT_GIFT_CARDS_MUTATION- user = staff_api_client.user-- gift_cards = [gift_card_expiry_date, gift_card_used]-- ids = [graphene.Node.to_global_id("Product", card.pk) for card in gift_cards]-- variables = {- "input": {- "scope": ExportScope.IDS.name,- "ids": ids,- "fileType": FileTypeEnum.CSV.name,- }- }-- # when- response = staff_api_client.post_graphql(- query,- variables=variables,- permissions=[- permission_manage_gift_card,- permission_manage_apps,- permission_manage_staff,- ],- )- content = get_graphql_content(response)-- # then- data = content["data"]["exportGiftCards"]-- errors = data["errors"]- assert len(errors) == 1- assert not data["exportFile"]- assert errors[0]["field"] == "ids"- assert errors[0]["code"] == ExportErrorCode.GRAPHQL_ERROR.name-- assert not ExportEvent.objects.filter(- user=user, app=None, type=ExportEvents.EXPORT_PENDING- )-- export_gift_cards_mock.assert_not_called()--- ("input", "error_field"),- [- (- {- "scope": ExportScope.FILTER.name,- "fileType": FileTypeEnum.CSV.name,- },- "filter",- ),- (- {- "scope": ExportScope.IDS.name,- "fileType": FileTypeEnum.CSV.name,- },- "ids",- ),- ],-)-@patch("saleor.graphql.csv.mutations.export_gift_cards.export_gift_cards_task.delay")-def test_export_gift_cards_mutation_failed(- export_gift_cards_mock,- input,- error_field,- app_api_client,- gift_card,- gift_card_expiry_date,- permission_manage_gift_card,- permission_manage_apps,- permission_manage_staff,-):- # given- query = EXPORT_GIFT_CARDS_MUTATION- app = app_api_client.app-- variables = {"input": input}-- # when- response = app_api_client.post_graphql(- query,- variables=variables,- permissions=[- permission_manage_gift_card,- permission_manage_apps,- permission_manage_staff,- ],- )- content = get_graphql_content(response)-- # then- data = content["data"]["exportGiftCards"]-- errors = data["errors"]- assert len(errors) == 1- assert not data["exportFile"]- assert errors[0]["field"] == error_field- assert errors[0]["code"] == ExportErrorCode.REQUIRED.name-- assert not ExportEvent.objects.filter(- user=None, app=app, type=ExportEvents.EXPORT_PENDING- )-- export_gift_cards_mock.assert_not_called()---EXPORT_GIFT_CARDS_MUTATION_BY_APP = """- mutation ExportGiftCards($input: ExportGiftCardsInput!){- exportGiftCards(input: $input){- exportFile {- id- status- createdAt- updatedAt- url- app {- name- }- }- errors {- field- code- message- }- }- }-"""---@patch("saleor.graphql.csv.mutations.export_gift_cards.export_gift_cards_task.delay")-def test_export_gift_cards_mutation_by_app(- export_gift_cards_mock,- app_api_client,- gift_card,- gift_card_expiry_date,- permission_manage_gift_card,- permission_manage_apps,- permission_manage_staff,-):- # given- query = EXPORT_GIFT_CARDS_MUTATION_BY_APP- app = app_api_client.app- variables = {- "input": {- "scope": ExportScope.ALL.name,- "fileType": FileTypeEnum.XLSX.name,- }- }-- # when- response = app_api_client.post_graphql(- query,- variables=variables,- permissions=[- permission_manage_gift_card,- permission_manage_apps,- ],- )- content = get_graphql_content(response)-- # then- data = content["data"]["exportGiftCards"]- export_file_data = data["exportFile"]-- export_gift_cards_mock.assert_called_once_with(- ANY, {"all": ""}, FileTypeEnum.XLSX.value- )-- assert not data["errors"]- assert data["exportFile"]["id"]- assert export_file_data["createdAt"]- assert export_file_data["app"]["name"] == app.name- assert ExportEvent.objects.filter(- user=None, app=app, type=ExportEvents.EXPORT_PENDING- ).exists()---@patch("saleor.plugins.manager.PluginsManager.gift_card_export_completed")-def test_export_gift_cards_webhooks(- gift_card_export_completed_mock,- staff_api_client,- gift_card,- gift_card_expiry_date,- permission_manage_gift_card,- permission_manage_apps,- media_root,-):- # given- query = EXPORT_GIFT_CARDS_MUTATION- input = {"scope": ExportScope.ALL.name, "fileType": FileTypeEnum.CSV.name}- variables = {"input": input}-- # when- response = staff_api_client.post_graphql(- query,- variables=variables,- permissions=[permission_manage_gift_card, permission_manage_apps],- )- content = get_graphql_content(response)-- # then- data = content["data"]["exportGiftCards"]- assert not data["errors"]-- gift_card_export_completed_mock.assert_called_once()diff --git a/saleor/graphql/csv/tests/mutations/test_export_voucher_codes.py b/saleor/graphql/csv/tests/mutations/test_export_voucher_codes.pydeleted file mode 100644index ad4ee23eaa..0000000000--- a/saleor/graphql/csv/tests/mutations/test_export_voucher_codes.py+++ /dev/null@@ -1,386 +0,0 @@-from unittest.mock import patch--import graphene--from .....csv import ExportEvents-from .....csv.error_codes import ExportErrorCode-from .....csv.models import ExportEvent-from ....tests.utils import assert_no_permission, get_graphql_content-from ...enums import FileTypeEnum--EXPORT_VOUCHER_CODES_MUTATION = """- mutation ExportVoucherCodes($input: ExportVoucherCodesInput!){- exportVoucherCodes(input: $input){- exportFile {- id- status- createdAt- updatedAt- url- user {- }- app {- name- }- }- errors {- field- code- message- }- }- }-"""---@patch(- "saleor.graphql.csv.mutations.export_voucher_codes.export_voucher_codes_task.delay"-)-def test_export_voucher_codes_by_voucher_id(- export_voucher_codes_mock,- staff_api_client,- voucher_with_many_codes,- permission_manage_discounts,-):- # given- user = staff_api_client.user- voucher_id = graphene.Node.to_global_id("Voucher", voucher_with_many_codes.id)- variables = {- "input": {- "voucherId": voucher_id,- "fileType": FileTypeEnum.CSV.name,- }- }-- # when- response = staff_api_client.post_graphql(- EXPORT_VOUCHER_CODES_MUTATION,- variables=variables,- permissions=[permission_manage_discounts],- )-- # then- content = get_graphql_content(response)- data = content["data"]["exportVoucherCodes"]- export_file_data = data["exportFile"]-- 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()-- export_voucher_codes_mock.assert_called_once()---@patch(- "saleor.graphql.csv.mutations.export_voucher_codes.export_voucher_codes_task.delay"-)-def test_export_voucher_codes_by_voucher_code_ids(- export_voucher_codes_mock,- staff_api_client,- voucher_with_many_codes,- permission_manage_discounts,-):- # given- user = staff_api_client.user- code_ids = [- graphene.Node.to_global_id("VoucherCode", code.id)- for code in voucher_with_many_codes.codes.all()- ]- variables = {- "input": {- "ids": code_ids,- "fileType": FileTypeEnum.CSV.name,- }- }-- # when- response = staff_api_client.post_graphql(- EXPORT_VOUCHER_CODES_MUTATION,- variables=variables,- permissions=[permission_manage_discounts],- )-- # then- content = get_graphql_content(response)- data = content["data"]["exportVoucherCodes"]- export_file_data = data["exportFile"]-- 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()-- export_voucher_codes_mock.assert_called_once()---@patch(- "saleor.graphql.csv.mutations.export_voucher_codes.export_voucher_codes_task.delay"-)-def test_export_voucher_codes_by_app(- export_voucher_codes_mock,- app_api_client,- voucher_with_many_codes,- permission_manage_discounts,- permission_manage_apps,-):- # given- query = """- mutation ExportVoucherCodes($input: ExportVoucherCodesInput!){- exportVoucherCodes(input: $input){- exportFile {- id- status- createdAt- updatedAt- url- app {- name- }- }- errors {- field- code- message- }- }- }- """- app = app_api_client.app- voucher_id = graphene.Node.to_global_id("Voucher", voucher_with_many_codes.id)- variables = {- "input": {- "voucherId": voucher_id,- "fileType": FileTypeEnum.CSV.name,- }- }-- # when- response = app_api_client.post_graphql(- query,- variables=variables,- permissions=[permission_manage_discounts, permission_manage_apps],- )-- # then- content = get_graphql_content(response)- data = content["data"]["exportVoucherCodes"]- export_file_data = data["exportFile"]-- assert not data["errors"]- assert data["exportFile"]["id"]- assert export_file_data["createdAt"]- assert export_file_data["app"]["name"] == app.name- assert ExportEvent.objects.filter(- user=None, app=app, type=ExportEvents.EXPORT_PENDING- ).exists()-- export_voucher_codes_mock.assert_called_once()---def test_export_voucher_codes_by_staff_no_permission(- staff_api_client,- voucher_with_many_codes,-):- # given- voucher_id = graphene.Node.to_global_id("Voucher", voucher_with_many_codes.id)- variables = {- "input": {- "voucherId": voucher_id,- "fileType": FileTypeEnum.CSV.name,- }- }-- # when- response = staff_api_client.post_graphql(- EXPORT_VOUCHER_CODES_MUTATION,- variables=variables,- )-- # then- assert_no_permission(response)---def test_export_voucher_codes_by_app_no_permission(- app_api_client,- voucher_with_many_codes,-):- # given- voucher_id = graphene.Node.to_global_id("Voucher", voucher_with_many_codes.id)- variables = {- "input": {- "voucherId": voucher_id,- "fileType": FileTypeEnum.CSV.name,- }- }-- # when- response = app_api_client.post_graphql(- EXPORT_VOUCHER_CODES_MUTATION,- variables=variables,- )-- # then- assert_no_permission(response)---def test_export_voucher_codes_error_too_many_arguments(- staff_api_client,- voucher_with_many_codes,- permission_manage_discounts,-):- # given- voucher_id = graphene.Node.to_global_id("Voucher", voucher_with_many_codes.id)- code_ids = [- graphene.Node.to_global_id("VoucherCode", code.id)- for code in voucher_with_many_codes.codes.all()- ]- variables = {- "input": {- "voucherId": voucher_id,- "ids": code_ids,- "fileType": FileTypeEnum.CSV.name,- }- }-- # when- response = staff_api_client.post_graphql(- EXPORT_VOUCHER_CODES_MUTATION,- variables=variables,- permissions=[permission_manage_discounts],- )-- # then- content = get_graphql_content(response)- data = content["data"]["exportVoucherCodes"]-- assert not data["exportFile"]- error = data["errors"][0]- assert error["field"] is None- assert error["code"] == ExportErrorCode.GRAPHQL_ERROR.name---def test_export_voucher_codes_error_lack_of_required_argument(- staff_api_client,- permission_manage_discounts,-):- # given- variables = {"input": {"fileType": FileTypeEnum.CSV.name}}-- # when- response = staff_api_client.post_graphql(- EXPORT_VOUCHER_CODES_MUTATION,- variables=variables,- permissions=[permission_manage_discounts],- )-- # then- content = get_graphql_content(response)- data = content["data"]["exportVoucherCodes"]-- assert not data["exportFile"]- error = data["errors"][0]- assert error["field"] is None- assert error["code"] == ExportErrorCode.GRAPHQL_ERROR.name---def test_export_voucher_codes_error_invalid_voucher_id(- staff_api_client,- voucher_with_many_codes,- permission_manage_discounts,-):- # given- voucher_id = graphene.Node.to_global_id("Product", voucher_with_many_codes.id)- variables = {- "input": {- "voucherId": voucher_id,- "fileType": FileTypeEnum.CSV.name,- }- }-- # when- response = staff_api_client.post_graphql(- EXPORT_VOUCHER_CODES_MUTATION,- variables=variables,- permissions=[permission_manage_discounts],- )-- # then- content = get_graphql_content(response)- data = content["data"]["exportVoucherCodes"]-- assert not data["exportFile"]- error = data["errors"][0]- assert error["field"] == "voucherId"- assert error["code"] == ExportErrorCode.INVALID.name---def test_export_voucher_codes_error_invalid_voucher_code_ids(- staff_api_client,- voucher_with_many_codes,- permission_manage_discounts,-):- # given- code_ids = [- graphene.Node.to_global_id("Product", code.id)- for code in voucher_with_many_codes.codes.all()- ]- variables = {- "input": {- "ids": code_ids,- "fileType": FileTypeEnum.CSV.name,- }- }-- # when- response = staff_api_client.post_graphql(- EXPORT_VOUCHER_CODES_MUTATION,- variables=variables,- permissions=[permission_manage_discounts],- )-- # then- content = get_graphql_content(response)- data = content["data"]["exportVoucherCodes"]-- assert not data["exportFile"]- error = data["errors"][0]- assert error["field"] == "ids"- assert error["code"] == ExportErrorCode.INVALID.name---@patch("saleor.plugins.manager.PluginsManager.voucher_code_export_completed")-def test_export_voucher_webhooks(- export_completed_webhook_mock,- staff_api_client,- voucher_with_many_codes,- permission_manage_discounts,- media_root,-):- # given- voucher_id = graphene.Node.to_global_id("Voucher", voucher_with_many_codes.id)- variables = {- "input": {- "voucherId": voucher_id,- "fileType": FileTypeEnum.CSV.name,- }- }-- # when- staff_api_client.post_graphql(- EXPORT_VOUCHER_CODES_MUTATION,- variables=variables,- permissions=[permission_manage_discounts],- )-- # then- export_completed_webhook_mock.assert_called_once()diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 008ea446a4..1d93437d58 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1886,9 +1886,6 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {"""A gift card metadata is updated."""GIFT_CARD_METADATA_UPDATED- """A gift card export is completed."""- GIFT_CARD_EXPORT_COMPLETED @deprecated(reason: "Export functionality is deprecated and will be removed. All data can be fetched via the GraphQL API and parsed into the desired format by apps or external tools.")-"""A new menu created."""MENU_CREATED@@ -2269,9 +2266,6 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {"""A voucher metadata is updated."""VOUCHER_METADATA_UPDATED- """A voucher code export is completed."""- VOUCHER_CODE_EXPORT_COMPLETED @deprecated(reason: "Export functionality is deprecated and will be removed. All data can be fetched via the GraphQL API and parsed into the desired format by apps or external tools.")-"""An observability event is created."""OBSERVABILITY @deprecated(reason: "The observability feature is no longer supported. This event will be removed in Saleor 3.24.")@@ -2516,9 +2510,6 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {"""A gift card metadata is updated."""GIFT_CARD_METADATA_UPDATED- """A gift card export is completed."""- GIFT_CARD_EXPORT_COMPLETED @deprecated(reason: "Export functionality is deprecated and will be removed. All data can be fetched via the GraphQL API and parsed into the desired format by apps or external tools.")-"""A new menu created."""MENU_CREATED@@ -2899,9 +2890,6 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {"""A voucher metadata is updated."""VOUCHER_METADATA_UPDATED- """A voucher code export is completed."""- VOUCHER_CODE_EXPORT_COMPLETED @deprecated(reason: "Export functionality is deprecated and will be removed. All data can be fetched via the GraphQL API and parsed into the desired format by apps or external tools.")-"""An observability event is created."""OBSERVABILITY @deprecated(reason: "The observability feature is no longer supported. This event will be removed in Saleor 3.24.")@@ -14309,7 +14297,6 @@ enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {GIFT_CARD_SENTGIFT_CARD_STATUS_CHANGEDGIFT_CARD_METADATA_UPDATED- GIFT_CARD_EXPORT_COMPLETED @deprecated(reason: "Export functionality is deprecated and will be removed. All data can be fetched via the GraphQL API and parsed into the desired format by apps or external tools.")MENU_CREATEDMENU_UPDATEDMENU_DELETED@@ -14424,7 +14411,6 @@ enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {VOUCHER_CODES_CREATEDVOUCHER_CODES_DELETEDVOUCHER_METADATA_UPDATED- VOUCHER_CODE_EXPORT_COMPLETED @deprecated(reason: "Export functionality is deprecated and will be removed. All data can be fetched via the GraphQL API and parsed into the desired format by apps or external tools.")OBSERVABILITY @deprecated(reason: "The observability feature is no longer supported. This event will be removed in Saleor 3.24.")THUMBNAIL_CREATEDSHOP_METADATA_UPDATED@@ -20979,33 +20965,6 @@ type Mutation {input: ExportProductsInput!): ExportProducts @doc(category: "Products") @webhookEventsInfo(asyncEvents: [NOTIFY_USER, PRODUCT_EXPORT_COMPLETED], syncEvents: []) @deprecated(reason: "Export functionality is deprecated and will be removed. All data can be fetched via the GraphQL API and parsed into the desired format by apps or external tools.")- """- Export gift cards to csv file.-- Requires one of the following permissions: MANAGE_GIFT_CARD.-- Triggers the following webhook events:- - NOTIFY_USER (async): A notification for the exported file.- - GIFT_CARD_EXPORT_COMPLETED (async): A notification for the exported file.- """- exportGiftCards(- """Fields required to export gift cards data."""- input: ExportGiftCardsInput!- ): ExportGiftCards @doc(category: "Gift cards") @webhookEventsInfo(asyncEvents: [NOTIFY_USER, GIFT_CARD_EXPORT_COMPLETED], syncEvents: []) @deprecated(reason: "Export functionality is deprecated and will be removed. All data can be fetched via the GraphQL API and parsed into the desired format by apps or external tools.")-- """- Export voucher codes to csv/xlsx file.-- Requires one of the following permissions: MANAGE_DISCOUNTS.-- Triggers the following webhook events:- - VOUCHER_CODE_EXPORT_COMPLETED (async): A notification for the exported file.- """- exportVoucherCodes(- """Fields required to export voucher codes."""- input: ExportVoucherCodesInput!- ): ExportVoucherCodes @doc(category: "Discounts") @webhookEventsInfo(asyncEvents: [VOUCHER_CODE_EXPORT_COMPLETED], syncEvents: []) @deprecated(reason: "Export functionality is deprecated and will be removed. All data can be fetched via the GraphQL API and parsed into the desired format by apps or external tools.")-"""Upload a file. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec@@ -30882,66 +30841,6 @@ enum FileTypesEnum {XLSX}-"""-Export gift cards to csv file.--Requires one of the following permissions: MANAGE_GIFT_CARD.--Triggers the following webhook events:-- NOTIFY_USER (async): A notification for the exported file.-- GIFT_CARD_EXPORT_COMPLETED (async): A notification for the exported file.-"""-type ExportGiftCards @doc(category: "Gift cards") @webhookEventsInfo(asyncEvents: [NOTIFY_USER, GIFT_CARD_EXPORT_COMPLETED], syncEvents: []) {- """- The newly created export file job which is responsible for export data.- """- exportFile: ExportFile- errors: [ExportError!]!-}--input ExportGiftCardsInput @doc(category: "Gift cards") {- """Determine which gift cards should be exported."""- scope: ExportScope!-- """Filtering options for gift cards."""- filter: GiftCardFilterInput-- """List of gift cards IDs to export."""- ids: [ID!]-- """Type of exported file."""- fileType: FileTypesEnum!-}--"""-Export voucher codes to csv/xlsx file.--Requires one of the following permissions: MANAGE_DISCOUNTS.--Triggers the following webhook events:-- VOUCHER_CODE_EXPORT_COMPLETED (async): A notification for the exported file.-"""-type ExportVoucherCodes @doc(category: "Discounts") @webhookEventsInfo(asyncEvents: [VOUCHER_CODE_EXPORT_COMPLETED], syncEvents: []) {- """- The newly created export file job which is responsible for export data.- """- exportFile: ExportFile- errors: [ExportError!]!-}--input ExportVoucherCodesInput @doc(category: "Discounts") {- """- The ID of the voucher. If provided, exports all codes belonging to the voucher.- """- voucherId: ID-- """List of voucher code IDs to export."""- ids: [ID!]-- """Type of exported file."""- fileType: FileTypesEnum!-}-"""Upload a file. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec@@ -36060,28 +35959,6 @@ type GiftCardMetadataUpdated implements Event @doc(category: "Gift cards") {giftCard: GiftCard}-"""-Event sent when gift card export is completed.--Export functionality is deprecated and will be removed. All data can be fetched via the GraphQL API and parsed into the desired format by apps or external tools.-"""-type GiftCardExportCompleted implements Event @doc(category: "Gift cards") {- """Time of the event."""- issuedAt: DateTime-- """Saleor version that triggered the event."""- version: String-- """The user or application that triggered the event."""- issuingPrincipal: IssuingPrincipal-- """The application receiving the webhook."""- recipient: App-- """The export file for gift cards."""- export: ExportFile @deprecated(reason: "Export functionality is deprecated and will be removed. All data can be fetched via the GraphQL API and parsed into the desired format by apps or external tools.")-}-"""Event sent when new menu is created."""type MenuCreated implements Event @doc(category: "Menu") {"""Time of the event."""@@ -37851,28 +37728,6 @@ type VoucherMetadataUpdated implements Event @doc(category: "Discounts") {): Voucher}-"""-Event sent when voucher code export is completed.--Export functionality is deprecated and will be removed. All data can be fetched via the GraphQL API and parsed into the desired format by apps or external tools.-"""-type VoucherCodeExportCompleted implements Event @doc(category: "Discounts") {- """Time of the event."""- issuedAt: DateTime-- """Saleor version that triggered the event."""- version: String-- """The user or application that triggered the event."""- issuingPrincipal: IssuingPrincipal-- """The application receiving the webhook."""- recipient: App-- """The export file for voucher codes."""- export: ExportFile @deprecated(reason: "Export functionality is deprecated and will be removed. All data can be fetched via the GraphQL API and parsed into the desired format by apps or external tools.")-}-"""Event sent when new warehouse is created."""type WarehouseCreated implements Event @doc(category: "Products") {"""Time of the event."""diff --git a/saleor/graphql/tests/queries/fragments.py b/saleor/graphql/tests/queries/fragments.pyindex 3a31bede39..548fdf84e4 100644--- a/saleor/graphql/tests/queries/fragments.py+++ b/saleor/graphql/tests/queries/fragments.py@@ -438,18 +438,6 @@ fragment GiftCardDetails on GiftCard{}"""-GIFT_CARD_EXPORT_DETAILS = """-fragment GiftCardExportDetails on ExportFile{- id- createdAt- updatedAt- status- url- message-}-"""--VOUCHER_DETAILS = """fragment VoucherDetails on Voucher{id@@ -470,18 +458,6 @@ fragment VoucherCodeDetails on VoucherCode{"""-VOUCHER_CODE_EXPORT_DETAILS = """-fragment VoucherCodeExportDetails on ExportFile {- id- createdAt- updatedAt- status- url- message-}-"""--MENU_DETAILS = """fragment MenuDetails on Menu{iddiff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.pyindex a04a631b00..912a342764 100644--- a/saleor/graphql/webhook/enums.py+++ b/saleor/graphql/webhook/enums.py@@ -101,7 +101,6 @@ WEBHOOK_EVENT_DESCRIPTION = {WebhookEventAsyncType.GIFT_CARD_SENT: "A gift card has been sent.",WebhookEventAsyncType.GIFT_CARD_STATUS_CHANGED: "A gift card status is changed.",WebhookEventAsyncType.GIFT_CARD_METADATA_UPDATED: "A gift card metadata is updated.",- WebhookEventAsyncType.GIFT_CARD_EXPORT_COMPLETED: "A gift card export is completed.",WebhookEventAsyncType.INVOICE_REQUESTED: "An invoice for order requested.",WebhookEventAsyncType.INVOICE_DELETED: "An invoice is deleted.",WebhookEventAsyncType.INVOICE_SENT: "Invoice has been sent.",@@ -240,9 +239,6 @@ WEBHOOK_EVENT_DESCRIPTION = {WebhookEventAsyncType.VOUCHER_UPDATED: "A voucher is updated.",WebhookEventAsyncType.VOUCHER_DELETED: "A voucher is deleted.",WebhookEventAsyncType.VOUCHER_METADATA_UPDATED: "A voucher metadata is updated.",- WebhookEventAsyncType.VOUCHER_CODE_EXPORT_COMPLETED: (- "A voucher code export is completed."- ),WebhookEventAsyncType.ANY: "All the events.",WebhookEventAsyncType.OBSERVABILITY: "An observability event is created.",WebhookEventAsyncType.THUMBNAIL_CREATED: "A thumbnail is created.",@@ -290,8 +286,6 @@ def description(enum):# Events emitted only by the deprecated export mutations, removed together with them.EXPORT_COMPLETED_EVENTS = {WebhookEventAsyncType.PRODUCT_EXPORT_COMPLETED,- WebhookEventAsyncType.GIFT_CARD_EXPORT_COMPLETED,- WebhookEventAsyncType.VOUCHER_CODE_EXPORT_COMPLETED,}diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex 68f5852912..d6cdcda57b 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -62,7 +62,6 @@ from ..core.descriptions import ()from ..core.doc_category import (DOC_CATEGORY_CHECKOUT,- DOC_CATEGORY_DISCOUNTS,DOC_CATEGORY_GIFT_CARDS,DOC_CATEGORY_MISC,DOC_CATEGORY_ORDERS,@@ -752,29 +751,6 @@ class GiftCardMetadataUpdated(SubscriptionObjectType, GiftCardBase):description = "Event sent when gift card metadata is updated."-class GiftCardExportCompleted(SubscriptionObjectType):- export = graphene.Field(- "saleor.graphql.csv.types.ExportFile",- description="The export file for gift cards.",- deprecation_reason=DEPRECATED_EXPORT_MUTATIONS,- )-- class Meta:- root_type = "ExportFile"- enable_dry_run = True- interfaces = (Event,)- description = (- "Event sent when gift card export is completed."- + DEPRECATED_EXPORT_MUTATIONS_TYPE_DESCRIPTION- )- doc_category = DOC_CATEGORY_GIFT_CARDS-- @staticmethod- def resolve_export(root, info: ResolveInfo):- _, export_file = root- return export_file--class MenuBase(AbstractType):menu = graphene.Field("saleor.graphql.menu.types.Menu",@@ -2634,29 +2610,6 @@ class VoucherMetadataUpdated(SubscriptionObjectType, VoucherBase):description = "Event sent when voucher metadata is updated."-class VoucherCodeExportCompleted(SubscriptionObjectType):- export = graphene.Field(- "saleor.graphql.csv.types.ExportFile",- description="The export file for voucher codes.",- deprecation_reason=DEPRECATED_EXPORT_MUTATIONS,- )-- class Meta:- root_type = "ExportFile"- enable_dry_run = True- interfaces = (Event,)- description = (- "Event sent when voucher code export is completed."- + DEPRECATED_EXPORT_MUTATIONS_TYPE_DESCRIPTION- )- doc_category = DOC_CATEGORY_DISCOUNTS-- @staticmethod- def resolve_export(root, _info: ResolveInfo):- _, export_file = root- return export_file--class ShopMetadataUpdated(SubscriptionObjectType, AbstractType):shop = graphene.Field(Shop, description="Shop data.")@@ -3262,7 +3215,6 @@ ASYNC_WEBHOOK_TYPES_MAP = {WebhookEventAsyncType.GIFT_CARD_SENT: GiftCardSent,WebhookEventAsyncType.GIFT_CARD_STATUS_CHANGED: GiftCardStatusChanged,WebhookEventAsyncType.GIFT_CARD_METADATA_UPDATED: GiftCardMetadataUpdated,- WebhookEventAsyncType.GIFT_CARD_EXPORT_COMPLETED: GiftCardExportCompleted,WebhookEventAsyncType.MENU_CREATED: MenuCreated,WebhookEventAsyncType.MENU_UPDATED: MenuUpdated,WebhookEventAsyncType.MENU_DELETED: MenuDeleted,@@ -3377,7 +3329,6 @@ ASYNC_WEBHOOK_TYPES_MAP = {WebhookEventAsyncType.VOUCHER_CODES_CREATED: VoucherCodesCreated,WebhookEventAsyncType.VOUCHER_CODES_DELETED: VoucherCodesDeleted,WebhookEventAsyncType.VOUCHER_METADATA_UPDATED: VoucherMetadataUpdated,- WebhookEventAsyncType.VOUCHER_CODE_EXPORT_COMPLETED: VoucherCodeExportCompleted,WebhookEventAsyncType.WAREHOUSE_CREATED: WarehouseCreated,WebhookEventAsyncType.WAREHOUSE_UPDATED: WarehouseUpdated,WebhookEventAsyncType.WAREHOUSE_DELETED: WarehouseDeleted,diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex b821b8ef88..882fb5f54f 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -819,15 +819,6 @@ class BasePlugin:# Webhook-related functionality will be moved from the plugin to core modules.gift_card_status_changed: Callable[["GiftCard", None, None], None]- # Trigger when gift cards export is completed.- #- # Overwrite this method if you need to trigger specific logic after a gift cards- # export is completed.- #- # Note: This method is deprecated and will be removed in a future release.- # Webhook-related functionality will be moved from the plugin to core modules.- gift_card_export_completed: Callable[["ExportFile", None], None]-# Trigger when draft order is created.## Overwrite this method if you need to trigger specific logic after an order is@@ -1696,10 +1687,6 @@ class BasePlugin:# Webhook-related functionality will be moved from the plugin to core modules.voucher_metadata_updated: Callable[["Voucher", None], None]- # Note: This method is deprecated and will be removed in a future release.- # Webhook-related functionality will be moved from the plugin to core modules.- voucher_code_export_completed: Callable[["ExportFile", None], None]-# Trigger when shop metadata is updated.## Overwrite this method if you need to trigger specific logic after a shopdiff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex f222f9b622..e71ed4a034 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -1954,17 +1954,6 @@ class PluginsManager(PaymentInterface):channel_slug=None,)- # Note: this method is deprecated and will be removed in a future release.- # Webhook-related functionality will be moved from plugin to core modules.- def gift_card_export_completed(self, export: "ExportFile"):- default_value = None- return self.__run_method_on_plugins(- "gift_card_export_completed",- default_value,- export,- channel_slug=None,- )-# Note: this method is deprecated and will be removed in a future release.# Webhook-related functionality will be moved from plugin to core modules.def menu_created(self, menu: "Menu"):@@ -2292,17 +2281,6 @@ class PluginsManager(PaymentInterface):channel_slug=None,)- # Note: this method is deprecated and will be removed in a future release.- # Webhook-related functionality will be moved from plugin to core modules.- def voucher_code_export_completed(self, export: "ExportFile"):- default_value = None- return self.__run_method_on_plugins(- "voucher_code_export_completed",- default_value,- export,- channel_slug=None,- )-# Note: this method is deprecated and will be removed in a future release.# Webhook-related functionality will be moved from plugin to core modules.def shop_metadata_updated(self, shop: "SiteSettings"):diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex ee226c18db..df5ed97303 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -754,17 +754,6 @@ class WebhookPlugin(BasePlugin):self.requestor,)- def gift_card_export_completed(- self, export: "ExportFile", previous_value: None- ) -> None:- if not self.active:- return previous_value- self._trigger_export_event(- WebhookEventAsyncType.GIFT_CARD_EXPORT_COMPLETED,- export,- )- return previous_value-def _get_webhooks_for_channel_events(self,event_type: str,@@ -2754,17 +2743,6 @@ class WebhookPlugin(BasePlugin):)return previous_value- def voucher_code_export_completed(- self, export: "ExportFile", previous_value: None- ) -> None:- if not self.active:- return previous_value- self._trigger_export_event(- WebhookEventAsyncType.VOUCHER_CODE_EXPORT_COMPLETED,- export,- )- return previous_value-def shop_metadata_updated(self, shop: "SiteSettings", previous_value: None) -> None:if not self.active:return previous_valuediff --git a/saleor/tests/e2e/vouchers/test_export_voucher_codes.py b/saleor/tests/e2e/vouchers/test_export_voucher_codes.pydeleted file mode 100644index f904039436..0000000000--- a/saleor/tests/e2e/vouchers/test_export_voucher_codes.py+++ /dev/null@@ -1,370 +0,0 @@-import uuid--import pytest--from ..shop.utils.preparing_shop import prepare_default_shop-from ..utils import assign_permissions-from .utils import (- create_voucher,- create_voucher_channel_listing,- export_voucher_codes,- raw_export_voucher_codes,-)---def create_vouchers_with_multiple_codes(e2e_staff_api_client, channel_id):- voucher_ids = []- voucher_code_ids = []-- for i in range(5):- voucher_code = f"voucher_code_{i + 1}_{uuid.uuid4()}"-- input_data = {- "addCodes": [voucher_code],- "discountValueType": "PERCENTAGE",- "type": "ENTIRE_ORDER",- }- voucher_data = create_voucher(e2e_staff_api_client, input_data)-- voucher_id = voucher_data["id"]- for i in range(len(voucher_data["codes"]["edges"])):- voucher_code_id = voucher_data["codes"]["edges"][i]["node"]["id"]- voucher_code_ids.append(voucher_code_id)-- channel_listing = [- {- "channelId": channel_id,- "discountValue": i + 1,- },- ]- create_voucher_channel_listing(- e2e_staff_api_client,- voucher_id,- channel_listing,- )-- voucher_ids.append(voucher_id)-- return voucher_ids, voucher_code_ids--- ("file_type", "voucher_id_array_index"),- [- ("CSV", 0),- ("XLSX", 2),- ],-)-def test_export_valid_voucher_ids_CORE_0925(- e2e_staff_api_client,- shop_permissions,- permission_manage_discounts,- permission_manage_checkouts,- file_type,- voucher_id_array_index,- media_root,-):- # Before- permissions = [- *shop_permissions,- permission_manage_discounts,- permission_manage_checkouts,- ]- assign_permissions(e2e_staff_api_client, permissions)-- shop_data = prepare_default_shop(e2e_staff_api_client)- channel_id = shop_data["channel"]["id"]-- voucher_ids, _voucher_code_ids = create_vouchers_with_multiple_codes(- e2e_staff_api_client, channel_id- )-- voucher_id_array_index = [voucher_ids[voucher_id_array_index]]-- # Step 1 - Export voucher codes and check status- input_data = {- "fileType": file_type,- "voucherId": voucher_id_array_index,- }- response = export_voucher_codes(e2e_staff_api_client, input_data)-- assert response["status"] == "SUCCESS"--- (- "file_type",- "voucher_code_id_indexes",- "voucher_id_array_index",- ),- [- (- "XLSX",- [3, 5],- 1,- ),- (- "CSV",- [0, 2],- 2,- ),- ],-)-def test_export_voucher_ids_and_codes_CORE_0925(- e2e_staff_api_client,- shop_permissions,- permission_manage_discounts,- permission_manage_checkouts,- file_type,- voucher_code_id_indexes,- voucher_id_array_index,-):- # Before- permissions = [- *shop_permissions,- permission_manage_discounts,- permission_manage_checkouts,- ]- assign_permissions(e2e_staff_api_client, permissions)-- shop_data = prepare_default_shop(e2e_staff_api_client)- channel_id = shop_data["channel"]["id"]-- voucher_ids, voucher_code_ids = create_vouchers_with_multiple_codes(- e2e_staff_api_client, channel_id- )-- voucher_id_array_index = [voucher_ids[voucher_id_array_index]]-- voucher_code_id_indexes = [- index for index in voucher_code_id_indexes if index < len(voucher_code_ids)- ]-- # Step 1 - Export voucher codes and check status- input = {- "fileType": file_type,- "ids": [voucher_code_ids[i] for i in voucher_code_id_indexes],- "voucherId": voucher_id_array_index,- }- response = raw_export_voucher_codes(e2e_staff_api_client, input)- error = response["data"]["exportVoucherCodes"]["errors"][0]- assert error["message"] == "Argument 'voucher_id' cannot be combined with 'ids'"- assert error["code"] == "GRAPHQL_ERROR"--- ("file_type", "voucher_code_id_indexes"),- [- ("CSV", [0]),- ("XLSX", [0, 1, 2, 3, 4, 5]),- ],-)-def test_export_valid_voucher_code_ids_CORE_0925(- e2e_staff_api_client,- shop_permissions,- permission_manage_discounts,- permission_manage_checkouts,- file_type,- voucher_code_id_indexes,- media_root,-):- # Before- permissions = [- *shop_permissions,- permission_manage_discounts,- permission_manage_checkouts,- ]-- assign_permissions(e2e_staff_api_client, permissions)-- shop_data = prepare_default_shop(e2e_staff_api_client)- channel_id = shop_data["channel"]["id"]-- _voucher_ids, voucher_code_ids = create_vouchers_with_multiple_codes(- e2e_staff_api_client, channel_id- )-- voucher_code_id_indexes = [- index for index in voucher_code_id_indexes if index < len(voucher_code_ids)- ]-- # Step 1 - Export voucher codes and check status- input_data = {- "fileType": file_type,- "ids": [voucher_code_ids[i] for i in voucher_code_id_indexes],- }- response = export_voucher_codes(e2e_staff_api_client, input_data)-- assert response["status"] == "SUCCESS"--- "file_type",- [- "XLSX",- "CSV",- ],-)-def test_export_voucher_codes_with_invalid_voucher_id_CORE_0925(- e2e_staff_api_client,- shop_permissions,- permission_manage_discounts,- permission_manage_checkouts,- file_type,-):- # Before- permissions = [- *shop_permissions,- permission_manage_discounts,- permission_manage_checkouts,- ]- assign_permissions(e2e_staff_api_client, permissions)-- # Step 1 - Export voucher codes and check status- input_data = {- "fileType": file_type,- "voucherId": "invalid_voucher_id",- }- response = raw_export_voucher_codes(e2e_staff_api_client, input_data)-- error = response["data"]["exportVoucherCodes"]["errors"][0]- assert error["message"] == "Invalid voucher ID."- assert error["code"] == "INVALID"- assert error["field"] == "voucherId"--- "file_type",- [- "XLSX",- "CSV",- ],-)-def test_export_voucher_codes_with_invalid_voucher_codes_CORE_0925(- e2e_staff_api_client,- shop_permissions,- permission_manage_discounts,- permission_manage_checkouts,- file_type,-):- # Before- permissions = [- *shop_permissions,- permission_manage_discounts,- permission_manage_checkouts,- ]- assign_permissions(e2e_staff_api_client, permissions)-- # Step 1 - Export voucher codes and check status- input_data = {- "fileType": file_type,- "ids": ["invalid_voucher_code"],- }- response = raw_export_voucher_codes(e2e_staff_api_client, input_data)- error = response["data"]["exportVoucherCodes"]["errors"][0]- assert error["message"] == "Invalid voucher code IDs."- assert error["code"] == "INVALID"- assert error["field"] == "ids"--- "file_type",- [- "XLSX",- "CSV",- ],-)-def test_export_voucher_codes_without_voucher_id_nor_codes_CORE_0925(- e2e_staff_api_client,- shop_permissions,- permission_manage_discounts,- permission_manage_checkouts,- file_type,-):- # Before- permissions = [- *shop_permissions,- permission_manage_discounts,- permission_manage_checkouts,- ]- assign_permissions(e2e_staff_api_client, permissions)-- # Step 1 - Export voucher codes and check status- input_data = {- "fileType": file_type,- }- response = raw_export_voucher_codes(e2e_staff_api_client, input_data)- error = response["data"]["exportVoucherCodes"]["errors"][0]- assert (- error["message"]- == "At least one of arguments is required: 'voucher_id', 'ids'."- )- assert error["code"] == "GRAPHQL_ERROR"--- ("file_type", "voucher_id"),- [- (- "",- "{voucher_id}",- ),- (- "SVG",- "{voucher_id}",- ),- ],-)-def test_export_voucher_codes_with_invalid_file_type_CORE_0925(- e2e_staff_api_client,- shop_permissions,- permission_manage_discounts,- permission_manage_checkouts,- file_type,- voucher_id,-):- # Before- permissions = [- *shop_permissions,- permission_manage_discounts,- permission_manage_checkouts,- ]- assign_permissions(e2e_staff_api_client, permissions)-- shop_data = prepare_default_shop(e2e_staff_api_client)- channel_id = shop_data["channel"]["id"]-- voucher_ids, _voucher_code_ids = create_vouchers_with_multiple_codes(- e2e_staff_api_client, channel_id- )-- voucher_id = voucher_ids[0]-- # Step 1 - Export voucher codes and check status- input_data = {- "fileType": file_type,- "voucherId": voucher_id,- }-- response = raw_export_voucher_codes(e2e_staff_api_client, input_data)-- response_errors = response.get("errors")-- expected_error_message = f'Variable "$input" got invalid value {{"fileType": "{file_type}", "voucherId": "{voucher_id}"}}.\nIn field "fileType": Expected type "FileTypesEnum", found "{file_type}".'-- expected_error = {- "extensions": {"exception": {"code": "GraphQLError"}},- "locations": [{"column": 24, "line": 2}],- "message": expected_error_message,- }-- expected_errors_list = [expected_error]-- assert response_errors == expected_errors_listdiff --git a/saleor/tests/e2e/vouchers/utils/__init__.py b/saleor/tests/e2e/vouchers/utils/__init__.pyindex f2d3c923ba..79eca7d6ea 100644--- a/saleor/tests/e2e/vouchers/utils/__init__.py+++ b/saleor/tests/e2e/vouchers/utils/__init__.py@@ -4,7 +4,6 @@ from .voucher_bulk_delete import voucher_bulk_deletefrom .voucher_catalogues_add import add_catalogue_to_voucherfrom .voucher_channel_listing import create_voucher_channel_listingfrom .voucher_code_bulk_delete import voucher_code_bulk_delete-from .voucher_codes_export import export_voucher_codes, raw_export_voucher_codesfrom .voucher_create import create_voucherfrom .voucher_delete import voucher_deletefrom .voucher_update import raw_update_voucher, update_voucher@@ -20,6 +19,4 @@ __all__ = ["get_vouchers","raw_update_voucher","update_voucher",- "export_voucher_codes",- "raw_export_voucher_codes",]diff --git a/saleor/tests/e2e/vouchers/utils/voucher_codes_export.py b/saleor/tests/e2e/vouchers/utils/voucher_codes_export.pydeleted file mode 100644index 17bfd8cb0c..0000000000--- a/saleor/tests/e2e/vouchers/utils/voucher_codes_export.py+++ /dev/null@@ -1,43 +0,0 @@-from ...utils import get_graphql_content--VOUCHER_CODES_EXPORT_MUTATION = """-mutation VoucherCreate($input: ExportVoucherCodesInput!) {- exportVoucherCodes(input: $input) {- errors {- code- field- message- }- exportFile {- status- id- }- }-}-"""---def raw_export_voucher_codes(staff_api_client, input_data):- variables = {- "input": input_data,- }-- response = staff_api_client.post_graphql(- VOUCHER_CODES_EXPORT_MUTATION,- variables,- check_no_permissions=False,- )- content = get_graphql_content(response, ignore_errors=True)-- return content---def export_voucher_codes(api_client, input_data):- response = raw_export_voucher_codes(api_client, input_data)-- assert response["data"]["exportVoucherCodes"]["errors"] == []-- data = response["data"]["exportVoucherCodes"]["exportFile"]- assert data["id"] is not None-- return datadiff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex db6c890d7e..942a6d083b 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -1183,7 +1183,6 @@ def async_subscription_webhooks_with_root_objects(subscription_gift_card_sent_webhook,subscription_gift_card_status_changed_webhook,subscription_gift_card_metadata_updated_webhook,- subscription_gift_card_export_completed_webhook,subscription_menu_created_webhook,subscription_menu_updated_webhook,subscription_menu_deleted_webhook,@@ -1281,7 +1280,6 @@ def async_subscription_webhooks_with_root_objects(subscription_voucher_codes_deleted_webhook,subscription_voucher_webhook_with_meta,subscription_voucher_metadata_updated_webhook,- subscription_voucher_code_export_completed_webhook,address,app,numeric_attribute,@@ -1399,10 +1397,6 @@ def async_subscription_webhooks_with_root_objects(subscription_gift_card_metadata_updated_webhook,gift_card,],- events.GIFT_CARD_EXPORT_COMPLETED: [- subscription_gift_card_export_completed_webhook,- user_export_file,- ],events.MENU_CREATED: [subscription_menu_created_webhook, menu],events.MENU_UPDATED: [subscription_menu_updated_webhook, menu],events.MENU_DELETED: [subscription_menu_deleted_webhook, menu],@@ -1638,10 +1632,6 @@ def async_subscription_webhooks_with_root_objects(subscription_voucher_metadata_updated_webhook,voucher,],- events.VOUCHER_CODE_EXPORT_COMPLETED: [- subscription_voucher_code_export_completed_webhook,- user_export_file,- ],events.WAREHOUSE_CREATED: [subscription_warehouse_created_webhook, warehouse],events.WAREHOUSE_UPDATED: [subscription_warehouse_updated_webhook, warehouse],events.WAREHOUSE_DELETED: [subscription_warehouse_deleted_webhook, warehouse],diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.pyindex 3b870e15b6..ed4e4868fd 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -65,7 +65,6 @@ class WebhookEventAsyncType:GIFT_CARD_SENT = "gift_card_sent"GIFT_CARD_STATUS_CHANGED = "gift_card_status_changed"GIFT_CARD_METADATA_UPDATED = "gift_card_metadata_updated"- GIFT_CARD_EXPORT_COMPLETED = "gift_card_export_completed"MENU_CREATED = "menu_created"MENU_UPDATED = "menu_updated"@@ -216,7 +215,6 @@ class WebhookEventAsyncType:VOUCHER_CODES_CREATED = "voucher_codes_created"VOUCHER_CODES_DELETED = "voucher_codes_deleted"VOUCHER_METADATA_UPDATED = "voucher_metadata_updated"- VOUCHER_CODE_EXPORT_COMPLETED = "voucher_code_export_completed"OBSERVABILITY = "observability"@@ -361,10 +359,6 @@ class WebhookEventAsyncType:"name": "Gift card metadata updated","permission": GiftcardPermissions.MANAGE_GIFT_CARD,},- GIFT_CARD_EXPORT_COMPLETED: {- "name": "Gift card export completed",- "permission": GiftcardPermissions.MANAGE_GIFT_CARD,- },MENU_CREATED: {"name": "Menu created","permission": MenuPermissions.MANAGE_MENUS,@@ -850,10 +844,6 @@ class WebhookEventAsyncType:"name": "Voucher metadata updated","permission": DiscountPermissions.MANAGE_DISCOUNTS,},- VOUCHER_CODE_EXPORT_COMPLETED: {- "name": "Voucher code export completed",- "permission": DiscountPermissions.MANAGE_DISCOUNTS,- },OBSERVABILITY: {"name": "Observability","permission": AppPermission.MANAGE_OBSERVABILITY,diff --git a/saleor/webhook/migrations/0015_drop_export_completed_events.py b/saleor/webhook/migrations/0015_drop_export_completed_events.pynew file mode 100644index 0000000000..708d0c2d02--- /dev/null+++ b/saleor/webhook/migrations/0015_drop_export_completed_events.py@@ -0,0 +1,25 @@+from django.db import migrations+++def drop_export_completed_events(apps, _schema_editor):+ WebhookEvent = apps.get_model("webhook", "WebhookEvent")+ # gift_card_export_completed and voucher_code_export_completed were emitted only by+ # the exportGiftCards and exportVoucherCodes mutations, both removed in 3.24. The+ # rows left behind reference event types that no longer exist in the GraphQL enum,+ # so resolving them would fail. Only apps subscribed to an export webhook have any,+ # so the number of records is small.+ WebhookEvent.objects.filter(+ event_type__in=["gift_card_export_completed", "voucher_code_export_completed"]+ ).delete()+++class Migration(migrations.Migration):+ dependencies = [+ ("webhook", "0014_webhook_identifier_unique_constraint"),+ ]++ operations = [+ migrations.RunPython(+ drop_export_completed_events, reverse_code=migrations.RunPython.noop+ )+ ]diff --git a/saleor/webhook/tests/fixtures/subscription_webhooks.py b/saleor/webhook/tests/fixtures/subscription_webhooks.pyindex b967473fd1..e61ab53fc9 100644--- a/saleor/webhook/tests/fixtures/subscription_webhooks.py+++ b/saleor/webhook/tests/fixtures/subscription_webhooks.py@@ -261,14 +261,6 @@ def subscription_gift_card_metadata_updated_webhook(subscription_webhook):)-def subscription_gift_card_export_completed_webhook(subscription_webhook):- return subscription_webhook(- queries.GIFT_CARD_EXPORT_COMPLETED,- WebhookEventAsyncType.GIFT_CARD_EXPORT_COMPLETED,- )--@pytest.fixturedef subscription_menu_created_webhook(subscription_webhook):return subscription_webhook(@@ -1287,14 +1279,6 @@ def subscription_voucher_metadata_updated_webhook(subscription_webhook):)-def subscription_voucher_code_export_completed_webhook(subscription_webhook):- return subscription_webhook(- queries.VOUCHER_CODE_EXPORT_COMPLETED,- WebhookEventAsyncType.VOUCHER_CODE_EXPORT_COMPLETED,- )--@pytest.fixturedef subscription_shop_metadata_updated_webhook(subscription_webhook):return subscription_webhook(diff --git a/saleor/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/webhook/tests/subscription_webhooks/subscription_queries.pyindex 79006bb452..09d0eeece3 100644--- a/saleor/webhook/tests/subscription_webhooks/subscription_queries.py+++ b/saleor/webhook/tests/subscription_webhooks/subscription_queries.py@@ -591,25 +591,6 @@ GIFT_CARD_METADATA_UPDATED = (""")-GIFT_CARD_EXPORT_COMPLETED = (- fragments.GIFT_CARD_EXPORT_DETAILS- + fragments.RECIPIENT_APP_DETAILS- + """- subscription{- event{- recipient{- ...Recipient- }- ...on GiftCardExportCompleted{- export{- ...GiftCardExportDetails- }- }- }- }-"""-)-VOUCHER_CREATED = (fragments.VOUCHER_DETAILS+ fragments.RECIPIENT_APP_DETAILS@@ -767,26 +748,6 @@ VOUCHER_METADATA_UPDATED = ()-VOUCHER_CODE_EXPORT_COMPLETED = (- fragments.VOUCHER_CODE_EXPORT_DETAILS- + fragments.RECIPIENT_APP_DETAILS- + """- subscription{- event{- recipient{- ...Recipient- }- ...on VoucherCodeExportCompleted{- export{- ...VoucherCodeExportDetails- }- }- }- }-"""-)--SHOP_METADATA_UPDATED = """subscription{event {diff --git a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.pyindex 9b6db04f15..83e9f448c0 100644--- a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py+++ b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py@@ -895,36 +895,6 @@ def test_gift_card_metadata_updated(assert deliveries[0].webhook == webhooks[0]-def test_gift_card_export_completed(- user_export_file, subscription_gift_card_export_completed_webhook, media_root-):- # given- file_mock = MagicMock(spec=File)- file_mock.name = "temp_file.csv"-- user_export_file.content_file = file_mock- user_export_file.save()-- webhooks = [subscription_gift_card_export_completed_webhook]- event_type = WebhookEventAsyncType.GIFT_CARD_EXPORT_COMPLETED- gift_card_id = graphene.Node.to_global_id("ExportFile", user_export_file.id)-- # when- deliveries = create_deliveries_for_subscriptions(- event_type, user_export_file, webhooks- )-- # then- expected_payload = generate_export_payload(- user_export_file,- gift_card_id,- subscription_gift_card_export_completed_webhook.app,- )- assert deliveries[0].payload.get_payload() == expected_payload- assert len(deliveries) == len(webhooks)- assert deliveries[0].webhook == webhooks[0]--def test_menu_created(menu, subscription_menu_created_webhook):# givenwebhooks = [subscription_menu_created_webhook]@@ -2999,38 +2969,6 @@ def test_voucher_metadata_updated(assert deliveries[0].webhook == webhooks[0]-def test_voucher_code_export_completed(- user_export_file,- media_root,- subscription_voucher_code_export_completed_webhook,-):- # given- file_mock = MagicMock(spec=File)- file_mock.name = "temp_file.csv"-- user_export_file.content_file = file_mock- user_export_file.save()-- webhooks = [subscription_voucher_code_export_completed_webhook]- event_type = WebhookEventAsyncType.VOUCHER_CODE_EXPORT_COMPLETED- export_file_id = graphene.Node.to_global_id("ExportFile", user_export_file.id)-- # when- deliveries = create_deliveries_for_subscriptions(- event_type, user_export_file, webhooks- )-- # then- expected_payload = generate_export_payload(- user_export_file,- export_file_id,- subscription_voucher_code_export_completed_webhook.app,- )- assert deliveries[0].payload.get_payload() == expected_payload- assert len(deliveries) == len(webhooks)- assert deliveries[0].webhook == webhooks[0]--def test_shop_metadata_updated(subscription_shop_metadata_updated_webhook):# givenwebhooks = [subscription_shop_metadata_updated_webhook]