Skip to content

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

Add `PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED` webhook event (#19006)

Iga Karbowiak9f4f15846add
diff --git a/AGENTS.md b/AGENTS.md
index 0192f2c50e..65d44478e0 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -33,6 +33,27 @@
- When building GraphQL query variables, use enum values instead of plain strings. For example: `{"field": TransactionSortField.CREATED_AT.name}` instead of `{"field": "CREATED_AT"}`
- Do not write unnecessary prefix to test names. If file name is `test_my_mutation.py`, do not write `test_my_mutation_with_x_y` but `test_with_x_y`
- When testing graphQL cases with expected errors ALWAYS assert expected length of errors list
+- When setting up test data, extract values into variables and reuse them in assertions. Do not repeat literal values between setup and assertion — use the variable instead.
+- When comparing JSON payloads in tests, use `json.loads()` to compare dicts instead of comparing serialized strings with `json.dumps()`. String comparison breaks when key order changes.
+
+
+# Webhooks and Events
+
+## Dispatching webhook events
+
+When triggering plugin manager methods to dispatch webhook events, always use `call_event` from `saleor.core.utils.events` instead of calling the manager method directly.
+
+**Bad:**
+```python
+manager.product_variant_discounted_price_updated(price_info, webhooks=webhooks)
+```
+
+**Good:**
+```python
+from saleor.core.utils.events import call_event
+
+call_event(manager.product_variant_discounted_price_updated, price_info, webhooks=webhooks)
+```
# Concurrency and Thread Safety
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
index 9b8a52bef6..c4cba85413 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
@@ -1433,6 +1433,7 @@ def test_checkout_add_voucher_triggers_webhooks(
"requestor_model_name": None,
"requestor_object_id": None,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py
index a8b6514ce5..3a86319a2a 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py
@@ -825,6 +825,7 @@ def test_checkout_billing_address_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": user_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
index 1d6ed4af6a..b8ba45db31 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
@@ -2818,6 +2818,7 @@ def test_checkout_create_triggers_webhooks(
"requestor_model_name": None,
"requestor_object_id": None,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py
index 8974e9d6bd..91926afc91 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py
@@ -365,6 +365,7 @@ def test_checkout_customer_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": user_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py
index 54b4450f23..814e6a71e3 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py
@@ -230,6 +230,7 @@ def test_checkout_customer_detach_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": user_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_note_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_note_update.py
index 41defd9c3e..ed8cb25794 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_note_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_note_update.py
@@ -192,6 +192,7 @@ def test_checkout_customer_note_update_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": user_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
index 7dad921a2a..e3d989e530 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
@@ -971,6 +971,7 @@ def test_checkout_delivery_method_update_triggers_webhooks(
"requestor_model_name": None,
"requestor_object_id": None,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
@@ -1073,6 +1074,7 @@ def test_checkout_delivery_method_update_cc_triggers_webhooks(
"requestor_model_name": None,
"requestor_object_id": None,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
@@ -1165,6 +1167,7 @@ def test_checkout_delivery_method_update_external_shipping_triggers_webhooks(
"requestor_model_name": None,
"requestor_object_id": None,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py
index 00657edb90..747770dfc9 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py
@@ -230,6 +230,7 @@ def test_checkout_email_update_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": user_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py
index 81823563d5..4118ede53a 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py
@@ -185,6 +185,7 @@ def test_checkout_update_language_code_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": user_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
index 3e615b9c76..ca5e05ea7d 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
@@ -453,6 +453,7 @@ def test_checkout_line_delete_triggers_webhooks(
"requestor_model_name": None,
"requestor_object_id": None,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
index 400538a99c..225bb8e6fb 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
@@ -2154,6 +2154,7 @@ def test_checkout_lines_add_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": user_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py
index 05dd693bc2..3bfee2ea6d 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py
@@ -417,6 +417,7 @@ def test_checkout_lines_delete_triggers_webhooks(
"requestor_model_name": None,
"requestor_object_id": None,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
index f602e5935b..84629bbaaf 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
@@ -1636,6 +1636,7 @@ def test_checkout_lines_update_triggers_webhooks(
"requestor_model_name": None,
"requestor_object_id": None,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
index d5a3e4032f..6c9ec32bc4 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
@@ -869,6 +869,7 @@ def test_checkout_remove_triggers_webhooks(
"requestor_model_name": None,
"requestor_object_id": None,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py
index af66f3e33a..5d0aee6329 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py
@@ -1204,6 +1204,7 @@ def test_checkout_shipping_address_update_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": user_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
index 6ca62c5a35..307d6e217b 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
@@ -658,6 +658,7 @@ def test_checkout_shipping_method_update_triggers_webhooks(
"requestor_model_name": None,
"requestor_object_id": None,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
@@ -757,6 +758,7 @@ def test_checkout_shipping_method_update_to_none_triggers_webhooks(
"requestor_model_name": None,
"requestor_object_id": None,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
index c907b391a7..01158cf694 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
@@ -1805,6 +1805,7 @@ def test_draft_order_complete_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": staff_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
index e80b3b4652..f8a172fc48 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -3784,6 +3784,7 @@ def test_draft_order_create_triggers_webhooks(
"requestor_model_name": "app.app",
"requestor_object_id": app_api_client.app.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_update.py b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
index 55011e2329..54c97bbbbd 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
@@ -2562,6 +2562,7 @@ def test_draft_order_update_triggers_webhooks(
"requestor_model_name": "app.app",
"requestor_object_id": app_api_client.app.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
@@ -2672,6 +2673,7 @@ def test_draft_order_update_triggers_webhooks_when_tax_webhook_not_needed(
"requestor_model_name": "app.app",
"requestor_object_id": app_api_client.app.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/order/tests/mutations/test_order_cancel.py b/saleor/graphql/order/tests/mutations/test_order_cancel.py
index 8a3d2b9155..8442286ff1 100644
--- a/saleor/graphql/order/tests/mutations/test_order_cancel.py
+++ b/saleor/graphql/order/tests/mutations/test_order_cancel.py
@@ -215,6 +215,7 @@ def test_order_cancel_skip_trigger_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": staff_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/order/tests/mutations/test_order_capture.py b/saleor/graphql/order/tests/mutations/test_order_capture.py
index 35b585e9bb..6b5d0ccd2a 100644
--- a/saleor/graphql/order/tests/mutations/test_order_capture.py
+++ b/saleor/graphql/order/tests/mutations/test_order_capture.py
@@ -270,6 +270,7 @@ def test_order_capture_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": staff_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/order/tests/mutations/test_order_confirm.py b/saleor/graphql/order/tests/mutations/test_order_confirm.py
index e39baac4d3..9e72308dd7 100644
--- a/saleor/graphql/order/tests/mutations/test_order_confirm.py
+++ b/saleor/graphql/order/tests/mutations/test_order_confirm.py
@@ -698,6 +698,7 @@ def test_order_confirm_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": staff_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/order/tests/mutations/test_order_fulfill.py b/saleor/graphql/order/tests/mutations/test_order_fulfill.py
index 43d6a1640a..ad723d896b 100644
--- a/saleor/graphql/order/tests/mutations/test_order_fulfill.py
+++ b/saleor/graphql/order/tests/mutations/test_order_fulfill.py
@@ -1610,6 +1610,7 @@ def test_order_fulfill_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": staff_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/order/tests/mutations/test_order_line_delete.py b/saleor/graphql/order/tests/mutations/test_order_line_delete.py
index 79d7b365e1..71c27e4864 100644
--- a/saleor/graphql/order/tests/mutations/test_order_line_delete.py
+++ b/saleor/graphql/order/tests/mutations/test_order_line_delete.py
@@ -382,6 +382,7 @@ def test_order_line_delete_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": staff_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/order/tests/mutations/test_order_line_update.py b/saleor/graphql/order/tests/mutations/test_order_line_update.py
index 80004002e0..973c621867 100644
--- a/saleor/graphql/order/tests/mutations/test_order_line_update.py
+++ b/saleor/graphql/order/tests/mutations/test_order_line_update.py
@@ -693,6 +693,7 @@ def test_order_line_update_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": staff_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/order/tests/mutations/test_order_lines_create.py b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
index 03d5050c34..bcf8ac4f2c 100644
--- a/saleor/graphql/order/tests/mutations/test_order_lines_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
@@ -1354,6 +1354,7 @@ def test_order_lines_create_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": staff_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/order/tests/mutations/test_order_note_add.py b/saleor/graphql/order/tests/mutations/test_order_note_add.py
index 1f6570085e..4e9fb2a59d 100644
--- a/saleor/graphql/order/tests/mutations/test_order_note_add.py
+++ b/saleor/graphql/order/tests/mutations/test_order_note_add.py
@@ -242,6 +242,7 @@ def test_order_note_add_user_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": staff_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/order/tests/mutations/test_order_note_update.py b/saleor/graphql/order/tests/mutations/test_order_note_update.py
index 5ac9812aa2..2636284e00 100644
--- a/saleor/graphql/order/tests/mutations/test_order_note_update.py
+++ b/saleor/graphql/order/tests/mutations/test_order_note_update.py
@@ -286,6 +286,7 @@ def test_order_note_update_user_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": staff_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/order/tests/mutations/test_order_update.py b/saleor/graphql/order/tests/mutations/test_order_update.py
index ce0e162f13..84d716328f 100644
--- a/saleor/graphql/order/tests/mutations/test_order_update.py
+++ b/saleor/graphql/order/tests/mutations/test_order_update.py
@@ -604,6 +604,7 @@ def test_order_update_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": staff_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/order/tests/mutations/test_order_update_shipping.py b/saleor/graphql/order/tests/mutations/test_order_update_shipping.py
index fc03f664e1..bb7ffcf8bc 100644
--- a/saleor/graphql/order/tests/mutations/test_order_update_shipping.py
+++ b/saleor/graphql/order/tests/mutations/test_order_update_shipping.py
@@ -729,6 +729,7 @@ def test_order_update_shipping_triggers_webhooks(
"requestor_model_name": "account.user",
"requestor_object_id": staff_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
@@ -825,6 +826,7 @@ def test_draft_order_update_shipping_triggers_proper_updated_webhook(
"requestor_model_name": "account.user",
"requestor_object_id": staff_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
@@ -893,6 +895,7 @@ def test_draft_order_update_shipping_triggers_proper_updated_webhook_for_null_sh
"requestor_model_name": "account.user",
"requestor_object_id": staff_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
@@ -963,6 +966,7 @@ def test_editable_order_update_shipping_triggers_proper_updated_webhook_for_null
"requestor_model_name": "account.user",
"requestor_object_id": staff_api_client.user.pk,
"request_time": None,
+ "subscribable_object_data": None,
},
"send_webhook_queue": settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
"telemetry_context": ANY,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index c0c0f5b09a..095591860f 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2051,6 +2051,7 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {
"""A product variant stock is updated"""
PRODUCT_VARIANT_STOCK_UPDATED
+ PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED
"""A new checkout is created."""
CHECKOUT_CREATED
@@ -2626,6 +2627,7 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {
"""A product variant stock is updated"""
PRODUCT_VARIANT_STOCK_UPDATED
+ PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED
"""A new checkout is created."""
CHECKOUT_CREATED
@@ -14145,6 +14147,7 @@ enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {
PRODUCT_VARIANT_OUT_OF_STOCK
PRODUCT_VARIANT_BACK_IN_STOCK
PRODUCT_VARIANT_STOCK_UPDATED
+ PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED
CHECKOUT_CREATED
CHECKOUT_UPDATED
CHECKOUT_FULLY_AUTHORIZED
@@ -33739,6 +33742,20 @@ type Subscription @doc(category: "Miscellaneous") {
"""
channels: [String!]
): CheckoutMetadataUpdated @doc(category: "Checkout")
+
+ """
+ Event sent when product variant discounted price is recalculated.
+
+ Added in Saleor 3.22.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ productVariantDiscountedPriceUpdated(
+ """
+ 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!]
+ ): ProductVariantDiscountedPriceUpdated @doc(category: "Products")
}
interface Event {
@@ -34127,6 +34144,37 @@ type CheckoutMetadataUpdated implements Event @doc(category: "Checkout") {
checkout: Checkout
}
+"""
+Event sent when product variant discounted price is recalculated.
+
+Added in Saleor 3.22.
+"""
+type ProductVariantDiscountedPriceUpdated implements Event @doc(category: "Products") {
+ """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: ProductVariant!
+
+ """The channel where the price changed."""
+ channel: Channel!
+
+ """The previous discounted price."""
+ previousPrice: Money!
+
+ """The new discounted price."""
+ newPrice: Money!
+}
+
enum DistanceUnitsEnum {
MM
CM
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index b064c3fb5f..d17195fc02 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -1,6 +1,10 @@
+from typing import TYPE_CHECKING
+
import graphene
from django.conf import settings
from graphene import AbstractType, Union
+from prices import Money
+from promise import Promise
from rx import Observable
from ... import __version__
@@ -37,6 +41,7 @@ from ...webhook.const import MAX_FILTERABLE_CHANNEL_SLUGS_LIMIT
from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ..account.types import User as UserType
from ..app.types import App as AppType
+from ..channel.dataloaders.by_self import ChannelBySlugLoader
from ..channel.enums import TransactionFlowStrategyEnum
from ..core import ResolveInfo
from ..core.context import (
@@ -49,6 +54,7 @@ from ..core.descriptions import (
ADDED_IN_319,
ADDED_IN_320,
ADDED_IN_321,
+ ADDED_IN_322,
DEPRECATED_IN_3X_EVENT,
PREVIEW_FEATURE,
)
@@ -77,6 +83,10 @@ from ..shipping.types import ShippingMethod
from ..translations import types as translation_types
from ..warehouse.dataloaders import WarehouseByIdLoader
+if TYPE_CHECKING:
+ from ...channel.models import Channel
+ from ...product.interface import VariantDiscountedPriceChange
+
TRANSLATIONS_TYPES_MAP = {
ProductTranslation: translation_types.ProductTranslation,
CollectionTranslation: translation_types.CollectionTranslation,
@@ -1043,6 +1053,80 @@ class ProductVariantStockUpdated(SubscriptionObjectType, ProductVariantBase):
return WarehouseByIdLoader(info.context).load(stock.warehouse_id)
+class ProductVariantDiscountedPriceUpdated(SubscriptionObjectType):
+ product_variant = graphene.Field(
+ "saleor.graphql.product.types.ProductVariant",
+ description="The product variant the event relates to.",
+ required=True,
+ )
+ channel = graphene.Field(
+ "saleor.graphql.channel.types.Channel",
+ description="The channel where the price changed.",
+ required=True,
+ )
+ previous_price = graphene.Field(
+ "saleor.graphql.core.types.money.Money",
+ description="The previous discounted price.",
+ required=True,
+ )
+ new_price = graphene.Field(
+ "saleor.graphql.core.types.money.Money",
+ description="The new discounted price.",
+ required=True,
+ )
+
+ class Meta:
+ root_type = None
+ enable_dry_run = False
+ interfaces = (Event,)
+ description = (
+ "Event sent when product variant discounted price is recalculated."
+ + ADDED_IN_322
+ )
+ doc_category = DOC_CATEGORY_PRODUCTS
+
+ @staticmethod
+ def resolve_product_variant(
+ root: tuple[str, "VariantDiscountedPriceChange"],
+ info: ResolveInfo,
+ ) -> Promise["ChannelContext"]:
+ _, price_info = root
+ channel_slug = price_info.channel_slug
+ return (
+ ProductVariantByIdLoader(info.context)
+ .load(price_info.variant_id)
+ .then(
+ lambda variant: ChannelContext(node=variant, channel_slug=channel_slug)
+ )
+ )
+
+ @staticmethod
+ def resolve_channel(
+ root: tuple[str, "VariantDiscountedPriceChange"],
+ info: ResolveInfo,
+ ) -> Promise["Channel"]:
+ _, price_info = root
+ return ChannelBySlugLoader(info.context).load(price_info.channel_slug)
+
+ @staticmethod
+ def resolve_previous_price(
+ root: tuple[str, "VariantDiscountedPriceChange"],
+ _info: ResolveInfo,
+ ) -> Money:
+ _, price_info = root
+ return Money(
+ amount=price_info.previous_price_amount, currency=price_info.currency
+ )
+
+ @staticmethod
+ def resolve_new_price(
+ root: tuple[str, "VariantDiscountedPriceChange"],
+ _info: ResolveInfo,
+ ) -> Money:
+ _, price_info = root
+ return Money(amount=price_info.new_price_amount, currency=price_info.currency)
+
+
class ProductExportCompleted(SubscriptionObjectType):
export = graphene.Field(
"saleor.graphql.csv.types.ExportFile",
@@ -2819,6 +2903,17 @@ class Subscription(SubscriptionObjectType):
channels=channels_argument,
doc_category=DOC_CATEGORY_CHECKOUT,
)
+ product_variant_discounted_price_updated = BaseField(
+ ProductVariantDiscountedPriceUpdated,
+ description=(
+ "Event sent when product variant discounted price is recalculated."
+ + ADDED_IN_322
+ + PREVIEW_FEATURE
+ ),
+ resolver=default_channel_filterable_resolver,
+ channels=channels_argument,
+ doc_category=DOC_CATEGORY_PRODUCTS,
+ )
class Meta:
doc_category = DOC_CATEGORY_MISC
@@ -2999,6 +3094,7 @@ ASYNC_WEBHOOK_TYPES_MAP = {
WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK: ProductVariantOutOfStock,
WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK: ProductVariantBackInStock,
WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED: ProductVariantStockUpdated,
+ WebhookEventAsyncType.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED: ProductVariantDiscountedPriceUpdated,
WebhookEventAsyncType.PRODUCT_VARIANT_DELETED: ProductVariantDeleted,
WebhookEventAsyncType.PRODUCT_VARIANT_METADATA_UPDATED: (
ProductVariantMetadataUpdated
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 8ab37c3998..255531c37c 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -1332,6 +1332,12 @@ class BasePlugin:
# Webhook-related functionality will be moved from the plugin to core modules.
product_variant_updated: Callable[["ProductVariant", Any, None], Any]
+ # Trigger when product variant discounted price is recalculated.
+ #
+ # Overwrite this method if you need to trigger specific logic after a product
+ # variant price is updated.
+ product_variant_discounted_price_updated: Callable[[Any, Any, None], Any]
+
# Trigger when product variant metadata is updated.
#
# Overwrite this method if you need to trigger specific logic after a product
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index c445cf87a8..f1d780de6b 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -866,6 +866,18 @@ class PluginsManager(PaymentInterface):
channel_slug=None,
)
+ def product_variant_discounted_price_updated(
+ self, variant_price_info, webhooks=None
+ ):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "product_variant_discounted_price_updated",
+ default_value,
+ variant_price_info,
+ webhooks=webhooks,
+ channel_slug=None,
+ )
+
# Note: this method is deprecated and will be removed in a future release.
# Webhook-related functionality will be moved from plugin to core modules.
def product_variant_deleted(self, product_variant: "ProductVariant", webhooks=None):
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 2692886a2f..c67119a557 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -1957,6 +1957,25 @@ class WebhookPlugin(BasePlugin):
)
return previous_value
+ def product_variant_discounted_price_updated(
+ self, variant_price_info, previous_value: None, webhooks=None
+ ) -> None:
+ if not self.active:
+ return previous_value
+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED
+ channel_slug = variant_price_info.channel_slug
+ if webhooks := self._get_webhooks_for_channel_events(
+ event_type, channel_slug, webhooks
+ ):
+ self.trigger_webhooks_async(
+ None,
+ event_type,
+ webhooks,
+ variant_price_info,
+ self.requestor,
+ )
+ return previous_value
+
def product_variant_deleted(
self, product_variant: "ProductVariant", previous_value: None, webhooks=None
) -> None:
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_product_variant_discounted_price_updated.py b/saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_product_variant_discounted_price_updated.py
new file mode 100644
index 0000000000..f07e6d7aff
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_product_variant_discounted_price_updated.py
@@ -0,0 +1,212 @@
+import json
+from decimal import Decimal
+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 ......product.interface import VariantDiscountedPriceChange
+from ......webhook.event_types import WebhookEventAsyncType
+from .....manager import get_plugins_manager
+
+PRICE_UPDATED_SUBSCRIPTION = """
+subscription {
+ productVariantDiscountedPriceUpdated(channels: ["%s"]) {
+ ... on ProductVariantDiscountedPriceUpdated {
+ productVariant {
+ id
+ pricing {
+ price {
+ gross {
+ amount
+ }
+ }
+ }
+ }
+ channel {
+ slug
+ }
+ previousPrice {
+ amount
+ currency
+ }
+ newPrice {
+ amount
+ currency
+ }
+ }
+ }
+}"""
+
+
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
+)
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
+def test_product_variant_discounted_price_updated(
+ mocked_async, variant_with_many_stocks, channel_USD, subscription_webhook
+):
+ # given
+ manager = get_plugins_manager(False)
+ variant = variant_with_many_stocks
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED
+
+ query = PRICE_UPDATED_SUBSCRIPTION % channel_USD.slug
+ webhook = subscription_webhook(query, event_type)
+ subscription_query = SubscriptionQuery(query)
+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()
+ webhook.save()
+
+ previous_price = Decimal("10.00")
+ new_price = Decimal("8.00")
+ currency = channel_USD.currency_code
+
+ price_info = VariantDiscountedPriceChange(
+ variant_id=variant.id,
+ channel_slug=channel_USD.slug,
+ previous_price_amount=previous_price,
+ new_price_amount=new_price,
+ currency=currency,
+ )
+
+ # when
+ manager.product_variant_discounted_price_updated(price_info)
+
+ # then
+ deliveries = EventDelivery.objects.all()
+ assert len(deliveries) == 1
+ payload = json.loads(deliveries[0].payload.get_payload())
+ event_data = payload["data"]["productVariantDiscountedPriceUpdated"]
+ assert event_data["productVariant"]["id"] == variant_id
+ variant_channel_listing = variant.channel_listings.get(channel=channel_USD)
+ assert (
+ event_data["productVariant"]["pricing"]["price"]["gross"]["amount"]
+ == variant_channel_listing.discounted_price_amount
+ )
+ assert event_data["channel"] == {"slug": channel_USD.slug}
+ assert event_data["previousPrice"] == {
+ "amount": previous_price,
+ "currency": currency,
+ }
+ assert event_data["newPrice"] == {"amount": new_price, "currency": currency}
+ 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"])
+def test_product_variant_discounted_price_updated_with_different_channel(
+ mocked_async,
+ mocked_create_event_delivery_list_for_webhooks,
+ variant_with_many_stocks,
+ channel_USD,
+ channel_PLN,
+ subscription_webhook,
+):
+ # given
+ manager = get_plugins_manager(False)
+ variant = variant_with_many_stocks
+
+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED
+
+ query = PRICE_UPDATED_SUBSCRIPTION % channel_PLN.slug
+ webhook = subscription_webhook(query, event_type)
+ subscription_query = SubscriptionQuery(query)
+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()
+ webhook.save()
+
+ price_info = VariantDiscountedPriceChange(
+ variant_id=variant.id,
+ channel_slug=channel_USD.slug,
+ previous_price_amount=Decimal("10.00"),
+ new_price_amount=Decimal("8.00"),
+ currency=channel_USD.currency_code,
+ )
+
+ # when
+ manager.product_variant_discounted_price_updated(price_info)
+
+ # 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.send_webhook_request_async.apply_async"
+)
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
+def test_product_variant_discounted_price_updated_without_channels_input(
+ mocked_async, variant_with_many_stocks, channel_USD, subscription_webhook
+):
+ # given
+ manager = get_plugins_manager(False)
+ variant = variant_with_many_stocks
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED
+
+ query = """subscription {
+ productVariantDiscountedPriceUpdated {
+ ... on ProductVariantDiscountedPriceUpdated {
+ productVariant {
+ id
+ }
+ channel {
+ slug
+ }
+ previousPrice {
+ amount
+ currency
+ }
+ newPrice {
+ amount
+ currency
+ }
+ }
+ }
+ }"""
+ webhook = subscription_webhook(query, event_type)
+ subscription_query = SubscriptionQuery(query)
+ webhook.filterable_channel_slugs = subscription_query.get_filterable_channel_slugs()
+ webhook.save()
+
+ previous_price = Decimal("10.00")
+ new_price = Decimal("8.00")
+ currency = channel_USD.currency_code
+
+ price_info = VariantDiscountedPriceChange(
+ variant_id=variant.id,
+ channel_slug=channel_USD.slug,
+ previous_price_amount=previous_price,
+ new_price_amount=new_price,
+ currency=currency,
+ )
+
+ # when
+ manager.product_variant_discounted_price_updated(price_info)
+
+ # then
+ deliveries = EventDelivery.objects.all()
+ assert len(deliveries) == 1
+ payload = json.loads(deliveries[0].payload.get_payload())
+ event_data = payload["data"]["productVariantDiscountedPriceUpdated"]
+ assert event_data["productVariant"]["id"] == variant_id
+ assert event_data["channel"] == {"slug": channel_USD.slug}
+ assert event_data["previousPrice"] == {
+ "amount": previous_price,
+ "currency": currency,
+ }
+ assert event_data["newPrice"] == {"amount": new_price, "currency": currency}
+ assert deliveries[0].webhook == webhook
+ assert mocked_async.called
diff --git a/saleor/product/interface.py b/saleor/product/interface.py
new file mode 100644
index 0000000000..5bb3463b51
--- /dev/null
+++ b/saleor/product/interface.py
@@ -0,0 +1,20 @@
+from dataclasses import dataclass
+from decimal import Decimal
+
+
+@dataclass
+class VariantDiscountedPriceChange:
+ variant_id: int
+ channel_slug: str
+ previous_price_amount: Decimal
+ new_price_amount: Decimal
+ currency: str
+
+ @property
+ def pk(self) -> tuple[int, str]:
+ """Required by deferred payload mechanism to group deliveries per object.
+
+ Uses (variant_id, channel_slug) because the same variant can have
+ separate price change events for different channels.
+ """
+ return (self.variant_id, self.channel_slug)
diff --git a/saleor/product/tasks.py b/saleor/product/tasks.py
index 03997d21a9..1cf54f0fa4 100644
--- a/saleor/product/tasks.py
+++ b/saleor/product/tasks.py
@@ -15,6 +15,7 @@ from ..celeryconf import app
from ..core.db.connection import allow_writer
from ..core.exceptions import PreorderAllocationError
from ..core.http_client import HTTPClient
+from ..core.utils.events import call_event
from ..core.utils.validators import get_mime_type
from ..discount import PromotionType
from ..discount.models import Promotion, PromotionRule
@@ -23,6 +24,7 @@ from ..product import ProductMediaTypes
from ..warehouse.management import deactivate_preorder_for_variant
from ..webhook.event_types import WebhookEventAsyncType
from ..webhook.utils import get_webhooks_for_event
+from .interface import VariantDiscountedPriceChange
from .lock_objects import product_qs_select_for_update
from .models import (
Product,
@@ -247,6 +249,25 @@ def update_products_discounted_prices_for_promotion_task(
PromotionRule.objects.filter(variants_dirty=False).update(variants_dirty=True)
+def _send_variant_price_updated_webhooks(
+ changed_prices: list[VariantDiscountedPriceChange],
+) -> None:
+ if not changed_prices:
+ return
+ webhooks = get_webhooks_for_event(
+ WebhookEventAsyncType.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED
+ )
+ if not webhooks:
+ return
+ manager = get_plugins_manager(allow_replica=True)
+ for price_info in changed_prices:
+ call_event(
+ manager.product_variant_discounted_price_updated,
+ price_info,
+ webhooks=webhooks,
+ )
+
+
@app.task
@allow_writer()
def recalculate_discounted_price_for_products_task():
@@ -266,7 +287,10 @@ def recalculate_discounted_price_for_products_task():
products = Product.objects.using(
settings.DATABASE_CONNECTION_REPLICA_NAME
).filter(id__in=products_ids)
- update_discounted_prices_for_promotion(products, only_dirty_products=True)
+ changed_prices = update_discounted_prices_for_promotion(
+ products, only_dirty_products=True
+ )
+ _send_variant_price_updated_webhooks(changed_prices)
with transaction.atomic():
channel_listings_ids = list(
ProductChannelListing.objects.select_for_update(of=("self",))
diff --git a/saleor/product/tests/test_product_minimal_variant_price.py b/saleor/product/tests/test_product_minimal_variant_price.py
index 27e19a1d43..1882a7d0f8 100644
--- a/saleor/product/tests/test_product_minimal_variant_price.py
+++ b/saleor/product/tests/test_product_minimal_variant_price.py
@@ -9,7 +9,13 @@ from prices import Money
from ...discount import RewardValueType
from ...discount.models import Promotion, PromotionRule
-from ...product.models import Product, VariantChannelListingPromotionRule
+from ...product.interface import VariantDiscountedPriceChange
+from ...product.models import (
+ Product,
+ ProductChannelListing,
+ ProductVariantChannelListing,
+ VariantChannelListingPromotionRule,
+)
from ...tests import race_condition
from ..utils.variant_prices import update_discounted_prices_for_promotion
@@ -663,3 +669,138 @@ def test_update_discounted_prices_for_promotion_only_dirty_products(
)
second_listing.refresh_from_db()
assert second_listing.discounted_price_amount == second_channel_discounted_price
+
+
+def test_update_discounted_prices_returns_changed_prices_when_discount_applied(
+ product, channel_USD
+):
+ # given
+ variant = product.variants.first()
+ variant_channel_listing = variant.channel_listings.get(channel_id=channel_USD.id)
+ variant_price = Money("9.99", "USD")
+ variant_channel_listing.price = variant_price
+ variant_channel_listing.discounted_price = variant_price
+ variant_channel_listing.save()
+
+ reward_value = Decimal(2)
+ promotion = Promotion.objects.create(name="Promotion")
+ rule = promotion.rules.create(
+ name="Fixed promotion rule",
+ promotion=promotion,
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant.id)]
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ )
+ rule.channels.add(channel_USD)
+ rule.variants.add(variant)
+
+ # when
+ changed_prices = update_discounted_prices_for_promotion(
+ Product.objects.filter(id__in=[product.id])
+ )
+
+ # then
+ assert len(changed_prices) == 1
+ cp = changed_prices[0]
+ assert isinstance(cp, VariantDiscountedPriceChange)
+ assert cp.variant_id == variant.id
+ assert cp.channel_slug == channel_USD.slug
+ assert cp.currency == channel_USD.currency_code
+ assert cp.previous_price_amount == variant_price.amount
+ assert cp.new_price_amount == variant_price.amount - reward_value
+
+
+def test_update_discounted_prices_returns_empty_when_prices_unchanged(
+ product, channel_USD
+):
+ # given
+ variant = product.variants.first()
+ variant_channel_listing = variant.channel_listings.get(channel_id=channel_USD.id)
+
+ # Ensure discounted_price already equals price (no promotion)
+ variant_channel_listing.discounted_price_amount = (
+ variant_channel_listing.price_amount
+ )
+ variant_channel_listing.save()
+
+ # when
+ changed_prices = update_discounted_prices_for_promotion(
+ Product.objects.filter(id__in=[product.id])
+ )
+
+ # then
+ assert changed_prices == []
+
+
+def test_update_discounted_prices_returns_changed_prices_for_multiple_channels(
+ product, channel_USD, channel_PLN
+):
+ # given
+ variant = product.variants.first()
+ variant_channel_listing_usd = variant.channel_listings.get(
+ channel_id=channel_USD.id
+ )
+ variant_price_usd = Money("9.99", "USD")
+ variant_channel_listing_usd.price = variant_price_usd
+ variant_channel_listing_usd.discounted_price = variant_price_usd
+ variant_channel_listing_usd.save()
+
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_PLN,
+ is_published=True,
+ discounted_price_amount=Decimal("40.00"),
+ currency=channel_PLN.currency_code,
+ visible_in_listings=True,
+ available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
+ )
+ variant_price_pln = Decimal("40.00")
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_PLN,
+ price_amount=variant_price_pln,
+ discounted_price_amount=variant_price_pln,
+ currency=channel_PLN.currency_code,
+ )
+
+ reward_value = Decimal(2)
+ promotion = Promotion.objects.create(name="Promotion")
+ rule = promotion.rules.create(
+ name="Fixed promotion rule",
+ promotion=promotion,
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant.id)]
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ )
+ rule.channels.add(channel_USD, channel_PLN)
+ rule.variants.add(variant)
+
+ # when
+ changed_prices = update_discounted_prices_for_promotion(
+ Product.objects.filter(id__in=[product.id])
+ )
+
+ # then
+ assert len(changed_prices) == 2
+
+ prices_by_channel = {cp.channel_slug: cp for cp in changed_prices}
+
+ cp_usd = prices_by_channel[channel_USD.slug]
+ assert cp_usd.variant_id == variant.id
+ assert cp_usd.currency == channel_USD.currency_code
+ assert cp_usd.previous_price_amount == variant_price_usd.amount
+ assert cp_usd.new_price_amount == variant_price_usd.amount - reward_value
+
+ cp_pln = prices_by_channel[channel_PLN.slug]
+ assert cp_pln.variant_id == variant.id
+ assert cp_pln.currency == channel_PLN.currency_code
+ assert cp_pln.previous_price_amount == variant_price_pln
+ assert cp_pln.new_price_amount == variant_price_pln - reward_value
diff --git a/saleor/product/tests/test_tasks.py b/saleor/product/tests/test_tasks.py
index 9ffe71973e..2b1cc5851d 100644
--- a/saleor/product/tests/test_tasks.py
+++ b/saleor/product/tests/test_tasks.py
@@ -13,6 +13,7 @@ from requests.exceptions import HTTPError, InvalidSchema, RequestException
from ...discount import PromotionType, RewardValueType
from ...discount.models import Promotion, PromotionRule
+from ..interface import VariantDiscountedPriceChange
from ..models import (
Product,
ProductChannelListing,
@@ -199,7 +200,7 @@ def test_recalculate_discounted_price_for_products_task(
assert recalculate_discounted_price_for_products_task_mock.called
-@patch("saleor.product.tasks.update_discounted_prices_for_promotion")
+@patch("saleor.product.tasks.update_discounted_prices_for_promotion", return_value=[])
@patch("saleor.product.tasks.recalculate_discounted_price_for_products_task.delay")
def test_recalculate_discounted_price_for_products_task_with_correct_prices(
recalculate_discounted_price_for_products_task_mock,
@@ -217,7 +218,7 @@ def test_recalculate_discounted_price_for_products_task_with_correct_prices(
assert not update_discounted_prices_for_promotion_mock.called
-@patch("saleor.product.tasks.update_discounted_prices_for_promotion")
+@patch("saleor.product.tasks.update_discounted_prices_for_promotion", return_value=[])
@patch("saleor.product.tasks.recalculate_discounted_price_for_products_task.delay")
def test_recalculate_discounted_price_for_products_task_updates_only_dirty_listings(
recalculate_discounted_price_for_products_task_mock,
@@ -644,3 +645,68 @@ def test_fetch_product_media_image_client_error_does_not_retry(
# then
assert not ProductMedia.objects.filter(pk=product_media.pk).exists()
+
+
+@patch("saleor.product.tasks.call_event")
+@patch("saleor.product.tasks.get_plugins_manager")
+@patch("saleor.product.tasks.get_webhooks_for_event")
+@patch("saleor.product.tasks.recalculate_discounted_price_for_products_task.delay")
+def test_recalculate_discounted_price_triggers_variant_price_updated_webhook(
+ recalculate_task_mock,
+ get_webhooks_mock,
+ get_manager_mock,
+ call_event_mock,
+ product_list,
+ channel_USD,
+):
+ # given
+ variant_listings = ProductVariantChannelListing.objects.filter(
+ variant__product__in=product_list
+ )
+ expected_prices = {
+ listing.variant_id: listing.price_amount for listing in variant_listings
+ }
+ current_price = Decimal(1)
+ ProductChannelListing.objects.update(
+ discounted_price_amount=current_price, discounted_price_dirty=True
+ )
+ ProductVariantChannelListing.objects.update(discounted_price_amount=current_price)
+
+ mock_webhooks = [patch]
+ get_webhooks_mock.return_value = mock_webhooks
+
+ # when
+ recalculate_discounted_price_for_products_task()
+
+ # then
+ assert call_event_mock.called
+ calls = call_event_mock.call_args_list
+ assert len(calls) == len(expected_prices)
+ for call in calls:
+ price_info = call[0][1]
+ assert isinstance(price_info, VariantDiscountedPriceChange)
+ assert price_info.channel_slug == channel_USD.slug
+ assert price_info.currency == channel_USD.currency_code
+ assert price_info.previous_price_amount == current_price
+ assert price_info.new_price_amount == expected_prices[price_info.variant_id]
+
+
+@patch("saleor.product.tasks.call_event")
+@patch("saleor.product.tasks.get_webhooks_for_event")
+@patch("saleor.product.tasks.update_discounted_prices_for_promotion", return_value=[])
+@patch("saleor.product.tasks.recalculate_discounted_price_for_products_task.delay")
+def test_recalculate_discounted_price_no_webhook_when_prices_unchanged(
+ recalculate_task_mock,
+ update_prices_mock,
+ get_webhooks_mock,
+ call_event_mock,
+ product_list,
+):
+ # given
+ ProductChannelListing.objects.update(discounted_price_dirty=True)
+
+ # when
+ recalculate_discounted_price_for_products_task()
+
+ # then
+ assert not call_event_mock.called
diff --git a/saleor/product/utils/variant_prices.py b/saleor/product/utils/variant_prices.py
index f4cf1e96bd..7d6a57de5f 100644
--- a/saleor/product/utils/variant_prices.py
+++ b/saleor/product/utils/variant_prices.py
@@ -1,5 +1,6 @@
from collections import defaultdict
from decimal import Decimal
+from typing import cast
from uuid import UUID
from django.conf import settings
@@ -15,6 +16,7 @@ from ...discount.utils.promotion import (
calculate_discounted_price_for_promotions,
get_variants_to_promotion_rules_map,
)
+from ..interface import VariantDiscountedPriceChange
from ..managers import ProductsQueryset, ProductVariantQueryset
from ..models import (
ProductChannelListing,
@@ -26,7 +28,7 @@ from ..models import (
def update_discounted_prices_for_promotion(
products: ProductsQueryset, only_dirty_products: bool = False
-):
+) -> list[VariantDiscountedPriceChange]:
"""Update Products and ProductVariants discounted prices.
The discounted price is the minimal price of the product/variant based on active
@@ -37,6 +39,9 @@ def update_discounted_prices_for_promotion(
When only_dirty_products set to True, the prices will be recalculated only for the
listings marked as dirty.
+
+ Returns a list of VariantDiscountedPriceChange for variants whose discounted price
+ changed.
"""
variant_qs = ProductVariant.objects.using(
settings.DATABASE_CONNECTION_REPLICA_NAME
@@ -55,6 +60,8 @@ def update_discounted_prices_for_promotion(
changed_variant_listing_promotion_rule_to_create = []
changed_variant_listing_promotion_rule_to_update = []
+ changed_variant_prices: list[VariantDiscountedPriceChange] = []
+
product_channel_listings = (
ProductChannelListing.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
.filter(Exists(products.filter(id=OuterRef("product_id"))))
@@ -76,6 +83,7 @@ def update_discounted_prices_for_promotion(
variant_listings_to_update,
variant_listing_promotion_rule_to_create,
variant_listing_promotion_rule_to_update,
+ variant_price_changes,
) = _get_discounted_variants_prices_for_promotions(
variant_listings,
rules_info_per_variant,
@@ -92,6 +100,8 @@ def update_discounted_prices_for_promotion(
variant_listing_promotion_rule_to_update
)
+ changed_variant_prices.extend(variant_price_changes)
+
# check if the product discounted_price has changed
if product_channel_listing.discounted_price != product_discounted_price:
product_channel_listing.discounted_price_amount = (
@@ -106,6 +116,8 @@ def update_discounted_prices_for_promotion(
changed_variant_listing_promotion_rule_to_update,
)
+ return changed_variant_prices
+
def _update_or_create_listings(
changed_products_listings_to_update: list[ProductChannelListing],
@@ -245,10 +257,11 @@ def _get_discounted_variants_prices_for_promotions(
channel: Channel,
variant_listing_to_listing_rule_per_rule_map: dict,
) -> tuple[
- Money,
+ list[Money],
list[ProductVariantChannelListing],
list[VariantChannelListingPromotionRule],
list[VariantChannelListingPromotionRule],
+ list[VariantDiscountedPriceChange],
]:
variants_listings_to_update: list[ProductVariantChannelListing] = []
discounted_variants_price: list[Money] = []
@@ -258,6 +271,8 @@ def _get_discounted_variants_prices_for_promotions(
variant_listing_promotion_rule_to_update: list[
VariantChannelListingPromotionRule
] = []
+ variant_price_changes: list[VariantDiscountedPriceChange] = []
+
for variant_listing in variant_listings:
applied_discount = calculate_discounted_price_for_promotions(
price=variant_listing.price,
@@ -286,6 +301,22 @@ def _get_discounted_variants_prices_for_promotions(
)
if variant_listing.discounted_price != discounted_variant_price:
+ previous_price_amount = cast(
+ Decimal,
+ variant_listing.discounted_price_amount
+ if variant_listing.discounted_price_amount is not None
+ else variant_listing.price_amount,
+ )
+ variant_price_changes.append(
+ VariantDiscountedPriceChange(
+ variant_id=variant_listing.variant_id,
+ channel_slug=channel.slug,
+ previous_price_amount=previous_price_amount,
+ new_price_amount=discounted_variant_price.amount,
+ currency=channel.currency_code,
+ )
+ )
+
variant_listing.discounted_price_amount = discounted_variant_price.amount
variants_listings_to_update.append(variant_listing)
@@ -302,6 +333,7 @@ def _get_discounted_variants_prices_for_promotions(
variants_listings_to_update,
variant_listing_promotion_rule_to_create,
variant_listing_promotion_rule_to_update,
+ variant_price_changes,
)
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index 4a7454e25f..aba8867221 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -142,6 +142,9 @@ 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"
+ PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED = (
+ "product_variant_discounted_price_updated"
+ )
CHECKOUT_CREATED = "checkout_created"
CHECKOUT_UPDATED = "checkout_updated"
@@ -616,6 +619,11 @@ class WebhookEventAsyncType:
"name": "Product variant stock updated",
"permission": ProductPermissions.MANAGE_PRODUCTS,
},
+ PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED: {
+ "name": "Product variant discounted price updated",
+ "permission": ProductPermissions.MANAGE_PRODUCTS,
+ "is_deferred_payload": True,
+ },
CHECKOUT_CREATED: {
"name": "Checkout created",
"permission": CheckoutPermissions.MANAGE_CHECKOUTS,
diff --git a/saleor/webhook/tests/fixtures/subscription_webhooks.py b/saleor/webhook/tests/fixtures/subscription_webhooks.py
index ac80791771..d31c542683 100644
--- a/saleor/webhook/tests/fixtures/subscription_webhooks.py
+++ b/saleor/webhook/tests/fixtures/subscription_webhooks.py
@@ -480,6 +480,14 @@ def subscription_product_variant_stock_updated_webhook(subscription_webhook):
)
+def subscription_product_variant_discounted_price_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ queries.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED,
+ WebhookEventAsyncType.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED,
+ )
+
+
@pytest.fixture
def subscription_order_created_webhook(subscription_webhook):
return subscription_webhook(
diff --git a/saleor/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/webhook/tests/subscription_webhooks/subscription_queries.py
index 067523249e..bb4315dbe4 100644
--- a/saleor/webhook/tests/subscription_webhooks/subscription_queries.py
+++ b/saleor/webhook/tests/subscription_webhooks/subscription_queries.py
@@ -1231,7 +1231,6 @@ PRODUCT_VARIANT_UPDATED = """
}
"""
-
PRODUCT_VARIANT_DELETED = """
subscription{
event{
@@ -1295,6 +1294,36 @@ PRODUCT_VARIANT_STOCK_UPDATED = """
}
"""
+PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED = """
+ subscription{
+ event{
+ ...on ProductVariantDiscountedPriceUpdated{
+ productVariant{
+ id
+ pricing{
+ price{
+ gross{
+ amount
+ }
+ }
+ }
+ }
+ channel{
+ slug
+ }
+ previousPrice{
+ amount
+ currency
+ }
+ newPrice{
+ amount
+ currency
+ }
+ }
+ }
+ }
+"""
+
ORDER_CREATED = """
subscription{
event{
diff --git a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
index 206c445d57..196a1a1a86 100644
--- a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
+++ b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
@@ -11,6 +11,7 @@ from ....channel.models import Channel
from ....giftcard.models import GiftCard
from ....graphql.webhook.subscription_query import SubscriptionQuery
from ....menu.models import Menu, MenuItem
+from ....product.interface import VariantDiscountedPriceChange
from ....product.models import Category
from ....shipping.models import (
ShippingMethod,
@@ -1550,6 +1551,57 @@ def test_product_variant_stock_updated(
assert deliveries[0].webhook == webhooks[0]
+def test_product_variant_discounted_price_updated(
+ variant_with_many_stocks,
+ channel_USD,
+ subscription_product_variant_discounted_price_updated_webhook,
+):
+ # given
+ webhooks = [subscription_product_variant_discounted_price_updated_webhook]
+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED
+ variant = variant_with_many_stocks
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ previous_price = Decimal("10.00")
+ new_price = Decimal("8.00")
+ currency = channel_USD.currency_code
+
+ price_info = VariantDiscountedPriceChange(
+ variant_id=variant.id,
+ channel_slug=channel_USD.slug,
+ previous_price_amount=previous_price,
+ new_price_amount=new_price,
+ currency=currency,
+ )
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, price_info, webhooks)
+
+ # then
+ payload = json.loads(deliveries[0].payload.get_payload())
+ variant_channel_listing = variant.channel_listings.get(channel=channel_USD)
+ assert payload == {
+ "productVariant": {
+ "id": variant_id,
+ "pricing": {
+ "price": {
+ "gross": {
+ "amount": variant_channel_listing.discounted_price_amount,
+ }
+ }
+ },
+ },
+ "channel": {"slug": channel_USD.slug},
+ "previousPrice": {
+ "amount": previous_price,
+ "currency": currency,
+ },
+ "newPrice": {"amount": new_price, "currency": currency},
+ }
+ 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/transport/asynchronous/tests/test_deferred_payload.py b/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py
index 67ae46314d..ca7c83b91d 100644
--- a/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py
+++ b/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py
@@ -2,8 +2,10 @@ import datetime
import json
import uuid
from dataclasses import asdict
+from decimal import Decimal
from unittest import mock
+import graphene
import pytest
from celery.exceptions import Retry
from django.test import override_settings
@@ -13,10 +15,15 @@ from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....core import EventDeliveryStatus
from .....core.models import EventDelivery
from .....core.telemetry import get_task_context
+from .....product.interface import VariantDiscountedPriceChange
from ....event_types import WebhookEventAsyncType
+from ....tests.subscription_webhooks.subscription_queries import (
+ PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED,
+)
from ....utils import get_webhooks_for_event
from ..transport import (
DeferredPayloadData,
+ _reconstruct_subscribable_object,
generate_deferred_payloads,
trigger_webhooks_async,
)
@@ -318,3 +325,166 @@ def test_pass_queue_to_send_webhook_request_async(
mocked_send_webhook_request_async.call_args.kwargs
)
assert call_kwargs_send_webhook_request["queue"] == queue
+
+
+ "saleor.webhook.transport.asynchronous.transport"
+ ".generate_deferred_payloads.apply_async"
+)
+def test_call_trigger_webhook_async_deferred_payload_with_dataclass(
+ mocked_generate_deferred_payloads,
+ variant_with_many_stocks,
+ channel_USD,
+ subscription_webhook,
+ staff_user,
+):
+ # given
+ variant = variant_with_many_stocks
+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED
+
+ webhook = subscription_webhook(PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED, event_type)
+ webhooks = get_webhooks_for_event(event_type)
+
+ previous_price = Decimal("10.00")
+ new_price = Decimal("8.00")
+ currency = channel_USD.currency_code
+
+ price_info = VariantDiscountedPriceChange(
+ variant_id=variant.id,
+ channel_slug=channel_USD.slug,
+ previous_price_amount=previous_price,
+ new_price_amount=new_price,
+ currency=currency,
+ )
+
+ # when
+ trigger_webhooks_async(
+ data=None,
+ event_type=event_type,
+ webhooks=webhooks,
+ subscribable_object=price_info,
+ requestor=staff_user,
+ )
+
+ # then
+ delivery = webhook.eventdelivery_set.first()
+ call_kwargs = mocked_generate_deferred_payloads.call_args.kwargs
+ deferred_payload_data = call_kwargs["kwargs"]["deferred_payload_data"]
+
+ assert deferred_payload_data["model_name"] is None
+ assert deferred_payload_data["object_id"] is None
+ assert deferred_payload_data["subscribable_object_data"] == {
+ "variant_id": variant.id,
+ "channel_slug": channel_USD.slug,
+ "previous_price_amount": str(previous_price),
+ "new_price_amount": str(new_price),
+ "currency": currency,
+ }
+ assert deferred_payload_data["requestor_model_name"] == "account.user"
+ assert deferred_payload_data["requestor_object_id"] == staff_user.pk
+ assert call_kwargs["kwargs"]["event_delivery_ids"] == [delivery.id]
+
+ assert delivery.event_type == event_type
+ assert delivery.payload is None
+ assert delivery.webhook == webhook
+
+
+ "saleor.webhook.transport.asynchronous.transport"
+ ".send_webhook_request_async.apply_async"
+)
+def test_generate_deferred_payload_with_dataclass(
+ mocked_send_webhook_request_async,
+ variant_with_many_stocks,
+ channel_USD,
+ subscription_webhook,
+ staff_user,
+):
+ # given
+ variant = variant_with_many_stocks
+ variant_global_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED
+
+ webhook = subscription_webhook(PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED, event_type)
+
+ previous_price = Decimal("10.00")
+ new_price = Decimal("8.00")
+ currency = channel_USD.currency_code
+
+ deferred_payload_data = DeferredPayloadData(
+ subscribable_object_data={
+ "variant_id": variant.id,
+ "channel_slug": channel_USD.slug,
+ "previous_price_amount": str(previous_price),
+ "new_price_amount": str(new_price),
+ "currency": currency,
+ },
+ requestor_model_name="account.user",
+ requestor_object_id=staff_user.pk,
+ request_time=None,
+ )
+ delivery = EventDelivery(
+ event_type=event_type,
+ webhook=webhook,
+ status=EventDeliveryStatus.PENDING,
+ )
+ delivery.save()
+
+ # when
+ generate_deferred_payloads(
+ event_delivery_ids=[delivery.pk],
+ deferred_payload_data=asdict(deferred_payload_data),
+ )
+
+ # then
+ delivery.refresh_from_db()
+ assert delivery.payload
+
+ payload = json.loads(delivery.payload.get_payload())
+ variant_channel_listing = variant.channel_listings.get(channel=channel_USD)
+ assert payload["productVariant"]["id"] == variant_global_id
+ assert payload["productVariant"]["pricing"]["price"]["gross"]["amount"] == (
+ variant_channel_listing.discounted_price_amount
+ )
+ assert payload["channel"]["slug"] == channel_USD.slug
+ assert payload["previousPrice"] == {
+ "amount": float(previous_price),
+ "currency": currency,
+ }
+ assert payload["newPrice"] == {
+ "amount": float(new_price),
+ "currency": currency,
+ }
+
+ assert mocked_send_webhook_request_async.call_count == 1
+ call_kwargs = mocked_send_webhook_request_async.call_args.kwargs
+ assert call_kwargs["kwargs"]["event_delivery_id"] == delivery.pk
+
+
+def test_reconstruct_subscribable_object_with_invalid_data():
+ # given
+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED
+ deferred_data = DeferredPayloadData(
+ subscribable_object_data={"variant_id": 1, "unexpected_field": "value"},
+ requestor_model_name=None,
+ requestor_object_id=None,
+ request_time=None,
+ )
+
+ # when / then
+ with pytest.raises(ValueError, match="Failed to reconstruct"):
+ _reconstruct_subscribable_object(event_type, deferred_data)
+
+
+def test_reconstruct_subscribable_object_with_unregistered_event_type():
+ # given
+ deferred_data = DeferredPayloadData(
+ subscribable_object_data={"variant_id": 1},
+ requestor_model_name=None,
+ requestor_object_id=None,
+ request_time=None,
+ )
+
+ # when / then
+ with pytest.raises(ValueError, match="No subscribable object class registered"):
+ _reconstruct_subscribable_object("unregistered_event_type", deferred_data)
diff --git a/saleor/webhook/transport/asynchronous/transport.py b/saleor/webhook/transport/asynchronous/transport.py
index c28f0e84d3..9832ae845b 100644
--- a/saleor/webhook/transport/asynchronous/transport.py
+++ b/saleor/webhook/transport/asynchronous/transport.py
@@ -2,7 +2,7 @@ import datetime
import json
import logging
from collections import defaultdict
-from collections.abc import Callable, Sequence
+from collections.abc import Callable, Hashable, Sequence
from dataclasses import asdict, dataclass
from typing import TYPE_CHECKING, Any
from urllib.parse import urlparse
@@ -39,6 +39,7 @@ from ...event_types import WebhookEventAsyncType, WebhookEventSyncType
from ...observability import WebhookData
from ..metrics import record_external_request, record_first_delivery_attempt_delay
from ..utils import (
+ DEFERRED_SUBSCRIBABLE_OBJECT_MAP,
DeferredPayloadData,
RequestorModelName,
WebhookResponse,
@@ -257,10 +258,10 @@ def create_deliveries_for_deferred_payload_subscriptions(
requestor=None,
allow_replica=False,
request_time=None,
-) -> dict[int, list[tuple[EventDelivery, DeferredPayloadData]]]:
+) -> dict[Hashable, list[tuple[EventDelivery, DeferredPayloadData]]]:
deliveries_to_create = []
deliveries_per_object: dict[
- int, list[tuple[EventDelivery, DeferredPayloadData]]
+ Hashable, list[tuple[EventDelivery, DeferredPayloadData]]
] = defaultdict(list)
for subscribable_object in subscribable_objects:
@@ -368,7 +369,7 @@ def trigger_webhooks_async_for_multiple_objects(
# List of deliveries and data to generate deferred payloads for each subscribable
# object. Note: we assume that all subscribable objects are of the same type.
deferred_deliveries_per_object: dict[
- int, list[tuple[EventDelivery, DeferredPayloadData]]
+ Hashable, list[tuple[EventDelivery, DeferredPayloadData]]
] = defaultdict(list)
for webhook_payload_detail in webhook_payloads_data:
@@ -632,12 +633,18 @@ def _generate_deferred_payloads(
.first()
)
- subscribable_object = (
- apps.get_model(args_obj.model_name)
- .objects.using(database_connection_name)
- .filter(pk=args_obj.object_id)
- .first()
- )
+ if args_obj.subscribable_object_data is not None:
+ event_type = deliveries[0].event_type
+ subscribable_object = _reconstruct_subscribable_object(event_type, args_obj)
+ elif args_obj.model_name and args_obj.object_id is not None:
+ subscribable_object = (
+ apps.get_model(args_obj.model_name)
+ .objects.using(database_connection_name)
+ .filter(pk=args_obj.object_id)
+ .first()
+ )
+ else:
+ subscribable_object = None
if not subscribable_object:
EventDelivery.objects.filter(pk__in=event_delivery_ids).update(
status=EventDeliveryStatus.FAILED
@@ -720,6 +727,36 @@ def _generate_deferred_payloads(
return
+def _reconstruct_subscribable_object(
+ event_type: str,
+ deferred_data: "DeferredPayloadData",
+):
+ """Reconstruct a dataclass subscribable object from serialized data.
+
+ Looks up the expected dataclass from the event type mapping and instantiates
+ it with the stored data. The dataclass constructor validates the structure —
+ missing or unexpected fields will raise a TypeError.
+ """
+ data = deferred_data.subscribable_object_data
+ if data is None:
+ raise ValueError(
+ "subscribable_object_data is required for "
+ "dataclass-based deferred payloads."
+ )
+ cls = DEFERRED_SUBSCRIBABLE_OBJECT_MAP.get(event_type)
+ if cls is None:
+ raise ValueError(
+ f"No subscribable object class registered for event type: "
+ f"{event_type}. Add it to DEFERRED_SUBSCRIBABLE_OBJECT_MAP."
+ )
+ try:
+ return cls(**data)
+ except (TypeError, ValueError) as e:
+ raise ValueError(
+ f"Failed to reconstruct {cls.__name__} from deferred payload data: {e}"
+ ) from e
+
+
@app.task(
queue=settings.WEBHOOK_CELERY_QUEUE_NAME,
bind=True,
diff --git a/saleor/webhook/transport/utils.py b/saleor/webhook/transport/utils.py
index 17a1cf842e..a774034d14 100644
--- a/saleor/webhook/transport/utils.py
+++ b/saleor/webhook/transport/utils.py
@@ -1,3 +1,4 @@
+import dataclasses
import datetime
import hashlib
import json
@@ -37,9 +38,12 @@ from ...core.models import (
from ...core.tasks import delete_files_from_private_storage_task
from ...core.telemetry import tracer
from ...core.utils import build_absolute_uri
+from ...core.utils.json_serializer import CustomJsonEncoder
from ...core.utils.url import sanitize_url_for_logging
+from ...product.interface import VariantDiscountedPriceChange
from .. import observability
from ..const import APP_ID_PREFIX
+from ..event_types import WebhookEventAsyncType
from ..models import Webhook
from . import signature_for_payload
@@ -85,30 +89,85 @@ class RequestorModelName:
@dataclass
class DeferredPayloadData:
- model_name: str
- object_id: int | UUID
requestor_model_name: str | None
requestor_object_id: int | UUID | None
request_time: datetime.datetime | None
+ # Legacy: used when subscribable_object is a Django model.
+ model_name: str | None = None
+ object_id: int | UUID | None = None
+ # New: used when subscribable_object is a dataclass with object IDs
+ # resolved by subscription resolvers.
+ subscribable_object_data: dict | None = None
+
+
+# Mapping from event type to subscribable object dataclass. Used by deferred
+# payloads to validate and reconstruct subscribable objects from serialized JSON.
+# Only event types that use dataclass subscribable objects (instead of Django
+# models) need to be listed here.
+DEFERRED_SUBSCRIBABLE_OBJECT_MAP: dict[str, type] = {
+ WebhookEventAsyncType.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED: (
+ VariantDiscountedPriceChange
+ ),
+}
+
+
+def _prepare_deferred_payload_for_model(
+ subscribable_object, requestor_model_name, requestor_object_id, request_time
+) -> DeferredPayloadData:
+ """Prepare deferred payload data for a Django model subscribable object."""
+ model_name = (
+ f"{subscribable_object._meta.app_label}.{subscribable_object._meta.model_name}"
+ )
+ return DeferredPayloadData(
+ model_name=model_name,
+ object_id=subscribable_object.pk,
+ request_time=request_time,
+ requestor_model_name=requestor_model_name,
+ requestor_object_id=requestor_object_id,
+ )
+
+
+def _prepare_deferred_payload_for_dataclass(
+ subscribable_object, requestor_model_name, requestor_object_id, request_time
+) -> DeferredPayloadData:
+ """Prepare deferred payload data for a dataclass subscribable object.
+
+ Serializes all fields as JSON data. Resolvers are responsible for fetching
+ DB objects from the IDs stored in the data.
+ """
+ subscribable_object_data = json.loads(
+ json.dumps(dataclasses.asdict(subscribable_object), cls=CustomJsonEncoder)
+ )
+ return DeferredPayloadData(
+ subscribable_object_data=subscribable_object_data,
+ request_time=request_time,
+ requestor_model_name=requestor_model_name,
+ requestor_object_id=requestor_object_id,
+ )
def prepare_deferred_payload_data(
subscribable_object, requestor, request_time
) -> DeferredPayloadData:
- model_name = (
- f"{subscribable_object._meta.app_label}.{subscribable_object._meta.model_name}"
- )
requestor_model_name = (
f"{requestor._meta.app_label}.{requestor._meta.model_name}"
if requestor
else None
)
- return DeferredPayloadData(
- model_name=model_name,
- object_id=subscribable_object.pk,
- request_time=request_time,
- requestor_model_name=requestor_model_name,
- requestor_object_id=(requestor.pk if requestor else None),
+ requestor_object_id = requestor.pk if requestor else None
+
+ if hasattr(subscribable_object, "_meta"):
+ return _prepare_deferred_payload_for_model(
+ subscribable_object,
+ requestor_model_name,
+ requestor_object_id,
+ request_time,
+ )
+ return _prepare_deferred_payload_for_dataclass(
+ subscribable_object,
+ requestor_model_name,
+ requestor_object_id,
+ request_time,
)