Skip to content

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

Added metadata for channels (#13230)

Smit Parmar45cfb26218c8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 20ab0198a0..2b870aec09 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -64,6 +64,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Added `metadata` and `privateMetadata` in `ShopSettingsInput`. #13128 by @Smit-Parmar
- 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
- Remove `Preview feature` label from `metafield`, `metafields`, `metadata`,
`privateMetafield`, `privateMetafields` and `privateMetadata` fields - #13245 by @korycins
- Add `search` to `giftCards` query - #13173 by @zedzior
diff --git a/saleor/channel/migrations/0013_auto_20230630_1039.py b/saleor/channel/migrations/0013_auto_20230630_1039.py
new file mode 100644
index 0000000000..ef1271af4a
--- /dev/null
+++ b/saleor/channel/migrations/0013_auto_20230630_1039.py
@@ -0,0 +1,46 @@
+# Generated by Django 3.2.19 on 2023-06-30 10:39
+
+import django.contrib.postgres.indexes
+from django.db import migrations, models
+import saleor.core.utils.json_serializer
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("channel", "0012_channel_delete_expired_orders_after"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="channel",
+ name="metadata",
+ field=models.JSONField(
+ blank=True,
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="channel",
+ name="private_metadata",
+ field=models.JSONField(
+ blank=True,
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ null=True,
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="channel",
+ index=django.contrib.postgres.indexes.GinIndex(
+ fields=["private_metadata"], name="channel_p_meta_idx"
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="channel",
+ index=django.contrib.postgres.indexes.GinIndex(
+ fields=["metadata"], name="channel_meta_idx"
+ ),
+ ),
+ ]
diff --git a/saleor/channel/models.py b/saleor/channel/models.py
index 30f8a3b56b..86c3201356 100644
--- a/saleor/channel/models.py
+++ b/saleor/channel/models.py
@@ -4,11 +4,12 @@ from django.conf import settings
from django.db import models
from django_countries.fields import CountryField
+from ..core.models import ModelWithMetadata
from ..permission.enums import ChannelPermissions
from . import AllocationStrategy, MarkAsPaidStrategy, TransactionFlowStrategy
-class Channel(models.Model):
+class Channel(ModelWithMetadata):
name = models.CharField(max_length=250)
is_active = models.BooleanField(default=False)
slug = models.SlugField(max_length=255, unique=True)
@@ -42,7 +43,7 @@ class Channel(models.Model):
default=timedelta(days=60),
)
- class Meta:
+ class Meta(ModelWithMetadata.Meta):
ordering = ("slug",)
app_label = "channel"
permissions = (
diff --git a/saleor/graphql/channel/mutations/channel_create.py b/saleor/graphql/channel/mutations/channel_create.py
index 65b6046be9..52e6b6248b 100644
--- a/saleor/graphql/channel/mutations/channel_create.py
+++ b/saleor/graphql/channel/mutations/channel_create.py
@@ -15,6 +15,7 @@ from ...core.descriptions import (
ADDED_IN_312,
ADDED_IN_313,
ADDED_IN_314,
+ ADDED_IN_315,
PREVIEW_FEATURE,
)
from ...core.doc_category import (
@@ -25,7 +26,9 @@ from ...core.doc_category import (
from ...core.mutations import ModelMutation
from ...core.scalars import Day, Minute
from ...core.types import BaseInputObjectType, ChannelError, NonNullList
+from ...core.types import common as common_types
from ...core.utils import WebhookEventInfo
+from ...meta.inputs import MetadataInput
from ...plugins.dataloaders import get_plugin_manager_promise
from ..enums import (
AllocationStrategyEnum,
@@ -125,6 +128,16 @@ class ChannelInput(BaseInputObjectType):
description="The channel order settings" + ADDED_IN_312,
required=False,
)
+ metadata = common_types.NonNullList(
+ MetadataInput,
+ description="Channel public metadata." + ADDED_IN_315,
+ required=False,
+ )
+ private_metadata = common_types.NonNullList(
+ MetadataInput,
+ description="Channel private metadata." + ADDED_IN_315,
+ required=False,
+ )
class Meta:
doc_category = DOC_CATEGORY_CHANNELS
@@ -168,6 +181,8 @@ class ChannelCreate(ModelMutation):
description="A channel was created.",
),
]
+ support_meta_field = True
+ support_private_meta_field = True
@classmethod
def get_type_for_model(cls):
diff --git a/saleor/graphql/channel/mutations/channel_update.py b/saleor/graphql/channel/mutations/channel_update.py
index ee22294837..ead90427f6 100644
--- a/saleor/graphql/channel/mutations/channel_update.py
+++ b/saleor/graphql/channel/mutations/channel_update.py
@@ -76,6 +76,8 @@ class ChannelUpdate(ModelMutation):
description="A channel was updated.",
),
]
+ support_meta_field = True
+ support_private_meta_field = True
@classmethod
def clean_input(cls, info: ResolveInfo, instance, data, **kwargs):
diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.py
index 7ca17253a7..cd6accf291 100644
--- a/saleor/graphql/channel/types.py
+++ b/saleor/graphql/channel/types.py
@@ -23,6 +23,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_ORDERS, DOC_CATEGORY_PRODUCTS
@@ -324,7 +325,8 @@ class Channel(ModelObjectType):
class Meta:
description = "Represents channel."
model = models.Channel
- interfaces = [graphene.relay.Node]
+ interfaces = [graphene.relay.Node, ObjectWithMetadata]
+ metadata_since = ADDED_IN_315
@staticmethod
def resolve_has_orders(root: models.Channel, info: ResolveInfo):
diff --git a/saleor/graphql/meta/permissions.py b/saleor/graphql/meta/permissions.py
index 75dcd29328..86a7e528e6 100644
--- a/saleor/graphql/meta/permissions.py
+++ b/saleor/graphql/meta/permissions.py
@@ -14,6 +14,7 @@ from ...permission.enums import (
AccountPermissions,
AppPermission,
BasePermissionEnum,
+ ChannelPermissions,
CheckoutPermissions,
DiscountPermissions,
GiftcardPermissions,
@@ -196,6 +197,12 @@ def private_app_permssions(
return [AppPermission.MANAGE_APPS]
+def channel_permissions(
+ _info: ResolveInfo, _object_pk: Any
+) -> List[BasePermissionEnum]:
+ return [ChannelPermissions.MANAGE_CHANNELS]
+
+
def checkout_permissions(
_info: ResolveInfo, _object_pk: Any
) -> List[BasePermissionEnum]:
@@ -277,6 +284,7 @@ PUBLIC_META_PERMISSION_MAP: Dict[
"App": app_permissions,
"Attribute": attribute_permissions,
"Category": product_permissions,
+ "Channel": channel_permissions,
"Checkout": no_permissions,
"CheckoutLine": no_permissions,
"Collection": product_permissions,
@@ -315,6 +323,7 @@ PRIVATE_META_PERMISSION_MAP: Dict[
"App": private_app_permssions,
"Attribute": attribute_permissions,
"Category": product_permissions,
+ "Channel": channel_permissions,
"Checkout": checkout_permissions,
"CheckoutLine": checkout_permissions,
"Collection": product_permissions,
diff --git a/saleor/graphql/meta/resolvers.py b/saleor/graphql/meta/resolvers.py
index 604123a5d2..b9bcb498db 100644
--- a/saleor/graphql/meta/resolvers.py
+++ b/saleor/graphql/meta/resolvers.py
@@ -4,6 +4,7 @@ from operator import itemgetter
from ...account import models as account_models
from ...app import models as app_models
from ...attribute import models as attribute_models
+from ...channel import models as channel_models
from ...checkout import models as checkout_models
from ...core.exceptions import PermissionDenied
from ...core.models import ModelWithMetadata
@@ -31,6 +32,7 @@ def resolve_object_with_metadata_type(instance):
from ..account import types as account_types
from ..app import types as app_types
from ..attribute import types as attribute_types
+ from ..channel import types as channel_types
from ..checkout import types as checkout_types
from ..discount import types as discount_types
from ..giftcard import types as giftcard_types
@@ -51,6 +53,7 @@ def resolve_object_with_metadata_type(instance):
account_models.User: account_types.User,
app_models.App: app_types.App,
attribute_models.Attribute: attribute_types.Attribute,
+ channel_models.Channel: channel_types.Channel,
checkout_models.Checkout: checkout_types.Checkout,
checkout_models.CheckoutMetadata: checkout_types.Checkout,
checkout_models.CheckoutLine: checkout_types.CheckoutLine,
diff --git a/saleor/graphql/meta/tests/mutations/test_channel.py b/saleor/graphql/meta/tests/mutations/test_channel.py
new file mode 100644
index 0000000000..ab6213ac9e
--- /dev/null
+++ b/saleor/graphql/meta/tests/mutations/test_channel.py
@@ -0,0 +1,91 @@
+import graphene
+
+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,
+)
+
+
+def test_delete_private_metadata_for_channel(
+ staff_api_client, permission_manage_channels, channel_USD
+):
+ # given
+ channel_USD.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
+ channel_USD.save(update_fields=["private_metadata"])
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+
+ # when
+ response = execute_clear_private_metadata_for_item(
+ staff_api_client, permission_manage_channels, channel_id, "Channel"
+ )
+
+ # then
+ assert item_without_private_metadata(
+ response["data"]["deletePrivateMetadata"]["item"], channel_USD, channel_id
+ )
+
+
+def test_delete_public_metadata_for_gift_card(
+ staff_api_client, permission_manage_channels, channel_USD
+):
+ # given
+ channel_USD.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
+ channel_USD.save(update_fields=["metadata"])
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+
+ # when
+ response = execute_clear_public_metadata_for_item(
+ staff_api_client, permission_manage_channels, channel_id, "Channel"
+ )
+
+ # then
+ assert item_without_public_metadata(
+ response["data"]["deleteMetadata"]["item"], channel_USD, channel_id
+ )
+
+
+def test_add_public_metadata_for_channel_USD(
+ staff_api_client, permission_manage_channels, channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+
+ # when
+ response = execute_update_public_metadata_for_item(
+ staff_api_client, permission_manage_channels, channel_id, "Channel"
+ )
+
+ # then
+ assert item_contains_proper_public_metadata(
+ response["data"]["updateMetadata"]["item"], channel_USD, channel_id
+ )
+
+
+def test_add_private_metadata_for_channel_USD(
+ staff_api_client, permission_manage_channels, channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+
+ # when
+ response = execute_update_private_metadata_for_item(
+ staff_api_client, permission_manage_channels, channel_id, "Channel"
+ )
+
+ # then
+ assert item_contains_proper_private_metadata(
+ response["data"]["updatePrivateMetadata"]["item"], channel_USD, channel_id
+ )
diff --git a/saleor/graphql/meta/tests/queries/test_channel.py b/saleor/graphql/meta/tests/queries/test_channel.py
new file mode 100644
index 0000000000..5e8f65eaee
--- /dev/null
+++ b/saleor/graphql/meta/tests/queries/test_channel.py
@@ -0,0 +1,179 @@
+import graphene
+
+from ....tests.utils import assert_no_permission, get_graphql_content
+from .utils import PRIVATE_KEY, PRIVATE_VALUE, PUBLIC_KEY, PUBLIC_VALUE
+
+QUERY_CHANNEL_PRIVATE_META = """
+ query channelMeta($id: ID!){
+ channel(id: $id){
+ privateMetadata{
+ key
+ value
+ }
+ }
+ }
+"""
+
+
+def test_query_private_meta_for_channel_as_anonymous_user(api_client, channel_USD):
+ # given
+ variables = {
+ "id": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ }
+
+ # when
+ response = api_client.post_graphql(QUERY_CHANNEL_PRIVATE_META, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_query_private_meta_for_channel_as_customer(user_api_client, channel_USD):
+ # given
+ variables = {
+ "id": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ }
+
+ # when
+ response = user_api_client.post_graphql(QUERY_CHANNEL_PRIVATE_META, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_query_private_meta_for_channel_as_staff(
+ staff_api_client, channel_USD, permission_manage_channels
+):
+ # given
+ channel_USD.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
+ channel_USD.save(update_fields=["private_metadata"])
+ variables = {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_CHANNEL_PRIVATE_META,
+ variables,
+ [permission_manage_channels],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+
+ # then
+ metadata = content["data"]["channel"]["privateMetadata"][0]
+ assert metadata["key"] == PRIVATE_KEY
+ assert metadata["value"] == PRIVATE_VALUE
+
+
+def test_query_private_meta_for_channel_as_app(
+ app_api_client, channel_USD, permission_manage_channels
+):
+ # given
+ channel_USD.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
+ channel_USD.save(update_fields=["private_metadata"])
+ variables = {
+ "id": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_CHANNEL_PRIVATE_META,
+ variables,
+ [permission_manage_channels],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+
+ # then
+ metadata = content["data"]["channel"]["privateMetadata"][0]
+ assert metadata["key"] == PRIVATE_KEY
+ assert metadata["value"] == PRIVATE_VALUE
+
+
+QUERY_CHANNEL_PUBLIC_META = """
+ query channelMeta($id: ID!){
+ channel(id: $id){
+ metadata{
+ key
+ value
+ }
+ }
+ }
+"""
+
+
+def test_query_public_meta_for_channel_as_anonymous_user(api_client, channel_USD):
+ # given
+ channel_USD.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
+ channel_USD.save(update_fields=["metadata"])
+ variables = {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)}
+
+ # when
+ response = api_client.post_graphql(QUERY_CHANNEL_PUBLIC_META, variables)
+ content = get_graphql_content(response)
+
+ # then
+ metadata = content["data"]["channel"]["metadata"][0]
+ assert metadata["key"] == PUBLIC_KEY
+ assert metadata["value"] == PUBLIC_VALUE
+
+
+def test_query_public_meta_for_channel_as_customer(user_api_client, channel_USD):
+ # given
+ channel_USD.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
+ channel_USD.save(update_fields=["metadata"])
+ variables = {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)}
+
+ # when
+ response = user_api_client.post_graphql(QUERY_CHANNEL_PUBLIC_META, variables)
+ content = get_graphql_content(response)
+
+ # then
+ metadata = content["data"]["channel"]["metadata"][0]
+ assert metadata["key"] == PUBLIC_KEY
+ assert metadata["value"] == PUBLIC_VALUE
+
+
+def test_query_public_meta_for_channel_as_staff(
+ staff_api_client, channel_USD, permission_manage_channels
+):
+ # given
+ channel_USD.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
+ channel_USD.save(update_fields=["metadata"])
+ variables = {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_CHANNEL_PUBLIC_META,
+ variables,
+ [permission_manage_channels],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+
+ # then
+ metadata = content["data"]["channel"]["metadata"][0]
+ assert metadata["key"] == PUBLIC_KEY
+ assert metadata["value"] == PUBLIC_VALUE
+
+
+def test_query_public_meta_for_channel_as_app(
+ app_api_client, channel_USD, permission_manage_channels
+):
+ # given
+ channel_USD.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
+ channel_USD.save(update_fields=["metadata"])
+ variables = {"id": graphene.Node.to_global_id("Channel", channel_USD.pk)}
+
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_CHANNEL_PUBLIC_META,
+ variables,
+ [permission_manage_channels],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+
+ # then
+ metadata = content["data"]["channel"]["metadata"][0]
+ assert metadata["key"] == PUBLIC_KEY
+ assert metadata["value"] == PUBLIC_VALUE
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index b6f5b45640..5b967172b5 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -4740,10 +4740,56 @@ type ShippingMethodChannelListing implements Node @doc(category: "Shipping") {
}
"""Represents channel."""
-type Channel implements Node @doc(category: "Channels") {
+type Channel implements Node & ObjectWithMetadata @doc(category: "Channels") {
"""The ID of the channel."""
id: ID!
+ """
+ List of private metadata items. Requires staff permissions to access.
+
+ Added in Saleor 3.15.
+ """
+ privateMetadata: [MetadataItem!]!
+
+ """
+ A single key from private metadata. Requires staff permissions to access.
+
+ Tip: Use GraphQL aliases to fetch multiple keys.
+
+ Added in Saleor 3.15.
+ """
+ privateMetafield(key: String!): String
+
+ """
+ Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.
+
+ Added in Saleor 3.15.
+ """
+ privateMetafields(keys: [String!]): Metadata
+
+ """
+ List of public metadata items. Can be accessed without permissions.
+
+ Added in Saleor 3.15.
+ """
+ metadata: [MetadataItem!]!
+
+ """
+ A single key from public metadata.
+
+ Tip: Use GraphQL aliases to fetch multiple keys.
+
+ Added in Saleor 3.15.
+ """
+ metafield(key: String!): String
+
+ """
+ Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.
+
+ Added in Saleor 3.15.
+ """
+ metafields(keys: [String!]): Metadata
+
"""Slug of the channel."""
slug: String!
@@ -26244,6 +26290,20 @@ input ChannelCreateInput @doc(category: "Channels") {
"""
orderSettings: OrderSettingsInput
+ """
+ Channel public metadata.
+
+ Added in Saleor 3.15.
+ """
+ metadata: [MetadataInput!]
+
+ """
+ Channel private metadata.
+
+ Added in Saleor 3.15.
+ """
+ privateMetadata: [MetadataInput!]
+
"""Name of the channel."""
name: String!
@@ -26361,6 +26421,20 @@ input ChannelUpdateInput @doc(category: "Channels") {
"""
orderSettings: OrderSettingsInput
+ """
+ Channel public metadata.
+
+ Added in Saleor 3.15.
+ """
+ metadata: [MetadataInput!]
+
+ """
+ Channel private metadata.
+
+ Added in Saleor 3.15.
+ """
+ privateMetadata: [MetadataInput!]
+
"""Name of the channel."""
name: String