Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add voucherCodeCreated and voucherCodeDeleted webhooks (#14652)
SzymJddb8921a6744
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex af596493f1..a04488ffc8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,8 @@ All notable, unreleased changes to this project will be documented in this file.- Add JSON serialization immediately after creating observability events to eliminate extra cPickle serialization and deserialization steps - #14992 by @przlada- Added caching of GraphQL documents for common queries to improve performance - #14843 by @patrys+- Added `VOUCHER_CODES_CREATED` and `VOUCHER_CODES_DELETED` webhooks events. - #14652 by @SzymJ+# 3.18.0@@ -67,6 +69,7 @@ All notable, unreleased changes to this project will be documented in this file.- Change the Attribute - Page relation to decrease code complexity - #13621 by @michal-macioszczyk- Added validation for timestamp comparison - #14025 by @ritanjandawn+# 3.17.0### Highlightsdiff --git a/saleor/graphql/discount/mutations/voucher/voucher_code_bulk_delete.py b/saleor/graphql/discount/mutations/voucher/voucher_code_bulk_delete.pyindex 3795aa3e18..dc76c1589a 100644--- a/saleor/graphql/discount/mutations/voucher/voucher_code_bulk_delete.py+++ b/saleor/graphql/discount/mutations/voucher/voucher_code_bulk_delete.py@@ -34,9 +34,9 @@ class VoucherCodeBulkDelete(BaseMutation):error_type_class = VoucherCodeBulkDeleteErrorwebhook_events_info = [WebhookEventInfo(- type=WebhookEventAsyncType.VOUCHER_UPDATED,- description="A voucher was updated.",- )+ type=WebhookEventAsyncType.VOUCHER_CODES_DELETED,+ description="A voucher codes were deleted.",+ ),]doc_category = DOC_CATEGORY_DISCOUNTS@@ -65,10 +65,12 @@ class VoucherCodeBulkDelete(BaseMutation):return cleaned_ids@classmethod- def post_save_actions(cls, info, vouchers_code_map):+ def post_save_actions(cls, info, codes_instances):manager = get_plugin_manager_promise(info.context).get()- for voucher, code in vouchers_code_map.items():- cls.call_event(manager.voucher_updated, voucher, code)+ cls.call_event(+ manager.voucher_codes_deleted,+ codes_instances,+ )@classmethod@traced_atomic_transaction()@@ -79,20 +81,21 @@ class VoucherCodeBulkDelete(BaseMutation):if errors_list:return VoucherCodeBulkDelete(count=0, errors=errors_list)- queryset = models.VoucherCode.objects.filter(id__in=cleaned_ids).select_related(- "voucher"- )+ code_instances = models.VoucherCode.objects.filter(+ id__in=cleaned_ids+ ).select_related("voucher")- count = len(queryset)+ count = len(code_instances)- vouchers_code_map = {}+ # Copy deleted instance and reassign the original IDs+ ids_and_codes_tuple = [(code.id, code) for code in code_instances]+ code_instances.delete()- for code in queryset:- if code.voucher not in vouchers_code_map:- vouchers_code_map[code.voucher] = code.code+ for id, code in ids_and_codes_tuple:+ code.id = id- queryset.delete()-- cls.post_save_actions(info, vouchers_code_map)+ cls.post_save_actions(+ info, [id_and_code[1] for id_and_code in ids_and_codes_tuple]+ )return VoucherCodeBulkDelete(count=count)diff --git a/saleor/graphql/discount/mutations/voucher/voucher_create.py b/saleor/graphql/discount/mutations/voucher/voucher_create.pyindex 413bd86379..a9d891b1c7 100644--- a/saleor/graphql/discount/mutations/voucher/voucher_create.py+++ b/saleor/graphql/discount/mutations/voucher/voucher_create.py@@ -120,7 +120,11 @@ class VoucherCreate(ModelMutation):WebhookEventInfo(type=WebhookEventAsyncType.VOUCHER_CREATED,description="A voucher was created.",- )+ ),+ WebhookEventInfo(+ type=WebhookEventAsyncType.VOUCHER_CODES_CREATED,+ description="A voucher codes were created.",+ ),]@classmethod@@ -255,9 +259,18 @@ class VoucherCreate(ModelMutation):models.VoucherCode.objects.bulk_create(code_instances)@classmethod- def post_save_action(cls, info: ResolveInfo, instance, code):+ def post_save_action( # type: ignore[override]+ cls, info: ResolveInfo, instance, codes_instances, cleaned_input+ ):+ last_code = codes_instances[-1].code if codes_instances else Nonemanager = get_plugin_manager_promise(info.context).get()- cls.call_event(manager.voucher_created, instance, code)++ if codes_instances:+ cls.call_event(+ manager.voucher_codes_created,+ codes_instances,+ )+ cls.call_event(manager.voucher_created, instance, last_code)@classmethoddef success_response(cls, instance):@@ -293,5 +306,5 @@ class VoucherCreate(ModelMutation):cls.save(info, voucher_instance, code_instances, has_multiple_codes)cls._save_m2m(info, voucher_instance, cleaned_input)- cls.post_save_action(info, voucher_instance, voucher_instance.code)+ cls.post_save_action(info, voucher_instance, code_instances, cleaned_input)return cls.success_response(voucher_instance)diff --git a/saleor/graphql/discount/mutations/voucher/voucher_delete.py b/saleor/graphql/discount/mutations/voucher/voucher_delete.pyindex 9a027653e7..88aa0111fa 100644--- a/saleor/graphql/discount/mutations/voucher/voucher_delete.py+++ b/saleor/graphql/discount/mutations/voucher/voucher_delete.py@@ -57,5 +57,6 @@ class VoucherDelete(ModelDeleteMutation):# After the instance is deleted, set its ID to the original database's# ID so that the success response contains ID of the deleted object.instance.id = db_id+cls.post_save_action(info, instance, code)return cls.success_response(instance)diff --git a/saleor/graphql/discount/mutations/voucher/voucher_update.py b/saleor/graphql/discount/mutations/voucher/voucher_update.pyindex 83db14a8c5..3f89741715 100644--- a/saleor/graphql/discount/mutations/voucher/voucher_update.py+++ b/saleor/graphql/discount/mutations/voucher/voucher_update.py@@ -35,7 +35,11 @@ class VoucherUpdate(VoucherCreate):WebhookEventInfo(type=WebhookEventAsyncType.VOUCHER_UPDATED,description="A voucher was updated.",- )+ ),+ WebhookEventInfo(+ type=WebhookEventAsyncType.VOUCHER_CODES_CREATED,+ description="A voucher code was created.",+ ),]@classmethod@@ -129,6 +133,12 @@ class VoucherUpdate(VoucherCreate):models.VoucherCode.objects.bulk_update(codes_to_update, fields=["code"])@classmethod- def post_save_action(cls, info: ResolveInfo, instance, code):+ def post_save_action( # type: ignore[override]+ cls, info: ResolveInfo, instance, codes_instances, cleaned_input+ ):manager = get_plugin_manager_promise(info.context).get()- cls.call_event(manager.voucher_updated, instance, code)++ if cleaned_input:+ cls.call_event(manager.voucher_updated, instance, instance.code)+ if codes_instances:+ cls.call_event(manager.voucher_codes_created, codes_instances)diff --git a/saleor/graphql/discount/tests/deprecated/test_voucher_create.py b/saleor/graphql/discount/tests/deprecated/test_voucher_create.pyindex 15b14aaf4c..6c24b065cc 100644--- a/saleor/graphql/discount/tests/deprecated/test_voucher_create.py+++ b/saleor/graphql/discount/tests/deprecated/test_voucher_create.py@@ -1,6 +1,6 @@import jsonfrom datetime import timedelta-from unittest.mock import patch+from unittest.mock import call, patchimport graphenefrom django.utils import timezone@@ -125,9 +125,7 @@ def test_create_voucher_trigger_webhook(content = get_graphql_content(response)voucher = Voucher.objects.last()- # then- assert content["data"]["voucherCreate"]["voucher"]- mocked_webhook_trigger.assert_called_once_with(+ voucher_created = call(json.dumps({"id": graphene.Node.to_global_id("Voucher", voucher.id),@@ -148,6 +146,10 @@ def test_create_voucher_trigger_webhook(allow_replica=False,)+ # then+ assert content["data"]["voucherCreate"]["voucher"]+ assert voucher_created in mocked_webhook_trigger.call_args_list+def test_create_voucher_with_empty_code(staff_api_client, permission_manage_discounts):# givendiff --git a/saleor/graphql/discount/tests/deprecated/test_voucher_update.py b/saleor/graphql/discount/tests/deprecated/test_voucher_update.pyindex faf2fcc9c5..61b46336a1 100644--- a/saleor/graphql/discount/tests/deprecated/test_voucher_update.py+++ b/saleor/graphql/discount/tests/deprecated/test_voucher_update.py@@ -1,5 +1,5 @@import json-from unittest.mock import patch+from unittest.mock import call, patchimport graphenefrom django.utils.functional import SimpleLazyObject@@ -92,10 +92,7 @@ def test_update_voucher_trigger_webhook(UPDATE_VOUCHER_MUTATION, variables, permissions=[permission_manage_discounts])content = get_graphql_content(response)-- # then- assert content["data"]["voucherUpdate"]["voucher"]- mocked_webhook_trigger.assert_called_once_with(+ voucher_updated = call(json.dumps({"id": variables["id"],@@ -115,6 +112,9 @@ def test_update_voucher_trigger_webhook(SimpleLazyObject(lambda: staff_api_client.user),allow_replica=False,)+ # then+ assert content["data"]["voucherUpdate"]["voucher"]+ assert voucher_updated in mocked_webhook_trigger.call_args_listdef test_update_voucher_return_error_when_multiple_codes_already_exists(diff --git a/saleor/graphql/discount/tests/mutations/test_voucher_code_bulk_delete.py b/saleor/graphql/discount/tests/mutations/test_voucher_code_bulk_delete.pyindex 5aedb1740a..2d653ef61e 100644--- a/saleor/graphql/discount/tests/mutations/test_voucher_code_bulk_delete.py+++ b/saleor/graphql/discount/tests/mutations/test_voucher_code_bulk_delete.py@@ -77,7 +77,7 @@ def test_delete_voucher_codes_as_app(@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")-def test_delete_voucher_codes_trigger_voucher_update_webhook(+def test_delete_voucher_codes_trigger_voucher_codes_deleted_webhook(mocked_webhook_trigger,mocked_get_webhooks_for_event,any_webhook,@@ -89,8 +89,8 @@ def test_delete_voucher_codes_trigger_voucher_update_webhook(# givenvoucher.codes.create(code="voucher-1")voucher.codes.create(code="voucher-2")- vouchers = voucher.codes.all()- assert len(vouchers) == 3+ codes = voucher.codes.all()+ assert len(codes) == 3mocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]diff --git a/saleor/graphql/discount/tests/mutations/test_voucher_create.py b/saleor/graphql/discount/tests/mutations/test_voucher_create.pyindex c77ceb2870..e19be66dbf 100644--- a/saleor/graphql/discount/tests/mutations/test_voucher_create.py+++ b/saleor/graphql/discount/tests/mutations/test_voucher_create.py@@ -1,6 +1,6 @@import jsonfrom datetime import timedelta-from unittest.mock import patch+from unittest.mock import call, patchimport graphenefrom django.utils import timezone@@ -244,14 +244,14 @@ def test_create_voucher_return_error_when_code_or_codes_arg_not_in_input(@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")def test_create_voucher_trigger_webhook(mocked_webhook_trigger,- mocked_get_webhooks_for_event,+ mocked_get_webhooks_for_voucher_event,any_webhook,staff_api_client,permission_manage_discounts,settings,):# given- mocked_get_webhooks_for_event.return_value = [any_webhook]+ mocked_get_webhooks_for_voucher_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]start_date = timezone.now() - timedelta(days=365)@@ -282,9 +282,7 @@ def test_create_voucher_trigger_webhook(content = get_graphql_content(response)voucher = Voucher.objects.last()- # then- assert content["data"]["voucherCreate"]- mocked_webhook_trigger.assert_called_once_with(+ voucher_created = call(json.dumps({"id": graphene.Node.to_global_id("Voucher", voucher.id),@@ -305,6 +303,30 @@ def test_create_voucher_trigger_webhook(allow_replica=False,)+ new_codes = voucher.codes.filter(code__in=[code_1, code_2])+ codes_created = call(+ json.dumps(+ [+ {+ "id": graphene.Node.to_global_id("VoucherCode", code.id),+ "code": code.code,+ }+ for code in new_codes+ ],+ cls=CustomJsonEncoder,+ ),+ WebhookEventAsyncType.VOUCHER_CODES_CREATED,+ [any_webhook],+ list(new_codes),+ SimpleLazyObject(lambda: staff_api_client.user),+ )++ # then+ assert content["data"]["voucherCreate"]+ assert mocked_webhook_trigger.call_count == 2+ assert voucher_created in mocked_webhook_trigger.call_args_list+ assert codes_created in mocked_webhook_trigger.call_args_list+def test_create_voucher_with_empty_code(staff_api_client, permission_manage_discounts):# givendiff --git a/saleor/graphql/discount/tests/mutations/test_voucher_delete.py b/saleor/graphql/discount/tests/mutations/test_voucher_delete.pyindex cebf03f3a6..f123fe9f40 100644--- a/saleor/graphql/discount/tests/mutations/test_voucher_delete.py+++ b/saleor/graphql/discount/tests/mutations/test_voucher_delete.py@@ -58,7 +58,7 @@ def test_voucher_delete_mutation_trigger_webhook(# givenmocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- code = voucher.codes.first().code+ voucher_code = voucher.codes.first()variables = {"id": graphene.Node.to_global_id("Voucher", voucher.id)}# when@@ -74,7 +74,7 @@ def test_voucher_delete_mutation_trigger_webhook({"id": variables["id"],"name": voucher.name,- "code": code,+ "code": voucher_code.code,"meta": generate_meta(requestor_data=generate_requestor(SimpleLazyObject(lambda: staff_api_client.user)diff --git a/saleor/graphql/discount/tests/mutations/test_voucher_update.py b/saleor/graphql/discount/tests/mutations/test_voucher_update.pyindex c4f0e16e32..5dcbe6edd2 100644--- a/saleor/graphql/discount/tests/mutations/test_voucher_update.py+++ b/saleor/graphql/discount/tests/mutations/test_voucher_update.py@@ -1,5 +1,5 @@import json-from unittest.mock import patch+from unittest.mock import call, patchimport graphenefrom django.utils.functional import SimpleLazyObject@@ -191,12 +191,13 @@ def test_update_voucher_trigger_webhook():# givenmocked_get_webhooks_for_event.return_value = [any_webhook]+settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]new_code = "newCode"-+ new_name = "newName"variables = {"id": graphene.Node.to_global_id("Voucher", voucher.id),- "input": {"addCodes": [new_code]},+ "input": {"addCodes": [new_code], "name": new_name},}# when@@ -204,14 +205,13 @@ def test_update_voucher_trigger_webhook(UPDATE_VOUCHER_MUTATION, variables, permissions=[permission_manage_discounts])content = get_graphql_content(response)+ voucher_code = voucher.codes.last()- # then- assert content["data"]["voucherUpdate"]["voucher"]- mocked_webhook_trigger.assert_called_once_with(+ voucher_updated = call(json.dumps({"id": variables["id"],- "name": voucher.name,+ "name": new_name,"code": new_code,"meta": generate_meta(requestor_data=generate_requestor(@@ -228,6 +228,79 @@ def test_update_voucher_trigger_webhook(allow_replica=False,)+ code_created = call(+ json.dumps(+ [+ {+ "id": graphene.Node.to_global_id("VoucherCode", voucher_code.id),+ "code": new_code,+ }+ ],+ cls=CustomJsonEncoder,+ ),+ WebhookEventAsyncType.VOUCHER_CODES_CREATED,+ [any_webhook],+ [voucher_code],+ SimpleLazyObject(lambda: staff_api_client.user),+ )++ # then+ assert content["data"]["voucherUpdate"]["voucher"]+ assert mocked_webhook_trigger.call_count == 2+ assert voucher_updated in mocked_webhook_trigger.call_args_list+ assert code_created in mocked_webhook_trigger.call_args_list+++@freeze_time("2022-05-12 12:00:00")+@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_update_voucher_doesnt_trigger_voucher_updated_when_only_codes_added(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ staff_api_client,+ voucher,+ permission_manage_discounts,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]++ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ new_code = "newCode"+ variables = {+ "id": graphene.Node.to_global_id("Voucher", voucher.id),+ "input": {"addCodes": [new_code]},+ }++ # when+ response = staff_api_client.post_graphql(+ UPDATE_VOUCHER_MUTATION, variables, permissions=[permission_manage_discounts]+ )+ content = get_graphql_content(response)+ voucher_code = voucher.codes.last()++ code_created = call(+ json.dumps(+ [+ {+ "id": graphene.Node.to_global_id("VoucherCode", voucher_code.id),+ "code": new_code,+ }+ ],+ cls=CustomJsonEncoder,+ ),+ WebhookEventAsyncType.VOUCHER_CODES_CREATED,+ [any_webhook],+ [voucher_code],+ SimpleLazyObject(lambda: staff_api_client.user),+ )++ # then+ assert content["data"]["voucherUpdate"]["voucher"]+ assert mocked_webhook_trigger.call_count == 1+ assert code_created in mocked_webhook_trigger.call_args_list+def test_update_voucher_single_use_voucher_already_used_in_order(staff_api_client,diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex f9cc042b28..01ff68fb09 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2269,6 +2269,8 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {"""A voucher is deleted."""VOUCHER_DELETED+ VOUCHER_CODES_CREATED+ VOUCHER_CODES_DELETED"""A voucher metadata is updated.@@ -2993,6 +2995,8 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {"""A voucher is deleted."""VOUCHER_DELETED+ VOUCHER_CODES_CREATED+ VOUCHER_CODES_DELETED"""A voucher metadata is updated.@@ -3704,6 +3708,8 @@ enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {VOUCHER_CREATEDVOUCHER_UPDATEDVOUCHER_DELETED+ VOUCHER_CODES_CREATED+ VOUCHER_CODES_DELETEDVOUCHER_METADATA_UPDATEDVOUCHER_CODE_EXPORT_COMPLETEDOBSERVABILITY@@ -18177,11 +18183,12 @@ type Mutation {Triggers the following webhook events:- VOUCHER_CREATED (async): A voucher was created.+ - VOUCHER_CODES_CREATED (async): A voucher codes were created."""voucherCreate("""Fields required to create a voucher."""input: VoucherInput!- ): VoucherCreate @doc(category: "Discounts") @webhookEventsInfo(asyncEvents: [VOUCHER_CREATED], syncEvents: [])+ ): VoucherCreate @doc(category: "Discounts") @webhookEventsInfo(asyncEvents: [VOUCHER_CREATED, VOUCHER_CODES_CREATED], syncEvents: [])"""Deletes a voucher.@@ -18216,6 +18223,7 @@ type Mutation {Triggers the following webhook events:- VOUCHER_UPDATED (async): A voucher was updated.+ - VOUCHER_CODES_CREATED (async): A voucher code was created."""voucherUpdate("""ID of a voucher to update."""@@ -18223,7 +18231,7 @@ type Mutation {"""Fields required to update a voucher."""input: VoucherInput!- ): VoucherUpdate @doc(category: "Discounts") @webhookEventsInfo(asyncEvents: [VOUCHER_UPDATED], syncEvents: [])+ ): VoucherUpdate @doc(category: "Discounts") @webhookEventsInfo(asyncEvents: [VOUCHER_UPDATED, VOUCHER_CODES_CREATED], syncEvents: [])"""Adds products, categories, collections to a voucher.@@ -18297,12 +18305,12 @@ type Mutation {Requires one of the following permissions: MANAGE_DISCOUNTS.Triggers the following webhook events:- - VOUCHER_UPDATED (async): A voucher was updated.+ - VOUCHER_CODES_DELETED (async): A voucher codes were deleted."""voucherCodeBulkDelete("""List of voucher codes IDs to delete."""ids: [ID!]!- ): VoucherCodeBulkDelete @doc(category: "Discounts") @webhookEventsInfo(asyncEvents: [VOUCHER_UPDATED], syncEvents: [])+ ): VoucherCodeBulkDelete @doc(category: "Discounts") @webhookEventsInfo(asyncEvents: [VOUCHER_CODES_DELETED], syncEvents: [])"""Export products to csv file.@@ -28028,8 +28036,9 @@ Requires one of the following permissions: MANAGE_DISCOUNTS.Triggers the following webhook events:- VOUCHER_CREATED (async): A voucher was created.+- VOUCHER_CODES_CREATED (async): A voucher codes were created."""-type VoucherCreate @doc(category: "Discounts") @webhookEventsInfo(asyncEvents: [VOUCHER_CREATED], syncEvents: []) {+type VoucherCreate @doc(category: "Discounts") @webhookEventsInfo(asyncEvents: [VOUCHER_CREATED, VOUCHER_CODES_CREATED], syncEvents: []) {discountErrors: [DiscountError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")errors: [DiscountError!]!voucher: Voucher@@ -28147,8 +28156,9 @@ Requires one of the following permissions: MANAGE_DISCOUNTS.Triggers the following webhook events:- VOUCHER_UPDATED (async): A voucher was updated.+- VOUCHER_CODES_CREATED (async): A voucher code was created."""-type VoucherUpdate @doc(category: "Discounts") @webhookEventsInfo(asyncEvents: [VOUCHER_UPDATED], syncEvents: []) {+type VoucherUpdate @doc(category: "Discounts") @webhookEventsInfo(asyncEvents: [VOUCHER_UPDATED, VOUCHER_CODES_CREATED], syncEvents: []) {discountErrors: [DiscountError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")errors: [DiscountError!]!voucher: Voucher@@ -28237,9 +28247,9 @@ Added in Saleor 3.18.Requires one of the following permissions: MANAGE_DISCOUNTS.Triggers the following webhook events:-- VOUCHER_UPDATED (async): A voucher was updated.+- VOUCHER_CODES_DELETED (async): A voucher codes were deleted."""-type VoucherCodeBulkDelete @doc(category: "Discounts") @webhookEventsInfo(asyncEvents: [VOUCHER_UPDATED], syncEvents: []) {+type VoucherCodeBulkDelete @doc(category: "Discounts") @webhookEventsInfo(asyncEvents: [VOUCHER_CODES_DELETED], syncEvents: []) {"""Returns how many codes were deleted."""count: Int!errors: [VoucherCodeBulkDeleteError!]!@@ -34847,6 +34857,50 @@ type VoucherDeleted implements Event @doc(category: "Discounts") {): Voucher}+"""+Event sent when new voucher codes were created.++Added in Saleor 3.19.+"""+type VoucherCodesCreated implements Event {+ """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 voucher codes the event relates to."""+ voucherCodes: [VoucherCode!]+}++"""+Event sent when voucher codes were deleted.++Added in Saleor 3.19.+"""+type VoucherCodesDeleted implements Event {+ """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 voucher codes the event relates to."""+ voucherCodes: [VoucherCode!]+}+"""Event sent when voucher metadata is updated.diff --git a/saleor/graphql/tests/queries/fragments.py b/saleor/graphql/tests/queries/fragments.pyindex 8905f0784c..362cd86730 100644--- a/saleor/graphql/tests/queries/fragments.py+++ b/saleor/graphql/tests/queries/fragments.py@@ -439,6 +439,16 @@ fragment VoucherDetails on Voucher{"""+VOUCHER_CODE_DETAILS = """+fragment VoucherCodeDetails on VoucherCode{+ id+ code+ used+ isActive+}+"""++VOUCHER_CODE_EXPORT_DETAILS = """fragment VoucherCodeExportDetails on ExportFile {iddiff --git a/saleor/graphql/webhook/mutations/webhook_dry_run.py b/saleor/graphql/webhook/mutations/webhook_dry_run.pyindex 18808ea962..0c69d56f3c 100644--- a/saleor/graphql/webhook/mutations/webhook_dry_run.py+++ b/saleor/graphql/webhook/mutations/webhook_dry_run.py@@ -126,6 +126,12 @@ class WebhookDryRun(BaseMutation):payload = Noneif all([event_type, object, query]):request = info.context+ if event_type in [+ WebhookEventAsyncType.VOUCHER_CODES_CREATED,+ WebhookEventAsyncType.VOUCHER_CODES_DELETED,+ ]:+ object = [object]+payload = generate_payload_from_subscription(event_type, object, query, request)diff --git a/saleor/graphql/webhook/mutations/webhook_trigger.py b/saleor/graphql/webhook/mutations/webhook_trigger.pyindex e993a3e6ee..67712efa1a 100644--- a/saleor/graphql/webhook/mutations/webhook_trigger.py+++ b/saleor/graphql/webhook/mutations/webhook_trigger.py@@ -139,6 +139,12 @@ class WebhookTrigger(BaseMutation):delivery = Noneif all([event_type, object, webhook]):+ if event_type in [+ WebhookEventAsyncType.VOUCHER_CODES_CREATED,+ WebhookEventAsyncType.VOUCHER_CODES_DELETED,+ ]:+ object = [object]+deliveries = create_deliveries_for_subscriptions(event_type, object, [webhook])diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex 22c5980f3c..ce2a16668f 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -58,6 +58,7 @@ from ..core.descriptions import (ADDED_IN_316,ADDED_IN_317,ADDED_IN_318,+ ADDED_IN_319,DEPRECATED_IN_3X_EVENT,PREVIEW_FEATURE,)@@ -2413,6 +2414,34 @@ class VoucherDeleted(SubscriptionObjectType, VoucherBase):description = "Event sent when voucher is deleted." + ADDED_IN_34+class VoucherCodeBase(AbstractType):+ voucher_codes = NonNullList(+ "saleor.graphql.discount.types.VoucherCode",+ description="The voucher codes the event relates to.",+ )++ @staticmethod+ def resolve_voucher_codes(root, _info: ResolveInfo):+ _, voucher_codes = root+ return voucher_codes+++class VoucherCodesCreated(SubscriptionObjectType, VoucherCodeBase):+ class Meta:+ root_type = "VoucherCode"+ enable_dry_run = True+ interfaces = (Event,)+ description = "Event sent when new voucher codes were created." + ADDED_IN_319+++class VoucherCodesDeleted(SubscriptionObjectType, VoucherCodeBase):+ class Meta:+ root_type = "VoucherCode"+ enable_dry_run = True+ interfaces = (Event,)+ description = "Event sent when voucher codes were deleted." + ADDED_IN_319++class VoucherMetadataUpdated(SubscriptionObjectType, VoucherBase):class Meta:root_type = "Voucher"@@ -2853,6 +2882,8 @@ WEBHOOK_TYPES_MAP = {WebhookEventAsyncType.VOUCHER_CREATED: VoucherCreated,WebhookEventAsyncType.VOUCHER_UPDATED: VoucherUpdated,WebhookEventAsyncType.VOUCHER_DELETED: VoucherDeleted,+ 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,diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex d47be72ff1..80a7123532 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -54,7 +54,7 @@ if TYPE_CHECKING:from ..core.notify_events import NotifyEventTypefrom ..core.taxes import TaxData, TaxTypefrom ..csv.models import ExportFile- from ..discount.models import Promotion, PromotionRule, Voucher+ from ..discount.models import Promotion, PromotionRule, Voucher, VoucherCodefrom ..giftcard.models import GiftCardfrom ..invoice.models import Invoicefrom ..menu.models import Menu, MenuItem@@ -1224,6 +1224,18 @@ class BasePlugin:# updated.voucher_updated: Callable[["Voucher", str, None], None]+ # Trigger when voucher codes are created.+ #+ # Overwrite this method if you need to trigger specific logic after voucher codes+ # are created.+ voucher_codes_created: Callable[[list["VoucherCode"], None, None], None]++ # Trigger when voucher code are deleted.+ #+ # Overwrite this method if you need to trigger specific logic after voucher codes+ # are deleted.+ voucher_codes_deleted: Callable[[list["VoucherCode"], None, None], None]+# Trigger when voucher metadata is updated.## Overwrite this method if you need to trigger specific logic after a voucherdiff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex c3fbd60706..810252cf69 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -63,7 +63,7 @@ if TYPE_CHECKING:from ..core.middleware import Requestorfrom ..core.utils.translations import Translationfrom ..csv.models import ExportFile- from ..discount.models import Promotion, PromotionRule, Voucher+ from ..discount.models import Promotion, PromotionRule, Voucher, VoucherCodefrom ..giftcard.models import GiftCardfrom ..invoice.models import Invoicefrom ..menu.models import Menu, MenuItem@@ -1525,6 +1525,18 @@ class PluginsManager(PaymentInterface):"voucher_deleted", default_value, voucher, code, webhooks=webhooks)+ def voucher_codes_created(self, voucher_codes: list["VoucherCode"], webhooks=None):+ default_value = None+ return self.__run_method_on_plugins(+ "voucher_codes_created", default_value, voucher_codes, webhooks=webhooks+ )++ def voucher_codes_deleted(self, voucher_codes: list["VoucherCode"], webhooks=None):+ default_value = None+ return self.__run_method_on_plugins(+ "voucher_codes_deleted", default_value, voucher_codes, webhooks=webhooks+ )+def voucher_metadata_updated(self, voucher: "Voucher"):default_value = Nonereturn self.__run_method_on_plugins(diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 09612d7e6a..77292afd63 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -129,7 +129,7 @@ if TYPE_CHECKING:from ...channel.models import Channelfrom ...core.utils.translations import Translationfrom ...csv.models import ExportFile- from ...discount.models import Promotion, PromotionRule, Voucher+ from ...discount.models import Promotion, PromotionRule, Voucher, VoucherCodefrom ...giftcard.models import GiftCardfrom ...invoice.models import Invoicefrom ...menu.models import Menu, MenuItem@@ -2285,6 +2285,38 @@ class WebhookPlugin(BasePlugin):WebhookEventAsyncType.VOUCHER_DELETED, voucher, code, webhooks=webhooks)+ def _trigger_voucher_code_event(self, event_type, voucher_codes, webhooks=None):+ if webhooks := self._get_webhooks_for_event(event_type, webhooks):+ data = [+ {+ "id": graphene.Node.to_global_id("VoucherCode", voucher_code.id),+ "code": voucher_code.code,+ }+ for voucher_code in voucher_codes+ ]+ payload = self._serialize_payload(data)+ trigger_webhooks_async(+ payload, event_type, webhooks, voucher_codes, self.requestor+ )++ def voucher_codes_created(+ self, voucher_codes: list["VoucherCode"], previous_value: None, webhooks=None+ ) -> None:+ if not self.active:+ return previous_value+ self._trigger_voucher_code_event(+ WebhookEventAsyncType.VOUCHER_CODES_CREATED, voucher_codes, webhooks+ )++ def voucher_codes_deleted(+ self, voucher_codes: list["VoucherCode"], previous_value: None, webhooks=None+ ) -> None:+ if not self.active:+ return previous_value+ self._trigger_voucher_code_event(+ WebhookEventAsyncType.VOUCHER_CODES_DELETED, voucher_codes, webhooks+ )+def voucher_metadata_updated(self, voucher: "Voucher", previous_value: None) -> None:diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.pyindex 480bfb9997..0ab0f291ce 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py@@ -1000,6 +1000,20 @@ def subscription_voucher_deleted_webhook(subscription_webhook):)+def subscription_voucher_codes_created_webhook(subscription_webhook):+ return subscription_webhook(+ queries.VOUCHER_CODES_CREATED, WebhookEventAsyncType.VOUCHER_CODES_CREATED+ )+++def subscription_voucher_codes_deleted_webhook(subscription_webhook):+ return subscription_webhook(+ queries.VOUCHER_CODES_DELETED, WebhookEventAsyncType.VOUCHER_CODES_DELETED+ )++@pytest.fixturedef subscription_voucher_webhook_with_meta(subscription_webhook):return subscription_webhook(diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py b/saleor/plugins/webhook/tests/subscription_webhooks/payloads.pyindex c18ff1f846..0ba778c59b 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py@@ -412,6 +412,22 @@ def generate_voucher_payload(voucher, voucher_global_id):)+def generate_voucher_code_payload(voucher_codes):+ return json.dumps(+ {+ "voucherCodes": [+ {+ "id": graphene.Node.to_global_id("VoucherCode", code.id),+ "code": code.code,+ "used": code.used,+ "isActive": code.is_active,+ }+ for code in voucher_codes+ ]+ }+ )++def generate_voucher_created_payload_with_meta(voucher, voucher_global_id, requestor, requestor_type, webhook_app):diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.pyindex be9810d3e4..91c3138406 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py@@ -554,6 +554,39 @@ VOUCHER_DELETED = (""")++VOUCHER_CODES_CREATED = (+ fragments.VOUCHER_CODE_DETAILS+ + """+ subscription{+ event{+ ...on VoucherCodesCreated{+ voucherCodes{+ ...VoucherCodeDetails+ }+ }+ }+ }+"""+)+++VOUCHER_CODES_DELETED = (+ fragments.VOUCHER_CODE_DETAILS+ + """+ subscription{+ event{+ ...on VoucherCodesDeleted{+ voucherCodes{+ ...VoucherCodeDetails+ }+ }+ }+ }+"""+)++VOUCHER_METADATA_UPDATED = (fragments.VOUCHER_DETAILS+ """diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.pyindex 85ba07f770..728202de0e 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py@@ -48,6 +48,7 @@ from .payloads import (generate_shipping_method_payload,generate_shop_payload,generate_staff_payload,+ generate_voucher_code_payload,generate_voucher_created_payload_with_meta,generate_voucher_payload,generate_warehouse_payload,@@ -2475,6 +2476,50 @@ def test_voucher_deleted(voucher, subscription_voucher_deleted_webhook):assert deliveries[0].webhook == webhooks[0]+def test_voucher_codes_created(voucher, subscription_voucher_codes_created_webhook):+ # given+ webhooks = [subscription_voucher_codes_created_webhook]++ voucher_code = voucher.codes.first()++ event_type = WebhookEventAsyncType.VOUCHER_CODES_CREATED++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, [voucher_code], webhooks+ )++ # then+ expected_payload = generate_voucher_code_payload([voucher_code])+ assert deliveries[0].payload.payload == expected_payload+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]+++def test_voucher_codes_deleted(voucher, subscription_voucher_codes_deleted_webhook):+ # given+ webhooks = [subscription_voucher_codes_deleted_webhook]++ voucher_code = voucher.codes.first()++ voucher_code_id = voucher_code.id+ voucher_code.delete()+ voucher_code.id = voucher_code_id++ event_type = WebhookEventAsyncType.VOUCHER_CODES_DELETED++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, [voucher_code], webhooks+ )++ # then+ expected_payload = generate_voucher_code_payload([voucher_code])+ assert deliveries[0].payload.payload == expected_payload+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]++def test_voucher_metadata_updated(voucher, subscription_voucher_metadata_updated_webhook):diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex aab852b9ad..aa5d0b1c80 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -8341,6 +8341,8 @@ def async_subscription_webhooks_with_root_objects(subscription_voucher_created_webhook,subscription_voucher_updated_webhook,subscription_voucher_deleted_webhook,+ subscription_voucher_codes_created_webhook,+ subscription_voucher_codes_deleted_webhook,subscription_voucher_webhook_with_meta,subscription_voucher_metadata_updated_webhook,subscription_voucher_code_export_completed_webhook,@@ -8380,6 +8382,7 @@ def async_subscription_webhooks_with_root_objects(page_type = page.page_typetransaction_item_created_by_app.use_old_id = Truetransaction_item_created_by_app.save()+ voucher_code = voucher.codes.first()return {events.ACCOUNT_DELETED: [@@ -8668,6 +8671,14 @@ def async_subscription_webhooks_with_root_objects(events.VOUCHER_CREATED: [subscription_voucher_created_webhook, voucher],events.VOUCHER_UPDATED: [subscription_voucher_updated_webhook, voucher],events.VOUCHER_DELETED: [subscription_voucher_deleted_webhook, voucher],+ events.VOUCHER_CODES_CREATED: [+ subscription_voucher_codes_created_webhook,+ voucher_code,+ ],+ events.VOUCHER_CODES_DELETED: [+ subscription_voucher_codes_deleted_webhook,+ voucher_code,+ ],events.VOUCHER_METADATA_UPDATED: [subscription_voucher_metadata_updated_webhook,voucher,diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.pyindex 87de019858..d801ae32c1 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -189,6 +189,8 @@ class WebhookEventAsyncType:VOUCHER_CREATED = "voucher_created"VOUCHER_UPDATED = "voucher_updated"VOUCHER_DELETED = "voucher_deleted"+ 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"@@ -735,6 +737,14 @@ class WebhookEventAsyncType:"name": "Voucher deleted","permission": DiscountPermissions.MANAGE_DISCOUNTS,},+ VOUCHER_CODES_CREATED: {+ "name": "Voucher codes created",+ "permission": DiscountPermissions.MANAGE_DISCOUNTS,+ },+ VOUCHER_CODES_DELETED: {+ "name": "Voucher codes deleted",+ "permission": DiscountPermissions.MANAGE_DISCOUNTS,+ },VOUCHER_METADATA_UPDATED: {"name": "Voucher metadata updated","permission": DiscountPermissions.MANAGE_DISCOUNTS,