Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add Webhook payload via graphql subscriptions (#9394)

Jakubaca6418d6c36
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ce9485c7f0..a9d83489ec 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,9 +18,9 @@ All notable, unreleased changes to this project will be documented in this file.
- Fix failing `checkoutCustomerAttach` mutation - #9401 by @IKarbowiak
- Add new mutation `orderCreateFromCheckout` - #9343 by @korycins
- Add `language_code` field to webhook payload for `Order`, `Checkout` and `Customer` - #9433 by @rafalp
+- Add handling webhook payload via GraphQL subscriptions (#9394) @jakubkuc
- Fix access to own resources by App - #9425 by @korycins
-
# 3.1.7
- Handle `ValidationError` in metadata mutations (#9380) (75deaf6ea)
diff --git a/conftest.py b/conftest.py
index d5e4b91715..2659b99f50 100644
--- a/conftest.py
+++ b/conftest.py
@@ -6,4 +6,5 @@ pytest_plugins = [
"saleor.graphql.account.tests.benchmark.fixtures",
"saleor.graphql.order.tests.benchmark.fixtures",
"saleor.graphql.giftcard.tests.benchmark.fixtures",
+ "saleor.plugins.webhook.tests.subscription_webhooks.fixtures",
]
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index 667b169cc0..6eaeed641a 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -26,6 +26,7 @@ from .shop.schema import ShopMutations, ShopQueries
from .translations.schema import TranslationQueries
from .warehouse.schema import StockQueries, WarehouseMutations, WarehouseQueries
from .webhook.schema import WebhookMutations, WebhookQueries
+from .webhook.subscription_types import Subscription
API_PATH = SimpleLazyObject(lambda: reverse("api"))
@@ -83,4 +84,6 @@ class Mutation(
pass
-schema = build_federated_schema(query=Query, mutation=Mutation, types=unit_enums)
+schema = build_federated_schema(
+ Query, mutation=Mutation, types=unit_enums, subscription=Subscription
+)
diff --git a/saleor/graphql/core/federation/schema.py b/saleor/graphql/core/federation/schema.py
index 2263960e9f..4c62bfd963 100644
--- a/saleor/graphql/core/federation/schema.py
+++ b/saleor/graphql/core/federation/schema.py
@@ -42,12 +42,13 @@ class _Service(graphene.ObjectType):
sdl = graphene.String()
-def build_federated_schema(query=None, mutation=None, types=None):
+def build_federated_schema(query=None, mutation=None, types=None, subscription=None):
"""Create GraphQL schema that supports Apollo Federation."""
schema = graphene.Schema(
query=query,
mutation=mutation,
types=list(types) + [_Any, _Entity, _Service],
+ subscription=subscription,
)
entity_type = schema.get_type("_Entity")
diff --git a/saleor/graphql/page/tests/mutations/test_page_create.py b/saleor/graphql/page/tests/mutations/test_page_create.py
index 287a140aa6..d841d930d3 100644
--- a/saleor/graphql/page/tests/mutations/test_page_create.py
+++ b/saleor/graphql/page/tests/mutations/test_page_create.py
@@ -3,6 +3,7 @@ from unittest import mock
import graphene
import pytz
+from django.utils.functional import SimpleLazyObject
from django.utils.text import slugify
from freezegun import freeze_time
@@ -156,7 +157,11 @@ def test_page_create_trigger_page_webhook(
expected_data = generate_page_payload(page, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.PAGE_CREATED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.PAGE_CREATED,
+ [any_webhook],
+ page,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
diff --git a/saleor/graphql/page/tests/mutations/test_page_delete.py b/saleor/graphql/page/tests/mutations/test_page_delete.py
index 18249841ec..ea0a508d9e 100644
--- a/saleor/graphql/page/tests/mutations/test_page_delete.py
+++ b/saleor/graphql/page/tests/mutations/test_page_delete.py
@@ -2,6 +2,7 @@ from unittest import mock
import graphene
import pytest
+from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
from .....attribute.models import AttributeValue
@@ -64,7 +65,11 @@ def test_page_delete_trigger_webhook(
page.refresh_from_db()
expected_data = generate_page_payload(page, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.PAGE_DELETED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.PAGE_DELETED,
+ [any_webhook],
+ page,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
diff --git a/saleor/graphql/page/tests/mutations/test_page_update.py b/saleor/graphql/page/tests/mutations/test_page_update.py
index 3c41b81cd3..0cdecdad3e 100644
--- a/saleor/graphql/page/tests/mutations/test_page_update.py
+++ b/saleor/graphql/page/tests/mutations/test_page_update.py
@@ -3,6 +3,7 @@ from unittest import mock
import graphene
import pytest
+from django.utils.functional import SimpleLazyObject
from django.utils.text import slugify
from freezegun import freeze_time
@@ -167,7 +168,11 @@ def test_update_page_trigger_webhook(
page.publication_date = date(2020, 3, 18)
expected_data = generate_page_payload(page, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.PAGE_UPDATED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.PAGE_UPDATED,
+ [any_webhook],
+ page,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 915973ab2d..129c0a1582 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -14,6 +14,7 @@ from django.db import transaction
from django.db.models import Sum
from django.utils import timezone
from django.utils.dateparse import parse_datetime
+from django.utils.functional import SimpleLazyObject
from django.utils.html import strip_tags
from django.utils.text import slugify
from freezegun import freeze_time
@@ -7766,7 +7767,11 @@ def test_delete_product_trigger_webhook(
product, variants_id, staff_api_client.user
)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.PRODUCT_DELETED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.PRODUCT_DELETED,
+ [any_webhook],
+ product,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
mocked_recalculate_orders_task.assert_not_called()
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 5695bf76ac..4da396860a 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1,6 +1,7 @@
schema {
query: Query
mutation: Mutation
+ subscription: Subscription
}
type Query {
@@ -10630,6 +10631,11 @@ input WebhookCreateInput {
"""The secret key used to create a hash signature with each payload."""
secretKey: String
+
+ """
+ New in Saleor 3.2. Subscription query used to define a webhook payload. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ query: String
}
"""
@@ -10678,6 +10684,11 @@ input WebhookUpdateInput {
"""Use to create a hash signature with each payload."""
secretKey: String
+
+ """
+ New in Saleor 3.2. Subscription query used to define a webhook payload. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ query: String
}
"""
@@ -16400,6 +16411,343 @@ type PermissionGroupDelete {
group: Group
}
+type Subscription {
+ """
+ New in Saleor 3.2. Look up subscription event. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ event: Event
+}
+
+union Event = 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 | TranslationCreated | TranslationUpdated
+
+type OrderCreated {
+ """
+ New in Saleor 3.2. Look up an order. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ order: Order
+}
+
+type OrderUpdated {
+ """
+ New in Saleor 3.2. Look up an order. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ order: Order
+}
+
+type OrderConfirmed {
+ """
+ New in Saleor 3.2. Look up an order. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ order: Order
+}
+
+type OrderFullyPaid {
+ """
+ New in Saleor 3.2. Look up an order. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ order: Order
+}
+
+type OrderCancelled {
+ """
+ New in Saleor 3.2. Look up an order. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ order: Order
+}
+
+type OrderFulfilled {
+ """
+ New in Saleor 3.2. Look up an order. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ order: Order
+}
+
+type DraftOrderCreated {
+ """
+ New in Saleor 3.2. Look up an order. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ order: Order
+}
+
+type DraftOrderUpdated {
+ """
+ New in Saleor 3.2. Look up an order. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ order: Order
+}
+
+type DraftOrderDeleted {
+ """
+ New in Saleor 3.2. Look up an order. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ order: Order
+}
+
+type ProductCreated {
+ """
+ New in Saleor 3.2. Look up a product. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ product(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
+ ): Product
+
+ """
+ New in Saleor 3.2. Look up a category. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ category: Category
+}
+
+type ProductUpdated {
+ """
+ New in Saleor 3.2. Look up a product. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ product(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
+ ): Product
+
+ """
+ New in Saleor 3.2. Look up a category. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ category: Category
+}
+
+type ProductDeleted {
+ """
+ New in Saleor 3.2. Look up a product. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ product(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
+ ): Product
+
+ """
+ New in Saleor 3.2. Look up a category. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ category: Category
+}
+
+type ProductVariantCreated {
+ """
+ New in Saleor 3.2. Look up a product variant. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ productVariant(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
+ ): ProductVariant
+}
+
+type ProductVariantUpdated {
+ """
+ New in Saleor 3.2. Look up a product variant. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ productVariant(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
+ ): ProductVariant
+}
+
+type ProductVariantOutOfStock {
+ """
+ New in Saleor 3.2. Look up a product variant. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ productVariant(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
+ ): ProductVariant
+
+ """
+ New in Saleor 3.2. Look up a warehouse. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ warehouse: Warehouse
+}
+
+type ProductVariantBackInStock {
+ """
+ New in Saleor 3.2. Look up a product variant. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ productVariant(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
+ ): ProductVariant
+
+ """
+ New in Saleor 3.2. Look up a warehouse. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ warehouse: Warehouse
+}
+
+type ProductVariantDeleted {
+ """
+ New in Saleor 3.2. Look up a product variant. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ productVariant(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
+ ): ProductVariant
+}
+
+type SaleCreated {
+ """
+ New in Saleor 3.2. Look up a sale. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ sale(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
+ ): Sale
+}
+
+type SaleUpdated {
+ """
+ New in Saleor 3.2. Look up a sale. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ sale(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
+ ): Sale
+}
+
+type SaleDeleted {
+ """
+ New in Saleor 3.2. Look up a sale. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ sale(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
+ ): Sale
+}
+
+type InvoiceRequested {
+ """
+ New in Saleor 3.2. Look up an Invoice. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ invoice: Invoice
+}
+
+type InvoiceDeleted {
+ """
+ New in Saleor 3.2. Look up an Invoice. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ invoice: Invoice
+}
+
+type InvoiceSent {
+ """
+ New in Saleor 3.2. Look up an Invoice. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ invoice: Invoice
+}
+
+type FulfillmentCreated {
+ """
+ New in Saleor 3.2. Look up a Fulfillment. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ fulfillment: Fulfillment
+}
+
+type FulfillmentCanceled {
+ """
+ New in Saleor 3.2. Look up a Fulfillment. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ fulfillment: Fulfillment
+}
+
+type CustomerCreated {
+ """
+ New in Saleor 3.2. Look up a user. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ user: User
+}
+
+type CustomerUpdated {
+ """
+ New in Saleor 3.2. Look up a user. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ user: User
+}
+
+type CollectionCreated {
+ """
+ New in Saleor 3.2. Look up a collection. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ collection(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
+ ): Collection
+}
+
+type CollectionUpdated {
+ """
+ New in Saleor 3.2. Look up a collection. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ collection(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
+ ): Collection
+}
+
+type CollectionDeleted {
+ """
+ New in Saleor 3.2. Look up a collection. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ collection(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
+ ): Collection
+}
+
+type CheckoutCreated {
+ """
+ New in Saleor 3.2. Look up a Checkout. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ checkout: Checkout
+}
+
+type CheckoutUpdated {
+ """
+ New in Saleor 3.2. Look up a Checkout. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ checkout: Checkout
+}
+
+type PageCreated {
+ """
+ New in Saleor 3.2. Look up a page. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ page: Page
+}
+
+type PageUpdated {
+ """
+ New in Saleor 3.2. Look up a page. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ page: Page
+}
+
+type PageDeleted {
+ """
+ New in Saleor 3.2. Look up a page. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ page: Page
+}
+
+type TranslationCreated {
+ """
+ New in Saleor 3.2. Look up a translation. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ translation: TranslationTypes
+}
+
+union TranslationTypes = ProductTranslation | CollectionTranslation | CategoryTranslation | AttributeTranslation | AttributeValueTranslation | ProductVariantTranslation | PageTranslation | ShippingMethodTranslation | SaleTranslation | VoucherTranslation | MenuItemTranslation
+
+type TranslationUpdated {
+ """
+ New in Saleor 3.2. Look up a translation. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ translation: TranslationTypes
+}
+
"""An enumeration."""
enum DistanceUnitsEnum {
CM
diff --git a/saleor/graphql/translations/tests/test_translations.py b/saleor/graphql/translations/tests/test_translations.py
index c95193b4d8..66ea537475 100644
--- a/saleor/graphql/translations/tests/test_translations.py
+++ b/saleor/graphql/translations/tests/test_translations.py
@@ -4,6 +4,7 @@ from unittest.mock import patch
import graphene
import pytest
from django.contrib.auth.models import Permission
+from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
from ....tests.utils import dummy_editorjs
@@ -856,7 +857,11 @@ def test_product_create_translation(
translation = product.translations.first()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_CREATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_CREATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -1005,7 +1010,11 @@ def test_product_update_translation(
translation.refresh_from_db()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_UPDATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_UPDATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -1063,7 +1072,11 @@ def test_product_variant_create_translation(
translation = variant.translations.first()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_CREATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_CREATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -1117,7 +1130,11 @@ def test_product_variant_update_translation(
translation.refresh_from_db()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_UPDATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_UPDATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -1200,7 +1217,11 @@ def test_collection_create_translation(
translation = published_collection.translations.first()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_CREATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_CREATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -1292,7 +1313,11 @@ def test_collection_update_translation(
translation.refresh_from_db()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_UPDATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_UPDATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -1363,7 +1388,11 @@ def test_category_create_translation(
translation = category.translations.first()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_CREATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_CREATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -1453,7 +1482,11 @@ def test_category_update_translation(
translation.refresh_from_db()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_UPDATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_UPDATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -1504,7 +1537,11 @@ def test_voucher_create_translation(
translation = voucher.translations.first()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_CREATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_CREATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -1556,7 +1593,11 @@ def test_voucher_update_translation(
translation.refresh_from_db()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_UPDATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_UPDATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -1607,7 +1648,11 @@ def test_sale_create_translation(
translation = sale.translations.first()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_CREATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_CREATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -1660,7 +1705,11 @@ def test_sale_update_translation(
translation.refresh_from_db()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_UPDATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_UPDATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -1712,7 +1761,11 @@ def test_page_create_translation(
translation = page.translations.first()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_CREATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_CREATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -1798,7 +1851,11 @@ def test_page_update_translation(
translation.refresh_from_db()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_UPDATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_UPDATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -1851,7 +1908,11 @@ def test_attribute_create_translation(
translation = color_attribute.translations.first()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_CREATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_CREATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -1904,7 +1965,11 @@ def test_attribute_update_translation(
translation.refresh_from_db()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_UPDATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_UPDATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -1959,7 +2024,11 @@ def test_attribute_value_create_translation(
translation = pink_attribute_value.translations.first()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_CREATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_CREATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -2014,7 +2083,11 @@ def test_attribute_value_update_translation(
translation.refresh_from_db()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_UPDATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_UPDATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -2081,7 +2154,11 @@ def test_shipping_method_create_translation(
translation = shipping_method.translations.first()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_CREATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_CREATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -2160,7 +2237,11 @@ def test_shipping_method_update_translation(
translation.refresh_from_db()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_UPDATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_UPDATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -2216,7 +2297,11 @@ def test_menu_item_update_translation(
translation.refresh_from_db()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_UPDATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_UPDATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -2278,7 +2363,11 @@ def test_shop_create_translation(
translation = site_settings.translations.first()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_CREATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_CREATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
@@ -2335,7 +2424,11 @@ def test_shop_update_translation(
translation.refresh_from_db()
expected_payload = generate_translation_payload(translation, staff_api_client.user)
mocked_webhook_trigger.assert_called_once_with(
- expected_payload, WebhookEventAsyncType.TRANSLATION_UPDATED, [any_webhook]
+ expected_payload,
+ WebhookEventAsyncType.TRANSLATION_UPDATED,
+ [any_webhook],
+ translation,
+ SimpleLazyObject(lambda: staff_api_client.user),
)
diff --git a/saleor/graphql/webhook/mutations.py b/saleor/graphql/webhook/mutations.py
index 61480561e3..5754de3be0 100644
--- a/saleor/graphql/webhook/mutations.py
+++ b/saleor/graphql/webhook/mutations.py
@@ -4,13 +4,29 @@ from django.core.exceptions import ValidationError
from ...core.permissions import AppPermission, AuthorizationFilters
from ...webhook import models
from ...webhook.error_codes import WebhookErrorCode
-from ..core.descriptions import DEPRECATED_IN_3X_INPUT
+from ..core.descriptions import ADDED_IN_32, DEPRECATED_IN_3X_INPUT, PREVIEW_FEATURE
from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ..core.types import NonNullList, WebhookError
from . import enums
+from .subscription_payload import validate_subscription_query
from .types import EventDelivery, Webhook
+def validate_query(query):
+ if not query:
+ return
+ is_valid = validate_subscription_query(query)
+ if not is_valid:
+ raise ValidationError(
+ {
+ "query": ValidationError(
+ "Subscription query is not valid",
+ code=WebhookErrorCode.INVALID.value,
+ )
+ }
+ )
+
+
class WebhookCreateInput(graphene.InputObjectType):
name = graphene.String(description="The name of the webhook.", required=False)
target_url = graphene.String(description="The url to receive the payload.")
@@ -40,6 +56,11 @@ class WebhookCreateInput(graphene.InputObjectType):
description="The secret key used to create a hash signature with each payload.",
required=False,
)
+ query = graphene.String(
+ description=f"{ADDED_IN_32} Subscription query used to define a webhook "
+ f"payload. {PREVIEW_FEATURE}",
+ required=False,
+ )
def clean_webhook_events(_info, _instance, data):
@@ -93,6 +114,9 @@ class WebhookCreate(ModelMutation):
code=WebhookErrorCode.NOT_FOUND,
)
clean_webhook_events(info, instance, cleaned_data)
+ if query := cleaned_data.get("query"):
+ validate_query(query)
+ instance.subscription_query = query
return cleaned_data
@classmethod
@@ -147,6 +171,11 @@ class WebhookUpdateInput(graphene.InputObjectType):
secret_key = graphene.String(
description="Use to create a hash signature with each payload.", required=False
)
+ query = graphene.String(
+ description=f"{ADDED_IN_32} Subscription query used to define a webhook "
+ f"payload. {PREVIEW_FEATURE}",
+ required=False,
+ )
class WebhookUpdate(ModelMutation):
@@ -184,6 +213,10 @@ class WebhookUpdate(ModelMutation):
code=WebhookErrorCode.NOT_FOUND,
)
clean_webhook_events(info, instance, cleaned_data)
+
+ if query := cleaned_data.get("query"):
+ validate_query(query)
+ instance.subscription_query = query
return cleaned_data
@classmethod
diff --git a/saleor/graphql/webhook/subscription_payload.py b/saleor/graphql/webhook/subscription_payload.py
new file mode 100644
index 0000000000..8e11f19fad
--- /dev/null
+++ b/saleor/graphql/webhook/subscription_payload.py
@@ -0,0 +1,128 @@
+from typing import Any, Dict, Optional
+
+from celery.utils.log import get_task_logger
+from django.core.handlers.base import BaseHandler
+from django.http import HttpRequest
+from django.test.client import RequestFactory
+from graphql import GraphQLDocument, get_default_backend, parse
+from graphql.error import GraphQLSyntaxError
+from graphql.language.ast import FragmentDefinition, OperationDefinition
+from promise import Promise
+
+from ...app.models import App
+
+logger = get_task_logger(__name__)
+
+
+def validate_subscription_query(query: str) -> bool:
+ from ..api import schema
+
+ graphql_backend = get_default_backend()
+ try:
+ document = graphql_backend.document_from_string(schema, query)
+ except (ValueError, GraphQLSyntaxError):
+ return False
+ if not check_document_is_single_subscription(document):
+ return False
+ return True
+
+
+def check_document_is_single_subscription(document: GraphQLDocument) -> bool:
+ """Check if document contains only a single subscription definition.
+
+ Only fragments and single subscription definition are allowed.
+ """
+ subscriptions = []
+ for definition in document.document_ast.definitions:
+ if isinstance(definition, FragmentDefinition):
+ pass
+ elif isinstance(definition, OperationDefinition):
+ if definition.operation == "subscription":
+ subscriptions.append(definition)
+ else:
+ return False
+ else:
+ return False
+ return len(subscriptions) == 1
+
+
+def initialize_context() -> HttpRequest:
+ """Prepare a request object for webhook subscription.
+
+ It creates a dummy request object and initialize middleware on it. It is required
+ to process a request in the same way as API logic does.
+ return: HttpRequest
+ """
+ handler = BaseHandler()
+ context = RequestFactory().request()
+ handler.load_middleware()
+ handler.get_response(context)
+ return context
+
+
+def generate_payload_from_subscription(
+ event_type: str,
+ subscribable_object,
+ subscription_query: Optional[str],
+ context: HttpRequest,
+ app: Optional[App] = None,
+) -> Optional[Dict[str, Any]]:
+ """Generate webhook payload from subscription query.
+
+ It uses a graphql's engine to build payload by using the same logic as response.
+ As an input it expects given event type and object and the query which will be
+ used to resolve a payload.
+ event_type: is a event which will be triggered.
+ subscribable_object: is a object which have a dedicated own type in Subscription
+ definition.
+ subscription_query: query used to prepare a payload via graphql engine.
+ context: A dummy request used to share context between apps in order to use
+ dataloaders benefits.
+ app: the owner of the given payload. Required in case when webhook contains
+ protected fields.
+ return: A payload ready to send via webhook. None if the function was not able to
+ generate a payload
+ """
+ from ..api import schema
+
+ graphql_backend = get_default_backend()
+ ast = parse(subscription_query) # type: ignore
+ document = graphql_backend.document_from_string(
+ schema,
+ ast,
+ )
+ app_id = app.pk if app else None
+
+ context.app = app # type: ignore
+
+ results = document.execute(
+ allow_subscriptions=True,
+ root=(event_type, subscribable_object),
+ context=context,
+ )
+ if hasattr(results, "errors"):
+ logger.warning(
+ "Unable to build a payload for subscription. \n"
+ "error: %s" % str(results.errors),
+ extra={"query": subscription_query, "app": app_id},
+ )
+ return None
+ payload = [] # type: ignore
+ results.subscribe(payload.append)
+
+ if not payload:
+ logger.warning(
+ "Subscription did not return a payload.",
+ extra={"query": subscription_query, "app": app_id},
+ )
+ return None
+
+ payload_instance = payload[0]
+ event_payload = payload_instance.data.get("event")
+
+ # Queries that use dataloaders return Promise object for the "event" field. In that
+ # case, we need to resolve them first.
+ if isinstance(event_payload, Promise):
+ return event_payload.get()
+
+ return event_payload
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
new file mode 100644
index 0000000000..565ba51570
--- /dev/null
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -0,0 +1,481 @@
+import graphene
+from graphene import AbstractType, ObjectType, Union
+from rx import Observable
+
+from ...attribute.models import AttributeTranslation, AttributeValueTranslation
+from ...discount.models import SaleTranslation, VoucherTranslation
+from ...menu.models import MenuItemTranslation
+from ...page.models import PageTranslation
+from ...product.models import (
+ CategoryTranslation,
+ CollectionTranslation,
+ ProductTranslation,
+ ProductVariantTranslation,
+)
+from ...shipping.models import ShippingMethodTranslation
+from ...webhook.event_types import WebhookEventAsyncType
+from ..channel import ChannelContext
+from ..core.descriptions import ADDED_IN_32, PREVIEW_FEATURE
+from ..translations import types as translation_types
+
+TRANSLATIONS_TYPES_MAP = {
+ ProductTranslation: translation_types.ProductTranslation,
+ CollectionTranslation: translation_types.CollectionTranslation,
+ CategoryTranslation: translation_types.CategoryTranslation,
+ AttributeTranslation: translation_types.AttributeTranslation,
+ AttributeValueTranslation: translation_types.AttributeValueTranslation,
+ ProductVariantTranslation: translation_types.ProductVariantTranslation,
+ PageTranslation: translation_types.PageTranslation,
+ ShippingMethodTranslation: translation_types.ShippingMethodTranslation,
+ SaleTranslation: translation_types.SaleTranslation,
+ VoucherTranslation: translation_types.VoucherTranslation,
+ MenuItemTranslation: translation_types.MenuItemTranslation,
+}
+
+
+class OrderBase(AbstractType):
+ order = graphene.Field(
+ "saleor.graphql.order.types.Order",
+ description=f"{ADDED_IN_32} Look up an order. {PREVIEW_FEATURE}",
+ )
+
+ @staticmethod
+ def resolve_order(root, info):
+ _, order = root
+ return order
+
+
+class OrderCreated(ObjectType, OrderBase):
+ ...
+
+
+class OrderUpdated(ObjectType, OrderBase):
+ ...
+
+
+class OrderConfirmed(ObjectType, OrderBase):
+ ...
+
+
+class OrderFullyPaid(ObjectType, OrderBase):
+ ...
+
+
+class OrderFulfilled(ObjectType, OrderBase):
+ ...
+
+
+class OrderCancelled(ObjectType, OrderBase):
+ ...
+
+
+class DraftOrderCreated(ObjectType, OrderBase):
+ ...
+
+
+class DraftOrderUpdated(ObjectType, OrderBase):
+ ...
+
+
+class DraftOrderDeleted(ObjectType, OrderBase):
+ ...
+
+
+class ProductBase(AbstractType):
+ product = graphene.Field(
+ "saleor.graphql.product.types.Product",
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
+ description=f"{ADDED_IN_32} Look up a product. {PREVIEW_FEATURE}",
+ )
+ category = graphene.Field(
+ "saleor.graphql.product.types.products.Category",
+ description=f"{ADDED_IN_32} Look up a category. {PREVIEW_FEATURE}",
+ )
+
+ @staticmethod
+ def resolve_product(root, info, channel=None):
+ _, product = root
+ return ChannelContext(node=product, channel_slug=channel)
+
+ @staticmethod
+ def resolve_category(root, _info):
+ _, product = root
+ return product.category
+
+
+class ProductCreated(ObjectType, ProductBase):
+ ...
+
+
+class ProductUpdated(ObjectType, ProductBase):
+ ...
+
+
+class ProductDeleted(ObjectType, ProductBase):
+ ...
+
+
+class ProductVariantBase(AbstractType):
+ product_variant = graphene.Field(
+ "saleor.graphql.product.types.ProductVariant",
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
+ description=f"{ADDED_IN_32} Look up a product variant. {PREVIEW_FEATURE}",
+ )
+
+ @staticmethod
+ def resolve_product_variant(root, info, channel=None):
+ _, variant = root
+ return ChannelContext(node=variant, channel_slug=channel)
+
+
+class ProductVariantCreated(ObjectType, ProductVariantBase):
+ ...
+
+
+class ProductVariantUpdated(ObjectType, ProductVariantBase):
+ ...
+
+
+class ProductVariantDeleted(ObjectType, ProductVariantBase):
+ ...
+
+
+class ProductVariantOutOfStock(ObjectType, ProductVariantBase):
+ warehouse = graphene.Field(
+ "saleor.graphql.warehouse.types.Warehouse",
+ description=f"{ADDED_IN_32} Look up a warehouse. {PREVIEW_FEATURE}",
+ )
+
+ @staticmethod
+ def resolve_product_variant(root, info, channel=None):
+ _, stock = root
+ variant = stock.product_variant
+ return ChannelContext(node=variant, channel_slug=channel)
+
+ @staticmethod
+ def resolve_warehouse(root, _info):
+ _, stock = root
+ return stock.warehouse
+
+
+class ProductVariantBackInStock(ObjectType, ProductVariantBase):
+ warehouse = graphene.Field(
+ "saleor.graphql.warehouse.types.Warehouse",
+ description=f"{ADDED_IN_32} Look up a warehouse. {PREVIEW_FEATURE}",
+ )
+
+ @staticmethod
+ def resolve_product_variant(root, info, channel=None):
+ _, stock = root
+ variant = stock.product_variant
+ return ChannelContext(node=variant, channel_slug=channel)
+
+ @staticmethod
+ def resolve_warehouse(root, _info):
+ _, stock = root
+ return stock.warehouse
+
+
+class SaleBase(AbstractType):
+ sale = graphene.Field(
+ "saleor.graphql.discount.types.Sale",
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
+ description=f"{ADDED_IN_32} Look up a sale. {PREVIEW_FEATURE}",
+ )
+
+ @staticmethod
+ def resolve_sale(root, info, channel=None):
+ _, sale = root
+ return ChannelContext(node=sale, channel_slug=channel)
+
+
+class SaleCreated(ObjectType, SaleBase):
+ ...
+
+
+class SaleUpdated(ObjectType, SaleBase):
+ ...
+
+
+class SaleDeleted(ObjectType, SaleBase):
+ ...
+
+
+class InvoiceBase(AbstractType):
+ invoice = graphene.Field(
+ "saleor.graphql.invoice.types.Invoice",
+ description=f"{ADDED_IN_32} Look up an Invoice. {PREVIEW_FEATURE}",
+ )
+
+ @staticmethod
+ def resolve_invoice(root, _info):
+ _, invoice = root
+ return invoice
+
+
+class InvoiceRequested(ObjectType, InvoiceBase):
+ ...
+
+
+class InvoiceDeleted(ObjectType, InvoiceBase):
+ ...
+
+
+class InvoiceSent(ObjectType, InvoiceBase):
+ ...
+
+
+class FulfillmentBase(AbstractType):
+ fulfillment = graphene.Field(
+ "saleor.graphql.order.types.Fulfillment",
+ description=f"{ADDED_IN_32} Look up a Fulfillment. {PREVIEW_FEATURE}",
+ )
+
+ @staticmethod
+ def resolve_fulfillment(root, _info):
+ _, invoice = root
+ return invoice
+
+
+class FulfillmentCreated(ObjectType, FulfillmentBase):
+ ...
+
+
+class FulfillmentCanceled(ObjectType, FulfillmentBase):
+ ...
+
+
+class UserBase(AbstractType):
+ user = graphene.Field(
+ "saleor.graphql.account.types.User",
+ description=f"{ADDED_IN_32} Look up a user. {PREVIEW_FEATURE}",
+ )
+
+ @staticmethod
+ def resolve_user(root, _info):
+ _, user = root
+ return user
+
+
+class CustomerCreated(ObjectType, UserBase):
+ ...
+
+
+class CustomerUpdated(ObjectType, UserBase):
+ ...
+
+
+class CollectionBase(AbstractType):
+ collection = graphene.Field(
+ "saleor.graphql.product.types.products.Collection",
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
+ description=f"{ADDED_IN_32} Look up a collection. {PREVIEW_FEATURE}",
+ )
+
+ @staticmethod
+ def resolve_collection(root, info, channel=None):
+ _, collection = root
+ return ChannelContext(node=collection, channel_slug=channel)
+
+
+class CollectionCreated(ObjectType, CollectionBase):
+ ...
+
+
+class CollectionUpdated(ObjectType, CollectionBase):
+ ...
+
+
+class CollectionDeleted(ObjectType, CollectionBase):
+ ...
+
+
+class CheckoutBase(AbstractType):
+ checkout = graphene.Field(
+ "saleor.graphql.checkout.types.Checkout",
+ description=f"{ADDED_IN_32} Look up a Checkout. {PREVIEW_FEATURE}",
+ )
+
+ @staticmethod
+ def resolve_checkout(root, _info):
+ _, checkout = root
+ return checkout
+
+
+class CheckoutCreated(ObjectType, CheckoutBase):
+ ...
+
+
+class CheckoutUpdated(ObjectType, CheckoutBase):
+ ...
+
+
+class PageBase(AbstractType):
+ page = graphene.Field(
+ "saleor.graphql.page.types.Page",
+ description=f"{ADDED_IN_32} Look up a page. {PREVIEW_FEATURE}",
+ )
+
+ @staticmethod
+ def resolve_page(root, _info):
+ _, page = root
+ return page
+
+
+class PageCreated(ObjectType, PageBase):
+ ...
+
+
+class PageUpdated(ObjectType, PageBase):
+ ...
+
+
+class PageDeleted(ObjectType, PageBase):
+ ...
+
+
+class TranslationTypes(Union):
+ class Meta:
+ types = tuple(TRANSLATIONS_TYPES_MAP.values())
+
+ @classmethod
+ def resolve_type(cls, instance, info):
+ instance_type = type(instance)
+ if instance_type in TRANSLATIONS_TYPES_MAP:
+ return TRANSLATIONS_TYPES_MAP[instance_type]
+
+ return super(TranslationTypes, cls).resolve_type(instance, info)
+
+
+class TranslationBase(AbstractType):
+ translation = graphene.Field(
+ TranslationTypes,
+ description=f"{ADDED_IN_32} Look up a translation. {PREVIEW_FEATURE}",
+ )
+
+ @staticmethod
+ def resolve_translation(root, _info):
+ _, translation = root
+ return translation
+
+
+class TranslationCreated(ObjectType, TranslationBase):
+ ...
+
+
+class TranslationUpdated(ObjectType, TranslationBase):
+ ...
+
+
+class Event(Union):
+ class Meta:
+ types = (
+ 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,
+ TranslationCreated,
+ TranslationUpdated,
+ )
+
+ @classmethod
+ def get_type(cls, object_type: str):
+ types = {
+ WebhookEventAsyncType.ORDER_CREATED: OrderCreated,
+ WebhookEventAsyncType.ORDER_UPDATED: OrderUpdated,
+ WebhookEventAsyncType.ORDER_CONFIRMED: OrderConfirmed,
+ WebhookEventAsyncType.ORDER_FULLY_PAID: OrderFullyPaid,
+ WebhookEventAsyncType.ORDER_FULFILLED: OrderFulfilled,
+ WebhookEventAsyncType.ORDER_CANCELLED: OrderCancelled,
+ WebhookEventAsyncType.DRAFT_ORDER_CREATED: DraftOrderCreated,
+ WebhookEventAsyncType.DRAFT_ORDER_UPDATED: DraftOrderUpdated,
+ WebhookEventAsyncType.DRAFT_ORDER_DELETED: DraftOrderDeleted,
+ WebhookEventAsyncType.PRODUCT_CREATED: ProductCreated,
+ WebhookEventAsyncType.PRODUCT_UPDATED: ProductUpdated,
+ WebhookEventAsyncType.PRODUCT_DELETED: ProductDeleted,
+ WebhookEventAsyncType.PRODUCT_VARIANT_CREATED: ProductVariantCreated,
+ WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED: ProductVariantUpdated,
+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK: (
+ ProductVariantOutOfStock
+ ),
+ WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK: (
+ ProductVariantBackInStock
+ ),
+ WebhookEventAsyncType.PRODUCT_VARIANT_DELETED: ProductVariantDeleted,
+ WebhookEventAsyncType.SALE_CREATED: SaleCreated,
+ WebhookEventAsyncType.SALE_UPDATED: SaleUpdated,
+ WebhookEventAsyncType.SALE_DELETED: SaleDeleted,
+ WebhookEventAsyncType.INVOICE_REQUESTED: InvoiceRequested,
+ WebhookEventAsyncType.INVOICE_DELETED: InvoiceDeleted,
+ WebhookEventAsyncType.INVOICE_SENT: InvoiceSent,
+ WebhookEventAsyncType.FULFILLMENT_CREATED: FulfillmentCreated,
+ WebhookEventAsyncType.FULFILLMENT_CANCELED: FulfillmentCanceled,
+ WebhookEventAsyncType.CUSTOMER_CREATED: CustomerCreated,
+ WebhookEventAsyncType.CUSTOMER_UPDATED: CustomerUpdated,
+ WebhookEventAsyncType.COLLECTION_CREATED: CollectionCreated,
+ WebhookEventAsyncType.COLLECTION_UPDATED: CollectionUpdated,
+ WebhookEventAsyncType.COLLECTION_DELETED: CollectionDeleted,
+ WebhookEventAsyncType.CHECKOUT_CREATED: CheckoutCreated,
+ WebhookEventAsyncType.CHECKOUT_UPDATED: CheckoutUpdated,
+ WebhookEventAsyncType.PAGE_CREATED: PageCreated,
+ WebhookEventAsyncType.PAGE_UPDATED: PageUpdated,
+ WebhookEventAsyncType.PAGE_DELETED: PageDeleted,
+ WebhookEventAsyncType.TRANSLATION_CREATED: TranslationCreated,
+ WebhookEventAsyncType.TRANSLATION_UPDATED: TranslationUpdated,
+ }
+ return types.get(object_type)
+
+ @classmethod
+ def resolve_type(cls, instance, info):
+ type_str, _ = instance
+ return cls.get_type(type_str)
+
+
+class Subscription(ObjectType):
+ event = graphene.Field(
+ Event,
+ description=f"{ADDED_IN_32} Look up subscription event. {PREVIEW_FEATURE}",
+ )
+
+ @staticmethod
+ def resolve_event(root, info):
+ return Observable.from_([root])
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 12c440e76d..8aea9bb880 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -87,7 +87,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.ORDER_CREATED
if webhooks := _get_webhooks_for_event(event_type):
order_data = generate_order_payload(order, self.requestor)
- trigger_webhooks_async(order_data, event_type, webhooks)
+ trigger_webhooks_async(
+ order_data, event_type, webhooks, order, self.requestor
+ )
def order_confirmed(self, order: "Order", previous_value: Any) -> Any:
if not self.active:
@@ -95,7 +97,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.ORDER_CONFIRMED
if webhooks := _get_webhooks_for_event(event_type):
order_data = generate_order_payload(order, self.requestor)
- trigger_webhooks_async(order_data, event_type, webhooks)
+ trigger_webhooks_async(
+ order_data, event_type, webhooks, order, self.requestor
+ )
def order_fully_paid(self, order: "Order", previous_value: Any) -> Any:
if not self.active:
@@ -103,7 +107,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.ORDER_FULLY_PAID
if webhooks := _get_webhooks_for_event(event_type):
order_data = generate_order_payload(order, self.requestor)
- trigger_webhooks_async(order_data, event_type, webhooks)
+ trigger_webhooks_async(
+ order_data, event_type, webhooks, order, self.requestor
+ )
def order_updated(self, order: "Order", previous_value: Any) -> Any:
if not self.active:
@@ -111,7 +117,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.ORDER_UPDATED
if webhooks := _get_webhooks_for_event(event_type):
order_data = generate_order_payload(order, self.requestor)
- trigger_webhooks_async(order_data, event_type, webhooks)
+ trigger_webhooks_async(
+ order_data, event_type, webhooks, order, self.requestor
+ )
def sale_created(
self, sale: "Sale", current_catalogue: "NodeCatalogueInfo", previous_value: Any
@@ -126,7 +134,9 @@ class WebhookPlugin(BasePlugin):
current_catalogue=current_catalogue,
requestor=self.requestor,
)
- trigger_webhooks_async(sale_data, event_type, webhooks)
+ trigger_webhooks_async(
+ sale_data, event_type, webhooks, sale, self.requestor
+ )
def sale_updated(
self,
@@ -142,7 +152,9 @@ class WebhookPlugin(BasePlugin):
sale_data = generate_sale_payload(
sale, previous_catalogue, current_catalogue, self.requestor
)
- trigger_webhooks_async(sale_data, event_type, webhooks)
+ trigger_webhooks_async(
+ sale_data, event_type, webhooks, sale, self.requestor
+ )
def sale_deleted(
self, sale: "Sale", previous_catalogue: "NodeCatalogueInfo", previous_value: Any
@@ -154,7 +166,9 @@ class WebhookPlugin(BasePlugin):
sale_data = generate_sale_payload(
sale, previous_catalogue=previous_catalogue, requestor=self.requestor
)
- trigger_webhooks_async(sale_data, event_type, webhooks)
+ trigger_webhooks_async(
+ sale_data, event_type, webhooks, sale, self.requestor
+ )
def invoice_request(
self,
@@ -168,7 +182,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.INVOICE_REQUESTED
if webhooks := _get_webhooks_for_event(event_type):
invoice_data = generate_invoice_payload(invoice, self.requestor)
- trigger_webhooks_async(invoice_data, event_type, webhooks)
+ trigger_webhooks_async(
+ invoice_data, event_type, webhooks, invoice, self.requestor
+ )
def invoice_delete(self, invoice: "Invoice", previous_value: Any):
if not self.active:
@@ -176,7 +192,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.INVOICE_DELETED
if webhooks := _get_webhooks_for_event(event_type):
invoice_data = generate_invoice_payload(invoice, self.requestor)
- trigger_webhooks_async(invoice_data, event_type, webhooks)
+ trigger_webhooks_async(
+ invoice_data, event_type, webhooks, invoice, self.requestor
+ )
def invoice_sent(self, invoice: "Invoice", email: str, previous_value: Any) -> Any:
if not self.active:
@@ -184,7 +202,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.INVOICE_SENT
if webhooks := _get_webhooks_for_event(event_type):
invoice_data = generate_invoice_payload(invoice, self.requestor)
- trigger_webhooks_async(invoice_data, event_type, webhooks)
+ trigger_webhooks_async(
+ invoice_data, event_type, webhooks, invoice, self.requestor
+ )
def order_cancelled(self, order: "Order", previous_value: Any) -> Any:
if not self.active:
@@ -192,7 +212,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.ORDER_CANCELLED
if webhooks := _get_webhooks_for_event(event_type):
order_data = generate_order_payload(order, self.requestor)
- trigger_webhooks_async(order_data, event_type, webhooks)
+ trigger_webhooks_async(
+ order_data, event_type, webhooks, order, self.requestor
+ )
def order_fulfilled(self, order: "Order", previous_value: Any) -> Any:
if not self.active:
@@ -200,7 +222,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.ORDER_FULFILLED
if webhooks := _get_webhooks_for_event(event_type):
order_data = generate_order_payload(order, self.requestor)
- trigger_webhooks_async(order_data, event_type, webhooks)
+ trigger_webhooks_async(
+ order_data, event_type, webhooks, order, self.requestor
+ )
def draft_order_created(self, order: "Order", previous_value: Any) -> Any:
if not self.active:
@@ -208,7 +232,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.DRAFT_ORDER_CREATED
if webhooks := _get_webhooks_for_event(event_type):
order_data = generate_order_payload(order, self.requestor)
- trigger_webhooks_async(order_data, event_type, webhooks)
+ trigger_webhooks_async(
+ order_data, event_type, webhooks, order, self.requestor
+ )
def draft_order_updated(self, order: "Order", previous_value: Any) -> Any:
if not self.active:
@@ -216,7 +242,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.DRAFT_ORDER_UPDATED
if webhooks := _get_webhooks_for_event(event_type):
order_data = generate_order_payload(order, self.requestor)
- trigger_webhooks_async(order_data, event_type, webhooks)
+ trigger_webhooks_async(
+ order_data, event_type, webhooks, order, self.requestor
+ )
def draft_order_deleted(self, order: "Order", previous_value: Any) -> Any:
if not self.active:
@@ -224,7 +252,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.DRAFT_ORDER_DELETED
if webhooks := _get_webhooks_for_event(event_type):
order_data = generate_order_payload(order, self.requestor)
- trigger_webhooks_async(order_data, event_type, webhooks)
+ trigger_webhooks_async(
+ order_data, event_type, webhooks, order, self.requestor
+ )
def fulfillment_created(self, fulfillment: "Fulfillment", previous_value):
if not self.active:
@@ -232,7 +262,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.FULFILLMENT_CREATED
if webhooks := _get_webhooks_for_event(event_type):
fulfillment_data = generate_fulfillment_payload(fulfillment, self.requestor)
- trigger_webhooks_async(fulfillment_data, event_type, webhooks)
+ trigger_webhooks_async(
+ fulfillment_data, event_type, webhooks, fulfillment, self.requestor
+ )
def fulfillment_canceled(self, fulfillment: "Fulfillment", previous_value):
if not self.active:
@@ -240,7 +272,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.FULFILLMENT_CANCELED
if webhooks := _get_webhooks_for_event(event_type):
fulfillment_data = generate_fulfillment_payload(fulfillment, self.requestor)
- trigger_webhooks_async(fulfillment_data, event_type, webhooks)
+ trigger_webhooks_async(
+ fulfillment_data, event_type, webhooks, fulfillment, self.requestor
+ )
def customer_created(self, customer: "User", previous_value: Any) -> Any:
if not self.active:
@@ -248,7 +282,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.CUSTOMER_CREATED
if webhooks := _get_webhooks_for_event(event_type):
customer_data = generate_customer_payload(customer, self.requestor)
- trigger_webhooks_async(customer_data, event_type, webhooks)
+ trigger_webhooks_async(
+ customer_data, event_type, webhooks, customer, self.requestor
+ )
def customer_updated(self, customer: "User", previous_value: Any) -> Any:
if not self.active:
@@ -256,7 +292,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.CUSTOMER_UPDATED
if webhooks := _get_webhooks_for_event(event_type):
customer_data = generate_customer_payload(customer, self.requestor)
- trigger_webhooks_async(customer_data, event_type, webhooks)
+ trigger_webhooks_async(
+ customer_data, event_type, webhooks, customer, self.requestor
+ )
def collection_created(self, collection: "Collection", previous_value: Any) -> Any:
if not self.active:
@@ -264,7 +302,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.COLLECTION_CREATED
if webhooks := _get_webhooks_for_event(event_type):
collection_data = generate_collection_payload(collection, self.requestor)
- trigger_webhooks_async(collection_data, event_type, webhooks)
+ trigger_webhooks_async(
+ collection_data, event_type, webhooks, collection, self.requestor
+ )
def collection_updated(self, collection: "Collection", previous_value: Any) -> Any:
if not self.active:
@@ -272,7 +312,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.COLLECTION_UPDATED
if webhooks := _get_webhooks_for_event(event_type):
collection_data = generate_collection_payload(collection, self.requestor)
- trigger_webhooks_async(collection_data, event_type, webhooks)
+ trigger_webhooks_async(
+ collection_data, event_type, webhooks, collection, self.requestor
+ )
def collection_deleted(self, collection: "Collection", previous_value: Any) -> Any:
if not self.active:
@@ -280,7 +322,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.COLLECTION_DELETED
if webhooks := _get_webhooks_for_event(event_type):
collection_data = generate_collection_payload(collection, self.requestor)
- trigger_webhooks_async(collection_data, event_type, webhooks)
+ trigger_webhooks_async(
+ collection_data, event_type, webhooks, collection, self.requestor
+ )
def product_created(self, product: "Product", previous_value: Any) -> Any:
if not self.active:
@@ -288,7 +332,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.PRODUCT_CREATED
if webhooks := _get_webhooks_for_event(event_type):
product_data = generate_product_payload(product, self.requestor)
- trigger_webhooks_async(product_data, event_type, webhooks)
+ trigger_webhooks_async(
+ product_data, event_type, webhooks, product, self.requestor
+ )
def product_updated(self, product: "Product", previous_value: Any) -> Any:
if not self.active:
@@ -296,7 +342,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.PRODUCT_UPDATED
if webhooks := _get_webhooks_for_event(event_type):
product_data = generate_product_payload(product, self.requestor)
- trigger_webhooks_async(product_data, event_type, webhooks)
+ trigger_webhooks_async(
+ product_data, event_type, webhooks, product, self.requestor
+ )
def product_deleted(
self, product: "Product", variants: List[int], previous_value: Any
@@ -312,6 +360,8 @@ class WebhookPlugin(BasePlugin):
product_data,
event_type,
webhooks,
+ product,
+ self.requestor,
)
def product_variant_created(
@@ -328,6 +378,8 @@ class WebhookPlugin(BasePlugin):
product_variant_data,
event_type,
webhooks,
+ product_variant,
+ self.requestor,
)
def product_variant_updated(
@@ -344,6 +396,8 @@ class WebhookPlugin(BasePlugin):
product_variant_data,
event_type,
webhooks,
+ product_variant,
+ self.requestor,
)
def product_variant_deleted(
@@ -360,6 +414,8 @@ class WebhookPlugin(BasePlugin):
product_variant_data,
event_type,
webhooks,
+ product_variant,
+ self.requestor,
)
def product_variant_out_of_stock(self, stock: "Stock", previous_value: Any) -> Any:
@@ -368,7 +424,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK
if webhooks := _get_webhooks_for_event(event_type):
product_variant_data = generate_product_variant_with_stock_payload([stock])
- trigger_webhooks_async(product_variant_data, event_type, webhooks)
+ trigger_webhooks_async(
+ product_variant_data, event_type, webhooks, stock, self.requestor
+ )
def product_variant_back_in_stock(self, stock: "Stock", previous_value: Any) -> Any:
if not self.active:
@@ -378,7 +436,9 @@ class WebhookPlugin(BasePlugin):
product_variant_data = generate_product_variant_with_stock_payload(
[stock], self.requestor
)
- trigger_webhooks_async(product_variant_data, event_type, webhooks)
+ trigger_webhooks_async(
+ product_variant_data, event_type, webhooks, stock, self.requestor
+ )
def checkout_created(self, checkout: "Checkout", previous_value: Any) -> Any:
if not self.active:
@@ -386,7 +446,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.CHECKOUT_CREATED
if webhooks := _get_webhooks_for_event(event_type):
checkout_data = generate_checkout_payload(checkout, self.requestor)
- trigger_webhooks_async(checkout_data, event_type, webhooks)
+ trigger_webhooks_async(
+ checkout_data, event_type, webhooks, checkout, self.requestor
+ )
def checkout_updated(self, checkout: "Checkout", previous_value: Any) -> Any:
if not self.active:
@@ -394,7 +456,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.CHECKOUT_UPDATED
if webhooks := _get_webhooks_for_event(event_type):
checkout_data = generate_checkout_payload(checkout, self.requestor)
- trigger_webhooks_async(checkout_data, event_type, webhooks)
+ trigger_webhooks_async(
+ checkout_data, event_type, webhooks, checkout, self.requestor
+ )
def notify(
self, event: Union[NotifyEventType, str], payload: dict, previous_value
@@ -422,7 +486,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.PAGE_CREATED
if webhooks := _get_webhooks_for_event(event_type):
page_data = generate_page_payload(page, self.requestor)
- trigger_webhooks_async(page_data, event_type, webhooks)
+ trigger_webhooks_async(
+ page_data, event_type, webhooks, page, self.requestor
+ )
def page_updated(self, page: "Page", previous_value: Any) -> Any:
if not self.active:
@@ -430,7 +496,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.PAGE_UPDATED
if webhooks := _get_webhooks_for_event(event_type):
page_data = generate_page_payload(page, self.requestor)
- trigger_webhooks_async(page_data, event_type, webhooks)
+ trigger_webhooks_async(
+ page_data, event_type, webhooks, page, self.requestor
+ )
def page_deleted(self, page: "Page", previous_value: Any) -> Any:
if not self.active:
@@ -438,7 +506,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.PAGE_DELETED
if webhooks := _get_webhooks_for_event(event_type):
page_data = generate_page_payload(page, self.requestor)
- trigger_webhooks_async(page_data, event_type, webhooks)
+ trigger_webhooks_async(
+ page_data, event_type, webhooks, page, self.requestor
+ )
def translation_created(self, translation: "Translation", previous_value: Any):
if not self.active:
@@ -446,7 +516,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.TRANSLATION_CREATED
if webhooks := _get_webhooks_for_event(event_type):
translation_data = generate_translation_payload(translation, self.requestor)
- trigger_webhooks_async(translation_data, event_type, webhooks)
+ trigger_webhooks_async(
+ translation_data, event_type, webhooks, translation, self.requestor
+ )
def translation_updated(self, translation: "Translation", previous_value: Any):
if not self.active:
@@ -454,7 +526,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.TRANSLATION_UPDATED
if webhooks := _get_webhooks_for_event(event_type):
translation_data = generate_translation_payload(translation, self.requestor)
- trigger_webhooks_async(translation_data, event_type, webhooks)
+ trigger_webhooks_async(
+ translation_data, event_type, webhooks, translation, self.requestor
+ )
def event_delivery_retry(self, delivery: "EventDelivery", previous_value: Any):
if not self.active:
diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.py
index f88e944aed..677f477b32 100644
--- a/saleor/plugins/webhook/tasks.py
+++ b/saleor/plugins/webhook/tasks.py
@@ -3,7 +3,7 @@ import logging
from dataclasses import dataclass
from enum import Enum
from json import JSONDecodeError
-from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple, Type
+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Type
from urllib.parse import urlparse, urlunparse
import boto3
@@ -18,11 +18,20 @@ from ...celeryconf import app
from ...core import EventDeliveryStatus
from ...core.models import EventDelivery, EventPayload
from ...core.tracing import webhooks_opentracing_trace
+from ...graphql.webhook.subscription_payload import (
+ generate_payload_from_subscription,
+ initialize_context,
+)
from ...payment import PaymentError
from ...settings import WEBHOOK_SYNC_TIMEOUT, WEBHOOK_TIMEOUT
from ...site.models import Site
-from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from ...webhook.event_types import (
+ SUBSCRIBABLE_EVENTS,
+ WebhookEventAsyncType,
+ WebhookEventSyncType,
+)
from ...webhook.models import Webhook
+from ...webhook.payloads import generate_meta, generate_requestor
from . import signature_for_payload
from .utils import (
attempt_update,
@@ -82,17 +91,102 @@ def _get_webhooks_for_event(event_type, webhooks=None):
return webhooks
-def trigger_webhooks_async(data, event_type, webhooks):
- payload = EventPayload.objects.create(payload=data)
- deliveries = create_event_delivery_list_for_webhooks(
- webhooks=webhooks,
- event_payload=payload,
- event_type=event_type,
- )
+def create_deliveries_for_subscriptions(
+ event_type, subscribable_object, webhooks, meta=None
+) -> List[EventDelivery]:
+ """Create webhook payload based on subscription query.
+
+ It uses a defined subscription query, defined for webhook to explicitly determine
+ what fields should be included in the payload.
+
+ :param event_type: event type which should be triggered.
+ :param subscribable_object: subscribable object to process via subscription query.
+ :return: List of event deliveries to send via webhook tasks.
+ """
+ if event_type not in SUBSCRIBABLE_EVENTS:
+ logger.info(
+ "Skipping subscription webhook. Event %s is not subscribable.", event_type
+ )
+ return []
+
+ context = initialize_context()
+ event_payloads = []
+ event_deliveries = []
+ for webhook in webhooks:
+ data = generate_payload_from_subscription(
+ event_type=event_type,
+ subscribable_object=subscribable_object,
+ subscription_query=webhook.subscription_query,
+ context=context,
+ app=webhook.app,
+ )
+ if not data:
+ logger.warning(
+ "No payload was generated with subscription for event: %s" % event_type
+ )
+ continue
+
+ event_payload = EventPayload(payload=json.dumps([{**data, "meta": meta}]))
+ event_payloads.append(event_payload)
+ event_deliveries.append(
+ EventDelivery(
+ status=EventDeliveryStatus.PENDING,
+ event_type=event_type,
+ payload=event_payload,
+ webhook=webhook,
+ )
+ )
+
+ EventPayload.objects.bulk_create(event_payloads)
+ return EventDelivery.objects.bulk_create(event_deliveries)
+
+
+def trigger_webhooks_async(
+ data, event_type, webhooks, subscribable_object=None, requestor=None
+):
+ """Trigger async webhooks - both regular and subscription.
+
+ :param data: used as payload in regular webhooks.
+ :param event_type: used in both webhook types as event type.
+ :param webhooks: used in both webhook types, queryset of async webhooks.
+ :param subscribable_object: subscribable object used in subscription webhooks.
+ :param requestor: used in subscription webhooks to generate meta data for payload.
+ """
+ regular_webhooks, subscription_webhooks = group_webhooks_by_subscription(webhooks)
+ deliveries = []
+ if regular_webhooks:
+ payload = EventPayload.objects.create(payload=data)
+ deliveries.extend(
+ create_event_delivery_list_for_webhooks(
+ webhooks=webhooks,
+ event_payload=payload,
+ event_type=event_type,
+ )
+ )
+ if subscription_webhooks:
+ meta = {}
+ if requestor:
+ meta = generate_meta(requestor_data=generate_requestor(requestor))
+ deliveries.extend(
+ create_deliveries_for_subscriptions(
+ event_type=event_type,
+ subscribable_object=subscribable_object,
+ webhooks=subscription_webhooks,
+ meta=meta,
+ )
+ )
+
for delivery in deliveries:
send_webhook_request_async.delay(delivery.id)
+def group_webhooks_by_subscription(webhooks):
+ subscription = [webhook for webhook in webhooks if webhook.subscription_query]
+ regular = [webhook for webhook in webhooks if not webhook.subscription_query]
+
+ return regular, subscription
+
+
def trigger_webhook_sync(
event_type: str, data: str, app: "App", timeout=None
) -> Optional[Dict[Any, Any]]:
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/__init__.py b/saleor/plugins/webhook/tests/subscription_webhooks/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
new file mode 100644
index 0000000000..600f27d345
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
@@ -0,0 +1,868 @@
+import pytest
+
+from .....webhook.event_types import WebhookEventAsyncType
+from .....webhook.models import Webhook
+
+
+def subscription_webhook(app):
+ def fun(query, event_type, name="Subscription"):
+ webhook = Webhook.objects.create(
+ name=name,
+ app=app,
+ target_url="http://www.example.com/any",
+ subscription_query=query,
+ )
+ webhook.events.create(event_type=event_type)
+ return webhook
+
+ return fun
+
+
+PRODUCT_UPDATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on ProductUpdated{
+ product{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_product_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ PRODUCT_UPDATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.PRODUCT_UPDATED
+ )
+
+
+PRODUCT_CREATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on ProductCreated{
+ product{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_product_created_webhook(subscription_webhook):
+ return subscription_webhook(
+ PRODUCT_CREATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.PRODUCT_CREATED
+ )
+
+
+PRODUCT_DELETED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on ProductDeleted{
+ product{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_product_deleted_webhook(subscription_webhook):
+ return subscription_webhook(
+ PRODUCT_DELETED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.PRODUCT_DELETED
+ )
+
+
+PRODUCT_VARIANT_CREATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on ProductVariantCreated{
+ productVariant{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_product_variant_created_webhook(subscription_webhook):
+ return subscription_webhook(
+ PRODUCT_VARIANT_CREATED_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.PRODUCT_VARIANT_CREATED,
+ )
+
+
+PRODUCT_VARIANT_UPDATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on ProductVariantUpdated{
+ productVariant{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_product_variant_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ PRODUCT_VARIANT_UPDATED_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED,
+ )
+
+
+PRODUCT_VARIANT_DELETED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on ProductVariantDeleted{
+ productVariant{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_product_variant_deleted_webhook(subscription_webhook):
+ return subscription_webhook(
+ PRODUCT_VARIANT_DELETED_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.PRODUCT_VARIANT_DELETED,
+ )
+
+
+PRODUCT_VARIANT_OUT_OF_STOCK_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on ProductVariantOutOfStock{
+ productVariant{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_product_variant_out_of_stock_webhook(subscription_webhook):
+ return subscription_webhook(
+ PRODUCT_VARIANT_OUT_OF_STOCK_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK,
+ )
+
+
+PRODUCT_VARIANT_BACK_IN_STOCK_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on ProductVariantBackInStock{
+ productVariant{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_product_variant_back_in_stock_webhook(subscription_webhook):
+ return subscription_webhook(
+ PRODUCT_VARIANT_BACK_IN_STOCK_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK,
+ )
+
+
+ORDER_CREATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on OrderCreated{
+ order{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_order_created_webhook(subscription_webhook):
+ return subscription_webhook(
+ ORDER_CREATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.ORDER_CREATED
+ )
+
+
+ORDER_UPDATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on OrderUpdated{
+ order{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_order_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ ORDER_UPDATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.ORDER_UPDATED
+ )
+
+
+ORDER_CONFIRMED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on OrderConfirmed{
+ order{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_order_confirmed_webhook(subscription_webhook):
+ return subscription_webhook(
+ ORDER_CONFIRMED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.ORDER_CONFIRMED
+ )
+
+
+ORDER_FULLY_PAID_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on OrderFullyPaid{
+ order{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_order_fully_paid_webhook(subscription_webhook):
+ return subscription_webhook(
+ ORDER_FULLY_PAID_SUBSCRIPTION_QUERY, WebhookEventAsyncType.ORDER_FULLY_PAID
+ )
+
+
+ORDER_CANCELLED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on OrderCancelled{
+ order{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_order_cancelled_webhook(subscription_webhook):
+ return subscription_webhook(
+ ORDER_CANCELLED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.ORDER_CANCELLED
+ )
+
+
+ORDER_FULFILLED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on OrderFulfilled{
+ order{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_order_fulfilled_webhook(subscription_webhook):
+ return subscription_webhook(
+ ORDER_FULFILLED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.ORDER_FULFILLED
+ )
+
+
+DRAFT_ORDER_CREATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on DraftOrderCreated{
+ order{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_draft_order_created_webhook(subscription_webhook):
+ return subscription_webhook(
+ DRAFT_ORDER_CREATED_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.DRAFT_ORDER_CREATED,
+ )
+
+
+DRAFT_ORDER_UPDATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on DraftOrderUpdated{
+ order{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_draft_order_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ DRAFT_ORDER_UPDATED_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.DRAFT_ORDER_UPDATED,
+ )
+
+
+DRAFT_ORDER_DELETED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on DraftOrderDeleted{
+ order{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_draft_order_deleted_webhook(subscription_webhook):
+ return subscription_webhook(
+ DRAFT_ORDER_DELETED_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.DRAFT_ORDER_DELETED,
+ )
+
+
+SALE_CREATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on SaleCreated{
+ sale{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_sale_created_webhook(subscription_webhook):
+ return subscription_webhook(
+ SALE_CREATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.SALE_CREATED
+ )
+
+
+SALE_UPDATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on SaleUpdated{
+ sale{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_sale_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ SALE_UPDATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.SALE_UPDATED
+ )
+
+
+SALE_DELETED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on SaleDeleted{
+ sale{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_sale_deleted_webhook(subscription_webhook):
+ return subscription_webhook(
+ SALE_DELETED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.SALE_DELETED
+ )
+
+
+INVOICE_REQUESTED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on InvoiceRequested{
+ invoice{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_invoice_requested_webhook(subscription_webhook):
+ return subscription_webhook(
+ INVOICE_REQUESTED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.INVOICE_REQUESTED
+ )
+
+
+INVOICE_DELETED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on InvoiceDeleted{
+ invoice{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_invoice_deleted_webhook(subscription_webhook):
+ return subscription_webhook(
+ INVOICE_DELETED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.INVOICE_DELETED
+ )
+
+
+INVOICE_SENT_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on InvoiceSent{
+ invoice{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_invoice_sent_webhook(subscription_webhook):
+ return subscription_webhook(
+ INVOICE_SENT_SUBSCRIPTION_QUERY, WebhookEventAsyncType.INVOICE_SENT
+ )
+
+
+FULFILLMENT_CREATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on FulfillmentCreated{
+ fulfillment{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_fulfillment_created_webhook(subscription_webhook):
+ return subscription_webhook(
+ FULFILLMENT_CREATED_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.FULFILLMENT_CREATED,
+ )
+
+
+FULFILLMENT_CANCELED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on FulfillmentCanceled{
+ fulfillment{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_fulfillment_canceled_webhook(subscription_webhook):
+ return subscription_webhook(
+ FULFILLMENT_CANCELED_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.FULFILLMENT_CANCELED,
+ )
+
+
+CUSTOMER_CREATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on CustomerCreated{
+ user{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_customer_created_webhook(subscription_webhook):
+ return subscription_webhook(
+ CUSTOMER_CREATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.CUSTOMER_CREATED
+ )
+
+
+CUSTOMER_UPDATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on CustomerUpdated{
+ user{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_customer_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ CUSTOMER_UPDATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.CUSTOMER_UPDATED
+ )
+
+
+COLLECTION_CREATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on CollectionCreated{
+ collection{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_collection_created_webhook(subscription_webhook):
+ return subscription_webhook(
+ COLLECTION_CREATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.COLLECTION_CREATED
+ )
+
+
+COLLECTION_UPDATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on CollectionUpdated{
+ collection{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_collection_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ COLLECTION_UPDATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.COLLECTION_UPDATED
+ )
+
+
+COLLECTION_DELETED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on CollectionDeleted{
+ collection{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_collection_deleted_webhook(subscription_webhook):
+ return subscription_webhook(
+ COLLECTION_DELETED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.COLLECTION_DELETED
+ )
+
+
+CHECKOUT_CREATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on CheckoutCreated{
+ checkout{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_checkout_created_webhook(subscription_webhook):
+ return subscription_webhook(
+ CHECKOUT_CREATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.CHECKOUT_CREATED
+ )
+
+
+CHECKOUT_UPDATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on CheckoutUpdated{
+ checkout{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_checkout_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ CHECKOUT_UPDATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.CHECKOUT_UPDATED
+ )
+
+
+PAGE_CREATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on PageCreated{
+ page{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_page_created_webhook(subscription_webhook):
+ return subscription_webhook(
+ PAGE_CREATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.PAGE_CREATED
+ )
+
+
+PAGE_UPDATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on PageUpdated{
+ page{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_page_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ PAGE_UPDATED_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.PAGE_UPDATED,
+ )
+
+
+PAGE_DELETED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on PageDeleted{
+ page{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_page_deleted_webhook(subscription_webhook):
+ return subscription_webhook(
+ PAGE_DELETED_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.PAGE_DELETED,
+ )
+
+
+MULTIPLE_EVENTS_SUBSCRIPTION_QUERY = """
+subscription{
+ event{
+ ...on ProductCreated{
+ product{
+ id
+ }
+ }
+ ...on ProductUpdated{
+ product{
+ id
+ }
+ }
+ ...on OrderCreated{
+ order{
+ id
+ }
+ }
+ }
+}
+"""
+
+
+def subscription_product_created_multiple_events_webhook(subscription_webhook):
+ return subscription_webhook(
+ MULTIPLE_EVENTS_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.TRANSLATION_CREATED,
+ )
+
+
+TRANSLATION_CREATED_SUBSCRIPTION_QUERY = """
+subscription {
+ event {
+ ... on TranslationCreated {
+ translation {
+ ... on ProductTranslation {
+ id
+ }
+ ... on CollectionTranslation {
+ id
+ }
+ ... on CategoryTranslation {
+ id
+ }
+ ... on AttributeTranslation {
+ id
+ }
+ ... on ProductVariantTranslation {
+ id
+ }
+ ... on PageTranslation {
+ id
+ }
+ ... on ShippingMethodTranslation {
+ id
+ }
+ ... on SaleTranslation {
+ id
+ }
+ ... on VoucherTranslation {
+ id
+ }
+ ... on MenuItemTranslation {
+ id
+ }
+ ... on AttributeValueTranslation {
+ id
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def subscription_translation_created_webhook(subscription_webhook):
+ return subscription_webhook(
+ TRANSLATION_CREATED_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.TRANSLATION_CREATED,
+ )
+
+
+TRANSLATION_UPDATED_SUBSCRIPTION_QUERY = """
+subscription {
+ event {
+ ... on TranslationUpdated {
+ translation {
+ ... on ProductTranslation {
+ id
+ }
+ ... on CollectionTranslation {
+ id
+ }
+ ... on CategoryTranslation {
+ id
+ }
+ ... on AttributeTranslation {
+ id
+ }
+ ... on ProductVariantTranslation {
+ id
+ }
+ ... on PageTranslation {
+ id
+ }
+ ... on ShippingMethodTranslation {
+ id
+ }
+ ... on SaleTranslation {
+ id
+ }
+ ... on VoucherTranslation {
+ id
+ }
+ ... on MenuItemTranslation {
+ id
+ }
+ ... on AttributeValueTranslation {
+ id
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def subscription_translation_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ TRANSLATION_UPDATED_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.TRANSLATION_UPDATED,
+ )
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.py
new file mode 100644
index 0000000000..f9ca2d13f9
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
@@ -0,0 +1,613 @@
+import json
+from unittest.mock import patch
+
+import graphene
+
+from .....graphql.webhook.subscription_payload import validate_subscription_query
+from .....webhook.event_types import WebhookEventAsyncType
+from ...tasks import create_deliveries_for_subscriptions, logger
+
+
+def test_product_created(product, subscription_product_created_webhook):
+ webhooks = [subscription_product_created_webhook]
+ event_type = WebhookEventAsyncType.PRODUCT_CREATED
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, product, webhooks)
+ expected_payload = json.dumps([{"product": {"id": product_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_product_updated(product, subscription_product_updated_webhook):
+ webhooks = [subscription_product_updated_webhook]
+ event_type = WebhookEventAsyncType.PRODUCT_UPDATED
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, product, webhooks)
+ expected_payload = json.dumps([{"product": {"id": product_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_product_deleted(product, subscription_product_deleted_webhook):
+ webhooks = [subscription_product_deleted_webhook]
+ event_type = WebhookEventAsyncType.PRODUCT_DELETED
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, product, webhooks)
+ expected_payload = json.dumps([{"product": {"id": product_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_product_variant_created(variant, subscription_product_variant_created_webhook):
+ webhooks = [subscription_product_variant_created_webhook]
+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_CREATED
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, variant, webhooks)
+ expected_payload = json.dumps(
+ [{"productVariant": {"id": variant_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_product_variant_updated(variant, subscription_product_variant_updated_webhook):
+ webhooks = [subscription_product_variant_updated_webhook]
+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, variant, webhooks)
+ expected_payload = json.dumps(
+ [{"productVariant": {"id": variant_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_product_variant_deleted(variant, subscription_product_variant_deleted_webhook):
+ webhooks = [subscription_product_variant_deleted_webhook]
+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_DELETED
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, variant, webhooks)
+ expected_payload = json.dumps(
+ [{"productVariant": {"id": variant_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_product_variant_out_of_stock(
+ stock, subscription_product_variant_out_of_stock_webhook
+):
+ webhooks = [subscription_product_variant_out_of_stock_webhook]
+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK
+ variant_id = graphene.Node.to_global_id("ProductVariant", stock.product_variant.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, stock, webhooks)
+ expected_payload = json.dumps(
+ [{"productVariant": {"id": variant_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_product_variant_back_in_stock(
+ stock, subscription_product_variant_back_in_stock_webhook
+):
+ webhooks = [subscription_product_variant_back_in_stock_webhook]
+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK
+ variant_id = graphene.Node.to_global_id("ProductVariant", stock.product_variant.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, stock, webhooks)
+ expected_payload = json.dumps(
+ [{"productVariant": {"id": variant_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_order_created(order, subscription_order_created_webhook):
+ webhooks = [subscription_order_created_webhook]
+ event_type = WebhookEventAsyncType.ORDER_CREATED
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+ expected_payload = json.dumps([{"order": {"id": order_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_order_confirmed(order, subscription_order_confirmed_webhook):
+ webhooks = [subscription_order_confirmed_webhook]
+ event_type = WebhookEventAsyncType.ORDER_CONFIRMED
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+ expected_payload = json.dumps([{"order": {"id": order_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_order_fully_paid(order, subscription_order_fully_paid_webhook):
+ webhooks = [subscription_order_fully_paid_webhook]
+ event_type = WebhookEventAsyncType.ORDER_FULLY_PAID
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+ expected_payload = json.dumps([{"order": {"id": order_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_order_updated(order, subscription_order_updated_webhook):
+ webhooks = [subscription_order_updated_webhook]
+ event_type = WebhookEventAsyncType.ORDER_UPDATED
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+ expected_payload = json.dumps([{"order": {"id": order_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_order_cancelled(order, subscription_order_cancelled_webhook):
+ webhooks = [subscription_order_cancelled_webhook]
+ event_type = WebhookEventAsyncType.ORDER_CANCELLED
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+ expected_payload = json.dumps([{"order": {"id": order_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_order_fulfilled(order, subscription_order_fulfilled_webhook):
+ webhooks = [subscription_order_fulfilled_webhook]
+ event_type = WebhookEventAsyncType.ORDER_FULFILLED
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+ expected_payload = json.dumps([{"order": {"id": order_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_draft_order_created(order, subscription_draft_order_created_webhook):
+ webhooks = [subscription_draft_order_created_webhook]
+ event_type = WebhookEventAsyncType.DRAFT_ORDER_CREATED
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+ expected_payload = json.dumps([{"order": {"id": order_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_draft_order_updated(order, subscription_draft_order_updated_webhook):
+ webhooks = [subscription_draft_order_updated_webhook]
+ event_type = WebhookEventAsyncType.DRAFT_ORDER_UPDATED
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+ expected_payload = json.dumps([{"order": {"id": order_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_draft_order_deleted(order, subscription_draft_order_deleted_webhook):
+ webhooks = [subscription_draft_order_deleted_webhook]
+ event_type = WebhookEventAsyncType.DRAFT_ORDER_DELETED
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+ expected_payload = json.dumps([{"order": {"id": order_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_sale_created(sale, subscription_sale_created_webhook):
+ webhooks = [subscription_sale_created_webhook]
+ event_type = WebhookEventAsyncType.SALE_CREATED
+ sale_id = graphene.Node.to_global_id("Sale", sale.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, sale, webhooks)
+ expected_payload = json.dumps([{"sale": {"id": sale_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_sale_updated(sale, subscription_sale_updated_webhook):
+ webhooks = [subscription_sale_updated_webhook]
+ event_type = WebhookEventAsyncType.SALE_UPDATED
+ sale_id = graphene.Node.to_global_id("Sale", sale.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, sale, webhooks)
+ expected_payload = json.dumps([{"sale": {"id": sale_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_sale_deleted(sale, subscription_sale_deleted_webhook):
+ webhooks = [subscription_sale_deleted_webhook]
+ event_type = WebhookEventAsyncType.SALE_DELETED
+ sale_id = graphene.Node.to_global_id("Sale", sale.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, sale, webhooks)
+ expected_payload = json.dumps([{"sale": {"id": sale_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_invoice_requested(fulfilled_order, subscription_invoice_requested_webhook):
+ webhooks = [subscription_invoice_requested_webhook]
+ event_type = WebhookEventAsyncType.INVOICE_REQUESTED
+ invoice = fulfilled_order.invoices.first()
+ invoice_id = graphene.Node.to_global_id("Invoice", invoice.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, invoice, webhooks)
+ expected_payload = json.dumps([{"invoice": {"id": invoice_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_invoice_deleted(fulfilled_order, subscription_invoice_deleted_webhook):
+ webhooks = [subscription_invoice_deleted_webhook]
+ event_type = WebhookEventAsyncType.INVOICE_DELETED
+ invoice = fulfilled_order.invoices.first()
+ invoice_id = graphene.Node.to_global_id("Invoice", invoice.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, invoice, webhooks)
+ expected_payload = json.dumps([{"invoice": {"id": invoice_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_invoice_sent(fulfilled_order, subscription_invoice_sent_webhook):
+ webhooks = [subscription_invoice_sent_webhook]
+ event_type = WebhookEventAsyncType.INVOICE_SENT
+ invoice = fulfilled_order.invoices.first()
+ invoice_id = graphene.Node.to_global_id("Invoice", invoice.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, invoice, webhooks)
+ expected_payload = json.dumps([{"invoice": {"id": invoice_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_fulfillment_created(fulfillment, subscription_fulfillment_created_webhook):
+ webhooks = [subscription_fulfillment_created_webhook]
+ event_type = WebhookEventAsyncType.FULFILLMENT_CREATED
+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, fulfillment, webhooks)
+ expected_payload = json.dumps(
+ [{"fulfillment": {"id": fulfillment_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_fulfillment_canceled(fulfillment, subscription_fulfillment_canceled_webhook):
+ webhooks = [subscription_fulfillment_canceled_webhook]
+ event_type = WebhookEventAsyncType.FULFILLMENT_CANCELED
+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, fulfillment, webhooks)
+ expected_payload = json.dumps(
+ [{"fulfillment": {"id": fulfillment_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_customer_created(customer_user, subscription_customer_created_webhook):
+ webhooks = [subscription_customer_created_webhook]
+ event_type = WebhookEventAsyncType.CUSTOMER_CREATED
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, customer_user, webhooks
+ )
+ expected_payload = json.dumps([{"user": {"id": user_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_customer_updated(customer_user, subscription_customer_updated_webhook):
+ webhooks = [subscription_customer_updated_webhook]
+ event_type = WebhookEventAsyncType.CUSTOMER_UPDATED
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, customer_user, webhooks
+ )
+ expected_payload = json.dumps([{"user": {"id": user_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_collection_created(collection, subscription_collection_created_webhook):
+ webhooks = [subscription_collection_created_webhook]
+ event_type = WebhookEventAsyncType.COLLECTION_CREATED
+ collection_id = graphene.Node.to_global_id("Collection", collection.pk)
+ deliveries = create_deliveries_for_subscriptions(event_type, collection, webhooks)
+ expected_payload = json.dumps([{"collection": {"id": collection_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_collection_updated(collection, subscription_collection_updated_webhook):
+ webhooks = [subscription_collection_updated_webhook]
+ event_type = WebhookEventAsyncType.COLLECTION_UPDATED
+ collection_id = graphene.Node.to_global_id("Collection", collection.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, collection, webhooks)
+ expected_payload = json.dumps([{"collection": {"id": collection_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_collection_deleted(collection, subscription_collection_deleted_webhook):
+ webhooks = [subscription_collection_deleted_webhook]
+ event_type = WebhookEventAsyncType.COLLECTION_DELETED
+ collection_id = graphene.Node.to_global_id("Collection", collection.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, collection, webhooks)
+ expected_payload = json.dumps([{"collection": {"id": collection_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_checkout_create(checkout, subscription_checkout_created_webhook):
+ webhooks = [subscription_checkout_created_webhook]
+ event_type = WebhookEventAsyncType.CHECKOUT_CREATED
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ deliveries = create_deliveries_for_subscriptions(event_type, checkout, webhooks)
+ expected_payload = json.dumps([{"checkout": {"id": checkout_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_checkout_update(checkout, subscription_checkout_updated_webhook):
+ webhooks = [subscription_checkout_updated_webhook]
+ event_type = WebhookEventAsyncType.CHECKOUT_UPDATED
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ deliveries = create_deliveries_for_subscriptions(event_type, checkout, webhooks)
+ expected_payload = json.dumps([{"checkout": {"id": checkout_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_page_created(page, subscription_page_created_webhook):
+ webhooks = [subscription_page_created_webhook]
+ event_type = WebhookEventAsyncType.PAGE_CREATED
+ page_id = graphene.Node.to_global_id("Page", page.pk)
+ deliveries = create_deliveries_for_subscriptions(event_type, page, webhooks)
+ expected_payload = json.dumps([{"page": {"id": page_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_page_updated(page, subscription_page_updated_webhook):
+ webhooks = [subscription_page_updated_webhook]
+ event_type = WebhookEventAsyncType.PAGE_UPDATED
+ page_id = graphene.Node.to_global_id("Page", page.pk)
+ deliveries = create_deliveries_for_subscriptions(event_type, page, webhooks)
+ expected_payload = json.dumps([{"page": {"id": page_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_page_deleted(page, subscription_page_deleted_webhook):
+ webhooks = [subscription_page_deleted_webhook]
+ event_type = WebhookEventAsyncType.PAGE_DELETED
+ page_id = graphene.Node.to_global_id("Page", page.pk)
+ deliveries = create_deliveries_for_subscriptions(event_type, page, webhooks)
+ expected_payload = json.dumps([{"page": {"id": page_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_product_created_multiple_events_in_subscription(
+ product, subscription_product_created_multiple_events_webhook
+):
+ webhooks = [subscription_product_created_multiple_events_webhook]
+ event_type = WebhookEventAsyncType.PRODUCT_CREATED
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, product, webhooks)
+ expected_payload = json.dumps([{"product": {"id": product_id}, "meta": None}])
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
[email protected](logger, "info")
+def test_create_deliveries_for_subscriptions_unsubscribable_event(
+ mocked_logger, product, subscription_product_updated_webhook, any_webhook
+):
+ webhooks = [subscription_product_updated_webhook]
+ event_type = "unsubscribable_type"
+
+ deliveries = create_deliveries_for_subscriptions(event_type, product, webhooks)
+
+ mocked_logger.assert_called_with(
+ "Skipping subscription webhook. Event %s is not subscribable.", event_type
+ )
+ assert len(deliveries) == 0
+
+
+TEST_VALID_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on ProductUpdated{
+ product{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def test_validate_subscription_query_valid():
+ result = validate_subscription_query(TEST_VALID_SUBSCRIPTION_QUERY)
+ assert result is True
+
+
+def test_validate_subscription_query_invalid():
+
+ result = validate_subscription_query("invalid_query")
+ assert result is False
+
+
+TEST_VALID_SUBSCRIPTION_QUERY_WITH_FRAGMENT = """
+fragment productFragment on Product{
+ name
+}
+subscription{
+ event{
+ ...on ProductUpdated{
+ product{
+ id
+ ...productFragment
+ }
+ }
+ }
+}
+"""
+
+
+def test_validate_subscription_query_valid_with_fragment():
+
+ result = validate_subscription_query(TEST_VALID_SUBSCRIPTION_QUERY_WITH_FRAGMENT)
+ assert result is True
+
+
+TEST_INVALID_MULTIPLE_QUERY_AND_SUBSCRIPTION = """
+query{
+ products(first:100){
+ edges{
+ node{
+ id
+ }
+ }
+ }
+}
+subscription{
+ event{
+ ...on ProductUpdated{
+ product{
+ id
+ }
+ }
+ }
+}"""
+
+
+def test_validate_invalid_query_and_subscription():
+
+ result = validate_subscription_query(TEST_INVALID_MULTIPLE_QUERY_AND_SUBSCRIPTION)
+ assert result is False
+
+
+TEST_INVALID_MULTIPLE_SUBSCRIPTION_AND_QUERY = """
+subscription{
+ event{
+ ...on ProductUpdated{
+ product{
+ id
+ }
+ }
+ }
+}
+query{
+ products(first:100){
+ edges{
+ node{
+ id
+ }
+ }
+ }
+}
+"""
+
+
+def test_validate_invalid_subscription_and_query():
+
+ result = validate_subscription_query(TEST_INVALID_MULTIPLE_SUBSCRIPTION_AND_QUERY)
+ assert result is False
+
+
+TEST_INVALID_MULTIPLE_SUBSCRIPTION = """
+subscription{
+ event{
+ ...on ProductUpdated{
+ product{
+ id
+ }
+ }
+ }
+}
+subscription{
+ event{
+ ...on ProductCreated{
+ product{
+ id
+ }
+ }
+ }
+}
+"""
+
+
+def test_validate_invalid_multiple_subscriptions():
+
+ result = validate_subscription_query(TEST_INVALID_MULTIPLE_SUBSCRIPTION)
+ assert result is False
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_translation_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_translation_subscription.py
new file mode 100644
index 0000000000..60362280a0
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_translation_subscription.py
@@ -0,0 +1,468 @@
+import json
+
+import graphene
+
+from .....webhook.event_types import WebhookEventAsyncType
+from ...tasks import create_deliveries_for_subscriptions
+
+
+def test_translation_created_product(
+ product_translation_fr, subscription_translation_created_webhook
+):
+ webhooks = [subscription_translation_created_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_CREATED
+ translation_id = graphene.Node.to_global_id(
+ "ProductTranslation", product_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, product_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_created_product_variant(
+ variant_translation_fr, subscription_translation_created_webhook
+):
+ webhooks = [subscription_translation_created_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_CREATED
+ translation_id = graphene.Node.to_global_id(
+ "ProductVariantTranslation", variant_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, variant_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_created_collection(
+ collection_translation_fr, subscription_translation_created_webhook
+):
+ webhooks = [subscription_translation_created_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_CREATED
+ translation_id = graphene.Node.to_global_id(
+ "CollectionTranslation", collection_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, collection_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_created_category(
+ category_translation_fr, subscription_translation_created_webhook
+):
+ webhooks = [subscription_translation_created_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_CREATED
+ translation_id = graphene.Node.to_global_id(
+ "CategoryTranslation", category_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, category_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_created_attribute(
+ translated_attribute, subscription_translation_created_webhook
+):
+ webhooks = [subscription_translation_created_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_CREATED
+ translation_id = graphene.Node.to_global_id(
+ "AttributeTranslation", translated_attribute.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, translated_attribute, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_created_attribute_value(
+ translated_attribute_value, subscription_translation_created_webhook
+):
+ webhooks = [subscription_translation_created_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_CREATED
+ translation_id = graphene.Node.to_global_id(
+ "AttributeValueTranslation", translated_attribute_value.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, translated_attribute_value, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_created_page(
+ page_translation_fr, subscription_translation_created_webhook
+):
+ webhooks = [subscription_translation_created_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_CREATED
+ translation_id = graphene.Node.to_global_id(
+ "PageTranslation", page_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, page_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_created_shipping_method(
+ shipping_method_translation_fr, subscription_translation_created_webhook
+):
+ webhooks = [subscription_translation_created_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_CREATED
+ translation_id = graphene.Node.to_global_id(
+ "ShippingMethodTranslation", shipping_method_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, shipping_method_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_created_sale(
+ sale_translation_fr, subscription_translation_created_webhook
+):
+ webhooks = [subscription_translation_created_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_CREATED
+ translation_id = graphene.Node.to_global_id(
+ "SaleTranslation", sale_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, sale_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_created_voucher(
+ voucher_translation_fr, subscription_translation_created_webhook
+):
+ webhooks = [subscription_translation_created_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_CREATED
+ translation_id = graphene.Node.to_global_id(
+ "VoucherTranslation", voucher_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, voucher_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_created_menu_item(
+ menu_item_translation_fr, subscription_translation_created_webhook
+):
+ webhooks = [subscription_translation_created_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_CREATED
+ translation_id = graphene.Node.to_global_id(
+ "MenuItemTranslation", menu_item_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, menu_item_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_updated_product(
+ product_translation_fr, subscription_translation_updated_webhook
+):
+ webhooks = [subscription_translation_updated_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_UPDATED
+ translation_id = graphene.Node.to_global_id(
+ "ProductTranslation", product_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, product_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_updated_product_variant(
+ variant_translation_fr, subscription_translation_updated_webhook
+):
+ webhooks = [subscription_translation_updated_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_UPDATED
+ translation_id = graphene.Node.to_global_id(
+ "ProductVariantTranslation", variant_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, variant_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_updated_collection(
+ collection_translation_fr, subscription_translation_updated_webhook
+):
+ webhooks = [subscription_translation_updated_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_UPDATED
+ translation_id = graphene.Node.to_global_id(
+ "CollectionTranslation", collection_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, collection_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_updated_category(
+ category_translation_fr, subscription_translation_updated_webhook
+):
+ webhooks = [subscription_translation_updated_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_UPDATED
+ translation_id = graphene.Node.to_global_id(
+ "CategoryTranslation", category_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, category_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_updated_attribute(
+ translated_attribute, subscription_translation_updated_webhook
+):
+ webhooks = [subscription_translation_updated_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_UPDATED
+ translation_id = graphene.Node.to_global_id(
+ "AttributeTranslation", translated_attribute.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, translated_attribute, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_updated_attribute_value(
+ translated_attribute_value, subscription_translation_updated_webhook
+):
+ webhooks = [subscription_translation_updated_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_UPDATED
+ translation_id = graphene.Node.to_global_id(
+ "AttributeValueTranslation", translated_attribute_value.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, translated_attribute_value, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_updated_page(
+ page_translation_fr, subscription_translation_updated_webhook
+):
+ webhooks = [subscription_translation_updated_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_UPDATED
+ translation_id = graphene.Node.to_global_id(
+ "PageTranslation", page_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, page_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_updated_shipping_method(
+ shipping_method_translation_fr, subscription_translation_updated_webhook
+):
+ webhooks = [subscription_translation_updated_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_UPDATED
+ translation_id = graphene.Node.to_global_id(
+ "ShippingMethodTranslation", shipping_method_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, shipping_method_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_updated_sale(
+ sale_translation_fr, subscription_translation_updated_webhook
+):
+ webhooks = [subscription_translation_updated_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_UPDATED
+ translation_id = graphene.Node.to_global_id(
+ "SaleTranslation", sale_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, sale_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_updated_voucher(
+ voucher_translation_fr, subscription_translation_updated_webhook
+):
+ webhooks = [subscription_translation_updated_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_UPDATED
+ translation_id = graphene.Node.to_global_id(
+ "VoucherTranslation", voucher_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, voucher_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_translation_updated_menu_item(
+ menu_item_translation_fr, subscription_translation_updated_webhook
+):
+ webhooks = [subscription_translation_updated_webhook]
+ event_type = WebhookEventAsyncType.TRANSLATION_UPDATED
+ translation_id = graphene.Node.to_global_id(
+ "MenuItemTranslation", menu_item_translation_fr.id
+ )
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, menu_item_translation_fr, webhooks
+ )
+
+ expected_payload = json.dumps(
+ [{"translation": {"id": translation_id}, "meta": None}]
+ )
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_webhook.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_webhook.py
new file mode 100644
index 0000000000..f38a40b110
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_webhook.py
@@ -0,0 +1,78 @@
+import dataclasses
+from unittest import mock
+
+from freezegun import freeze_time
+
+from .....webhook.event_types import WebhookEventAsyncType
+from .....webhook.models import Webhook
+from .....webhook.payloads import generate_meta, generate_requestor
+from ...tasks import trigger_webhooks_async
+
+TEST_ID = "test_id"
+
+
+class FakeDelivery:
+ id = TEST_ID
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async.delay")
[email protected]("saleor.plugins.webhook.tasks.create_deliveries_for_subscriptions")
+def test_trigger_webhooks_async_without_meta(
+ mocked_create_deliveries_for_subscription,
+ mocked_send_webhook_request,
+ subscription_order_updated_webhook,
+ order,
+):
+ webhook = subscription_order_updated_webhook
+ webhook_type = WebhookEventAsyncType.ORDER_UPDATED
+ mocked_create_deliveries_for_subscription.return_value = [FakeDelivery()]
+
+ data = {"regular_webhook": "data"}
+ trigger_webhooks_async(data, webhook_type, [webhook], order)
+ mocked_create_deliveries_for_subscription.assert_called_once_with(
+ event_type=webhook_type,
+ subscribable_object=order,
+ webhooks=[webhook],
+ meta={},
+ )
+ mocked_send_webhook_request.assert_called_once_with(TEST_ID)
+
+
+@freeze_time("2018-05-31 12:00:01")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async.delay")
[email protected]("saleor.plugins.webhook.tasks.create_deliveries_for_subscriptions")
+def test_trigger_webhooks_async_with_meta(
+ mocked_create_deliveries_for_subscription,
+ mocked_send_webhook_request,
+ subscription_order_updated_webhook,
+ order,
+ staff_user,
+):
+ webhook = subscription_order_updated_webhook
+ webhook_type = WebhookEventAsyncType.ORDER_UPDATED
+ mocked_create_deliveries_for_subscription.return_value = [FakeDelivery()]
+ data = {"regular_webhook": "data"}
+ trigger_webhooks_async(data, webhook_type, [webhook], order, staff_user)
+ mocked_create_deliveries_for_subscription.assert_called_once_with(
+ event_type=webhook_type,
+ subscribable_object=order,
+ webhooks=[webhook],
+ meta=generate_meta(requestor_data=generate_requestor(staff_user)),
+ )
+ mocked_send_webhook_request.assert_called_once_with(TEST_ID)
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async.delay")
[email protected]("saleor.plugins.webhook.tasks.create_deliveries_for_subscriptions")
+def test_trigger_webhooks_async_no_subscription_webhooks(
+ mocked_create_deliveries_for_subscriptions,
+ mocked_send_webhook_request,
+ webhook,
+ order,
+):
+ webhook_type = WebhookEventAsyncType.ORDER_UPDATED
+ webhooks = Webhook.objects.all()
+ data = {"regular_webhook": "data"}
+ trigger_webhooks_async(data, webhook_type, webhooks, order)
+ mocked_create_deliveries_for_subscriptions.assert_not_called()
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index 84a0c7360b..f11ca67c51 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -132,7 +132,11 @@ def test_order_created(
expected_data = generate_order_payload(order_with_lines)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.ORDER_CREATED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.ORDER_CREATED,
+ [any_webhook],
+ order_with_lines,
+ None,
)
@@ -153,7 +157,11 @@ def test_order_confirmed(
expected_data = generate_order_payload(order_with_lines)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.ORDER_CONFIRMED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.ORDER_CONFIRMED,
+ [any_webhook],
+ order_with_lines,
+ None,
)
@@ -174,7 +182,11 @@ def test_draft_order_created(
expected_data = generate_order_payload(order_with_lines)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.DRAFT_ORDER_CREATED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.DRAFT_ORDER_CREATED,
+ [any_webhook],
+ order_with_lines,
+ None,
)
@@ -195,7 +207,11 @@ def test_draft_order_deleted(
expected_data = generate_order_payload(order_with_lines)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.DRAFT_ORDER_DELETED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.DRAFT_ORDER_DELETED,
+ [any_webhook],
+ order_with_lines,
+ None,
)
@@ -216,7 +232,11 @@ def test_draft_order_updated(
expected_data = generate_order_payload(order_with_lines)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.DRAFT_ORDER_UPDATED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.DRAFT_ORDER_UPDATED,
+ [any_webhook],
+ order_with_lines,
+ None,
)
@@ -237,7 +257,11 @@ def test_customer_created(
expected_data = generate_customer_payload(customer_user)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.CUSTOMER_CREATED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.CUSTOMER_CREATED,
+ [any_webhook],
+ customer_user,
+ None,
)
@@ -258,7 +282,11 @@ def test_customer_updated(
expected_data = generate_customer_payload(customer_user)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.CUSTOMER_UPDATED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.CUSTOMER_UPDATED,
+ [any_webhook],
+ customer_user,
+ None,
)
@@ -279,7 +307,11 @@ def test_order_fully_paid(
expected_data = generate_order_payload(order_with_lines)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.ORDER_FULLY_PAID, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.ORDER_FULLY_PAID,
+ [any_webhook],
+ order_with_lines,
+ None,
)
@@ -300,7 +332,11 @@ def test_collection_created(
expected_data = generate_collection_payload(collection)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.COLLECTION_CREATED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.COLLECTION_CREATED,
+ [any_webhook],
+ collection,
+ None,
)
@@ -321,7 +357,11 @@ def test_collection_updated(
expected_data = generate_collection_payload(collection)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.COLLECTION_UPDATED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.COLLECTION_UPDATED,
+ [any_webhook],
+ collection,
+ None,
)
@@ -342,7 +382,11 @@ def test_collection_deleted(
expected_data = generate_collection_payload(collection)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.COLLECTION_DELETED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.COLLECTION_DELETED,
+ [any_webhook],
+ collection,
+ None,
)
@@ -363,7 +407,11 @@ def test_product_created(
expected_data = generate_product_payload(product)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.PRODUCT_CREATED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.PRODUCT_CREATED,
+ [any_webhook],
+ product,
+ None,
)
@@ -384,7 +432,11 @@ def test_product_updated(
expected_data = generate_product_payload(product)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.PRODUCT_UPDATED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.PRODUCT_UPDATED,
+ [any_webhook],
+ product,
+ None,
)
@@ -420,7 +472,11 @@ def test_product_deleted(
assert variant_global_ids == expected_data_dict["variants"]
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.PRODUCT_DELETED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.PRODUCT_DELETED,
+ [any_webhook],
+ product,
+ None,
)
@@ -441,7 +497,11 @@ def test_product_variant_created(
expected_data = generate_product_variant_payload([variant])
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.PRODUCT_VARIANT_CREATED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.PRODUCT_VARIANT_CREATED,
+ [any_webhook],
+ variant,
+ None,
)
@@ -462,7 +522,11 @@ def test_product_variant_updated(
expected_data = generate_product_variant_payload([variant])
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED,
+ [any_webhook],
+ variant,
+ None,
)
@@ -483,7 +547,11 @@ def test_product_variant_deleted(
expected_data = generate_product_variant_payload([variant])
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.PRODUCT_VARIANT_DELETED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.PRODUCT_VARIANT_DELETED,
+ [any_webhook],
+ variant,
+ None,
)
@@ -497,16 +565,19 @@ def test_product_variant_out_of_stock(
settings,
variant_with_many_stocks,
):
+ variant = variant_with_many_stocks.stocks.first()
mocked_get_webhooks_for_event.return_value = [any_webhook]
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
manager = get_plugins_manager()
- manager.product_variant_out_of_stock(variant_with_many_stocks.stocks.first())
+ manager.product_variant_out_of_stock(variant)
- expected_data = generate_product_variant_with_stock_payload(
- [variant_with_many_stocks.stocks.first()]
- )
+ expected_data = generate_product_variant_with_stock_payload([variant])
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK,
+ [any_webhook],
+ variant,
+ None,
)
@@ -520,18 +591,19 @@ def test_product_variant_back_in_stock(
settings,
variant_with_many_stocks,
):
+ variant = variant_with_many_stocks.stocks.first()
mocked_get_webhooks_for_event.return_value = [any_webhook]
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
manager = get_plugins_manager()
- manager.product_variant_back_in_stock(variant_with_many_stocks.stocks.first())
+ manager.product_variant_back_in_stock(variant)
- expected_data = generate_product_variant_with_stock_payload(
- [variant_with_many_stocks.stocks.first()]
- )
+ expected_data = generate_product_variant_with_stock_payload([variant])
mocked_webhook_trigger.assert_called_once_with(
expected_data,
WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK,
[any_webhook],
+ variant,
+ None,
)
@@ -552,7 +624,11 @@ def test_order_updated(
expected_data = generate_order_payload(order_with_lines)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.ORDER_UPDATED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.ORDER_UPDATED,
+ [any_webhook],
+ order_with_lines,
+ None,
)
@@ -573,7 +649,11 @@ def test_order_cancelled(
expected_data = generate_order_payload(order_with_lines)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.ORDER_CANCELLED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.ORDER_CANCELLED,
+ [any_webhook],
+ order_with_lines,
+ None,
)
@@ -594,7 +674,11 @@ def test_checkout_created(
expected_data = generate_checkout_payload(checkout_with_items)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.CHECKOUT_CREATED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.CHECKOUT_CREATED,
+ [any_webhook],
+ checkout_with_items,
+ None,
)
@@ -637,7 +721,11 @@ def test_checkout_updated(
expected_data = generate_checkout_payload(checkout_with_items)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.CHECKOUT_UPDATED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.CHECKOUT_UPDATED,
+ [any_webhook],
+ checkout_with_items,
+ None,
)
@@ -654,9 +742,7 @@ def test_page_created(
expected_data = generate_page_payload(page)
mocked_webhook_trigger.assert_called_once_with(
- expected_data,
- WebhookEventAsyncType.PAGE_CREATED,
- [any_webhook],
+ expected_data, WebhookEventAsyncType.PAGE_CREATED, [any_webhook], page, None
)
@@ -673,7 +759,7 @@ def test_page_updated(
expected_data = generate_page_payload(page)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.PAGE_UPDATED, [any_webhook]
+ expected_data, WebhookEventAsyncType.PAGE_UPDATED, [any_webhook], page, None
)
@@ -693,7 +779,7 @@ def test_page_deleted(
expected_data = generate_page_payload(page)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.PAGE_DELETED, [any_webhook]
+ expected_data, WebhookEventAsyncType.PAGE_DELETED, [any_webhook], page, None
)
@@ -715,7 +801,11 @@ def test_invoice_request(
expected_data = generate_invoice_payload(invoice)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.INVOICE_REQUESTED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.INVOICE_REQUESTED,
+ [any_webhook],
+ invoice,
+ None,
)
@@ -737,7 +827,11 @@ def test_invoice_delete(
expected_data = generate_invoice_payload(invoice)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.INVOICE_DELETED, [any_webhook]
+ expected_data,
+ WebhookEventAsyncType.INVOICE_DELETED,
+ [any_webhook],
+ invoice,
+ None,
)
@@ -759,7 +853,7 @@ def test_invoice_sent(
expected_data = generate_invoice_payload(invoice)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.INVOICE_SENT, [any_webhook]
+ expected_data, WebhookEventAsyncType.INVOICE_SENT, [any_webhook], invoice, None
)
@@ -865,7 +959,7 @@ def test_sale_created(
manager.sale_created(sale, current_catalogue=sale_catalogue_info)
expected_data = generate_sale_payload(sale, current_catalogue=sale_catalogue_info)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.SALE_CREATED, [any_webhook]
+ expected_data, WebhookEventAsyncType.SALE_CREATED, [any_webhook], sale, None
)
@@ -902,7 +996,7 @@ def test_sale_updated(
previous_catalogue=previous_sale_catalogue_info,
)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.SALE_UPDATED, [any_webhook]
+ expected_data, WebhookEventAsyncType.SALE_UPDATED, [any_webhook], sale, None
)
@@ -921,7 +1015,7 @@ def test_sale_deleted(
manager.sale_deleted(sale, previous_catalogue=sale_catalogue_info)
expected_data = generate_sale_payload(sale, previous_catalogue=sale_catalogue_info)
mocked_webhook_trigger.assert_called_once_with(
- expected_data, WebhookEventAsyncType.SALE_DELETED, [any_webhook]
+ expected_data, WebhookEventAsyncType.SALE_DELETED, [any_webhook], sale, None
)
diff --git a/saleor/plugins/webhook/utils.py b/saleor/plugins/webhook/utils.py
index 9521e8dde7..009c708c06 100644
--- a/saleor/plugins/webhook/utils.py
+++ b/saleor/plugins/webhook/utils.py
@@ -137,7 +137,6 @@ def create_event_delivery_list_for_webhooks(
event_payload: "EventPayload",
event_type: str,
) -> List[EventDelivery]:
-
event_deliveries = EventDelivery.objects.bulk_create(
[
EventDelivery(
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index 7912167841..ab984f044e 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -262,3 +262,44 @@ class WebhookEventSyncType:
ORDER_FILTER_SHIPPING_METHODS: OrderPermissions.MANAGE_ORDERS,
CHECKOUT_FILTER_SHIPPING_METHODS: CheckoutPermissions.MANAGE_CHECKOUTS,
}
+
+
+SUBSCRIBABLE_EVENTS = [
+ WebhookEventAsyncType.ORDER_CREATED,
+ WebhookEventAsyncType.ORDER_UPDATED,
+ WebhookEventAsyncType.ORDER_CONFIRMED,
+ WebhookEventAsyncType.ORDER_FULLY_PAID,
+ WebhookEventAsyncType.ORDER_FULFILLED,
+ WebhookEventAsyncType.ORDER_CANCELLED,
+ WebhookEventAsyncType.DRAFT_ORDER_CREATED,
+ WebhookEventAsyncType.DRAFT_ORDER_UPDATED,
+ WebhookEventAsyncType.DRAFT_ORDER_DELETED,
+ WebhookEventAsyncType.PRODUCT_CREATED,
+ WebhookEventAsyncType.PRODUCT_UPDATED,
+ WebhookEventAsyncType.PRODUCT_DELETED,
+ WebhookEventAsyncType.PRODUCT_VARIANT_DELETED,
+ WebhookEventAsyncType.PRODUCT_VARIANT_CREATED,
+ WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED,
+ WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK,
+ WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK,
+ WebhookEventAsyncType.SALE_CREATED,
+ WebhookEventAsyncType.SALE_UPDATED,
+ WebhookEventAsyncType.SALE_DELETED,
+ WebhookEventAsyncType.INVOICE_REQUESTED,
+ WebhookEventAsyncType.INVOICE_DELETED,
+ WebhookEventAsyncType.INVOICE_SENT,
+ WebhookEventAsyncType.FULFILLMENT_CREATED,
+ WebhookEventAsyncType.FULFILLMENT_CANCELED,
+ WebhookEventAsyncType.CUSTOMER_CREATED,
+ WebhookEventAsyncType.CUSTOMER_UPDATED,
+ WebhookEventAsyncType.COLLECTION_CREATED,
+ WebhookEventAsyncType.COLLECTION_UPDATED,
+ WebhookEventAsyncType.COLLECTION_DELETED,
+ WebhookEventAsyncType.CHECKOUT_CREATED,
+ WebhookEventAsyncType.CHECKOUT_UPDATED,
+ WebhookEventAsyncType.PAGE_CREATED,
+ WebhookEventAsyncType.PAGE_UPDATED,
+ WebhookEventAsyncType.PAGE_DELETED,
+ WebhookEventAsyncType.TRANSLATION_CREATED,
+ WebhookEventAsyncType.TRANSLATION_UPDATED,
+]
diff --git a/saleor/webhook/migrations/0008_webhook_subscription_query.py b/saleor/webhook/migrations/0008_webhook_subscription_query.py
new file mode 100644
index 0000000000..af8545b4c3
--- /dev/null
+++ b/saleor/webhook/migrations/0008_webhook_subscription_query.py
@@ -0,0 +1,18 @@
+# Generated by Django 3.2.6 on 2021-11-27 13:39
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("webhook", "0007_auto_20210319_0945"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="webhook",
+ name="subscription_query",
+ field=models.TextField(blank=True, null=True),
+ ),
+ ]
diff --git a/saleor/webhook/models.py b/saleor/webhook/models.py
index 56fbc2f70d..c1be5677e6 100644
--- a/saleor/webhook/models.py
+++ b/saleor/webhook/models.py
@@ -16,6 +16,7 @@ class Webhook(models.Model):
target_url = WebhookURLField(max_length=255)
is_active = models.BooleanField(default=True)
secret_key = models.CharField(max_length=255, null=True, blank=True)
+ subscription_query = models.TextField(null=True, blank=True)
class Meta:
ordering = ("pk",)