Skip to content

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

Run metadata webhooks only when metadata has changed (#13404)

Marcin Gębalab5189eb613b6
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 3cd0fd6e4d..7d4350f72a 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -951,7 +951,7 @@ def delete_external_shipping_id(checkout: Checkout):
metadata.delete_value_from_private_metadata(PRIVATE_META_APP_SHIPPING_ID)
-def get_or_create_checkout_metadata(checkout: "Checkout"):
+def get_or_create_checkout_metadata(checkout: "Checkout") -> CheckoutMetadata:
if hasattr(checkout, "metadata_storage"):
return checkout.metadata_storage
else:
diff --git a/saleor/graphql/meta/extra_methods.py b/saleor/graphql/meta/extra_methods.py
index a3ea64692e..aed1306612 100644
--- a/saleor/graphql/meta/extra_methods.py
+++ b/saleor/graphql/meta/extra_methods.py
@@ -72,7 +72,7 @@ def extra_shop_actions(instance, info: ResolveInfo, **data):
manager.shop_metadata_updated(instance)
-MODEL_EXTRA_METHODS = {
+TYPE_EXTRA_METHODS = {
"Checkout": extra_checkout_actions,
"Collection": extra_collection_actions,
"Fulfillment": extra_fulfillment_actions,
@@ -89,7 +89,7 @@ MODEL_EXTRA_METHODS = {
}
-MODEL_EXTRA_PREFETCH = {
+TYPE_EXTRA_PREFETCH = {
"Product": Product.objects.prefetched_for_webhook,
"ProductVariant": ProductVariant.objects.prefetched_for_webhook,
}
diff --git a/saleor/graphql/meta/mutations/base.py b/saleor/graphql/meta/mutations/base.py
index 7575578fb3..c27245b192 100644
--- a/saleor/graphql/meta/mutations/base.py
+++ b/saleor/graphql/meta/mutations/base.py
@@ -19,9 +19,10 @@ from ...core import ResolveInfo
from ...core.mutations import BaseMutation
from ...core.utils import from_global_id_or_error
from ...payment.utils import metadata_contains_empty_key
-from ..extra_methods import MODEL_EXTRA_METHODS, MODEL_EXTRA_PREFETCH
+from ..extra_methods import TYPE_EXTRA_METHODS, TYPE_EXTRA_PREFETCH
from ..permissions import AccountPermissions
from ..types import ObjectWithMetadata
+from .utils import get_valid_metadata_instance
class MetadataPermissionOptions(graphene.types.mutation.MutationOptions):
@@ -165,10 +166,40 @@ class BaseMetadataMutation(BaseMutation):
if not cls.check_permissions(info.context, permissions):
raise PermissionDenied(permissions=permissions)
+ try:
+ instance = cls.get_instance(info, id=data["id"])
+ except ValidationError as e:
+ return cls.handle_errors(e)
+
+ if instance:
+ metadata_instance = get_valid_metadata_instance(instance)
+ old_metadata = dict(metadata_instance.metadata)
+ old_private_metadata = dict(metadata_instance.private_metadata)
+ else:
+ old_metadata = {}
+ old_private_metadata = {}
+
try:
result = super().mutate(root, info, **data)
- if not result.errors:
+
+ has_changed = False
+
+ instance = result.item
+ if isinstance(instance, ChannelContext):
+ instance = instance.node
+
+ if instance:
+ metadata_instance = get_valid_metadata_instance(instance)
+ new_metadata = metadata_instance.metadata
+ new_private_metadata = metadata_instance.private_metadata
+ has_changed = (
+ old_metadata != new_metadata
+ or old_private_metadata != new_private_metadata
+ )
+
+ if not result.errors and has_changed:
cls.perform_model_extra_actions(root, info, type_name, **data)
+
except ValidationError as e:
return cls.handle_errors(e)
return result
@@ -198,12 +229,12 @@ class BaseMetadataMutation(BaseMutation):
@classmethod
def perform_model_extra_actions(cls, root, info: ResolveInfo, type_name, **data):
"""Run extra metadata method based on mutating model."""
- if MODEL_EXTRA_METHODS.get(type_name):
- prefetch_method = MODEL_EXTRA_PREFETCH.get(type_name)
+ if TYPE_EXTRA_METHODS.get(type_name):
+ prefetch_method = TYPE_EXTRA_PREFETCH.get(type_name)
if prefetch_method:
data["qs"] = prefetch_method()
instance = cls.get_instance(info, **data)
- MODEL_EXTRA_METHODS[type_name](instance, info, **data)
+ TYPE_EXTRA_METHODS[type_name](instance, info, **data)
@classmethod
def success_response(cls, instance):
diff --git a/saleor/graphql/meta/mutations/delete_metadata.py b/saleor/graphql/meta/mutations/delete_metadata.py
index d1e2995882..f104f8b94a 100644
--- a/saleor/graphql/meta/mutations/delete_metadata.py
+++ b/saleor/graphql/meta/mutations/delete_metadata.py
@@ -6,9 +6,8 @@ from ....core import models
from ...core import ResolveInfo
from ...core.types import MetadataError, NonNullList
from ..permissions import PUBLIC_META_PERMISSION_MAP
-from ..types import get_valid_metadata_instance
from .base import BaseMetadataMutation
-from .utils import save_instance
+from .utils import get_valid_metadata_instance, save_instance
class DeleteMetadata(BaseMetadataMutation):
diff --git a/saleor/graphql/meta/mutations/delete_private_metadata.py b/saleor/graphql/meta/mutations/delete_private_metadata.py
index dae3ceee9d..c21aef15b8 100644
--- a/saleor/graphql/meta/mutations/delete_private_metadata.py
+++ b/saleor/graphql/meta/mutations/delete_private_metadata.py
@@ -5,9 +5,8 @@ import graphene
from ...core import ResolveInfo
from ...core.types import MetadataError, NonNullList
from ..permissions import PRIVATE_META_PERMISSION_MAP
-from ..types import get_valid_metadata_instance
from .base import BaseMetadataMutation
-from .utils import save_instance
+from .utils import get_valid_metadata_instance, save_instance
class DeletePrivateMetadata(BaseMetadataMutation):
diff --git a/saleor/graphql/meta/mutations/update_metadata.py b/saleor/graphql/meta/mutations/update_metadata.py
index e3a3fe8c90..ee687290bb 100644
--- a/saleor/graphql/meta/mutations/update_metadata.py
+++ b/saleor/graphql/meta/mutations/update_metadata.py
@@ -7,9 +7,8 @@ from ...core import ResolveInfo
from ...core.types import MetadataError, NonNullList
from ..inputs import MetadataInput
from ..permissions import PUBLIC_META_PERMISSION_MAP
-from ..types import get_valid_metadata_instance
from .base import BaseMetadataMutation
-from .utils import save_instance
+from .utils import get_valid_metadata_instance, save_instance
class UpdateMetadata(BaseMetadataMutation):
diff --git a/saleor/graphql/meta/mutations/update_private_metadata.py b/saleor/graphql/meta/mutations/update_private_metadata.py
index 99fe83b18e..483e11dda3 100644
--- a/saleor/graphql/meta/mutations/update_private_metadata.py
+++ b/saleor/graphql/meta/mutations/update_private_metadata.py
@@ -4,9 +4,8 @@ from ...core import ResolveInfo
from ...core.types import MetadataError, NonNullList
from ..inputs import MetadataInput
from ..permissions import PRIVATE_META_PERMISSION_MAP
-from ..types import get_valid_metadata_instance
from .base import BaseMetadataMutation
-from .utils import save_instance
+from .utils import get_valid_metadata_instance, save_instance
class UpdatePrivateMetadata(BaseMetadataMutation):
diff --git a/saleor/graphql/meta/mutations/utils.py b/saleor/graphql/meta/mutations/utils.py
index e5d4699aaf..79f3bff962 100644
--- a/saleor/graphql/meta/mutations/utils.py
+++ b/saleor/graphql/meta/mutations/utils.py
@@ -1,7 +1,21 @@
from django.core.exceptions import FieldDoesNotExist, ValidationError
from django.db import DatabaseError
+from ....checkout.models import Checkout
+from ....checkout.utils import get_or_create_checkout_metadata
from ....core.error_codes import MetadataErrorCode
+from ....core.models import ModelWithMetadata
+
+
+# `instance = get_checkout_metadata(instance)` is calling the
+# `get_checkout_metadata` function to retrieve the metadata associated with a
+# checkout instance. This function is defined in the `.../checkout/utils.py` file
+# and takes a `Checkout` instance as an argument. It returns a dictionary
+# containing the metadata associated with the checkout.
+def get_valid_metadata_instance(instance) -> ModelWithMetadata:
+ if isinstance(instance, Checkout):
+ instance = get_or_create_checkout_metadata(instance)
+ return instance
def save_instance(instance, metadata_field: str):
diff --git a/saleor/graphql/meta/tests/mutations/test_base.py b/saleor/graphql/meta/tests/mutations/test_base.py
index 57c2737771..366ea972bb 100644
--- a/saleor/graphql/meta/tests/mutations/test_base.py
+++ b/saleor/graphql/meta/tests/mutations/test_base.py
@@ -1,5 +1,27 @@
+from unittest import mock
+
+import graphene
+
from ....tests.utils import get_graphql_content
+UPDATE_METADATA = """
+ mutation UpdateMetadata($id: ID!, $input: [MetadataInput!]!) {
+ updateMetadata(id: $id, input: $input) {
+ errors {
+ code
+ field
+ message
+ }
+ item {
+ metadata {
+ key
+ value
+ }
+ }
+ }
+ }
+"""
+
def test_handling_invalid_graphene_type(api_client):
# given
@@ -7,27 +29,10 @@ def test_handling_invalid_graphene_type(api_client):
# This ID is invalid and represents "Che3kout:42953eb4-fa86-4e02-943f-403f47fbebe7"
# with a typo in the type name.
checkout_id = "Q2hlM2tvdXQ6NDI5NTNlYjQtZmE4Ni00ZTAyLTk0M2YtNDAzZjQ3ZmJlYmU3"
- query = """
- mutation UpdateMetadata($id: ID!, $input: [MetadataInput!]!) {
- updateMetadata(id: $id, input: $input) {
- errors {
- code
- field
- message
- }
- item {
- metadata {
- key
- value
- }
- }
- }
- }
- """
# when
response = api_client.post_graphql(
- query, {"id": checkout_id, "input": [{"key": "foo", "value": "bar"}]}
+ UPDATE_METADATA, {"id": checkout_id, "input": [{"key": "foo", "value": "bar"}]}
)
response = get_graphql_content(response)
@@ -37,3 +42,49 @@ def test_handling_invalid_graphene_type(api_client):
assert errors[0]["field"] == "id"
assert errors[0]["code"] == "GRAPHQL_ERROR"
assert errors[0]["message"] == "Invalid type: Che3kout"
+
+
[email protected]("saleor.plugins.manager.PluginsManager.product_metadata_updated")
+def test_call_extra_action_only_when_metadata_change(
+ mocked_product_metadata_webhook,
+ staff_api_client,
+ product,
+ permission_manage_products,
+):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ product.metadata = {"foo": "bar"}
+ product.save(update_fields=["metadata"])
+
+ # when
+ staff_api_client.post_graphql(
+ UPDATE_METADATA,
+ {"id": product_id, "input": [{"key": "foo", "value": "bar"}]},
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ mocked_product_metadata_webhook.assert_not_called()
+
+
[email protected]("saleor.plugins.manager.PluginsManager.product_metadata_updated")
+def test_call_extra_action_when_metadata_changed(
+ mocked_product_metadata_webhook,
+ staff_api_client,
+ product,
+ permission_manage_products,
+):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ product.metadata = {}
+ product.save(update_fields=["metadata"])
+
+ # when
+ staff_api_client.post_graphql(
+ UPDATE_METADATA,
+ {"id": product_id, "input": [{"key": "foo", "value": "bar"}]},
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ mocked_product_metadata_webhook.assert_called_once()
diff --git a/saleor/graphql/meta/types.py b/saleor/graphql/meta/types.py
index 9c8d5af0da..d67cf156ae 100644
--- a/saleor/graphql/meta/types.py
+++ b/saleor/graphql/meta/types.py
@@ -4,7 +4,6 @@ import graphene
from graphene.types.generic import GenericScalar
from ...checkout.models import Checkout
-from ...checkout.utils import get_or_create_checkout_metadata
from ...core.models import ModelWithMetadata
from ..channel import ChannelContext
from ..core import ResolveInfo
@@ -160,14 +159,3 @@ class ObjectWithMetadata(graphene.Interface):
return CheckoutType.resolve_type(instance, info)
item_type, _ = resolve_object_with_metadata_type(instance)
return item_type
-
-
-# `instance = get_checkout_metadata(instance)` is calling the
-# `get_checkout_metadata` function to retrieve the metadata associated with a
-# checkout instance. This function is defined in the `.../checkout/utils.py` file
-# and takes a `Checkout` instance as an argument. It returns a dictionary
-# containing the metadata associated with the checkout.
-def get_valid_metadata_instance(instance):
- if isinstance(instance, Checkout):
- instance = get_or_create_checkout_metadata(instance)
- return instance