Skip to content

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

feat(shop): add Announcements API (#19353)

Mikail7ebc4f698377
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 29b25bcde2..3993c17936 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -15159,6 +15159,13 @@ type Shop implements ObjectWithMetadata {
"""
limits: LimitInfo! @deprecated
+ """
+ List of announcements for this shop.
+
+ Requires one of the following permissions: AUTHENTICATED_STAFF_USER.
+ """
+ announcements: [Announcement!]!
+
"""
Saleor API version.
@@ -15304,6 +15311,43 @@ type Limits {
warehouses: Int
}
+"""Lists current announcements that the user should see."""
+type Announcement {
+ """The date & time at which this announcement was created."""
+ createdAt: DateTime!
+
+ """The date & time at which this announcement was last updated."""
+ updatedAt: DateTime!
+
+ """The announcement's title."""
+ title: String!
+
+ """The announcement's description, may contain HTML formatting."""
+ messageHtml: String!
+
+ """
+ Determine the how critical the announcement is. UNSET if no severity level was defined for this announcement. When value is `UNSET`, it should be considered as low importance or informational.
+ """
+ importance: AnnouncementImportanceEnum!
+
+ """
+ The announcement's type, for example "CUSTOM". Used to programatically distinguish between message types thus allowing to render the message differently, and allows to know the expected shape for the `extra` field.
+ """
+ type: String!
+
+ """Additional information about this announcement."""
+ extra: Metadata!
+}
+
+"""Defines a shop-level announcement's level/severity."""
+enum AnnouncementImportanceEnum @doc(category: "Shop") {
+ CRITICAL
+ HIGH
+ MODERATE
+ LOW
+ UNSET
+}
+
"""
Controls whether password-based authentication is allowed.
diff --git a/saleor/graphql/shop/enums.py b/saleor/graphql/shop/enums.py
index 07395423f9..3f981d9e4c 100644
--- a/saleor/graphql/shop/enums.py
+++ b/saleor/graphql/shop/enums.py
@@ -2,8 +2,16 @@ from typing import Final
import graphene
-from ...site import GiftCardSettingsExpiryType, PasswordLoginMode
-from ..core.doc_category import DOC_CATEGORY_AUTH, DOC_CATEGORY_GIFT_CARDS
+from ...site import (
+ AnnouncementImportance,
+ GiftCardSettingsExpiryType,
+ PasswordLoginMode,
+)
+from ..core.doc_category import (
+ DOC_CATEGORY_AUTH,
+ DOC_CATEGORY_GIFT_CARDS,
+ DOC_CATEGORY_SHOP,
+)
from ..core.enums import to_enum
GiftCardSettingsExpiryTypeEnum: Final[graphene.Enum] = to_enum(
@@ -17,3 +25,10 @@ PasswordLoginModeEnum: Final[graphene.Enum] = to_enum(
description=PasswordLoginMode.__doc__,
)
PasswordLoginModeEnum.doc_category = DOC_CATEGORY_AUTH
+
+AnnouncementImportanceEnum: Final[graphene.Enum] = to_enum(
+ AnnouncementImportance,
+ type_name="AnnouncementImportanceEnum",
+ description=AnnouncementImportance.__doc__,
+)
+AnnouncementImportanceEnum.doc_category = DOC_CATEGORY_SHOP
diff --git a/saleor/graphql/shop/tests/queries/test_shop_announcements.py b/saleor/graphql/shop/tests/queries/test_shop_announcements.py
new file mode 100644
index 0000000000..7c94729638
--- /dev/null
+++ b/saleor/graphql/shop/tests/queries/test_shop_announcements.py
@@ -0,0 +1,240 @@
+from collections.abc import Callable
+from contextlib import contextmanager
+from datetime import datetime
+
+from .....site.apps import SiteAppConfig
+from ....tests.utils import (
+ assert_no_permission,
+ get_graphql_content,
+ get_graphql_content_from_response,
+)
+from ...enums import AnnouncementImportanceEnum
+from ...types import Announcement
+
+QUERY_GET_ANNOUNCEMENTS_BASIC = """
+{
+ shop {
+ announcements {
+ title
+ messageHtml
+ }
+ }
+}
+"""
+
+QUERY_GET_ANNOUNCEMENTS_FULL = """
+{
+ shop {
+ announcements {
+ createdAt
+ updatedAt
+ title
+ messageHtml
+ importance
+ type
+ extra
+ }
+ }
+}
+"""
+
+DUMMY_TITLE = "Dummy Announcement"
+DUMMY_DESCRIPTION = (
+ "This is an example body. This supports <strong>HTML markup</strong>."
+)
+
+DUMMY_CREATED_AT = "2022-06-13T16:01:02.300000+00:00"
+DUMMY_UPDATED_AT = "2022-06-14T17:04:05.600000+00:00"
+
+# TODO: switch to frozendict once Saleor uses Python 3.15 (including child dicts)
+DUMMY_ANNOUNCEMENT = {
+ "created_at": datetime.fromisoformat(DUMMY_CREATED_AT),
+ "updated_at": datetime.fromisoformat(DUMMY_UPDATED_AT),
+ "title": DUMMY_TITLE,
+ "message_html": DUMMY_DESCRIPTION,
+ "importance": AnnouncementImportanceEnum.CRITICAL,
+ "type": "OTHER",
+ "extra": {"foo": "bar", "integer": 123},
+}
+
+
+def resolve_dummy_announcements() -> list[Announcement]:
+ return [Announcement(**DUMMY_ANNOUNCEMENT)]
+
+
+def resolve_dummy_announcements_with_empty_extra_dict() -> list[Announcement]:
+ """Return a dummy announcement with ``extra`` empty."""
+
+ announcement = {**DUMMY_ANNOUNCEMENT} # shallow copy
+ announcement["extra"] = {}
+
+ return [Announcement(**announcement)]
+
+
+def resolve_dummy_announcements_with_null_extra() -> list[Announcement]:
+ """Return a dummy announcement with ``extra`` empty."""
+
+ announcement = {**DUMMY_ANNOUNCEMENT} # shallow copy
+ announcement["extra"] = None
+
+ return [Announcement(**announcement)]
+
+
+@contextmanager
+def use_dummy_announcements(
+ settings,
+ resolver_func: Callable[[], list[Announcement]] = resolve_dummy_announcements,
+):
+ """Set the announcement resolver to the given ``resolver_func``.
+
+ Example usage:
+
+ >>> def resolver():
+ >>> return []
+ >>>
+ >>> def test_foo(settings):
+ >>> with use_dummy_announcements(settings, resolver): ...
+ """
+
+ # Ensure there wasn't any cross-test leakage where a fixture or test
+ # didn't reset the SiteAppConfig properly. If it raises an AssertionError,
+ # then you should fix the leakage
+ assert SiteAppConfig.announcements_resolver is None
+
+ import_path = f"{resolver_func.__module__}.{resolver_func.__name__}"
+ settings.SHOP_ANNOUNCEMENT_RESOLVER_IMPORT = import_path
+
+ try:
+ SiteAppConfig.setup_announcements() # loads the new resolver
+ yield
+ finally:
+ settings.SHOP_ANNOUNCEMENT_RESOLVER_IMPORT = None
+ SiteAppConfig.announcements_resolver = None
+
+
+def test_cannot_get_announcements_when_not_staff(user_api_client):
+ """Authenticated user are not authorized to get announcements when not a staff."""
+
+ query = QUERY_GET_ANNOUNCEMENTS_BASIC
+ response = user_api_client.post_graphql(query)
+ assert_no_permission(response)
+
+
+def test_cannot_get_announcements_when_anonymous(api_client):
+ """Anonymous users are not authorized to get announcements."""
+
+ query = QUERY_GET_ANNOUNCEMENTS_BASIC
+ response = api_client.post_graphql(query)
+ assert_no_permission(response)
+
+
+def test_can_get_announcements_when_staff(staff_api_client, staff_user):
+ """Staff users should be authorized to get announcements."""
+
+ # Ensures that the staff has no permissions as we do not expect
+ # the user to need any specific/given permissions.
+ assert len(staff_user.effective_permissions) == 0, (
+ "Expected the staff to not have any permission"
+ )
+
+ query = QUERY_GET_ANNOUNCEMENTS_BASIC
+ content = get_graphql_content(staff_api_client.post_graphql(query))
+
+ # Should return the announcements without any errors
+ assert content["data"] == {"shop": {"announcements": []}}
+
+
+def test_get_announcements_empty_when_unconfigured(staff_api_client):
+ """Ensure announcements are empty when not configured.
+
+ When ``settings.SHOP_ANNOUNCEMENT_RESOLVER_IMPORT`` is unset (``None``)
+ (default value), then, ``shop { announcements {...} }`` should return an empty list.
+ """
+
+ response = staff_api_client.post_graphql(QUERY_GET_ANNOUNCEMENTS_BASIC)
+ content = get_graphql_content(response)
+ assert content["data"] == {"shop": {"announcements": []}}
+
+
+def test_get_announcements_uses_custom_resolver(settings, staff_api_client):
+ """Ensure announcements are fetched from the custom resolver when configured.
+
+ When ``settings.SHOP_ANNOUNCEMENT_RESOLVER_IMPORT`` is configured (``!= None``),
+ then, Saleor should return the announcements from that resolver.
+ """
+
+ with use_dummy_announcements(settings):
+ response = staff_api_client.post_graphql(QUERY_GET_ANNOUNCEMENTS_FULL)
+
+ content = get_graphql_content(response)
+ assert content["data"] == {
+ "shop": {
+ "announcements": [
+ {
+ "createdAt": DUMMY_CREATED_AT,
+ "updatedAt": DUMMY_UPDATED_AT,
+ "title": DUMMY_TITLE,
+ "messageHtml": DUMMY_DESCRIPTION,
+ "importance": "CRITICAL",
+ "type": "OTHER",
+ "extra": {
+ "foo": "bar",
+ "integer": 123, # should have allowed the non-str type
+ },
+ }
+ ]
+ }
+ }
+
+
+def test_get_announcements_allows_empty_extra_dict(settings, staff_api_client):
+ """Ensure the ``extra`` field can be empty (``{}``)."""
+
+ with use_dummy_announcements(
+ settings,
+ resolve_dummy_announcements_with_empty_extra_dict,
+ ):
+ response = staff_api_client.post_graphql(
+ QUERY_GET_ANNOUNCEMENTS_FULL,
+ )
+
+ content = get_graphql_content(response)
+ assert content["data"] == {
+ "shop": {
+ "announcements": [
+ {
+ "createdAt": DUMMY_CREATED_AT,
+ "updatedAt": DUMMY_UPDATED_AT,
+ "title": DUMMY_TITLE,
+ "messageHtml": DUMMY_DESCRIPTION,
+ "importance": "CRITICAL",
+ "type": "OTHER",
+ "extra": {}, # Should have allowed the empty dict
+ }
+ ]
+ }
+ }
+
+
+def test_get_announcements_does_not_allow_null_extra(settings, staff_api_client):
+ """Ensure the ``extra`` field cannot be null.
+
+ ``extra=None`` shouldn't be allowed, instead it should be an empty dict.
+ This should cause Saleor to reject the value (crash).
+ """
+
+ with use_dummy_announcements(
+ settings,
+ resolve_dummy_announcements_with_null_extra,
+ ):
+ response = staff_api_client.post_graphql(
+ QUERY_GET_ANNOUNCEMENTS_FULL,
+ )
+
+ response = get_graphql_content_from_response(response)
+ errors = response.get("errors", [])
+ assert len(errors) == 1
+ assert (
+ errors[0]["message"]
+ == "Cannot return null for non-nullable field Announcement.extra."
+ )
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index 74c50097a2..be3afee654 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -13,6 +13,7 @@ from ...payment.gateway import get_payment_gateways
from ...permission.auth_filters import AuthorizationFilters
from ...permission.enums import AppPermission, SitePermissions, get_permissions
from ...site import models as site_models
+from ...site.apps import SiteAppConfig
from ..account.types import Address, AddressInput, StaffNotificationRecipient
from ..app.types import App
from ..core import ResolveInfo
@@ -31,6 +32,7 @@ from ..core.doc_category import (
)
from ..core.enums import LanguageCodeEnum, WeightUnitsEnum
from ..core.fields import PermissionsField
+from ..core.scalars import DateTime
from ..core.tracing import traced_resolver
from ..core.types import (
BaseObjectType,
@@ -42,7 +44,7 @@ from ..core.types import (
TimePeriod,
)
from ..core.utils import str_to_enum
-from ..meta.types import ObjectWithMetadata
+from ..meta.types import Metadata, ObjectWithMetadata
from ..page.types import PageType
from ..payment.types import PaymentGateway
from ..plugins.dataloaders import plugin_manager_promise_callback
@@ -52,7 +54,11 @@ from ..translations.fields import TranslationField
from ..translations.resolvers import resolve_translation
from ..translations.types import ShopTranslation
from ..utils import format_permissions_for_display
-from .enums import GiftCardSettingsExpiryTypeEnum, PasswordLoginModeEnum
+from .enums import (
+ AnnouncementImportanceEnum,
+ GiftCardSettingsExpiryTypeEnum,
+ PasswordLoginModeEnum,
+)
from .filters import CountryFilterInput
from .resolvers import resolve_available_shipping_methods, resolve_countries
@@ -177,6 +183,47 @@ class LimitInfo(graphene.ObjectType):
description = "Store the current and allowed usage."
+class Announcement(graphene.ObjectType):
+ created_at = DateTime(
+ required=True,
+ description="The date & time at which this announcement was created.",
+ )
+ updated_at = DateTime(
+ required=True,
+ description="The date & time at which this announcement was last updated.",
+ )
+
+ title = graphene.String(required=True, description="The announcement's title.")
+ message_html = graphene.String(
+ required=True,
+ description="The announcement's description, may contain HTML formatting.",
+ )
+ importance = AnnouncementImportanceEnum(
+ required=True,
+ description=(
+ "Determine the how critical the announcement is. UNSET if no "
+ "severity level was defined for this announcement. When value is `UNSET`, "
+ "it should be considered as low importance or informational."
+ ),
+ )
+
+ type = graphene.String(
+ required=True,
+ description=(
+ 'The announcement\'s type, for example "CUSTOM". Used to '
+ "programatically distinguish between message types thus allowing to "
+ "render the message differently, and allows to know the expected shape "
+ "for the `extra` field."
+ ),
+ )
+ extra = Metadata(
+ required=True, description="Additional information about this announcement."
+ )
+
+ class Meta:
+ description = "Lists current announcements that the user should see."
+
+
class Shop(graphene.ObjectType):
id = graphene.ID(description="ID of the shop.", required=True)
available_payment_gateways = NonNullList(
@@ -344,6 +391,12 @@ class Shop(graphene.ObjectType):
deprecation_reason=DEFAULT_DEPRECATION_REASON,
permissions=[AuthorizationFilters.AUTHENTICATED_STAFF_USER],
)
+ announcements = PermissionsField(
+ NonNullList(Announcement),
+ required=True,
+ description="List of announcements for this shop.",
+ permissions=[AuthorizationFilters.AUTHENTICATED_STAFF_USER],
+ )
version = PermissionsField(
graphene.String,
description="Saleor API version.",
@@ -631,6 +684,17 @@ class Shop(graphene.ObjectType):
def resolve_limits(_, _info):
return LimitInfo(current_usage=Limits(), allowed_usage=Limits())
+ @staticmethod
+ def resolve_announcements(_, _info):
+ """Return the list of announcements for this shop.
+
+ This is not implement in Saleor Core OSS. However, this can be implemented
+ by overriding ``settings.SHOP_ANNOUNCEMENT_RESOLVER_IMPORT``.
+ """
+ if SiteAppConfig.announcements_resolver is not None:
+ return SiteAppConfig.announcements_resolver()
+ return []
+
@staticmethod
def resolve_version(_, _info):
return __version__
diff --git a/saleor/settings.py b/saleor/settings.py
index 3ee784c50d..a3b83639a5 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -908,6 +908,20 @@ GRAPHQL_QUERY_MAX_COMPLEXITY = int(
# Set FEDERATED_QUERY_MAX_ENTITIES=0 in env to disable (not recommended)
FEDERATED_QUERY_MAX_ENTITIES = int(os.environ.get("FEDERATED_QUERY_MAX_ENTITIES", 100))
+# Optional - Python import path of a GraphQL resolver to allow Saleor to return
+# announcements. See ``saleor/site/apps.py`` and ``saleor/graphql/shop/types.py``
+# for details around the Announcements API.
+#
+# Value must be an import path, e.g.:
+# SHOP_ANNOUNCEMENT_RESOLVER_IMPORT="saleor.custom.announcements.resolve_announcements"
+#
+# Where ``resolve_announcements`` should have the following signature:
+#
+# >>> from saleor.graphql.shop.types import Announcement
+# >>>
+# >>> def resolve_announcements() -> list[Announcement]: ...
+SHOP_ANNOUNCEMENT_RESOLVER_IMPORT = None
+
BUILTIN_PLUGINS = [
"saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin",
"saleor.plugins.webhook.plugin.WebhookPlugin",
diff --git a/saleor/site/__init__.py b/saleor/site/__init__.py
index f0e2be169f..f3c4eda9d7 100644
--- a/saleor/site/__init__.py
+++ b/saleor/site/__init__.py
@@ -27,3 +27,21 @@ class GiftCardSettingsExpiryType:
(NEVER_EXPIRE, "Never expire"),
(EXPIRY_PERIOD, "Expiry period"),
]
+
+
+class AnnouncementImportance:
+ """Defines a shop-level announcement's level/severity."""
+
+ CRITICAL = "critical"
+ HIGH = "high"
+ MODERATE = "moderate"
+ LOW = "low"
+ UNSET = "unset"
+
+ CHOICES = [
+ (CRITICAL, "Critical"),
+ (HIGH, "High"),
+ (MODERATE, "Moderate"),
+ (LOW, "Low"),
+ (UNSET, "Unset"),
+ ]
diff --git a/saleor/site/apps.py b/saleor/site/apps.py
new file mode 100644
index 0000000000..e7977a9408
--- /dev/null
+++ b/saleor/site/apps.py
@@ -0,0 +1,25 @@
+from collections.abc import Callable
+from typing import TYPE_CHECKING
+
+from django.apps import AppConfig
+from django.conf import settings
+from django.utils.module_loading import import_string
+
+if TYPE_CHECKING is True:
+ from ..graphql.shop.types import Announcement
+
+
+class SiteAppConfig(AppConfig):
+ name = "saleor.site"
+
+ announcements_resolver: Callable[[], list["Announcement"]] | None = None
+
+ @classmethod
+ def setup_announcements(cls):
+ if settings.SHOP_ANNOUNCEMENT_RESOLVER_IMPORT is not None:
+ cls.announcements_resolver = import_string(
+ settings.SHOP_ANNOUNCEMENT_RESOLVER_IMPORT
+ )
+
+ def ready(self):
+ self.setup_announcements()