Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
New events related to vouchers changes. (#9657)
SzymJc168d0b73484
diff --git a/saleor/graphql/discount/bulk_mutations.py b/saleor/graphql/discount/bulk_mutations.pyindex 01b783fa14..b70ab52e24 100644--- a/saleor/graphql/discount/bulk_mutations.py+++ b/saleor/graphql/discount/bulk_mutations.py@@ -35,3 +35,10 @@ class VoucherBulkDelete(ModelBulkDeleteMutation):permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)error_type_class = DiscountErrorerror_type_field = "discount_errors"++ @classmethod+ def bulk_action(cls, info, queryset):+ vouchers = list(queryset)+ queryset.delete()+ for voucher in vouchers:+ info.context.plugins.voucher_deleted(voucher)diff --git a/saleor/graphql/discount/mutations.py b/saleor/graphql/discount/mutations.pyindex 41db2e1bd7..4a2a1c3896 100644--- a/saleor/graphql/discount/mutations.py+++ b/saleor/graphql/discount/mutations.py@@ -245,6 +245,10 @@ class VoucherCreate(ModelMutation):error.code = DiscountErrorCode.INVALID.valueraise ValidationError({"end_date": error})+ @classmethod+ def post_save_action(cls, info, instance, cleaned_input):+ info.context.plugins.voucher_created(instance)+class VoucherUpdate(VoucherCreate):class Arguments:@@ -261,6 +265,10 @@ class VoucherUpdate(VoucherCreate):error_type_class = DiscountErrorerror_type_field = "discount_errors"+ @classmethod+ def post_save_action(cls, info, instance, cleaned_input):+ info.context.plugins.voucher_updated(instance)+class VoucherDelete(ModelDeleteMutation):class Arguments:@@ -280,6 +288,10 @@ class VoucherDelete(ModelDeleteMutation):response = super().success_response(instance)return response+ @classmethod+ def post_save_action(cls, info, instance, cleaned_input):+ info.context.plugins.voucher_deleted(instance)+class VoucherBaseCatalogueMutation(BaseDiscountCatalogueMutation):voucher = graphene.Field(@@ -316,7 +328,12 @@ class VoucherAddCatalogues(VoucherBaseCatalogueMutation):voucher = cls.get_node_or_error(info, data.get("id"), only_type=Voucher, field="voucher_id")- cls.add_catalogues_to_node(voucher, data.get("input"))+ input_data = data.get("input", {})+ cls.add_catalogues_to_node(voucher, input_data)++ if input_data:+ info.context.plugins.voucher_updated(voucher)+return VoucherAddCatalogues(voucher=voucher)@@ -332,7 +349,12 @@ class VoucherRemoveCatalogues(VoucherBaseCatalogueMutation):voucher = cls.get_node_or_error(info, data.get("id"), only_type=Voucher, field="voucher_id")- cls.remove_catalogues_from_node(voucher, data.get("input"))+ input_data = data.get("input", {})+ cls.remove_catalogues_from_node(voucher, input_data)++ if input_data:+ info.context.plugins.voucher_updated(voucher)+return VoucherRemoveCatalogues(voucher=voucher)@@ -516,6 +538,8 @@ class VoucherChannelListingUpdate(BaseChannelListingMutation):raise ValidationError(errors)cls.save(voucher, cleaned_input)+ info.context.plugins.voucher_updated(voucher)+return VoucherChannelListingUpdate(voucher=ChannelContext(node=voucher, channel_slug=None))diff --git a/saleor/graphql/discount/tests/test_bulk_delete.py b/saleor/graphql/discount/tests/test_bulk_delete.pyindex 18398a51ef..384b050cdb 100644--- a/saleor/graphql/discount/tests/test_bulk_delete.py+++ b/saleor/graphql/discount/tests/test_bulk_delete.py@@ -1,3 +1,5 @@+from unittest import mock+import grapheneimport pytest@@ -74,15 +76,16 @@ def test_delete_sales(staff_api_client, sale_list, permission_manage_discounts):assert not Sale.objects.filter(id__in=[sale.id for sale in sale_list]).exists()-def test_delete_vouchers(staff_api_client, voucher_list, permission_manage_discounts):- query = """+BULK_DELETE_VOUCHERS_MUTATION = """mutation voucherBulkDelete($ids: [ID!]!) {voucherBulkDelete(ids: $ids) {count}}- """+"""++def test_delete_vouchers(staff_api_client, voucher_list, permission_manage_discounts):variables = {"ids": [graphene.Node.to_global_id("Voucher", voucher.id)@@ -90,7 +93,9 @@ def test_delete_vouchers(staff_api_client, voucher_list, permission_manage_disco]}response = staff_api_client.post_graphql(- query, variables, permissions=[permission_manage_discounts]+ BULK_DELETE_VOUCHERS_MUTATION,+ variables,+ permissions=[permission_manage_discounts],)content = get_graphql_content(response)@@ -98,3 +103,35 @@ def test_delete_vouchers(staff_api_client, voucher_list, permission_manage_discoassert not Voucher.objects.filter(id__in=[voucher.id for voucher in voucher_list]).exists()++[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_delete_vouchers_trigger_webhook(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ staff_api_client,+ voucher_list,+ permission_manage_discounts,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ variables = {+ "ids": [+ graphene.Node.to_global_id("Voucher", voucher.id)+ for voucher in voucher_list+ ]+ }+ response = staff_api_client.post_graphql(+ BULK_DELETE_VOUCHERS_MUTATION,+ variables,+ permissions=[permission_manage_discounts],+ )+ content = get_graphql_content(response)++ assert content["data"]["voucherBulkDelete"]["count"] == 3+ assert mocked_webhook_trigger.call_count == len(voucher_list)diff --git a/saleor/graphql/discount/tests/test_discount.py b/saleor/graphql/discount/tests/test_discount.pyindex 4146b9f827..6578b8bca8 100644--- a/saleor/graphql/discount/tests/test_discount.py+++ b/saleor/graphql/discount/tests/test_discount.py@@ -4,6 +4,7 @@ from unittest.mock import ANY, patchimport grapheneimport pytestfrom django.utils import timezone+from django.utils.functional import SimpleLazyObjectfrom django_countries import countriesfrom freezegun import freeze_time@@ -12,6 +13,7 @@ from ....discount.error_codes import DiscountErrorCodefrom ....discount.models import Sale, SaleChannelListing, Voucherfrom ....discount.utils import fetch_catalogue_infofrom ....graphql.discount.mutations import convert_catalogue_info_to_global_ids+from ....webhook.event_types import WebhookEventAsyncTypefrom ...tests.utils import (assert_no_permission,get_graphql_content,@@ -493,6 +495,57 @@ def test_create_voucher(staff_api_client, permission_manage_discounts):assert voucher.usage_limit == 3+@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_create_voucher_trigger_webhook(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ staff_api_client,+ permission_manage_discounts,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ start_date = timezone.now() - timedelta(days=365)+ end_date = timezone.now() + timedelta(days=365)+ variables = {+ "name": "test voucher",+ "type": VoucherTypeEnum.ENTIRE_ORDER.name,+ "code": "testcode123",+ "discountValueType": DiscountValueTypeEnum.FIXED.name,+ "minCheckoutItemsQuantity": 10,+ "startDate": start_date.isoformat(),+ "endDate": end_date.isoformat(),+ "applyOncePerOrder": True,+ "applyOncePerCustomer": True,+ "usageLimit": 3,+ }++ # when+ response = staff_api_client.post_graphql(+ CREATE_VOUCHER_MUTATION, variables, permissions=[permission_manage_discounts]+ )+ content = get_graphql_content(response)+ voucher = Voucher.objects.last()++ # then+ assert content["data"]["voucherCreate"]["voucher"]+ mocked_webhook_trigger.assert_called_once_with(+ {+ "id": graphene.Node.to_global_id("Voucher", voucher.id),+ "name": voucher.name,+ "code": voucher.code,+ },+ WebhookEventAsyncType.VOUCHER_CREATED,+ [any_webhook],+ voucher,+ SimpleLazyObject(lambda: staff_api_client.user),+ )++def test_create_voucher_with_empty_code(staff_api_client, permission_manage_discounts):start_date = timezone.now() - timedelta(days=365)end_date = timezone.now() + timedelta(days=365)@@ -600,8 +653,7 @@ def test_create_voucher_with_enddate_before_startdate(assert errors-def test_update_voucher(staff_api_client, voucher, permission_manage_discounts):- query = """+UPDATE_VOUCHER_MUTATION = """mutation voucherUpdate($code: String,$discountValueType: DiscountValueTypeEnum, $id: ID!,$applyOncePerOrder: Boolean, $minCheckoutItemsQuantity: Int) {@@ -623,7 +675,10 @@ def test_update_voucher(staff_api_client, voucher, permission_manage_discounts):}}}- """+"""+++def test_update_voucher(staff_api_client, voucher, permission_manage_discounts):apply_once_per_order = not voucher.apply_once_per_order# Set discount value type to 'fixed' and change it in mutationvoucher.discount_value_type = DiscountValueType.FIXED@@ -638,7 +693,7 @@ def test_update_voucher(staff_api_client, voucher, permission_manage_discounts):}response = staff_api_client.post_graphql(- query, variables, permissions=[permission_manage_discounts]+ UPDATE_VOUCHER_MUTATION, variables, permissions=[permission_manage_discounts])content = get_graphql_content(response)data = content["data"]["voucherUpdate"]["voucher"]@@ -648,28 +703,71 @@ def test_update_voucher(staff_api_client, voucher, permission_manage_discounts):assert data["minCheckoutItemsQuantity"] == 10+@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_update_voucher_trigger_webhook(+ 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"]++ variables = {+ "id": graphene.Node.to_global_id("Voucher", voucher.id),+ "code": "testcode123",+ }++ # when+ response = staff_api_client.post_graphql(+ 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(+ {+ "id": variables["id"],+ "name": voucher.name,+ "code": variables["code"],+ },+ WebhookEventAsyncType.VOUCHER_UPDATED,+ [any_webhook],+ voucher,+ SimpleLazyObject(lambda: staff_api_client.user),+ )+++VOUCHER_DELETE_MUTATION = """+ mutation DeleteVoucher($id: ID!) {+ voucherDelete(id: $id) {+ voucher {+ name+ id+ }+ errors {+ field+ code+ message+ }+ }+ }+"""++def test_voucher_delete_mutation(staff_api_client, voucher, permission_manage_discounts):- query = """- mutation DeleteVoucher($id: ID!) {- voucherDelete(id: $id) {- voucher {- name- id- }- errors {- field- code- message- }- }- }- """variables = {"id": graphene.Node.to_global_id("Voucher", voucher.id)}response = staff_api_client.post_graphql(- query, variables, permissions=[permission_manage_discounts]+ VOUCHER_DELETE_MUTATION, variables, permissions=[permission_manage_discounts])content = get_graphql_content(response)data = content["data"]["voucherDelete"]@@ -678,6 +776,60 @@ def test_voucher_delete_mutation(voucher.refresh_from_db()+@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_voucher_delete_mutation_trigger_webhook(+ 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"]++ variables = {"id": graphene.Node.to_global_id("Voucher", voucher.id)}++ # when+ response = staff_api_client.post_graphql(+ VOUCHER_DELETE_MUTATION, variables, permissions=[permission_manage_discounts]+ )+ content = get_graphql_content(response)++ # then+ assert content["data"]["voucherDelete"]["voucher"]+ mocked_webhook_trigger.assert_called_once_with(+ {+ "id": variables["id"],+ "name": voucher.name,+ "code": voucher.code,+ },+ WebhookEventAsyncType.VOUCHER_DELETED,+ [any_webhook],+ voucher,+ SimpleLazyObject(lambda: staff_api_client.user),+ )+++VOUCHER_ADD_CATALOGUES_MUTATION = """+ mutation voucherCataloguesAdd($id: ID!, $input: CatalogueInput!) {+ voucherCataloguesAdd(id: $id, input: $input) {+ voucher {+ name+ }+ errors {+ field+ code+ message+ }+ }+ }+"""++def test_voucher_add_catalogues(staff_api_client,voucher,@@ -687,20 +839,6 @@ def test_voucher_add_catalogues(product_variant_list,permission_manage_discounts,):- query = """- mutation voucherCataloguesAdd($id: ID!, $input: CatalogueInput!) {- voucherCataloguesAdd(id: $id, input: $input) {- voucher {- name- }- errors {- field- code- message- }- }- }- """product_id = graphene.Node.to_global_id("Product", product.id)collection_id = graphene.Node.to_global_id("Collection", collection.id)category_id = graphene.Node.to_global_id("Category", category.id)@@ -719,7 +857,9 @@ def test_voucher_add_catalogues(}response = staff_api_client.post_graphql(- query, variables, permissions=[permission_manage_discounts]+ VOUCHER_ADD_CATALOGUES_MUTATION,+ variables,+ permissions=[permission_manage_discounts],)content = get_graphql_content(response)data = content["data"]["voucherCataloguesAdd"]@@ -731,6 +871,67 @@ def test_voucher_add_catalogues(assert set(product_variant_list) == set(voucher.variants.all())+@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_voucher_add_catalogues_trigger_webhook(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ staff_api_client,+ voucher,+ category,+ product,+ collection,+ product_variant_list,+ permission_manage_discounts,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ product_id = graphene.Node.to_global_id("Product", product.id)+ collection_id = graphene.Node.to_global_id("Collection", collection.id)+ category_id = graphene.Node.to_global_id("Category", category.id)+ variant_ids = [+ graphene.Node.to_global_id("ProductVariant", variant.id)+ for variant in product_variant_list+ ]+ variables = {+ "id": graphene.Node.to_global_id("Voucher", voucher.id),+ "input": {+ "products": [product_id],+ "collections": [collection_id],+ "categories": [category_id],+ "variants": variant_ids,+ },+ }++ # when+ response = staff_api_client.post_graphql(+ VOUCHER_ADD_CATALOGUES_MUTATION,+ variables,+ permissions=[permission_manage_discounts],+ )+ content = get_graphql_content(response)+ data = content["data"]["voucherCataloguesAdd"]++ # then+ assert content["data"]["voucherCataloguesAdd"]["voucher"]+ assert not data["errors"]+ mocked_webhook_trigger.assert_called_once_with(+ {+ "id": variables["id"],+ "name": voucher.name,+ "code": voucher.code,+ },+ WebhookEventAsyncType.VOUCHER_UPDATED,+ [any_webhook],+ voucher,+ SimpleLazyObject(lambda: staff_api_client.user),+ )++def test_voucher_add_catalogues_with_product_without_variant(staff_api_client,voucher,@@ -776,6 +977,22 @@ def test_voucher_add_catalogues_with_product_without_variant(assert error["message"] == "Cannot manage products without variants."+VOUCHER_REMOVE_CATALOGUES = """+ mutation voucherCataloguesRemove($id: ID!, $input: CatalogueInput!) {+ voucherCataloguesRemove(id: $id, input: $input) {+ voucher {+ name+ }+ errors {+ field+ code+ message+ }+ }+ }+"""++def test_voucher_remove_catalogues(staff_api_client,voucher,@@ -790,20 +1007,6 @@ def test_voucher_remove_catalogues(voucher.categories.add(category)voucher.variants.add(*product_variant_list)- query = """- mutation voucherCataloguesRemove($id: ID!, $input: CatalogueInput!) {- voucherCataloguesRemove(id: $id, input: $input) {- voucher {- name- }- errors {- field- code- message- }- }- }- """product_id = graphene.Node.to_global_id("Product", product.id)collection_id = graphene.Node.to_global_id("Collection", collection.id)category_id = graphene.Node.to_global_id("Category", category.id)@@ -822,7 +1025,7 @@ def test_voucher_remove_catalogues(}response = staff_api_client.post_graphql(- query, variables, permissions=[permission_manage_discounts]+ VOUCHER_REMOVE_CATALOGUES, variables, permissions=[permission_manage_discounts])content = get_graphql_content(response)data = content["data"]["voucherCataloguesRemove"]diff --git a/saleor/graphql/discount/tests/test_voucher_channel_listing.py b/saleor/graphql/discount/tests/test_voucher_channel_listing.pyindex e4cea6b7b5..54162cbef2 100644--- a/saleor/graphql/discount/tests/test_voucher_channel_listing.py+++ b/saleor/graphql/discount/tests/test_voucher_channel_listing.py@@ -1,7 +1,11 @@+from unittest.mock import patch+import graphene+from django.utils.functional import SimpleLazyObjectfrom ....discount import DiscountValueTypefrom ....discount.error_codes import DiscountErrorCode+from ....webhook.event_types import WebhookEventAsyncTypefrom ...tests.utils import assert_no_permission, get_graphql_contentVOUCHER_CHANNEL_LISTING_UPDATE_MUTATION = """@@ -118,6 +122,53 @@ def test_voucher_channel_listing_update_as_customer(assert_no_permission(response)+@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_voucher_channel_listing_update_trigger_webhook(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ permission_manage_discounts,+ staff_api_client,+ voucher_without_channel,+ channel_USD,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ voucher = voucher_without_channel+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": voucher_id,+ "input": {"addChannels": [{"channelId": channel_id, "discountValue": 5.5}]},+ }++ # when+ response = staff_api_client.post_graphql(+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_discounts,),+ )+ content = get_graphql_content(response)++ # then+ assert content["data"]["voucherChannelListingUpdate"]["voucher"]+ mocked_webhook_trigger.assert_called_once_with(+ {+ "id": variables["id"],+ "name": voucher.name,+ "code": voucher.code,+ },+ WebhookEventAsyncType.VOUCHER_UPDATED,+ [any_webhook],+ voucher,+ SimpleLazyObject(lambda: staff_api_client.user),+ )++def test_voucher_channel_listing_update_as_anonymous(api_client, voucher_without_channel, channel_USD):diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 6e1ed72c6c..39351a0e77 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1469,6 +1469,15 @@ enum WebhookEventTypeEnum {TRANSACTION_ACTION_REQUESTTRANSLATION_CREATEDTRANSLATION_UPDATED++ """A new voucher created."""+ VOUCHER_CREATED++ """A voucher is updated."""+ VOUCHER_UPDATED++ """A voucher is deleted."""+ VOUCHER_DELETEDPAYMENT_AUTHORIZEPAYMENT_CAPTUREPAYMENT_CONFIRM@@ -1669,6 +1678,15 @@ enum WebhookEventTypeAsyncEnum {TRANSACTION_ACTION_REQUESTTRANSLATION_CREATEDTRANSLATION_UPDATED++ """A new voucher created."""+ VOUCHER_CREATED++ """A voucher is updated."""+ VOUCHER_UPDATED++ """A voucher is deleted."""+ VOUCHER_DELETED}"""Represents app data."""@@ -2181,6 +2199,9 @@ enum WebhookSampleEventTypeEnum {TRANSACTION_ACTION_REQUESTTRANSLATION_CREATEDTRANSLATION_UPDATED+ VOUCHER_CREATED+ VOUCHER_UPDATED+ VOUCHER_DELETED}"""Represents warehouse."""@@ -19949,7 +19970,7 @@ type Subscription {event: Event}-union Event = CategoryCreated | CategoryUpdated | CategoryDeleted | ChannelCreated | ChannelUpdated | ChannelDeleted | ChannelStatusChanged | GiftCardCreated | GiftCardUpdated | GiftCardDeleted | GiftCardStatusChanged | OrderCreated | OrderUpdated | OrderConfirmed | OrderFullyPaid | OrderCancelled | OrderFulfilled | DraftOrderCreated | DraftOrderUpdated | DraftOrderDeleted | ProductCreated | ProductUpdated | ProductDeleted | ProductVariantCreated | ProductVariantUpdated | ProductVariantOutOfStock | ProductVariantBackInStock | ProductVariantDeleted | SaleCreated | SaleUpdated | SaleDeleted | InvoiceRequested | InvoiceDeleted | InvoiceSent | FulfillmentCreated | FulfillmentCanceled | CustomerCreated | CustomerUpdated | CollectionCreated | CollectionUpdated | CollectionDeleted | CheckoutCreated | CheckoutUpdated | PageCreated | PageUpdated | PageDeleted | ShippingPriceCreated | ShippingPriceUpdated | ShippingPriceDeleted | ShippingZoneCreated | ShippingZoneUpdated | ShippingZoneDeleted | TransactionActionRequest | TranslationCreated | TranslationUpdated+union Event = CategoryCreated | CategoryUpdated | CategoryDeleted | ChannelCreated | ChannelUpdated | ChannelDeleted | ChannelStatusChanged | GiftCardCreated | GiftCardUpdated | GiftCardDeleted | GiftCardStatusChanged | OrderCreated | OrderUpdated | OrderConfirmed | OrderFullyPaid | OrderCancelled | OrderFulfilled | DraftOrderCreated | DraftOrderUpdated | DraftOrderDeleted | ProductCreated | ProductUpdated | ProductDeleted | ProductVariantCreated | ProductVariantUpdated | ProductVariantOutOfStock | ProductVariantBackInStock | ProductVariantDeleted | SaleCreated | SaleUpdated | SaleDeleted | InvoiceRequested | InvoiceDeleted | InvoiceSent | FulfillmentCreated | FulfillmentCanceled | CustomerCreated | CustomerUpdated | CollectionCreated | CollectionUpdated | CollectionDeleted | CheckoutCreated | CheckoutUpdated | PageCreated | PageUpdated | PageDeleted | ShippingPriceCreated | ShippingPriceUpdated | ShippingPriceDeleted | ShippingZoneCreated | ShippingZoneUpdated | ShippingZoneDeleted | TransactionActionRequest | TranslationCreated | TranslationUpdated | VoucherCreated | VoucherUpdated | VoucherDeletedtype CategoryCreated {"""@@ -20716,6 +20737,48 @@ type TranslationUpdated {translation: TranslationTypes}+type VoucherCreated {+ """+ Look up a voucher.++ Added in Saleor 3.4.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ voucher(+ """Slug of a channel for which the data should be returned."""+ channel: String+ ): Voucher+}++type VoucherUpdated {+ """+ Look up a voucher.++ Added in Saleor 3.4.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ voucher(+ """Slug of a channel for which the data should be returned."""+ channel: String+ ): Voucher+}++type VoucherDeleted {+ """+ Look up a voucher.++ Added in Saleor 3.4.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ voucher(+ """Slug of a channel for which the data should be returned."""+ channel: String+ ): Voucher+}+"""An enumeration."""enum DistanceUnitsEnum {CMdiff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.pyindex 4a25450e14..2863795cd1 100644--- a/saleor/graphql/webhook/enums.py+++ b/saleor/graphql/webhook/enums.py@@ -41,6 +41,9 @@ WEBHOOK_EVENT_DESCRIPTION = {WebhookEventAsyncType.GIFT_CARD_UPDATED: "A gift card is updated.",WebhookEventAsyncType.GIFT_CARD_DELETED: "A gift card is deleted.",WebhookEventAsyncType.GIFT_CARD_STATUS_CHANGED: "A gift card status is changed.",+ WebhookEventAsyncType.INVOICE_REQUESTED: "An invoice for order requested.",+ WebhookEventAsyncType.INVOICE_DELETED: "An invoice is deleted.",+ WebhookEventAsyncType.INVOICE_SENT: "Invoice has been sent.",WebhookEventAsyncType.NOTIFY_USER: "User notification triggered.",WebhookEventAsyncType.ORDER_CREATED: "A new order is placed.",WebhookEventAsyncType.ORDER_CONFIRMED: order_confirmed_event_enum_description,@@ -65,9 +68,9 @@ WEBHOOK_EVENT_DESCRIPTION = {WebhookEventAsyncType.SHIPPING_ZONE_CREATED: "A new shipping zone is created.",WebhookEventAsyncType.SHIPPING_ZONE_UPDATED: "A shipping zone is updated.",WebhookEventAsyncType.SHIPPING_ZONE_DELETED: "A shipping zone is deleted.",- WebhookEventAsyncType.INVOICE_REQUESTED: "An invoice for order requested.",- WebhookEventAsyncType.INVOICE_DELETED: "An invoice is deleted.",- WebhookEventAsyncType.INVOICE_SENT: "Invoice has been sent.",+ WebhookEventAsyncType.VOUCHER_CREATED: "A new voucher created.",+ WebhookEventAsyncType.VOUCHER_UPDATED: "A voucher is updated.",+ WebhookEventAsyncType.VOUCHER_DELETED: "A voucher is deleted.",WebhookEventAsyncType.ANY: "All the events.",}diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex 3372a15567..ea522cfe63 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -567,6 +567,33 @@ class TranslationUpdated(ObjectType, TranslationBase):...+class VoucherBase(AbstractType):+ voucher = graphene.Field(+ "saleor.graphql.discount.types.Voucher",+ channel=graphene.String(+ description="Slug of a channel for which the data should be returned."+ ),+ description="Look up a voucher." + ADDED_IN_34 + PREVIEW_FEATURE,+ )++ @staticmethod+ def resolve_voucher(root, _info):+ _, voucher = root+ return ChannelContext(node=voucher, channel_slug=None)+++class VoucherCreated(ObjectType, VoucherBase):+ ...+++class VoucherUpdated(ObjectType, VoucherBase):+ ...+++class VoucherDeleted(ObjectType, VoucherBase):+ ...++class Event(Union):class Meta:types = (@@ -625,6 +652,9 @@ class Event(Union):TransactionActionRequest,TranslationCreated,TranslationUpdated,+ VoucherCreated,+ VoucherUpdated,+ VoucherDeleted,)@classmethod@@ -689,6 +719,9 @@ class Event(Union):WebhookEventAsyncType.TRANSACTION_ACTION_REQUEST: TransactionActionRequest,WebhookEventAsyncType.TRANSLATION_CREATED: TranslationCreated,WebhookEventAsyncType.TRANSLATION_UPDATED: TranslationUpdated,+ WebhookEventAsyncType.VOUCHER_CREATED: VoucherCreated,+ WebhookEventAsyncType.VOUCHER_UPDATED: VoucherUpdated,+ WebhookEventAsyncType.VOUCHER_DELETED: VoucherDeleted,}return types.get(object_type)diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex f121ed23d3..0a0ce562c9 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -34,7 +34,7 @@ if TYPE_CHECKING:from ..core.middleware import Requestorfrom ..core.notify_events import NotifyEventTypefrom ..core.taxes import TaxType- from ..discount import DiscountInfo+ from ..discount import DiscountInfo, Voucherfrom ..discount.models import Salefrom ..giftcard.models import GiftCardfrom ..graphql.discount.mutations import NodeCatalogueInfo@@ -657,6 +657,24 @@ class BasePlugin:void_payment: Callable[["PaymentData", Any], GatewayResponse]+ # Trigger when voucher is created.+ #+ # Overwrite this method if you need to trigger specific logic after a voucher is+ # created.+ voucher_created: Callable[["Voucher", None], None]++ # Trigger when voucher is deleted.+ #+ # Overwrite this method if you need to trigger specific logic after a voucher is+ # deleted.+ voucher_deleted: Callable[["Voucher", None], None]++ # Trigger when voucher is updated.+ #+ # Overwrite this method if you need to trigger specific logic after a voucher is+ # updated.+ voucher_updated: Callable[["Voucher", None], None]+# Handle received http request.## Overwrite this method if the plugin expects the incoming requests.diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 30ba79791e..e8cb4ae3c5 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -42,7 +42,7 @@ if TYPE_CHECKING:from ..checkout.fetch import CheckoutInfo, CheckoutLineInfofrom ..checkout.models import Checkoutfrom ..core.middleware import Requestor- from ..discount.models import Sale+ from ..discount.models import Sale, Voucherfrom ..giftcard.models import GiftCardfrom ..invoice.models import Invoicefrom ..order.models import Fulfillment, Order, OrderLine@@ -890,6 +890,18 @@ class PluginsManager(PaymentInterface):"shipping_zone_deleted", default_value, shipping_zone)+ def voucher_created(self, voucher: "Voucher"):+ default_value = None+ return self.__run_method_on_plugins("voucher_created", default_value, voucher)++ def voucher_updated(self, voucher: "Voucher"):+ default_value = None+ return self.__run_method_on_plugins("voucher_updated", default_value, voucher)++ def voucher_deleted(self, voucher: "Voucher"):+ default_value = None+ return self.__run_method_on_plugins("voucher_deleted", default_value, voucher)+def initialize_payment(self, gateway, payment_data: dict, channel_slug: str) -> Optional["InitializedPaymentResponse"]:diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 8552fa034c..153bf47713 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -53,7 +53,7 @@ if TYPE_CHECKING:from ...account.models import Userfrom ...channel.models import Channelfrom ...checkout.models import Checkout- from ...discount.models import Sale+ from ...discount.models import Sale, Voucherfrom ...giftcard.models import GiftCardfrom ...graphql.discount.mutations import NodeCatalogueInfofrom ...invoice.models import Invoice@@ -750,6 +750,32 @@ class WebhookPlugin(BasePlugin):translation_data, event_type, webhooks, translation, self.requestor)+ def _trigger_voucher_event(self, event_type, voucher):+ if webhooks := get_webhooks_for_event(event_type):+ payload = {+ "id": graphene.Node.to_global_id("Voucher", voucher.id),+ "name": voucher.name,+ "code": voucher.code,+ }+ trigger_webhooks_async(+ payload, event_type, webhooks, voucher, self.requestor+ )++ def voucher_created(self, voucher: "Voucher", previous_value: None) -> None:+ if not self.active:+ return previous_value+ self._trigger_voucher_event(WebhookEventAsyncType.VOUCHER_CREATED, voucher)++ def voucher_updated(self, voucher: "Voucher", previous_value: None) -> None:+ if not self.active:+ return previous_value+ self._trigger_voucher_event(WebhookEventAsyncType.VOUCHER_UPDATED, voucher)++ def voucher_deleted(self, voucher: "Voucher", previous_value: None) -> None:+ if not self.active:+ return previous_value+ self._trigger_voucher_event(WebhookEventAsyncType.VOUCHER_DELETED, voucher)+def event_delivery_retry(self, delivery: "EventDelivery", previous_value: Any):if not self.active:return previous_valuediff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.pyindex 79d51ed5e1..92eed628c5 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py@@ -1274,3 +1274,81 @@ def subscription_translation_updated_webhook(subscription_webhook):TRANSLATION_UPDATED_SUBSCRIPTION_QUERY,WebhookEventAsyncType.TRANSLATION_UPDATED,)+++VOUCHER_DETAILS_FRAGMENT = """+ fragment VoucherDetails on Voucher{+ id+ name+ code+ usageLimit+ }+"""++VOUCHER_CREATED_SUBSCRIPTION_QUERY = (+ VOUCHER_DETAILS_FRAGMENT+ + """+ subscription{+ event{+ ...on VoucherCreated{+ voucher{+ ...VoucherDetails+ }+ }+ }+ }+"""+)+++def subscription_voucher_created_webhook(subscription_webhook):+ return subscription_webhook(+ VOUCHER_CREATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.VOUCHER_CREATED+ )+++VOUCHER_UPDATED_SUBSCRIPTION_QUERY = (+ VOUCHER_DETAILS_FRAGMENT+ + """+ subscription{+ event{+ ...on VoucherUpdated{+ voucher{+ ...VoucherDetails+ }+ }+ }+ }+"""+)+++def subscription_voucher_updated_webhook(subscription_webhook):+ return subscription_webhook(+ VOUCHER_UPDATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.VOUCHER_UPDATED+ )+++VOUCHER_DELETED_SUBSCRIPTION_QUERY = (+ VOUCHER_DETAILS_FRAGMENT+ + """+ subscription{+ event{+ ...on VoucherDeleted{+ voucher{+ ...VoucherDetails+ }+ }+ }+ }+"""+)+++def subscription_voucher_deleted_webhook(subscription_webhook):+ return subscription_webhook(+ VOUCHER_DELETED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.VOUCHER_DELETED+ )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 c9732dac6c..49805186d4 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@@ -899,6 +899,73 @@ def test_product_created_multiple_events_in_subscription(assert deliveries[0].webhook == webhooks[0]+def generate_expected_payload_for_voucher(voucher, voucher_global_id):+ return json.dumps(+ {+ "voucher": {+ "id": voucher_global_id,+ "name": voucher.name,+ "code": voucher.code,+ "usageLimit": voucher.usage_limit,+ },+ "meta": None,+ }+ )+++def test_voucher_created(voucher, subscription_voucher_created_webhook):+ # given+ webhooks = [subscription_voucher_created_webhook]+ event_type = WebhookEventAsyncType.VOUCHER_CREATED+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)++ # when+ deliveries = create_deliveries_for_subscriptions(event_type, voucher, webhooks)++ # then+ expected_payload = generate_expected_payload_for_voucher(voucher, voucher_id)+ assert deliveries[0].payload.payload == expected_payload+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]+++def test_voucher_updated(voucher, subscription_voucher_updated_webhook):+ # given+ webhooks = [subscription_voucher_updated_webhook]+ event_type = WebhookEventAsyncType.VOUCHER_UPDATED+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)++ # when+ deliveries = create_deliveries_for_subscriptions(event_type, voucher, webhooks)++ # then+ expected_payload = generate_expected_payload_for_voucher(voucher, voucher_id)+ assert deliveries[0].payload.payload == expected_payload+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]+++def test_voucher_deleted(voucher, subscription_voucher_deleted_webhook):+ # given+ webhooks = [subscription_voucher_deleted_webhook]++ voucher_id = voucher.id+ voucher.delete()+ voucher.id = voucher_id++ event_type = WebhookEventAsyncType.VOUCHER_DELETED+ voucher_global_id = graphene.Node.to_global_id("Voucher", voucher.id)++ # when+ deliveries = create_deliveries_for_subscriptions(event_type, voucher, webhooks)++ # then+ expected_payload = generate_expected_payload_for_voucher(voucher, voucher_global_id)+ assert deliveries[0].payload.payload == expected_payload+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]++@patch.object(logger, "info")def test_create_deliveries_for_subscriptions_unsubscribable_event(mocked_logger, product, subscription_product_updated_webhook, any_webhookdiff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 4a2f3b8494..0fbffcbe6c 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -5125,10 +5125,16 @@ def app(db):@pytest.fixture-def webhook_app(db, permission_manage_shipping, permission_manage_gift_card):+def webhook_app(+ db,+ permission_manage_shipping,+ permission_manage_gift_card,+ permission_manage_discounts,+):app = App.objects.create(name="Sample app objects", is_active=True)app.permissions.add(permission_manage_shipping)app.permissions.add(permission_manage_gift_card)+ app.permissions.add(permission_manage_discounts)return appdiff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.pyindex e6fbe20e67..c0e4b60d89 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -92,6 +92,10 @@ class WebhookEventAsyncType:TRANSLATION_CREATED = "translation_created"TRANSLATION_UPDATED = "translation_updated"+ VOUCHER_CREATED = "voucher_created"+ VOUCHER_UPDATED = "voucher_updated"+ VOUCHER_DELETED = "voucher_deleted"+DISPLAY_LABELS = {ANY: "Any events",CATEGORY_CREATED: "Category created",@@ -150,6 +154,9 @@ class WebhookEventAsyncType:TRANSACTION_ACTION_REQUEST: "Payment action request",TRANSLATION_CREATED: "Create translation",TRANSLATION_UPDATED: "Update translation",+ VOUCHER_CREATED: "Voucher created",+ VOUCHER_UPDATED: "Voucher updated",+ VOUCHER_DELETED: "Voucher deleted",}CHOICES = [@@ -210,6 +217,9 @@ class WebhookEventAsyncType:(TRANSACTION_ACTION_REQUEST, DISPLAY_LABELS[TRANSACTION_ACTION_REQUEST]),(TRANSLATION_CREATED, DISPLAY_LABELS[TRANSLATION_CREATED]),(TRANSLATION_UPDATED, DISPLAY_LABELS[TRANSLATION_UPDATED]),+ (VOUCHER_CREATED, DISPLAY_LABELS[VOUCHER_CREATED]),+ (VOUCHER_UPDATED, DISPLAY_LABELS[VOUCHER_UPDATED]),+ (VOUCHER_DELETED, DISPLAY_LABELS[VOUCHER_DELETED]),]ALL = [event[0] for event in CHOICES]@@ -271,6 +281,9 @@ class WebhookEventAsyncType:TRANSACTION_ACTION_REQUEST: PaymentPermissions.HANDLE_PAYMENTS,TRANSLATION_CREATED: SitePermissions.MANAGE_TRANSLATIONS,TRANSLATION_UPDATED: SitePermissions.MANAGE_TRANSLATIONS,+ VOUCHER_CREATED: DiscountPermissions.MANAGE_DISCOUNTS,+ VOUCHER_UPDATED: DiscountPermissions.MANAGE_DISCOUNTS,+ VOUCHER_DELETED: DiscountPermissions.MANAGE_DISCOUNTS,}@@ -401,4 +414,7 @@ SUBSCRIBABLE_EVENTS = [WebhookEventAsyncType.TRANSACTION_ACTION_REQUEST,WebhookEventAsyncType.TRANSLATION_CREATED,WebhookEventAsyncType.TRANSLATION_UPDATED,+ WebhookEventAsyncType.VOUCHER_CREATED,+ WebhookEventAsyncType.VOUCHER_UPDATED,+ WebhookEventAsyncType.VOUCHER_DELETED,]