Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add filterable subscriptions for async checkout webhooks (#17647)
Maciej Korycinskib79cf8f91f04
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ba3a4c015d..ea2bdb6b82 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -70,6 +70,7 @@ All notable, unreleased changes to this project will be documented in this file.- Expose line-level discounts through the `OrderLineDiscount` type, retrievable via the `OrderLine.discounts` API field - #17510 by @korycins- Introduce total field in OrderDiscount to replace the amount field, with OrderDiscount.amount now deprecated - #17510 by @korycins- Introduce `useLegacyLineVoucherPropagation` flag to control legacy propagation behavior for specific voucher types - #17587 - by @korycins+- Add filterable subscriptions for checkout events (`checkoutCreated`, `checkoutUpdated`, `checkoutFullyPaid`, `checkoutMetadataUpdated`) - #17647 by @korycins### Webhooksdiff --git a/saleor/app/tests/fixtures/app.py b/saleor/app/tests/fixtures/app.pyindex 13cf6109a9..0172816bdc 100644--- a/saleor/app/tests/fixtures/app.py+++ b/saleor/app/tests/fixtures/app.py@@ -39,6 +39,7 @@ def webhook_app(permission_manage_staff,permission_manage_orders,permission_manage_users,+ permission_manage_checkouts,):app = App.objects.create(name="Webhook app", is_active=True)app.permissions.add(permission_manage_shipping)@@ -49,6 +50,7 @@ def webhook_app(app.permissions.add(permission_manage_staff)app.permissions.add(permission_manage_orders)app.permissions.add(permission_manage_users)+ app.permissions.add(permission_manage_checkouts)return appdiff --git a/saleor/checkout/tests/fixtures/checkout.py b/saleor/checkout/tests/fixtures/checkout.pyindex 2885bd945c..9cb05cf6fe 100644--- a/saleor/checkout/tests/fixtures/checkout.py+++ b/saleor/checkout/tests/fixtures/checkout.py@@ -30,6 +30,7 @@ def checkout_JPY(channel_JPY):currency=channel_JPY.currency_code, channel=channel_JPY)checkout.set_country("JP", commit=True)+ CheckoutMetadata.objects.create(checkout=checkout)return checkoutdiff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 3722234c9e..e039314386 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -29752,7 +29752,7 @@ type Subscription @doc(category: "Miscellaneous") {"""draftOrderCreated("""- List of channel slugs. The event will be sent only if the order belongs to one of the provided channels. If the channel slug list is empty, orders that belong to any channel will be sent. Maximally 500 items.+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items."""channels: [String!]): DraftOrderCreated @doc(category: "Orders")@@ -29766,7 +29766,7 @@ type Subscription @doc(category: "Miscellaneous") {"""draftOrderUpdated("""- List of channel slugs. The event will be sent only if the order belongs to one of the provided channels. If the channel slug list is empty, orders that belong to any channel will be sent. Maximally 500 items.+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items."""channels: [String!]): DraftOrderUpdated @doc(category: "Orders")@@ -29780,7 +29780,7 @@ type Subscription @doc(category: "Miscellaneous") {"""draftOrderDeleted("""- List of channel slugs. The event will be sent only if the order belongs to one of the provided channels. If the channel slug list is empty, orders that belong to any channel will be sent. Maximally 500 items.+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items."""channels: [String!]): DraftOrderDeleted @doc(category: "Orders")@@ -29794,7 +29794,7 @@ type Subscription @doc(category: "Miscellaneous") {"""orderCreated("""- List of channel slugs. The event will be sent only if the order belongs to one of the provided channels. If the channel slug list is empty, orders that belong to any channel will be sent. Maximally 500 items.+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items."""channels: [String!]): OrderCreated @doc(category: "Orders")@@ -29808,7 +29808,7 @@ type Subscription @doc(category: "Miscellaneous") {"""orderUpdated("""- List of channel slugs. The event will be sent only if the order belongs to one of the provided channels. If the channel slug list is empty, orders that belong to any channel will be sent. Maximally 500 items.+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items."""channels: [String!]): OrderUpdated @doc(category: "Orders")@@ -29822,7 +29822,7 @@ type Subscription @doc(category: "Miscellaneous") {"""orderConfirmed("""- List of channel slugs. The event will be sent only if the order belongs to one of the provided channels. If the channel slug list is empty, orders that belong to any channel will be sent. Maximally 500 items.+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items."""channels: [String!]): OrderConfirmed @doc(category: "Orders")@@ -29836,7 +29836,7 @@ type Subscription @doc(category: "Miscellaneous") {"""orderPaid("""- List of channel slugs. The event will be sent only if the order belongs to one of the provided channels. If the channel slug list is empty, orders that belong to any channel will be sent. Maximally 500 items.+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items."""channels: [String!]): OrderPaid @doc(category: "Orders")@@ -29850,7 +29850,7 @@ type Subscription @doc(category: "Miscellaneous") {"""orderFullyPaid("""- List of channel slugs. The event will be sent only if the order belongs to one of the provided channels. If the channel slug list is empty, orders that belong to any channel will be sent. Maximally 500 items.+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items."""channels: [String!]): OrderFullyPaid @doc(category: "Orders")@@ -29864,7 +29864,7 @@ type Subscription @doc(category: "Miscellaneous") {"""orderRefunded("""- List of channel slugs. The event will be sent only if the order belongs to one of the provided channels. If the channel slug list is empty, orders that belong to any channel will be sent. Maximally 500 items.+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items."""channels: [String!]): OrderRefunded @doc(category: "Orders")@@ -29878,7 +29878,7 @@ type Subscription @doc(category: "Miscellaneous") {"""orderFullyRefunded("""- List of channel slugs. The event will be sent only if the order belongs to one of the provided channels. If the channel slug list is empty, orders that belong to any channel will be sent. Maximally 500 items.+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items."""channels: [String!]): OrderFullyRefunded @doc(category: "Orders")@@ -29892,7 +29892,7 @@ type Subscription @doc(category: "Miscellaneous") {"""orderFulfilled("""- List of channel slugs. The event will be sent only if the order belongs to one of the provided channels. If the channel slug list is empty, orders that belong to any channel will be sent. Maximally 500 items.+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items."""channels: [String!]): OrderFulfilled @doc(category: "Orders")@@ -29906,7 +29906,7 @@ type Subscription @doc(category: "Miscellaneous") {"""orderCancelled("""- List of channel slugs. The event will be sent only if the order belongs to one of the provided channels. If the channel slug list is empty, orders that belong to any channel will be sent. Maximally 500 items.+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items."""channels: [String!]): OrderCancelled @doc(category: "Orders")@@ -29920,7 +29920,7 @@ type Subscription @doc(category: "Miscellaneous") {"""orderExpired("""- List of channel slugs. The event will be sent only if the order belongs to one of the provided channels. If the channel slug list is empty, orders that belong to any channel will be sent. Maximally 500 items.+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items."""channels: [String!]): OrderExpired @doc(category: "Orders")@@ -29934,7 +29934,7 @@ type Subscription @doc(category: "Miscellaneous") {"""orderMetadataUpdated("""- List of channel slugs. The event will be sent only if the order belongs to one of the provided channels. If the channel slug list is empty, orders that belong to any channel will be sent. Maximally 500 items.+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items."""channels: [String!]): OrderMetadataUpdated @doc(category: "Orders")@@ -29948,10 +29948,66 @@ type Subscription @doc(category: "Miscellaneous") {"""orderBulkCreated("""- List of channel slugs. The event will be sent only if the order belongs to one of the provided channels. If the channel slug list is empty, orders that belong to any channel will be sent. Maximally 500 items.+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items."""channels: [String!]): OrderBulkCreated @doc(category: "Orders")++ """+ Event sent when new checkout is created.++ Added in Saleor 3.21.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ checkoutCreated(+ """+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items.+ """+ channels: [String!]+ ): CheckoutCreated @doc(category: "Checkout")++ """+ Event sent when checkout is updated.++ Added in Saleor 3.21.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ checkoutUpdated(+ """+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items.+ """+ channels: [String!]+ ): CheckoutUpdated @doc(category: "Checkout")++ """+ Event sent when checkout is fully-paid.++ Added in Saleor 3.21.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ checkoutFullyPaid(+ """+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items.+ """+ channels: [String!]+ ): CheckoutFullyPaid @doc(category: "Checkout")++ """+ Event sent when checkout metadata is updated.++ Added in Saleor 3.21.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ checkoutMetadataUpdated(+ """+ List of channel slugs. The event will be sent only if the object belongs to one of the provided channels. If the channel slug list is empty, objects that belong to any channel will be sent. Maximally 500 items.+ """+ channels: [String!]+ ): CheckoutMetadataUpdated @doc(category: "Checkout")}interface Event {@@ -30242,6 +30298,80 @@ type OrderBulkCreated implements Event @doc(category: "Orders") {orders: [Order!]}+"""Event sent when new checkout is created."""+type CheckoutCreated implements Event @doc(category: "Checkout") {+ """Time of the event."""+ issuedAt: DateTime++ """Saleor version that triggered the event."""+ version: String++ """The user or application that triggered the event."""+ issuingPrincipal: IssuingPrincipal++ """The application receiving the webhook."""+ recipient: App++ """The checkout the event relates to."""+ checkout: Checkout+}++"""Event sent when checkout is updated."""+type CheckoutUpdated implements Event @doc(category: "Checkout") {+ """Time of the event."""+ issuedAt: DateTime++ """Saleor version that triggered the event."""+ version: String++ """The user or application that triggered the event."""+ issuingPrincipal: IssuingPrincipal++ """The application receiving the webhook."""+ recipient: App++ """The checkout the event relates to."""+ checkout: Checkout+}++"""+Event sent when checkout is fully paid with transactions. The checkout is considered as fully paid when the checkout `charge_status` is `FULL` or `OVERCHARGED`. The event is not sent when the checkout authorization flow strategy is used.+"""+type CheckoutFullyPaid implements Event @doc(category: "Checkout") {+ """Time of the event."""+ issuedAt: DateTime++ """Saleor version that triggered the event."""+ version: String++ """The user or application that triggered the event."""+ issuingPrincipal: IssuingPrincipal++ """The application receiving the webhook."""+ recipient: App++ """The checkout the event relates to."""+ checkout: Checkout+}++"""Event sent when checkout metadata is updated."""+type CheckoutMetadataUpdated implements Event @doc(category: "Checkout") {+ """Time of the event."""+ issuedAt: DateTime++ """Saleor version that triggered the event."""+ version: String++ """The user or application that triggered the event."""+ issuingPrincipal: IssuingPrincipal++ """The application receiving the webhook."""+ recipient: App++ """The checkout the event relates to."""+ checkout: Checkout+}+enum DistanceUnitsEnum {MMCM@@ -32014,80 +32144,6 @@ type CollectionMetadataUpdated implements Event @doc(category: "Products") {): Collection}-"""Event sent when new checkout is created."""-type CheckoutCreated implements Event @doc(category: "Checkout") {- """Time of the event."""- issuedAt: DateTime-- """Saleor version that triggered the event."""- version: String-- """The user or application that triggered the event."""- issuingPrincipal: IssuingPrincipal-- """The application receiving the webhook."""- recipient: App-- """The checkout the event relates to."""- checkout: Checkout-}--"""Event sent when checkout is updated."""-type CheckoutUpdated implements Event @doc(category: "Checkout") {- """Time of the event."""- issuedAt: DateTime-- """Saleor version that triggered the event."""- version: String-- """The user or application that triggered the event."""- issuingPrincipal: IssuingPrincipal-- """The application receiving the webhook."""- recipient: App-- """The checkout the event relates to."""- checkout: Checkout-}--"""-Event sent when checkout is fully paid with transactions. The checkout is considered as fully paid when the checkout `charge_status` is `FULL` or `OVERCHARGED`. The event is not sent when the checkout authorization flow strategy is used.-"""-type CheckoutFullyPaid implements Event @doc(category: "Checkout") {- """Time of the event."""- issuedAt: DateTime-- """Saleor version that triggered the event."""- version: String-- """The user or application that triggered the event."""- issuingPrincipal: IssuingPrincipal-- """The application receiving the webhook."""- recipient: App-- """The checkout the event relates to."""- checkout: Checkout-}--"""Event sent when checkout metadata is updated."""-type CheckoutMetadataUpdated implements Event @doc(category: "Checkout") {- """Time of the event."""- issuedAt: DateTime-- """Saleor version that triggered the event."""- version: String-- """The user or application that triggered the event."""- issuingPrincipal: IssuingPrincipal-- """The application receiving the webhook."""- recipient: App-- """The checkout the event relates to."""- checkout: Checkout-}-"""Event sent when new page is created."""type PageCreated implements Event @doc(category: "Pages") {"""Time of the event."""diff --git a/saleor/graphql/schema_printer.py b/saleor/graphql/schema_printer.pyindex b517a28cee..08b4ddc79e 100644--- a/saleor/graphql/schema_printer.py+++ b/saleor/graphql/schema_printer.py@@ -156,13 +156,15 @@ def print_object_directives(type_) -> str:def print_field_directives_for_category(field, name) -> str:- # Get doc_category for `type Query` fields.- doc_category = getattr(field.resolver, "doc_category", None)-- # Get doc_category for `type Mutation` fields.- if not doc_category and hasattr(field.type, "graphene_type"):+ doc_category = None+ # Get doc_category for `type Mutation` & `type Subscription` fields.+ if hasattr(field.type, "graphene_type"):doc_category = getattr(field.type.graphene_type, "doc_category", None)+ if not doc_category:+ # Get doc_category for `type Query` fields.+ doc_category = getattr(field.resolver, "doc_category", None)+return f' @doc(category: "{doc_category}")' if doc_category else ""@@ -457,15 +459,17 @@ def print_block_string(value: str, minimize: bool = False) -> str:def print_description(- def_: GraphQLArgument- | GraphQLDirective- | GraphQLEnumType- | GraphQLEnumValue- | GraphQLInputObjectType- | GraphQLInterfaceType- | GraphQLObjectType- | GraphQLScalarType- | GraphQLUnionType,+ def_: (+ GraphQLArgument+ | GraphQLDirective+ | GraphQLEnumType+ | GraphQLEnumValue+ | GraphQLInputObjectType+ | GraphQLInterfaceType+ | GraphQLObjectType+ | GraphQLScalarType+ | GraphQLUnionType+ ),indentation: str = "",first_in_block: bool = True,) -> str:diff --git a/saleor/graphql/webhook/subscription_payload.py b/saleor/graphql/webhook/subscription_payload.pyindex 6efa725c88..b53909a6e4 100644--- a/saleor/graphql/webhook/subscription_payload.py+++ b/saleor/graphql/webhook/subscription_payload.py@@ -65,6 +65,19 @@ def get_event_payload(event):return event+def _process_payload_instance(payload_instance):+ """Process a payload instance to extract data."""+ for payload_key in payload_instance.data:+ extracted_payload = get_event_payload(payload_instance.data.get(payload_key))+ payload_instance.data[payload_key] = extracted_payload+ if "event" in payload_instance.data or not payload_instance.data:+ event_payload = payload_instance.data.get("event") or {}+ else:+ event_payload = {"data": payload_instance.data}++ return event_payload++def generate_payload_promise_from_subscription(event_type: str,subscribable_object,@@ -129,7 +142,7 @@ def generate_payload_promise_from_subscription(return Nonepayload_instance = payload[0]- event_payload = payload_instance.data.get("event") or {}+ event_payload = _process_payload_instance(payload_instance)def check_errors(event_payload, payload_instance=payload_instance):if payload_instance.errors:@@ -207,15 +220,7 @@ def generate_payload_from_subscription(return Nonepayload_instance = payload[0]- payload_data_keys = payload_instance.data.keys()- for key in payload_data_keys:- extracted_payload = get_event_payload(payload_instance.data.get(key))- payload_instance.data[key] = extracted_payload- if "event" in payload_instance.data or not payload_instance.data:- event_payload = payload_instance.data.get("event") or {}- else:- event_payload = {"data": payload_instance.data}-+ event_payload = _process_payload_instance(payload_instance)if payload_instance.errors:event_payload["errors"] = [format_error(error, (GraphQLError, PermissionDenied))diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex e9a9bfa39f..b70dbfe4ca 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -47,6 +47,7 @@ from ..core.descriptions import (ADDED_IN_318,ADDED_IN_319,ADDED_IN_320,+ ADDED_IN_321,DEPRECATED_IN_3X_EVENT,PREVIEW_FEATURE,)@@ -2593,16 +2594,16 @@ class WarehouseMetadataUpdated(SubscriptionObjectType, WarehouseBase):description = "Event sent when warehouse metadata is updated."-def default_order_resolver(root, info, channels=None):+def default_channel_filterable_resolver(root, info, channels=None):return Observable.from_([root])channels_argument = graphene.Argument(NonNullList(graphene.String),description=(- "List of channel slugs. The event will be sent only if the order "+ "List of channel slugs. The event will be sent only if the object ""belongs to one of the provided channels. If the channel slug list is "- "empty, orders that belong to any channel will be sent. Maximally "+ "empty, objects that belong to any channel will be sent. Maximally "f"{MAX_FILTERABLE_CHANNEL_SLUGS_LIMIT} items."),)@@ -2620,7 +2621,7 @@ class Subscription(SubscriptionObjectType):+ ADDED_IN_320+ PREVIEW_FEATURE),- resolver=default_order_resolver,+ resolver=default_channel_filterable_resolver,channels=channels_argument,doc_category=DOC_CATEGORY_ORDERS,)@@ -2629,7 +2630,7 @@ class Subscription(SubscriptionObjectType):description=("Event sent when draft order is updated." + ADDED_IN_320 + PREVIEW_FEATURE),- resolver=default_order_resolver,+ resolver=default_channel_filterable_resolver,channels=channels_argument,doc_category=DOC_CATEGORY_ORDERS,)@@ -2638,7 +2639,7 @@ class Subscription(SubscriptionObjectType):description=("Event sent when draft order is deleted." + ADDED_IN_320 + PREVIEW_FEATURE),- resolver=default_order_resolver,+ resolver=default_channel_filterable_resolver,channels=channels_argument,doc_category=DOC_CATEGORY_ORDERS,)@@ -2647,7 +2648,7 @@ class Subscription(SubscriptionObjectType):description=("Event sent when new order is created." + ADDED_IN_320 + PREVIEW_FEATURE),- resolver=default_order_resolver,+ resolver=default_channel_filterable_resolver,channels=channels_argument,doc_category=DOC_CATEGORY_ORDERS,)@@ -2656,7 +2657,7 @@ class Subscription(SubscriptionObjectType):description=("Event sent when order is updated." + ADDED_IN_320 + PREVIEW_FEATURE),- resolver=default_order_resolver,+ resolver=default_channel_filterable_resolver,channels=channels_argument,doc_category=DOC_CATEGORY_ORDERS,)@@ -2665,7 +2666,7 @@ class Subscription(SubscriptionObjectType):description=("Event sent when order is confirmed." + ADDED_IN_320 + PREVIEW_FEATURE),- resolver=default_order_resolver,+ resolver=default_channel_filterable_resolver,channels=channels_argument,doc_category=DOC_CATEGORY_ORDERS,)@@ -2676,7 +2677,7 @@ class Subscription(SubscriptionObjectType):+ ADDED_IN_320+ PREVIEW_FEATURE),- resolver=default_order_resolver,+ resolver=default_channel_filterable_resolver,channels=channels_argument,doc_category=DOC_CATEGORY_ORDERS,)@@ -2685,7 +2686,7 @@ class Subscription(SubscriptionObjectType):description=("Event sent when order is fully paid." + ADDED_IN_320 + PREVIEW_FEATURE),- resolver=default_order_resolver,+ resolver=default_channel_filterable_resolver,channels=channels_argument,doc_category=DOC_CATEGORY_ORDERS,)@@ -2695,14 +2696,14 @@ class Subscription(SubscriptionObjectType):"The order received a refund. The order may be partially or fully ""refunded." + ADDED_IN_320 + PREVIEW_FEATURE),- resolver=default_order_resolver,+ resolver=default_channel_filterable_resolver,channels=channels_argument,doc_category=DOC_CATEGORY_ORDERS,)order_fully_refunded = BaseField(OrderFullyRefunded,description=("The order is fully refunded." + ADDED_IN_320 + PREVIEW_FEATURE),- resolver=default_order_resolver,+ resolver=default_channel_filterable_resolver,channels=channels_argument,doc_category=DOC_CATEGORY_ORDERS,)@@ -2711,7 +2712,7 @@ class Subscription(SubscriptionObjectType):description=("Event sent when order is fulfilled." + ADDED_IN_320 + PREVIEW_FEATURE),- resolver=default_order_resolver,+ resolver=default_channel_filterable_resolver,channels=channels_argument,doc_category=DOC_CATEGORY_ORDERS,)@@ -2720,7 +2721,7 @@ class Subscription(SubscriptionObjectType):description=("Event sent when order is cancelled." + ADDED_IN_320 + PREVIEW_FEATURE),- resolver=default_order_resolver,+ resolver=default_channel_filterable_resolver,channels=channels_argument,doc_category=DOC_CATEGORY_ORDERS,)@@ -2729,7 +2730,7 @@ class Subscription(SubscriptionObjectType):description=("Event sent when order becomes expired." + ADDED_IN_320 + PREVIEW_FEATURE),- resolver=default_order_resolver,+ resolver=default_channel_filterable_resolver,channels=channels_argument,doc_category=DOC_CATEGORY_ORDERS,)@@ -2740,7 +2741,7 @@ class Subscription(SubscriptionObjectType):+ ADDED_IN_320+ PREVIEW_FEATURE),- resolver=default_order_resolver,+ resolver=default_channel_filterable_resolver,channels=channels_argument,doc_category=DOC_CATEGORY_ORDERS,)@@ -2753,6 +2754,45 @@ class Subscription(SubscriptionObjectType):doc_category=DOC_CATEGORY_ORDERS,)+ checkout_created = BaseField(+ CheckoutCreated,+ description=(+ "Event sent when new checkout is created." + ADDED_IN_321 + PREVIEW_FEATURE+ ),+ resolver=default_channel_filterable_resolver,+ channels=channels_argument,+ doc_category=DOC_CATEGORY_CHECKOUT,+ )+ checkout_updated = BaseField(+ CheckoutUpdated,+ description=(+ "Event sent when checkout is updated." + ADDED_IN_321 + PREVIEW_FEATURE+ ),+ resolver=default_channel_filterable_resolver,+ channels=channels_argument,+ doc_category=DOC_CATEGORY_CHECKOUT,+ )+ checkout_fully_paid = BaseField(+ CheckoutFullyPaid,+ description=(+ "Event sent when checkout is fully-paid." + ADDED_IN_321 + PREVIEW_FEATURE+ ),+ resolver=default_channel_filterable_resolver,+ channels=channels_argument,+ doc_category=DOC_CATEGORY_CHECKOUT,+ )+ checkout_metadata_updated = BaseField(+ CheckoutMetadataUpdated,+ description=(+ "Event sent when checkout metadata is updated."+ + ADDED_IN_321+ + PREVIEW_FEATURE+ ),+ resolver=default_channel_filterable_resolver,+ channels=channels_argument,+ doc_category=DOC_CATEGORY_CHECKOUT,+ )+class Meta:doc_category = DOC_CATEGORY_MISCdiff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 4aa43ac6c1..186e871542 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -776,18 +776,17 @@ class WebhookPlugin(BasePlugin):)return previous_value- def _get_webhooks_for_order_events(+ def _get_webhooks_for_channel_events(self,event_type: str,- order: "Order",+ channel_slug: str,webhooks: Iterable["Webhook"] | None = None,) -> Iterable["Webhook"]:- """Get webhooks for order events.+ """Get webhooks for channel-based events.Fetch all valid webhooks and filter out the ones that have a subscription query- with filter that doesn't match to the order.+ with filter that doesn't match to the channel."""- order_channel_slug = order.channel.slugif webhooks is None:webhooks = get_webhooks_for_event(event_type)filtered_webhooks = []@@ -799,7 +798,7 @@ class WebhookPlugin(BasePlugin):if not filterable_channel_slugs:filtered_webhooks.append(webhook)continue- if order_channel_slug in filterable_channel_slugs:+ if channel_slug in filterable_channel_slugs:filtered_webhooks.append(webhook)return filtered_webhooks@@ -809,7 +808,9 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.ORDER_CREATED- if webhooks := self._get_webhooks_for_order_events(event_type, order, webhooks):+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, order.channel.slug, webhooks+ ):order_data_generator = partial(generate_order_payload, order, self.requestor)@@ -909,7 +910,9 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.ORDER_CONFIRMED- if webhooks := self._get_webhooks_for_order_events(event_type, order, webhooks):+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, order.channel.slug, webhooks+ ):order_data_generator = partial(generate_order_payload, order, self.requestor)@@ -930,7 +933,9 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.ORDER_FULLY_PAID- if webhooks := self._get_webhooks_for_order_events(event_type, order, webhooks):+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, order.channel.slug, webhooks+ ):order_data_generator = partial(generate_order_payload, order, self.requestor)@@ -949,7 +954,9 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.ORDER_PAID- if webhooks := self._get_webhooks_for_order_events(event_type, order, webhooks):+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, order.channel.slug, webhooks+ ):order_data_generator = partial(generate_order_payload, order, self.requestor)@@ -970,7 +977,9 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.ORDER_REFUNDED- if webhooks := self._get_webhooks_for_order_events(event_type, order, webhooks):+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, order.channel.slug, webhooks+ ):order_data_generator = partial(generate_order_payload, order, self.requestor)@@ -991,7 +1000,9 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.ORDER_FULLY_REFUNDED- if webhooks := self._get_webhooks_for_order_events(event_type, order, webhooks):+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, order.channel.slug, webhooks+ ):order_data_generator = partial(generate_order_payload, order, self.requestor)@@ -1012,7 +1023,9 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.ORDER_UPDATED- if webhooks := self._get_webhooks_for_order_events(event_type, order, webhooks):+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, order.channel.slug, webhooks+ ):order_data_generator = partial(generate_order_payload, order, self.requestor)@@ -1033,7 +1046,9 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.ORDER_EXPIRED- if webhooks := self._get_webhooks_for_order_events(event_type, order, webhooks):+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, order.channel.slug, webhooks+ ):order_data_generator = partial(generate_order_payload, order, self.requestor)@@ -1353,7 +1368,9 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.ORDER_CANCELLED- if webhooks := self._get_webhooks_for_order_events(event_type, order, webhooks):+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, order.channel.slug, webhooks+ ):order_data_generator = partial(generate_order_payload, order, self.requestor)@@ -1374,7 +1391,9 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.ORDER_FULFILLED- if webhooks := self._get_webhooks_for_order_events(event_type, order, webhooks):+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, order.channel.slug, webhooks+ ):order_data_generator = partial(generate_order_payload, order, self.requestor)@@ -1395,7 +1414,9 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.ORDER_METADATA_UPDATED- webhooks = self._get_webhooks_for_order_events(event_type, order, webhooks)+ webhooks = self._get_webhooks_for_channel_events(+ event_type, order.channel.slug, webhooks+ )self._trigger_metadata_updated_event(event_type,order,@@ -1460,7 +1481,9 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.DRAFT_ORDER_CREATED- if webhooks := self._get_webhooks_for_order_events(event_type, order, webhooks):+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, order.channel.slug, webhooks+ ):order_data_generator = partial(generate_order_payload, order, self.requestor)@@ -1481,7 +1504,9 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.DRAFT_ORDER_UPDATED- if webhooks := self._get_webhooks_for_order_events(event_type, order, webhooks):+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, order.channel.slug, webhooks+ ):order_data_generator = partial(generate_order_payload, order, self.requestor)@@ -1502,7 +1527,9 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.DRAFT_ORDER_DELETED- if webhooks := self._get_webhooks_for_order_events(event_type, order, webhooks):+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, order.channel.slug, webhooks+ ):order_data_generator = partial(generate_order_payload, order, self.requestor)@@ -2042,9 +2069,13 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.CHECKOUT_CREATED- if webhooks := self._get_webhooks_for_event(event_type, webhooks):+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, checkout.channel.slug, webhooks+ ):checkout_data_generator = partial(- generate_checkout_payload, checkout, self.requestor+ generate_checkout_payload,+ checkout,+ self.requestor,)self.trigger_webhooks_async(None,@@ -2063,9 +2094,13 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.CHECKOUT_UPDATED- if webhooks := self._get_webhooks_for_event(event_type, webhooks):+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, checkout.channel.slug, webhooks+ ):checkout_data_generator = partial(- generate_checkout_payload, checkout, self.requestor+ generate_checkout_payload,+ checkout,+ self.requestor,)self.trigger_webhooks_async(None,@@ -2084,9 +2119,13 @@ class WebhookPlugin(BasePlugin):if not self.active:return previous_valueevent_type = WebhookEventAsyncType.CHECKOUT_FULLY_PAID- if webhooks := self._get_webhooks_for_event(event_type, webhooks):+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, checkout.channel.slug, webhooks+ ):checkout_data_generator = partial(- generate_checkout_payload, checkout, self.requestor+ generate_checkout_payload,+ checkout,+ self.requestor,)self.trigger_webhooks_async(None,@@ -2104,9 +2143,13 @@ class WebhookPlugin(BasePlugin):) -> None:if not self.active:return previous_value- self._trigger_metadata_updated_event(- WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED, checkout, webhooks=webhooks- )+ event_type = WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED+ if webhooks := self._get_webhooks_for_channel_events(+ event_type, checkout.channel.slug, webhooks+ ):+ self._trigger_metadata_updated_event(+ event_type, checkout, webhooks=webhooks+ )return previous_valuedef notify(diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_checkout_created.py b/saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_checkout_created.pynew file mode 100644index 0000000000..251d9ffa43--- /dev/null+++ b/saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_checkout_created.py@@ -0,0 +1,243 @@+import json+from unittest.mock import patch++import graphene+from django.test import override_settings++from ......core.models import EventDelivery+from ......graphql.webhook.subscription_query import SubscriptionQuery+from ......webhook.event_types import WebhookEventAsyncType+from .....manager import get_plugins_manager++CHECKOUT_CREATED_SUBSCRIPTION = """+subscription {+ checkoutCreated(channels: ["%s"]) {+ checkout {+ id+ token+ lines {+ id+ variant {+ id+ }+ }+ }+ }+}+"""+++@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(+ PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"],+ CELERY_TASK_ALWAYS_EAGER=True,+)+def test_checkout_created(+ mocked_async, checkout_with_item, subscription_webhook, settings+):+ # given+ manager = get_plugins_manager(False)+ checkout = checkout_with_item+ checkout_line = checkout.lines.first()++ channel = checkout.channel+ assert channel.slug == settings.DEFAULT_CHANNEL_SLUG++ event_type = WebhookEventAsyncType.CHECKOUT_CREATED++ query = CHECKOUT_CREATED_SUBSCRIPTION % settings.DEFAULT_CHANNEL_SLUG+ webhook = subscription_webhook(query, event_type)+ subscription_query = SubscriptionQuery(query)+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()+ webhook.save()++ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)++ # when+ manager.checkout_created(checkout)++ # then+ expected_payload = json.dumps(+ {+ "data": {+ "checkoutCreated": {+ "checkout": {+ "id": checkout_id,+ "token": str(checkout.token),+ "lines": [+ {+ "id": graphene.Node.to_global_id(+ "CheckoutLine", checkout_line.id+ ),+ "variant": {+ "id": graphene.Node.to_global_id(+ "ProductVariant", checkout_line.variant_id+ )+ },+ }+ ],+ }+ }+ }+ }+ )+ deliveries = EventDelivery.objects.all()+ assert len(deliveries) == 1+ assert deliveries[0].payload.get_payload() == expected_payload+ assert deliveries[0].webhook == webhook+ assert mocked_async.called+++@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(+ PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"],+ CELERY_TASK_ALWAYS_EAGER=True,+)+def test_checkout_created_without_channels_input(+ mocked_async, checkout_with_item, subscription_webhook+):+ # given+ manager = get_plugins_manager(False)+ checkout = checkout_with_item+ checkout_line = checkout.lines.first()++ event_type = WebhookEventAsyncType.CHECKOUT_CREATED++ query = """subscription {+ checkoutCreated {+ checkout {+ id+ token+ lines {+ id+ variant {+ id+ }+ }+ }+ }+ }"""+ webhook = subscription_webhook(query, event_type)+ subscription_query = SubscriptionQuery(query)+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()+ webhook.save()++ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)++ # when+ manager.checkout_created(checkout)++ # then+ expected_payload = json.dumps(+ {+ "data": {+ "checkoutCreated": {+ "checkout": {+ "id": checkout_id,+ "token": str(checkout.token),+ "lines": [+ {+ "id": graphene.Node.to_global_id(+ "CheckoutLine", checkout_line.id+ ),+ "variant": {+ "id": graphene.Node.to_global_id(+ "ProductVariant", checkout_line.variant_id+ )+ },+ }+ ],+ }+ }+ }+ }+ )+ deliveries = EventDelivery.objects.all()+ assert len(deliveries) == 1+ assert deliveries[0].payload.get_payload() == expected_payload+ assert deliveries[0].webhook == webhook+ assert mocked_async.called+++@patch(+ "saleor.webhook.transport.asynchronous.transport.create_event_delivery_list_for_webhooks"+)+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(+ PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"],+ CELERY_TASK_ALWAYS_EAGER=True,+)+def test_checkout_created_with_different_channel(+ mocked_async,+ mocked_create_event_delivery_list_for_webhooks,+ checkout_JPY_with_item,+ subscription_webhook,+ settings,+):+ # given+ manager = get_plugins_manager(False)+ checkout = checkout_JPY_with_item+ channel = checkout.channel+ assert channel.slug != settings.DEFAULT_CHANNEL_SLUG++ event_type = WebhookEventAsyncType.CHECKOUT_CREATED++ query = CHECKOUT_CREATED_SUBSCRIPTION % settings.DEFAULT_CHANNEL_SLUG+ webhook = subscription_webhook(query, event_type)+ subscription_query = SubscriptionQuery(query)+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()+ webhook.save()++ # when+ manager.checkout_created(checkout)++ # then+ assert not mocked_async.called+ assert not mocked_create_event_delivery_list_for_webhooks.called+ deliveries = EventDelivery.objects.all()+ assert len(deliveries) == 0+++@patch(+ "saleor.webhook.transport.asynchronous.transport.create_event_delivery_list_for_webhooks"+)+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_different_event_doesnt_trigger_webhook(+ mocked_async,+ mocked_create_event_delivery_list_for_webhooks,+ checkout_with_item,+ subscription_webhook,+ settings,+):+ # given+ manager = get_plugins_manager(False)+ checkout = checkout_with_item++ channel = checkout.channel+ assert channel.slug == settings.DEFAULT_CHANNEL_SLUG++ event_type = WebhookEventAsyncType.CHECKOUT_UPDATED++ query = CHECKOUT_CREATED_SUBSCRIPTION % settings.DEFAULT_CHANNEL_SLUG+ webhook = subscription_webhook(query, event_type)+ subscription_query = SubscriptionQuery(query)+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()+ webhook.save()++ # when+ manager.checkout_created(checkout)++ # then+ assert not mocked_async.called+ assert not mocked_create_event_delivery_list_for_webhooks.called+ deliveries = EventDelivery.objects.all()+ assert len(deliveries) == 0diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_checkout_fully_paid.py b/saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_checkout_fully_paid.pynew file mode 100644index 0000000000..6b2dddc8df--- /dev/null+++ b/saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_checkout_fully_paid.py@@ -0,0 +1,247 @@+import json+from unittest.mock import patch++import graphene+from django.test import override_settings++from ......core.models import EventDelivery+from ......graphql.webhook.subscription_query import SubscriptionQuery+from ......webhook.event_types import WebhookEventAsyncType+from .....manager import get_plugins_manager++CHECKOUT_FULLY_PAID_SUBSCRIPTION = """+subscription {+ checkoutFullyPaid(channels: ["%s"]) {+ checkout {+ id+ token+ lines {+ id+ variant {+ id+ }+ }+ }+ }+}+"""+++@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(+ PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"],+ CELERY_TASK_ALWAYS_EAGER=True,+)+def test_checkout_fully_paid(+ mocked_async, checkout_with_item, subscription_webhook, settings+):+ # given+ manager = get_plugins_manager(False)+ checkout = checkout_with_item+ checkout_line = checkout.lines.first()++ channel = checkout.channel+ assert channel.slug == settings.DEFAULT_CHANNEL_SLUG++ event_type = WebhookEventAsyncType.CHECKOUT_FULLY_PAID++ query = CHECKOUT_FULLY_PAID_SUBSCRIPTION % settings.DEFAULT_CHANNEL_SLUG+ webhook = subscription_webhook(query, event_type)+ subscription_query = SubscriptionQuery(query)+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()+ webhook.save()++ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)++ # when+ manager.checkout_fully_paid(checkout)++ # then+ expected_payload = json.dumps(+ {+ "data": {+ "checkoutFullyPaid": {+ "checkout": {+ "id": checkout_id,+ "token": str(checkout.token),+ "lines": [+ {+ "id": graphene.Node.to_global_id(+ "CheckoutLine", checkout_line.id+ ),+ "variant": {+ "id": graphene.Node.to_global_id(+ "ProductVariant", checkout_line.variant_id+ )+ },+ }+ ],+ }+ }+ }+ }+ )+ deliveries = EventDelivery.objects.all()+ assert len(deliveries) == 1+ assert deliveries[0].payload.get_payload() == expected_payload+ assert deliveries[0].webhook == webhook+ assert mocked_async.called+++@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(+ PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"],+ CELERY_TASK_ALWAYS_EAGER=True,+)+def test_checkout_fully_paid_without_channels_input(+ mocked_async, checkout_with_item, subscription_webhook+):+ # given+ manager = get_plugins_manager(False)+ checkout = checkout_with_item+ checkout_line = checkout.lines.first()++ event_type = WebhookEventAsyncType.CHECKOUT_FULLY_PAID++ query = """subscription {+ checkoutFullyPaid {+ checkout {+ id+ token+ lines {+ id+ variant {+ id+ }+ }+ }+ }+ }"""+ webhook = subscription_webhook(query, event_type)+ subscription_query = SubscriptionQuery(query)+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()+ webhook.save()++ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)++ # when+ manager.checkout_fully_paid(checkout)++ # then+ expected_payload = json.dumps(+ {+ "data": {+ "checkoutFullyPaid": {+ "checkout": {+ "id": checkout_id,+ "token": str(checkout.token),+ "lines": [+ {+ "id": graphene.Node.to_global_id(+ "CheckoutLine", checkout_line.id+ ),+ "variant": {+ "id": graphene.Node.to_global_id(+ "ProductVariant", checkout_line.variant_id+ )+ },+ }+ ],+ }+ }+ }+ }+ )+ deliveries = EventDelivery.objects.all()+ assert len(deliveries) == 1+ assert deliveries[0].payload.get_payload() == expected_payload+ assert deliveries[0].webhook == webhook+ assert mocked_async.called+++@patch(+ "saleor.webhook.transport.asynchronous.transport.create_event_delivery_list_for_webhooks"+)+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(+ PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"],+ CELERY_TASK_ALWAYS_EAGER=True,+)+def test_checkout_fully_paid_with_different_channel(+ mocked_async,+ mocked_create_event_delivery_list_for_webhooks,+ checkout_JPY_with_item,+ subscription_webhook,+ settings,+):+ # given+ manager = get_plugins_manager(False)+ checkout = checkout_JPY_with_item+ channel = checkout.channel+ assert channel.slug != settings.DEFAULT_CHANNEL_SLUG++ event_type = WebhookEventAsyncType.CHECKOUT_FULLY_PAID++ query = CHECKOUT_FULLY_PAID_SUBSCRIPTION % settings.DEFAULT_CHANNEL_SLUG+ webhook = subscription_webhook(query, event_type)+ subscription_query = SubscriptionQuery(query)+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()+ webhook.save()++ # when+ manager.checkout_fully_paid(checkout)++ # then+ assert not mocked_async.called+ assert not mocked_create_event_delivery_list_for_webhooks.called+ deliveries = EventDelivery.objects.all()+ assert len(deliveries) == 0+++@patch(+ "saleor.webhook.transport.asynchronous.transport.create_event_delivery_list_for_webhooks"+)+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(+ PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"],+ CELERY_TASK_ALWAYS_EAGER=True,+)+def test_different_event_doesnt_trigger_webhook(+ mocked_async,+ mocked_create_event_delivery_list_for_webhooks,+ checkout_with_item,+ subscription_webhook,+ settings,+):+ # given+ manager = get_plugins_manager(False)++ checkout = checkout_with_item++ channel = checkout.channel+ assert channel.slug == settings.DEFAULT_CHANNEL_SLUG++ event_type = WebhookEventAsyncType.CHECKOUT_UPDATED++ query = CHECKOUT_FULLY_PAID_SUBSCRIPTION % settings.DEFAULT_CHANNEL_SLUG+ webhook = subscription_webhook(query, event_type)+ subscription_query = SubscriptionQuery(query)+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()+ webhook.save()++ # when+ manager.checkout_fully_paid(checkout)++ # then+ assert not mocked_async.called+ assert not mocked_create_event_delivery_list_for_webhooks.called+ deliveries = EventDelivery.objects.all()+ assert len(deliveries) == 0diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_checkout_metadata_updated.py b/saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_checkout_metadata_updated.pynew file mode 100644index 0000000000..e66b442cc7--- /dev/null+++ b/saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_checkout_metadata_updated.py@@ -0,0 +1,273 @@+import json+from unittest.mock import patch++import graphene+from django.test import override_settings++from ......core.models import EventDelivery+from ......graphql.webhook.subscription_query import SubscriptionQuery+from ......webhook.event_types import WebhookEventAsyncType+from .....manager import get_plugins_manager++CHECKOUT_METADATA_UPDATED_SUBSCRIPTION = """+subscription {+ checkoutMetadataUpdated(channels: ["%s"]) {+ checkout {+ id+ token+ metadata {+ key+ value+ }+ lines {+ id+ variant {+ id+ }+ }+ }+ }+}+"""+++@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(+ PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"],+ CELERY_TASK_ALWAYS_EAGER=True,+)+def test_checkout_metadata_updated(+ mocked_async, checkout_with_item, subscription_webhook, settings+):+ # given+ manager = get_plugins_manager(False)+ checkout = checkout_with_item+ checkout_line = checkout.lines.first()+ channel = checkout.channel+ assert channel.slug == settings.DEFAULT_CHANNEL_SLUG++ # Add metadata to checkout+ metadata_items = [{"key": "test_key", "value": "test_value"}]+ checkout.metadata_storage.metadata = {"test_key": "test_value"}+ checkout.metadata_storage.save(update_fields=["metadata"])++ event_type = WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED++ query = CHECKOUT_METADATA_UPDATED_SUBSCRIPTION % settings.DEFAULT_CHANNEL_SLUG+ webhook = subscription_webhook(query, event_type)+ subscription_query = SubscriptionQuery(query)+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()+ webhook.save()++ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)++ # when+ manager.checkout_metadata_updated(checkout)++ # then+ expected_payload = json.dumps(+ {+ "data": {+ "checkoutMetadataUpdated": {+ "checkout": {+ "id": checkout_id,+ "token": str(checkout.token),+ "metadata": metadata_items,+ "lines": [+ {+ "id": graphene.Node.to_global_id(+ "CheckoutLine", checkout_line.id+ ),+ "variant": {+ "id": graphene.Node.to_global_id(+ "ProductVariant", checkout_line.variant_id+ )+ },+ }+ ],+ }+ }+ }+ }+ )+ deliveries = EventDelivery.objects.all()+ assert len(deliveries) == 1+ assert deliveries[0].payload.get_payload() == expected_payload+ assert deliveries[0].webhook == webhook+ assert mocked_async.called+++@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(+ PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"],+ CELERY_TASK_ALWAYS_EAGER=True,+)+def test_checkout_metadata_updated_without_channels_input(+ mocked_async, checkout_with_item, subscription_webhook+):+ # given+ manager = get_plugins_manager(False)+ checkout = checkout_with_item+ checkout_line = checkout.lines.first()++ # Add metadata to checkout+ metadata_items = [{"key": "test_key", "value": "test_value"}]+ checkout.metadata_storage.metadata = {"test_key": "test_value"}+ checkout.metadata_storage.save(update_fields=["metadata"])++ event_type = WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED++ query = """subscription {+ checkoutMetadataUpdated {+ checkout {+ id+ token+ metadata {+ key+ value+ }+ lines {+ id+ variant {+ id+ }+ }+ }+ }+ }"""+ webhook = subscription_webhook(query, event_type)+ subscription_query = SubscriptionQuery(query)+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()+ webhook.save()++ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)++ # when+ manager.checkout_metadata_updated(checkout)++ # then+ expected_payload = json.dumps(+ {+ "data": {+ "checkoutMetadataUpdated": {+ "checkout": {+ "id": checkout_id,+ "token": str(checkout.token),+ "metadata": metadata_items,+ "lines": [+ {+ "id": graphene.Node.to_global_id(+ "CheckoutLine", checkout_line.id+ ),+ "variant": {+ "id": graphene.Node.to_global_id(+ "ProductVariant", checkout_line.variant_id+ )+ },+ }+ ],+ }+ }+ }+ }+ )+ deliveries = EventDelivery.objects.all()+ assert len(deliveries) == 1+ assert deliveries[0].payload.get_payload() == expected_payload+ assert deliveries[0].webhook == webhook+ assert mocked_async.called+++@patch(+ "saleor.webhook.transport.asynchronous.transport.create_event_delivery_list_for_webhooks"+)+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(+ PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"],+ CELERY_TASK_ALWAYS_EAGER=True,+)+def test_checkout_metadata_updated_with_different_channel(+ mocked_async,+ mocked_create_event_delivery_list_for_webhooks,+ checkout_JPY_with_item,+ subscription_webhook,+ settings,+):+ # given+ manager = get_plugins_manager(False)+ checkout = checkout_JPY_with_item+ channel = checkout.channel+ assert channel.slug != settings.DEFAULT_CHANNEL_SLUG++ # Add metadata to checkout+ checkout.metadata_storage.metadata = {"test_key": "test_value"}+ checkout.metadata_storage.save(update_fields=["metadata"])++ event_type = WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED++ query = CHECKOUT_METADATA_UPDATED_SUBSCRIPTION % settings.DEFAULT_CHANNEL_SLUG+ webhook = subscription_webhook(query, event_type)+ subscription_query = SubscriptionQuery(query)+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()+ webhook.save()++ # when+ manager.checkout_metadata_updated(checkout)++ # then+ assert not mocked_async.called+ assert not mocked_create_event_delivery_list_for_webhooks.called+ deliveries = EventDelivery.objects.all()+ assert len(deliveries) == 0+++@patch(+ "saleor.webhook.transport.asynchronous.transport.create_event_delivery_list_for_webhooks"+)+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(+ PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"],+ CELERY_TASK_ALWAYS_EAGER=True,+)+def test_different_event_doesnt_trigger_webhook(+ mocked_async,+ mocked_create_event_delivery_list_for_webhooks,+ checkout_with_item,+ subscription_webhook,+ settings,+):+ # given+ manager = get_plugins_manager(False)+ checkout = checkout_with_item++ channel = checkout.channel+ assert channel.slug == settings.DEFAULT_CHANNEL_SLUG++ # Add metadata to checkout+ checkout.metadata_storage.metadata = {"test_key": "test_value"}+ checkout.metadata_storage.save(update_fields=["metadata"])++ event_type = WebhookEventAsyncType.CHECKOUT_UPDATED++ query = CHECKOUT_METADATA_UPDATED_SUBSCRIPTION % settings.DEFAULT_CHANNEL_SLUG+ webhook = subscription_webhook(query, event_type)+ subscription_query = SubscriptionQuery(query)+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()+ webhook.save()++ # when+ manager.checkout_metadata_updated(checkout)++ # then+ assert not mocked_async.called+ assert not mocked_create_event_delivery_list_for_webhooks.called+ deliveries = EventDelivery.objects.all()+ assert len(deliveries) == 0diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_checkout_updated.py b/saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_checkout_updated.pynew file mode 100644index 0000000000..7e3b7e6525--- /dev/null+++ b/saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_checkout_updated.py@@ -0,0 +1,242 @@+import json+from unittest.mock import patch++import graphene+from django.test import override_settings++from ......core.models import EventDelivery+from ......graphql.webhook.subscription_query import SubscriptionQuery+from ......webhook.event_types import WebhookEventAsyncType+from .....manager import get_plugins_manager++CHECKOUT_UPDATED_SUBSCRIPTION = """+subscription {+ checkoutUpdated(channels: ["%s"]) {+ checkout {+ id+ token+ lines {+ id+ variant {+ id+ }+ }+ }+ }+}+"""+++@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(+ PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"],+ CELERY_TASK_ALWAYS_EAGER=True,+)+def test_checkout_updated(+ mocked_async,+ checkout_with_item,+ subscription_webhook,+ settings,+):+ # given+ manager = get_plugins_manager(False)+ checkout = checkout_with_item+ checkout_line = checkout.lines.first()++ channel = checkout.channel+ assert channel.slug == settings.DEFAULT_CHANNEL_SLUG++ event_type = WebhookEventAsyncType.CHECKOUT_UPDATED++ query = CHECKOUT_UPDATED_SUBSCRIPTION % settings.DEFAULT_CHANNEL_SLUG+ webhook = subscription_webhook(query, event_type)+ subscription_query = SubscriptionQuery(query)+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()+ webhook.save()++ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)++ # when+ manager.checkout_updated(checkout)++ # then+ expected_payload = json.dumps(+ {+ "data": {+ "checkoutUpdated": {+ "checkout": {+ "id": checkout_id,+ "token": str(checkout.token),+ "lines": [+ {+ "id": graphene.Node.to_global_id(+ "CheckoutLine", checkout_line.id+ ),+ "variant": {+ "id": graphene.Node.to_global_id(+ "ProductVariant", checkout_line.variant_id+ )+ },+ }+ ],+ }+ }+ }+ }+ )+ deliveries = EventDelivery.objects.all()+ assert len(deliveries) == 1+ assert deliveries[0].payload.get_payload() == expected_payload+ assert deliveries[0].webhook == webhook+ assert mocked_async.called+++@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_checkout_updated_without_channels_input(+ mocked_async, checkout_with_item, subscription_webhook+):+ # given+ manager = get_plugins_manager(False)+ checkout = checkout_with_item+ checkout_line = checkout.lines.first()++ event_type = WebhookEventAsyncType.CHECKOUT_UPDATED++ query = """subscription {+ checkoutUpdated {+ checkout {+ id+ token+ lines {+ id+ variant {+ id+ }+ }+ }+ }+ }"""+ webhook = subscription_webhook(query, event_type)+ subscription_query = SubscriptionQuery(query)+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()+ webhook.save()++ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)++ # when+ manager.checkout_updated(checkout)++ # then+ expected_payload = json.dumps(+ {+ "data": {+ "checkoutUpdated": {+ "checkout": {+ "id": checkout_id,+ "token": str(checkout.token),+ "lines": [+ {+ "id": graphene.Node.to_global_id(+ "CheckoutLine", checkout_line.id+ ),+ "variant": {+ "id": graphene.Node.to_global_id(+ "ProductVariant", checkout_line.variant_id+ )+ },+ }+ ],+ }+ }+ }+ }+ )+ deliveries = EventDelivery.objects.all()+ assert len(deliveries) == 1+ assert deliveries[0].payload.get_payload() == expected_payload+ assert deliveries[0].webhook == webhook+ assert mocked_async.called+++@patch(+ "saleor.webhook.transport.asynchronous.transport.create_event_delivery_list_for_webhooks"+)+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(+ PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"],+ CELERY_TASK_ALWAYS_EAGER=True,+)+def test_checkout_updated_with_different_channel(+ mocked_async,+ mocked_create_event_delivery_list_for_webhooks,+ checkout_JPY_with_item,+ subscription_webhook,+ settings,+):+ # given+ manager = get_plugins_manager(False)+ checkout = checkout_JPY_with_item+ channel = checkout.channel+ assert channel.slug != settings.DEFAULT_CHANNEL_SLUG++ event_type = WebhookEventAsyncType.CHECKOUT_UPDATED++ query = CHECKOUT_UPDATED_SUBSCRIPTION % settings.DEFAULT_CHANNEL_SLUG+ webhook = subscription_webhook(query, event_type)+ subscription_query = SubscriptionQuery(query)+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()+ webhook.save()++ # when+ manager.checkout_updated(checkout)++ # then+ assert not mocked_async.called+ assert not mocked_create_event_delivery_list_for_webhooks.called+ deliveries = EventDelivery.objects.all()+ assert len(deliveries) == 0+++@patch(+ "saleor.webhook.transport.asynchronous.transport.create_event_delivery_list_for_webhooks"+)+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_different_event_doesnt_trigger_webhook(+ mocked_async,+ mocked_create_event_delivery_list_for_webhooks,+ checkout_with_item,+ subscription_webhook,+ settings,+):+ # given+ manager = get_plugins_manager(False)+ checkout = checkout_with_item+ channel = checkout.channel+ assert channel.slug == settings.DEFAULT_CHANNEL_SLUG++ event_type = WebhookEventAsyncType.CHECKOUT_CREATED++ query = CHECKOUT_UPDATED_SUBSCRIPTION % settings.DEFAULT_CHANNEL_SLUG+ webhook = subscription_webhook(query, event_type)+ subscription_query = SubscriptionQuery(query)+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()+ webhook.save()++ # when+ manager.checkout_updated(checkout)++ # then+ assert not mocked_async.called+ assert not mocked_create_event_delivery_list_for_webhooks.called+ deliveries = EventDelivery.objects.all()+ assert len(deliveries) == 0