Skip to content

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

Add new event for stock update (#11665)

Jakubc4f01d449c62
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1152342d7b..b77c301866 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,7 @@ All notable, unreleased changes to this project will be documented in this file.
### Other changes
- Allow `webhookCreate` and `webhookUpdate` mutations to inherit events from `query` field - #11736 by @zedzior
+- Add new `PRODUCT_VARIANT_STOCK_UPDATED` event - #11665 by @jakubkuc
# 3.10.0 [Unreleased]
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.py
index 539aa30a57..d1b69086e5 100644
--- a/saleor/graphql/product/bulk_mutations/products.py
+++ b/saleor/graphql/product/bulk_mutations/products.py
@@ -908,6 +908,7 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):
stock.quantity = stock_data["quantity"]
stocks.append(stock)
+ transaction.on_commit(lambda: manager.product_variant_stock_updated(stock))
warehouse_models.Stock.objects.bulk_update(stocks, ["quantity"])
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py
index 23abf88a22..fc503ebc1a 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py
@@ -323,11 +323,13 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_success(
product_variant_stock_out_of_stock_webhook.assert_not_called()
+@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")
@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
def test_update_or_create_variant_with_back_in_stock_webhooks_only_failed(
product_variant_stock_out_of_stock_webhook,
product_variant_back_in_stock_webhook,
+ product_variant_stock_update_webhook,
settings,
variant,
warehouses,
@@ -358,8 +360,11 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_failed(
product_variant_stock_out_of_stock_webhook.assert_called_once_with(
Stock.objects.all()[1]
)
+ assert product_variant_stock_update_webhook.call_count == 1
+ product_variant_stock_update_webhook.assert_called_with(Stock.objects.all()[1])
+@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")
@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
def test_update_or_create_variant_with_back_in_stock_webhooks_with_allocations(
@@ -426,11 +431,13 @@ def test_update_or_create_variant_with_out_of_stock_webhooks_with_allocations(
product_variant_back_in_stock_webhook.assert_not_called()
+@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")
@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
def test_update_or_create_variant_stocks_with_out_of_stock_webhook_only(
product_variant_stock_out_of_stock_webhook,
product_variant_back_in_stock_webhook,
+ product_variant_stock_update_webhook,
settings,
variant,
warehouses,
@@ -465,6 +472,8 @@ def test_update_or_create_variant_stocks_with_out_of_stock_webhook_only(
product_variant_stock_out_of_stock_webhook.assert_called_once_with(
Stock.objects.last()
)
+ assert product_variant_stock_update_webhook.call_count == 2
+ product_variant_stock_update_webhook.assert_called_with(Stock.objects.last())
product_variant_back_in_stock_webhook.assert_not_called()
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 2495a29008..a8e261d804 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1717,6 +1717,9 @@ enum WebhookEventTypeEnum {
"""A product variant is back in stock."""
PRODUCT_VARIANT_BACK_IN_STOCK
+ """A product variant stock is updated"""
+ PRODUCT_VARIANT_STOCK_UPDATED
+
"""
A product variant metadata is updated.
@@ -2236,6 +2239,9 @@ enum WebhookEventTypeAsyncEnum {
"""A product variant is back in stock."""
PRODUCT_VARIANT_BACK_IN_STOCK
+ """A product variant stock is updated"""
+ PRODUCT_VARIANT_STOCK_UPDATED
+
"""
A product variant metadata is updated.
@@ -2928,6 +2934,7 @@ enum WebhookSampleEventTypeEnum {
PRODUCT_VARIANT_DELETED
PRODUCT_VARIANT_OUT_OF_STOCK
PRODUCT_VARIANT_BACK_IN_STOCK
+ PRODUCT_VARIANT_STOCK_UPDATED
PRODUCT_VARIANT_METADATA_UPDATED
CHECKOUT_CREATED
CHECKOUT_UPDATED
@@ -24898,6 +24905,36 @@ type ProductVariantBackInStock implements Event {
warehouse: Warehouse
}
+"""
+Event sent when product variant stock is updated.
+
+Added in Saleor 3.11.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type ProductVariantStockUpdated implements Event {
+ """Time of the event."""
+ issuedAt: DateTime
+
+ """Saleor version that triggered the event."""
+ version: String
+
+ """The user or application that triggered the event."""
+ issuingPrincipal: IssuingPrincipal
+
+ """The application receiving the webhook."""
+ recipient: App
+
+ """The product variant the event relates to."""
+ productVariant(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
+ ): ProductVariant
+
+ """Look up a warehouse."""
+ warehouse: Warehouse
+}
+
"""
Event sent when product variant is deleted.
diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.py
index a2e3d4a923..0aa926d638 100644
--- a/saleor/graphql/webhook/enums.py
+++ b/saleor/graphql/webhook/enums.py
@@ -129,6 +129,9 @@ WEBHOOK_EVENT_DESCRIPTION = {
WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK: (
"A product variant is back in stock."
),
+ WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED: (
+ "A product variant stock is updated"
+ ),
WebhookEventAsyncType.SHIPPING_PRICE_CREATED: "A new shipping price is created.",
WebhookEventAsyncType.SHIPPING_PRICE_UPDATED: "A shipping price is updated.",
WebhookEventAsyncType.SHIPPING_PRICE_DELETED: "A shipping price is deleted.",
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index a7557f3e84..ac3411d633 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -33,6 +33,7 @@ from ..core.descriptions import (
ADDED_IN_37,
ADDED_IN_38,
ADDED_IN_310,
+ ADDED_IN_311,
PREVIEW_FEATURE,
)
from ..core.scalars import PositiveDecimal
@@ -41,9 +42,11 @@ from ..order.dataloaders import OrderByIdLoader
from ..payment.enums import TransactionActionEnum
from ..payment.types import TransactionItem
from ..plugins.dataloaders import plugin_manager_promise_callback
+from ..product.dataloaders import ProductVariantByIdLoader
from ..shipping.dataloaders import ShippingMethodChannelListingByChannelSlugLoader
from ..shipping.types import ShippingMethod
from ..translations import types as translation_types
+from ..warehouse.dataloaders import WarehouseByIdLoader
from .resolvers import resolve_shipping_methods_for_checkout
TRANSLATIONS_TYPES_MAP = {
@@ -837,6 +840,34 @@ class ProductVariantBackInStock(SubscriptionObjectType, ProductVariantBase):
return stock.warehouse
+class ProductVariantStockUpdated(SubscriptionObjectType, ProductVariantBase):
+ warehouse = graphene.Field(
+ "saleor.graphql.warehouse.types.Warehouse", description="Look up a warehouse."
+ )
+
+ class Meta:
+ interfaces = (Event,)
+ description = (
+ "Event sent when product variant stock is updated."
+ + ADDED_IN_311
+ + PREVIEW_FEATURE
+ )
+
+ @staticmethod
+ def resolve_product_variant(root, info: ResolveInfo, channel=None):
+ _, stock = root
+ return (
+ ProductVariantByIdLoader(info.context)
+ .load(stock.product_variant.id)
+ .then(lambda variant: ChannelContext(node=variant, channel_slug=None))
+ )
+
+ @staticmethod
+ def resolve_warehouse(root, info: ResolveInfo):
+ _, stock = root
+ return WarehouseByIdLoader(info.context).load(stock.warehouse_id)
+
+
class SaleBase(AbstractType):
sale = graphene.Field(
"saleor.graphql.discount.types.Sale",
@@ -1898,6 +1929,7 @@ WEBHOOK_TYPES_MAP = {
WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED: ProductVariantUpdated,
WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK: ProductVariantOutOfStock,
WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK: ProductVariantBackInStock,
+ WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED: ProductVariantStockUpdated,
WebhookEventAsyncType.PRODUCT_VARIANT_DELETED: ProductVariantDeleted,
WebhookEventAsyncType.PRODUCT_VARIANT_METADATA_UPDATED: (
ProductVariantMetadataUpdated
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 9c8197605e..4b69ecbf65 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -649,6 +649,12 @@ class PluginsManager(PaymentInterface):
"product_variant_back_in_stock", default_value, stock
)
+ def product_variant_stock_updated(self, stock: "Stock"):
+ default_value = None
+ self.__run_method_on_plugins(
+ "product_variant_stock_updated", default_value, stock
+ )
+
def product_variant_metadata_updated(self, product_variant: "ProductVariant"):
default_value = None
self.__run_method_on_plugins(
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 0196504653..825acc7157 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -898,6 +898,18 @@ class WebhookPlugin(BasePlugin):
product_variant_data, event_type, webhooks, stock, self.requestor
)
+ def product_variant_stock_updated(self, stock: "Stock", previous_value: Any) -> Any:
+ if not self.active:
+ return previous_value
+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED
+ if webhooks := get_webhooks_for_event(event_type):
+ product_variant_data = generate_product_variant_with_stock_payload(
+ [stock], self.requestor
+ )
+ 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:
return previous_value
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
index 7a2a9c0723..377f1f3acc 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
@@ -372,6 +372,14 @@ def subscription_product_variant_back_in_stock_webhook(subscription_webhook):
)
+def subscription_product_variant_stock_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ queries.PRODUCT_VARIANT_STOCK_UPDATED,
+ WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED,
+ )
+
+
@pytest.fixture
def subscription_order_created_webhook(subscription_webhook):
return subscription_webhook(
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
index 9ba670343b..2d4ab69c0c 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
@@ -761,6 +761,21 @@ PRODUCT_VARIANT_BACK_IN_STOCK = """
}
"""
+PRODUCT_VARIANT_STOCK_UPDATED = """
+ subscription{
+ event{
+ ...on ProductVariantStockUpdated{
+ productVariant{
+ id
+ }
+ warehouse{
+ id
+ }
+ }
+ }
+ }
+"""
+
ORDER_CREATED = """
subscription{
event{
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
index fe26dd7d86..70d3aa1451 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
@@ -1042,6 +1042,26 @@ def test_product_variant_back_in_stock(
assert deliveries[0].webhook == webhooks[0]
+def test_product_variant_stock_updated(
+ stock, subscription_product_variant_stock_updated_webhook
+):
+ webhooks = [subscription_product_variant_stock_updated_webhook]
+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED
+ variant_id = graphene.Node.to_global_id("ProductVariant", stock.product_variant.id)
+ warehouse_id = graphene.Node.to_global_id("Warehouse", stock.warehouse.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, stock, webhooks)
+ expected_payload = json.dumps(
+ {
+ "productVariant": {"id": variant_id},
+ "warehouse": {"id": warehouse_id},
+ }
+ )
+
+ 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
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index e9ac74cf17..2b78bb653d 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -106,6 +106,7 @@ class WebhookEventAsyncType:
PRODUCT_VARIANT_OUT_OF_STOCK = "product_variant_out_of_stock"
PRODUCT_VARIANT_BACK_IN_STOCK = "product_variant_back_in_stock"
+ PRODUCT_VARIANT_STOCK_UPDATED = "product_variant_stock_updated"
CHECKOUT_CREATED = "checkout_created"
CHECKOUT_UPDATED = "checkout_updated"
@@ -224,6 +225,7 @@ class WebhookEventAsyncType:
PRODUCT_VARIANT_METADATA_UPDATED: "Product variant metadata updated",
PRODUCT_VARIANT_OUT_OF_STOCK: "Product variant stock changed",
PRODUCT_VARIANT_BACK_IN_STOCK: "Product variant back in stock",
+ PRODUCT_VARIANT_STOCK_UPDATED: "Product variant stock updated",
CHECKOUT_CREATED: "Checkout created",
CHECKOUT_UPDATED: "Checkout updated",
CHECKOUT_METADATA_UPDATED: "Checkout metadata updated",
@@ -333,6 +335,7 @@ class WebhookEventAsyncType:
(PRODUCT_VARIANT_DELETED, DISPLAY_LABELS[PRODUCT_VARIANT_DELETED]),
(PRODUCT_VARIANT_OUT_OF_STOCK, DISPLAY_LABELS[PRODUCT_VARIANT_OUT_OF_STOCK]),
(PRODUCT_VARIANT_BACK_IN_STOCK, DISPLAY_LABELS[PRODUCT_VARIANT_BACK_IN_STOCK]),
+ (PRODUCT_VARIANT_STOCK_UPDATED, DISPLAY_LABELS[PRODUCT_VARIANT_STOCK_UPDATED]),
(
PRODUCT_VARIANT_METADATA_UPDATED,
DISPLAY_LABELS[PRODUCT_VARIANT_METADATA_UPDATED],
@@ -454,6 +457,7 @@ class WebhookEventAsyncType:
PRODUCT_VARIANT_METADATA_UPDATED: ProductPermissions.MANAGE_PRODUCTS,
PRODUCT_VARIANT_BACK_IN_STOCK: ProductPermissions.MANAGE_PRODUCTS,
PRODUCT_VARIANT_OUT_OF_STOCK: ProductPermissions.MANAGE_PRODUCTS,
+ PRODUCT_VARIANT_STOCK_UPDATED: ProductPermissions.MANAGE_PRODUCTS,
CHECKOUT_CREATED: CheckoutPermissions.MANAGE_CHECKOUTS,
CHECKOUT_UPDATED: CheckoutPermissions.MANAGE_CHECKOUTS,
CHECKOUT_METADATA_UPDATED: CheckoutPermissions.MANAGE_CHECKOUTS,