Skip to content

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

Support shop in generic metadata api (#13364)

Marcin Gębalab5e645041d51
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2b870aec09..05308c6279 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -58,10 +58,12 @@ All notable, unreleased changes to this project will be documented in this file.
### GraphQL API
- Add `lines` to `OrderGrantedRefund` - #13014 by @korycins
-
- Add `orderNoteAdd` and `orderNoteUpdate` mutations and deprecate `orderAddNote` mutation - #12434 by @pawelzar
- Deprecate `Order.trackingClientId` field - #13146 by @SzymJ
-- Added `metadata` and `privateMetadata` in `ShopSettingsInput`. #13128 by @Smit-Parmar
+- Add ability to use metadata in the `Shop` type - #13128 by @Smit-Parmar, #13364 by @maarcingebala
+ - Add `metadata` and `privateMetadata` in `ShopSettingsInput`.
+ - Add `Shop.id` field.
+ - Add support for modifying metadata via generic metadata API.
- Fix error "Cannot return null for non-nullable field Webhook.name" - #12989 by @Smit-Parmar
- Added `GiftCardFilterInput.createdByEmail` filter - #13132 by @Smit-Parmar
- Add metadata support for channels. #13230 by @Smit-Parmar
@@ -74,6 +76,7 @@ All notable, unreleased changes to this project will be documented in this file.
### Saleor Apps
- Introduce `Saleor-Schema-Version` HTTP header in app manifest fetching and app installation handshake requests. - #13075 by @przlada
+- Add `SHOP_METADATA_UPDATED` webhook - #13364 by @maarcingebala
### Other changes
- Add POC of Core API tests - #13034 by @fowczarek
diff --git a/saleor/graphql/meta/extra_methods.py b/saleor/graphql/meta/extra_methods.py
index 6a1e5dfdd6..a3ea64692e 100644
--- a/saleor/graphql/meta/extra_methods.py
+++ b/saleor/graphql/meta/extra_methods.py
@@ -67,6 +67,11 @@ def extra_voucher_actions(instance, info: ResolveInfo, **data):
manager.voucher_metadata_updated(instance)
+def extra_shop_actions(instance, info: ResolveInfo, **data):
+ manager = get_plugin_manager_promise(info.context).get()
+ manager.shop_metadata_updated(instance)
+
+
MODEL_EXTRA_METHODS = {
"Checkout": extra_checkout_actions,
"Collection": extra_collection_actions,
@@ -76,6 +81,7 @@ MODEL_EXTRA_METHODS = {
"Product": extra_product_actions,
"ProductVariant": extra_variant_actions,
"ShippingZone": extra_shipping_zone_actions,
+ "Shop": extra_shop_actions,
"TransactionItem": extra_transaction_item_actions,
"User": extra_user_actions,
"Warehouse": extra_warehouse_actions,
diff --git a/saleor/graphql/meta/mutations/base.py b/saleor/graphql/meta/mutations/base.py
index 44b3c648dd..7575578fb3 100644
--- a/saleor/graphql/meta/mutations/base.py
+++ b/saleor/graphql/meta/mutations/base.py
@@ -129,7 +129,11 @@ class BaseMetadataMutation(BaseMutation):
if type_name in ["ShippingMethodType", "ShippingMethod"]:
return shipping_models.ShippingMethod
- graphene_type = info.schema.get_type(type_name).graphene_type
+ type_obj = info.schema.get_type(type_name)
+ if not type_obj:
+ raise GraphQLError(f"Invalid type: {type_name}")
+
+ graphene_type = type_obj.graphene_type
if hasattr(graphene_type, "get_model"):
return graphene_type.get_model()
diff --git a/saleor/graphql/meta/tests/mutations/test_base.py b/saleor/graphql/meta/tests/mutations/test_base.py
new file mode 100644
index 0000000000..57c2737771
--- /dev/null
+++ b/saleor/graphql/meta/tests/mutations/test_base.py
@@ -0,0 +1,39 @@
+from ....tests.utils import get_graphql_content
+
+
+def test_handling_invalid_graphene_type(api_client):
+ # given
+
+ # 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"}]}
+ )
+ response = get_graphql_content(response)
+
+ # then
+ errors = response["data"]["updateMetadata"]["errors"]
+ assert errors
+ assert errors[0]["field"] == "id"
+ assert errors[0]["code"] == "GRAPHQL_ERROR"
+ assert errors[0]["message"] == "Invalid type: Che3kout"
diff --git a/saleor/graphql/meta/tests/mutations/test_shop.py b/saleor/graphql/meta/tests/mutations/test_shop.py
index b9478b0ead..7e1961b25b 100644
--- a/saleor/graphql/meta/tests/mutations/test_shop.py
+++ b/saleor/graphql/meta/tests/mutations/test_shop.py
@@ -1,18 +1,38 @@
+import graphene
+
+from .....site.models import SiteSettings
+from ....shop.types import SHOP_ID
from ....tests.utils import get_graphql_content
from . import PRIVATE_KEY, PRIVATE_VALUE, PUBLIC_KEY, PUBLIC_VALUE
+from .test_delete_metadata import (
+ execute_clear_public_metadata_for_item,
+ item_without_public_metadata,
+)
+from .test_delete_private_metadata import (
+ execute_clear_private_metadata_for_item,
+ item_without_private_metadata,
+)
+from .test_update_metadata import (
+ execute_update_public_metadata_for_item,
+ item_contains_proper_public_metadata,
+)
+from .test_update_private_metadata import (
+ execute_update_private_metadata_for_item,
+ item_contains_proper_private_metadata,
+)
SHOP_SETTINGS_UPDATE_METADATA_MUTATION = """
mutation updateShopMetadata($input: ShopSettingsInput!) {
shopSettingsUpdate(input: $input) {
shop {
- metadata {
- key
- value
- }
- privateMetadata {
- key
- value
- }
+ metadata {
+ key
+ value
+ }
+ privateMetadata {
+ key
+ value
+ }
}
}
}
@@ -41,3 +61,85 @@ def test_shop_settings_update_metadata(staff_api_client, permission_manage_setti
data = content["data"]["shopSettingsUpdate"]["shop"]
assert data["metadata"] == metadata
assert data["privateMetadata"] == private_metadata
+
+
+def test_delete_private_metadata_for_shop(staff_api_client, permission_manage_settings):
+ # given
+ site_settings = SiteSettings.objects.first()
+ shop_id = graphene.Node.to_global_id("Shop", SHOP_ID)
+
+ # when
+ response = execute_clear_private_metadata_for_item(
+ staff_api_client,
+ permission_manage_settings,
+ shop_id,
+ "Shop",
+ )
+
+ # then
+ assert item_without_private_metadata(
+ response["data"]["deletePrivateMetadata"]["item"],
+ site_settings,
+ shop_id,
+ )
+
+
+def test_delete_public_metadata_for_shop(staff_api_client, permission_manage_settings):
+ # given
+ site_settings = SiteSettings.objects.first()
+ shop_id = graphene.Node.to_global_id("Shop", SHOP_ID)
+
+ # when
+ response = execute_clear_public_metadata_for_item(
+ staff_api_client,
+ permission_manage_settings,
+ shop_id,
+ "Shop",
+ )
+
+ # then
+ assert item_without_public_metadata(
+ response["data"]["deleteMetadata"]["item"],
+ site_settings,
+ shop_id,
+ )
+
+
+def test_add_public_metadata_for_shop(staff_api_client, permission_manage_settings):
+ # given
+ site_settings = SiteSettings.objects.first()
+ shop_id = graphene.Node.to_global_id("Shop", SHOP_ID)
+
+ # when
+ response = execute_update_public_metadata_for_item(
+ staff_api_client,
+ permission_manage_settings,
+ shop_id,
+ "Shop",
+ )
+
+ # then
+ assert item_contains_proper_public_metadata(
+ response["data"]["updateMetadata"]["item"], site_settings, shop_id
+ )
+
+
+def test_add_private_metadata_for_shop(staff_api_client, permission_manage_settings):
+ # given
+ site_settings = SiteSettings.objects.first()
+ shop_id = graphene.Node.to_global_id("Shop", SHOP_ID)
+
+ # when
+ response = execute_update_private_metadata_for_item(
+ staff_api_client,
+ permission_manage_settings,
+ shop_id,
+ "Shop",
+ )
+
+ # then
+ assert item_contains_proper_private_metadata(
+ response["data"]["updatePrivateMetadata"]["item"],
+ site_settings,
+ shop_id,
+ )
diff --git a/saleor/graphql/meta/tests/queries/test_shop.py b/saleor/graphql/meta/tests/queries/test_shop.py
index a5e942328b..3c9b2291fa 100644
--- a/saleor/graphql/meta/tests/queries/test_shop.py
+++ b/saleor/graphql/meta/tests/queries/test_shop.py
@@ -1,51 +1,79 @@
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
from .utils import PRIVATE_KEY, PRIVATE_VALUE, PUBLIC_KEY, PUBLIC_VALUE
-SHOP_METADATA_QUERY = """
- query {
+SHOP_PRIVATE_AND_PUBLIC_METADATA_QUERY = """
+ query shopMetadata($key: String!, $privateKey: String!) {
shop {
metadata {
- key
- value
+ key
+ value
}
- metafield(key: "key")
- metafields(keys: ["key"])
+ metafield(key: $key)
+ metafields(keys: [$key])
privateMetadata {
- key
- value
+ key
+ value
}
- privateMetafield(key: "private_key")
- privateMetafields(keys: ["private_key"])
+ privateMetafield(key: $privateKey)
+ privateMetafields(keys: [$privateKey])
}
}
"""
+SHOP_PUBLIC_METADATA_QUERY = """
+ query shopMetadata($key: String!) {
+ shop {
+ metadata {
+ key
+ value
+ }
+ metafield(key: $key)
+ metafields(keys: [$key])
+ }
+}
+"""
-def test_shop_metadata_query_as_user(
- user_api_client, site_settings, permission_manage_settings
+
+def test_customer_user_has_no_permission_to_shop_private_metadata(
+ user_api_client, site_settings
):
# given
site_settings.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
site_settings.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
site_settings.save()
+
# when
response = user_api_client.post_graphql(
- SHOP_METADATA_QUERY, permissions=[permission_manage_settings]
+ SHOP_PRIVATE_AND_PUBLIC_METADATA_QUERY,
+ variables={"key": PUBLIC_KEY, "privateKey": PRIVATE_KEY},
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_customer_user_has_access_to_shop_public_metadata(
+ user_api_client, site_settings
+):
+ # given
+ site_settings.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
+ site_settings.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
+ site_settings.save()
+
+ # when
+ response = user_api_client.post_graphql(
+ SHOP_PUBLIC_METADATA_QUERY,
+ variables={"key": PUBLIC_KEY},
)
- content = get_graphql_content(response)
- data = content["data"]["shop"]
# then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]
assert data["metadata"][0]["key"] == PUBLIC_KEY
assert data["metadata"][0]["value"] == PUBLIC_VALUE
assert data["metafield"] == PUBLIC_VALUE
assert data["metafields"] == {PUBLIC_KEY: PUBLIC_VALUE}
- assert data["privateMetadata"][0]["key"] == PRIVATE_KEY
- assert data["privateMetadata"][0]["value"] == PRIVATE_VALUE
- assert data["privateMetafield"] == PRIVATE_VALUE
- assert data["privateMetafields"] == {PRIVATE_KEY: PRIVATE_VALUE}
-
def test_shop_metadata_query_as_staff_user(
staff_api_client, site_settings, permission_manage_settings
@@ -56,7 +84,9 @@ def test_shop_metadata_query_as_staff_user(
site_settings.save()
# when
response = staff_api_client.post_graphql(
- SHOP_METADATA_QUERY, permissions=[permission_manage_settings]
+ SHOP_PRIVATE_AND_PUBLIC_METADATA_QUERY,
+ permissions=[permission_manage_settings],
+ variables={"key": PUBLIC_KEY, "privateKey": PRIVATE_KEY},
)
content = get_graphql_content(response)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 5b967172b5..1244c80539 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2173,6 +2173,13 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {
"""
THUMBNAIL_CREATED
+ """
+ Shop metadata is updated.
+
+ Added in Saleor 3.15.
+ """
+ SHOP_METADATA_UPDATED
+
"""Authorize payment."""
PAYMENT_AUTHORIZE
@@ -2805,6 +2812,13 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {
Added in Saleor 3.12.
"""
THUMBNAIL_CREATED
+
+ """
+ Shop metadata is updated.
+
+ Added in Saleor 3.15.
+ """
+ SHOP_METADATA_UPDATED
}
"""Represents app data."""
@@ -3464,6 +3478,7 @@ enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {
VOUCHER_METADATA_UPDATED
OBSERVABILITY
THUMBNAIL_CREATED
+ SHOP_METADATA_UPDATED
}
"""Represents warehouse."""
@@ -9238,6 +9253,9 @@ type Shop implements ObjectWithMetadata {
"""
metafields(keys: [String!]): Metadata
+ """ID of the shop."""
+ id: ID!
+
"""List of available payment gateways."""
availablePaymentGateways(
"""
@@ -31957,6 +31975,28 @@ type TransactionProcessSession implements Event @doc(category: "Payments") {
action: TransactionProcessAction!
}
+"""
+Event sent when shop metadata is updated.
+
+Added in Saleor 3.15.
+"""
+type ShopMetadataUpdated 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
+
+ """Shop data."""
+ shop: Shop
+}
+
"""_Any value scalar as defined by Federation spec."""
scalar _Any
diff --git a/saleor/graphql/shop/mutations/shop_settings_update.py b/saleor/graphql/shop/mutations/shop_settings_update.py
index 8a7d660b76..ec2616ad12 100644
--- a/saleor/graphql/shop/mutations/shop_settings_update.py
+++ b/saleor/graphql/shop/mutations/shop_settings_update.py
@@ -85,7 +85,7 @@ class ShopSettingsInput(graphene.InputObjectType):
)
private_metadata = common_types.NonNullList(
MetadataInput,
- description=("Shop private metadata." + ADDED_IN_315),
+ description="Shop private metadata." + ADDED_IN_315,
required=False,
)
# deprecated
diff --git a/saleor/graphql/shop/tests/queries/test_shop.py b/saleor/graphql/shop/tests/queries/test_shop.py
index d1bcdb0e4f..36abaa6f55 100644
--- a/saleor/graphql/shop/tests/queries/test_shop.py
+++ b/saleor/graphql/shop/tests/queries/test_shop.py
@@ -11,6 +11,26 @@ from .....shipping.models import ShippingMethod
from ....account.enums import CountryCodeEnum
from ....core.utils import str_to_enum
from ....tests.utils import assert_no_permission, get_graphql_content
+from ...types import SHOP_ID
+
+SHOP_ID_QUERY = """
+ query {
+ shop {
+ id
+ }
+ }
+"""
+
+
+def test_shop_id_query(api_client):
+ # when
+ response = api_client.post_graphql(SHOP_ID_QUERY)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]
+ assert data["id"] == graphene.Node.to_global_id("Shop", SHOP_ID)
+
COUNTRIES_QUERY = """
query {
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index a507686c75..d7b3644ae7 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -53,6 +53,11 @@ from .enums import GiftCardSettingsExpiryTypeEnum
from .filters import CountryFilterInput
from .resolvers import resolve_available_shipping_methods, resolve_countries
+# The "Shop" type always have the same ID since there is a single instance of it.
+# Some mutations, such as generic metadata API, require an ID. To make it work we
+# assume that Shop's ID is always 1.
+SHOP_ID = "1"
+
class Domain(graphene.ObjectType):
host = graphene.String(description="The host name of the domain.", required=True)
@@ -137,6 +142,7 @@ class LimitInfo(graphene.ObjectType):
class Shop(graphene.ObjectType):
+ id = graphene.ID(description="ID of the shop.", required=True)
available_payment_gateways = NonNullList(
PaymentGateway,
currency=graphene.Argument(
@@ -360,6 +366,18 @@ class Shop(graphene.ObjectType):
)
interfaces = [ObjectWithMetadata]
+ @staticmethod
+ def get_model():
+ return site_models.SiteSettings
+
+ @staticmethod
+ def get_node(_info: ResolveInfo, id):
+ return site_models.SiteSettings.objects.first() if id == SHOP_ID else None
+
+ @staticmethod
+ def resolve_id(_, _info):
+ return graphene.Node.to_global_id("Shop", SHOP_ID)
+
@staticmethod
@traced_resolver
@plugin_manager_promise_callback
diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.py
index 18fd88441c..b476db53e7 100644
--- a/saleor/graphql/webhook/enums.py
+++ b/saleor/graphql/webhook/enums.py
@@ -7,6 +7,7 @@ from ..core.descriptions import (
ADDED_IN_312,
ADDED_IN_313,
ADDED_IN_314,
+ ADDED_IN_315,
PREVIEW_FEATURE,
)
from ..core.doc_category import DOC_CATEGORY_WEBHOOKS
@@ -206,6 +207,8 @@ WEBHOOK_EVENT_DESCRIPTION = {
WebhookEventAsyncType.ANY: "All the events.",
WebhookEventAsyncType.OBSERVABILITY: "An observability event is created.",
WebhookEventAsyncType.THUMBNAIL_CREATED: "A thumbnail is created." + ADDED_IN_312,
+ WebhookEventAsyncType.SHOP_METADATA_UPDATED: "Shop metadata is updated."
+ + ADDED_IN_315,
WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT: (
"Fetch external shipping methods for checkout."
),
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index abd69148bb..5ffb54b50a 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -1846,6 +1846,20 @@ class VoucherMetadataUpdated(SubscriptionObjectType, VoucherBase):
description = "Event sent when voucher metadata is updated." + ADDED_IN_38
+class ShopMetadataUpdated(SubscriptionObjectType, AbstractType):
+ shop = graphene.Field(Shop, description="Shop data.")
+
+ class Meta:
+ root_type = "Shop"
+ enable_dry_run = True
+ interfaces = (Event,)
+ description = "Event sent when shop metadata is updated." + ADDED_IN_315
+
+ @staticmethod
+ def resolve_shop(root, _info: ResolveInfo):
+ return Shop()
+
+
class PaymentBase(AbstractType):
payment = graphene.Field(
"saleor.graphql.payment.types.Payment",
@@ -2256,4 +2270,5 @@ WEBHOOK_TYPES_MAP = {
),
WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION: TransactionInitializeSession,
WebhookEventSyncType.TRANSACTION_PROCESS_SESSION: TransactionProcessSession,
+ WebhookEventAsyncType.SHOP_METADATA_UPDATED: ShopMetadataUpdated,
}
diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
index a8596c9c05..875854da18 100644
--- a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
@@ -4,6 +4,7 @@ import uuid
import graphene
import pytest
+from .....graphql.shop.types import SHOP_ID
from .....graphql.tests.utils import get_graphql_content
from .....webhook.error_codes import WebhookDryRunErrorCode
from .....webhook.event_types import WebhookEventAsyncType
@@ -601,7 +602,10 @@ def test_webhook_dry_run_root_type(
query = WEBHOOK_DRY_RUN_MUTATION
for event_name, event_type in WEBHOOK_TYPES_MAP.items():
- if not event_type._meta.enable_dry_run:
+ if (
+ not event_type._meta.enable_dry_run
+ or event_name not in async_subscription_webhooks_with_root_objects
+ ):
continue
webhook = async_subscription_webhooks_with_root_objects[event_name][0]
@@ -621,6 +625,27 @@ def test_webhook_dry_run_root_type(
assert not json.loads(payload).get("errors")
+def test_webhook_dry_run_shop_type(
+ superuser_api_client,
+ subscription_shop_metadata_updated_webhook,
+):
+ # given
+ query = WEBHOOK_DRY_RUN_MUTATION
+ webhook = subscription_shop_metadata_updated_webhook
+ object_id = graphene.Node.to_global_id("Shop", SHOP_ID)
+ variables = {"objectId": object_id, "query": webhook.subscription_query}
+
+ # when
+ response = superuser_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ assert not content["data"]["webhookDryRun"]["errors"]
+ payload = content["data"]["webhookDryRun"]["payload"]
+ assert payload
+ assert not json.loads(payload).get("errors")
+
+
def test_webhook_dry_run_root_type_for_transaction_item_metadata_updated(
superuser_api_client,
transaction_item_generator,
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 8b1adb96e7..31de866c11 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -64,6 +64,7 @@ if TYPE_CHECKING:
)
from ..shipping.interface import ShippingMethodData
from ..shipping.models import ShippingMethod, ShippingZone
+ from ..site.models import SiteSettings
from ..tax.models import TaxClass
from ..warehouse.models import Warehouse
@@ -1070,6 +1071,12 @@ class BasePlugin:
# metadata is updated.
voucher_metadata_updated: Callable[["Voucher", None], None]
+ # Trigger when shop metadata is updated.
+ #
+ # Overwrite this method if you need to trigger specific logic after a shop
+ # metadata is updated.
+ shop_metadata_updated: Callable[["SiteSettings", None], None]
+
# Handle received http request.
#
# Overwrite this method if the plugin expects the incoming requests.
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 6553b892dc..6e30dfb4cb 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -71,6 +71,7 @@ if TYPE_CHECKING:
)
from ..shipping.interface import ShippingMethodData
from ..shipping.models import ShippingMethod, ShippingZone
+ from ..site.models import SiteSettings
from ..tax.models import TaxClass
from ..thumbnail.models import Thumbnail
from ..translation.models import Translation
@@ -1364,6 +1365,12 @@ class PluginsManager(PaymentInterface):
"voucher_metadata_updated", default_value, voucher
)
+ def shop_metadata_updated(self, shop: "SiteSettings"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "shop_metadata_updated", default_value, shop
+ )
+
def initialize_payment(
self, gateway, payment_data: dict, channel_slug: str
) -> Optional["InitializedPaymentResponse"]:
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 51b21cb11b..ce2bed1f38 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -103,6 +103,7 @@ if TYPE_CHECKING:
)
from ...shipping.interface import ShippingMethodData
from ...shipping.models import ShippingMethod, ShippingZone
+ from ...site.models import SiteSettings
from ...tax.models import TaxClass
from ...translation.models import Translation
from ...warehouse.models import Stock, Warehouse
@@ -1531,6 +1532,13 @@ class WebhookPlugin(BasePlugin):
WebhookEventAsyncType.VOUCHER_METADATA_UPDATED, voucher
)
+ def shop_metadata_updated(self, shop: "SiteSettings", previous_value: None) -> None:
+ if not self.active:
+ return previous_value
+ self._trigger_metadata_updated_event(
+ WebhookEventAsyncType.SHOP_METADATA_UPDATED, shop
+ )
+
def event_delivery_retry(self, delivery: "EventDelivery", previous_value: 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 4e34802654..d543f30b89 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
@@ -895,6 +895,14 @@ def subscription_voucher_metadata_updated_webhook(subscription_webhook):
)
+def subscription_shop_metadata_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ queries.SHOP_METADATA_UPDATED,
+ WebhookEventAsyncType.SHOP_METADATA_UPDATED,
+ )
+
+
@pytest.fixture
def subscription_payment_authorize_webhook(subscription_webhook):
return subscription_webhook(
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py b/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py
index 3b44b08ce2..73e9dc92c6 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py
@@ -5,6 +5,7 @@ from django.utils import timezone
from ..... import __version__
from .....graphql.attribute.enums import AttributeInputTypeEnum, AttributeTypeEnum
+from .....graphql.shop.types import SHOP_ID
from .....product.models import Product
@@ -483,3 +484,13 @@ def generate_payment_payload(payment):
"isActive": payment.is_active,
}
}
+
+
+def generate_shop_payload():
+ return json.dumps(
+ {
+ "shop": {
+ "id": graphene.Node.to_global_id("Shop", SHOP_ID),
+ }
+ }
+ )
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
index 1d3aa319af..1ba66fe8d5 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
@@ -482,6 +482,19 @@ VOUCHER_METADATA_UPDATED = (
)
+SHOP_METADATA_UPDATED = """
+ subscription{
+ event {
+ ...on ShopMetadataUpdated{
+ shop {
+ id
+ }
+ }
+ }
+ }
+"""
+
+
CHANNEL_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 b764204773..9961bb755b 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
@@ -11,6 +11,7 @@ from .....graphql.webhook.subscription_query import SubscriptionQuery
from .....menu.models import Menu, MenuItem
from .....product.models import Category
from .....shipping.models import ShippingMethod, ShippingZone
+from .....site.models import SiteSettings
from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ...tasks import create_deliveries_for_subscriptions, logger
from . import subscription_queries
@@ -33,6 +34,7 @@ from .payloads import (
generate_permission_group_payload,
generate_sale_payload,
generate_shipping_method_payload,
+ generate_shop_payload,
generate_staff_payload,
generate_voucher_created_payload_with_meta,
generate_voucher_payload,
@@ -2104,6 +2106,24 @@ def test_voucher_metadata_updated(
assert deliveries[0].webhook == webhooks[0]
+def test_shop_metadata_updated(subscription_shop_metadata_updated_webhook):
+ # given
+ webhooks = [subscription_shop_metadata_updated_webhook]
+ event_type = WebhookEventAsyncType.SHOP_METADATA_UPDATED
+ site_settings = SiteSettings.objects.first()
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, site_settings, webhooks
+ )
+
+ # then
+ expected_payload = generate_shop_payload()
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
def test_transaction_item_metadata_updated(
transaction_item_created_by_app,
subscription_transaction_item_metadata_updated_webhook,
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index d8f3aa2be1..b094ed976e 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -38,6 +38,7 @@ from ....graphql.discount.mutations.utils import convert_catalogue_info_to_globa
from ....payment import TransactionAction, TransactionEventType
from ....payment.interface import TransactionActionData
from ....payment.models import TransactionItem
+from ....site.models import SiteSettings
from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....webhook.payloads import (
generate_checkout_payload,
@@ -1250,6 +1251,32 @@ def test_voucher_metadata_updated(
)
+@freeze_time("1914-06-28 10:50")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_shop_metadata_updated(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ settings,
+):
+ site_settings = SiteSettings.objects.first()
+ assert site_settings
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ manager = get_plugins_manager()
+ manager.shop_metadata_updated(site_settings)
+ expected_data = generate_metadata_updated_payload(site_settings)
+
+ mocked_webhook_trigger.assert_called_once_with(
+ expected_data,
+ WebhookEventAsyncType.SHOP_METADATA_UPDATED,
+ [any_webhook],
+ site_settings,
+ None,
+ )
+
+
@freeze_time("1914-06-28 10:50")
@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index 9a087c786d..662ab31c1f 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -173,6 +173,8 @@ class WebhookEventAsyncType:
THUMBNAIL_CREATED = "thumbnail_created"
+ SHOP_METADATA_UPDATED = "shop_metadata_updated"
+
DISPLAY_LABELS = {
ANY: "Any events",
ACCOUNT_CONFIRMATION_REQUESTED: "Account confirmation requested",
@@ -295,6 +297,7 @@ class WebhookEventAsyncType:
VOUCHER_METADATA_UPDATED: "Voucher metadata updated",
OBSERVABILITY: "Observability",
THUMBNAIL_CREATED: "Thumbnail created",
+ SHOP_METADATA_UPDATED: "Shop metadata updated",
}
CHOICES = [
@@ -434,6 +437,7 @@ class WebhookEventAsyncType:
(VOUCHER_METADATA_UPDATED, DISPLAY_LABELS[VOUCHER_METADATA_UPDATED]),
(OBSERVABILITY, DISPLAY_LABELS[OBSERVABILITY]),
(THUMBNAIL_CREATED, DISPLAY_LABELS[THUMBNAIL_CREATED]),
+ (SHOP_METADATA_UPDATED, DISPLAY_LABELS[SHOP_METADATA_UPDATED]),
]
ALL = [event[0] for event in CHOICES]
@@ -559,6 +563,7 @@ class WebhookEventAsyncType:
WAREHOUSE_METADATA_UPDATED: ProductPermissions.MANAGE_PRODUCTS,
OBSERVABILITY: AppPermission.MANAGE_OBSERVABILITY,
THUMBNAIL_CREATED: ProductPermissions.MANAGE_PRODUCTS,
+ SHOP_METADATA_UPDATED: SitePermissions.MANAGE_SETTINGS,
}