Skip to content

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

Add `attribute` field to `page` type (#17741)

Iga Karbowiakcd79226d62e2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fd6022d836..d0fee69316 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ All notable, unreleased changes to this project will be documented in this file.
### Breaking changes
### GraphQL API
+- Extend the `Page` type with an `attribute` field. Adds support for querying a specific attribute on a page by `slug`, returning the matching attribute and its assigned values, or null if no match is found.
### Webhooks
diff --git a/saleor/graphql/page/dataloaders.py b/saleor/graphql/page/dataloaders.py
index 388605010c..238402796b 100644
--- a/saleor/graphql/page/dataloaders.py
+++ b/saleor/graphql/page/dataloaders.py
@@ -1,4 +1,5 @@
from collections import defaultdict
+from collections.abc import Iterable
from django.db.models import Exists, OuterRef
from promise import Promise
@@ -8,6 +9,8 @@ from ...page.models import Page, PageType
from ..attribute.dataloaders import AttributesByAttributeId, AttributeValueByIdLoader
from ..core.dataloaders import DataLoader
+PageTypeIdAndAttributeSlug = tuple[int, str]
+
class PageByIdLoader(DataLoader[int, Page]):
context_key = "page_by_id"
@@ -190,3 +193,179 @@ class SelectedAttributesVisibleInStorefrontPageIdLoader(DataLoader[int, list[dic
return AttributeValuesVisibleInStorefrontByPageIdLoader(self.context).load_many(
page_ids
)
+
+
+class BasePageAttributeByPageTypeIdAndAttributeSlugLoader(
+ DataLoader[PageTypeIdAndAttributeSlug, Attribute]
+):
+ """Loads page attributes by page type ID and attribute slug."""
+
+ context_key = "page_attributes_by_pagetype_and_attributeslug"
+
+ def get_queryset(self, slugs):
+ raise NotImplementedError()
+
+ def batch_load(self, keys: Iterable[PageTypeIdAndAttributeSlug]):
+ slugs = [slug for _, slug in keys]
+ qs = self.get_queryset(slugs)
+ page_ids = [page_id for page_id, _ in keys]
+ page_type_attribute_pairs = qs.filter(page_type_id__in=page_ids).values_list(
+ "page_type_id", "attribute_id"
+ )
+
+ def map_attributes(attributes):
+ attribute_slug_map = {
+ attr.id: attr.slug for attr in attributes if attr.slug in slugs
+ }
+ attributes_map = {attr.id: attr for attr in attributes}
+
+ page_type_to_attributes_map = {}
+ for page_type_id, attr_id in page_type_attribute_pairs:
+ page_type_to_attributes_map[
+ (page_type_id, attribute_slug_map.get(attr_id))
+ ] = attributes_map.get(attr_id)
+
+ return [
+ page_type_to_attributes_map.get((page_type_id, slug))
+ for page_type_id, slug in keys
+ ]
+
+ return (
+ AttributesByAttributeId(self.context)
+ .load_many({attr_id for _, attr_id in page_type_attribute_pairs})
+ .then(map_attributes)
+ )
+
+
+class PageAttributeByPageTypeIdAndAttributeSlugLoader(
+ BasePageAttributeByPageTypeIdAndAttributeSlugLoader
+):
+ """Loads page attributes by page type ID and attribute slug."""
+
+ context_key = "page_attribute_by_pagetype_and_attributeslug"
+
+ def get_queryset(self, slugs):
+ return AttributePage.objects.using(self.database_connection_name).filter(
+ Exists(
+ Attribute.objects.filter(pk=OuterRef("attribute_id"), slug__in=slugs)
+ ),
+ )
+
+
+class PageAttributeVisibleInStorefrontByPageTypeIdAndAttributeSlugLoader(
+ BasePageAttributeByPageTypeIdAndAttributeSlugLoader
+):
+ """Loads page attributes by page type ID and attribute slug."""
+
+ context_key = "page_attributes_visible_in_storefront_by_pagetype_and_attributeslug"
+
+ def get_queryset(self, slugs):
+ return AttributePage.objects.using(self.database_connection_name).filter(
+ Exists(
+ Attribute.objects.filter(
+ pk=OuterRef("attribute_id"),
+ visible_in_storefront=True,
+ slug__in=slugs,
+ )
+ ),
+ )
+
+
+class BaseAttributeValuesByPageIdAndAttributeSlugLoader(
+ DataLoader[PageTypeIdAndAttributeSlug, dict]
+):
+ def get_page_attributes_dataloader(self):
+ raise NotImplementedError()
+
+ def batch_load(self, keys: Iterable[PageTypeIdAndAttributeSlug]):
+ # Using list + iterator is a small optimisation because iterator causes
+ # the db to not store the whole resultset into the memory
+ # https://docs.djangoproject.com/en/3.2/ref/models/querysets/#iterator
+ page_ids = [page_id for page_id, _ in keys]
+ slugs = [slug for _, slug in keys]
+ attribute_values = list(
+ AssignedPageAttributeValue.objects.using(self.database_connection_name)
+ .filter(page_id__in=page_ids)
+ .iterator()
+ )
+ value_ids = [a.value_id for a in attribute_values]
+
+ def with_pages(pages):
+ pages = [page for page in pages if page]
+ page_type_ids = [p.page_type_id for p in pages]
+
+ def with_attributes_and_values(result):
+ attribute_pages, values = result
+ page_type_attribute = dict(
+ zip(page_type_ids, attribute_pages, strict=False)
+ )
+ values_by_id_map = dict(zip(value_ids, values, strict=False))
+ assigned_page_map = {}
+
+ for page in pages:
+ page_values = [
+ values_by_id_map.get(page_value.value_id)
+ for page_value in attribute_values
+ if page_value.page_id == page.id
+ ]
+
+ attribute = page_type_attribute[page.page_type_id]
+ if attribute:
+ values = [
+ value
+ for value in page_values
+ if value and value.attribute_id == attribute.id
+ ]
+ assigned_page_map[(page.id, attribute.slug)] = {
+ "attribute": attribute,
+ "values": values,
+ }
+ return [assigned_page_map.get(key) for key in keys]
+
+ attributes = self.get_page_attributes_dataloader().load_many(
+ list(zip(page_type_ids, slugs, strict=False))
+ )
+ values = AttributeValueByIdLoader(self.context).load_many(value_ids)
+ return Promise.all([attributes, values]).then(with_attributes_and_values)
+
+ return PageByIdLoader(self.context).load_many(page_ids).then(with_pages)
+
+
+class AttributeValuesAllByPageIdAndAttributeSlugLoader(
+ BaseAttributeValuesByPageIdAndAttributeSlugLoader
+):
+ context_key = "attributevalues_all_by_page_and_attributeslug"
+
+ def get_page_attributes_dataloader(self):
+ return PageAttributeByPageTypeIdAndAttributeSlugLoader(self.context)
+
+
+class AttributeValuesVisibleInStorefrontByPageIdAndAttributeSlugLoader(
+ BaseAttributeValuesByPageIdAndAttributeSlugLoader
+):
+ context_key = "attributevalues_visible_in_storefront_by_page_and_attributeslug"
+
+ def get_page_attributes_dataloader(self):
+ return PageAttributeVisibleInStorefrontByPageTypeIdAndAttributeSlugLoader(
+ self.context
+ )
+
+
+class SelectedAttributeAllByPageIdAttributeSlugLoader(DataLoader[int, list[dict]]):
+ context_key = "selectedattributes_all_by_page_and_attribute_slug"
+
+ def batch_load(self, page_ids):
+ return AttributeValuesAllByPageIdAndAttributeSlugLoader(self.context).load_many(
+ page_ids
+ )
+
+
+class SelectedAttributeVisibleInStorefrontPageIdAttributeSlugLoader(
+ DataLoader[int, list[dict]]
+):
+ context_key = "selectedattributes_visible_in_storefront_by_page_and_attribute_slug"
+
+ def batch_load(self, page_ids):
+ return AttributeValuesVisibleInStorefrontByPageIdAndAttributeSlugLoader(
+ self.context
+ ).load_many(page_ids)
diff --git a/saleor/graphql/page/tests/queries/test_page.py b/saleor/graphql/page/tests/queries/test_page.py
index 8d47a1eeb1..26d28fc60a 100644
--- a/saleor/graphql/page/tests/queries/test_page.py
+++ b/saleor/graphql/page/tests/queries/test_page.py
@@ -322,7 +322,7 @@ def test_get_page_with_sorted_attribute_values(
]
-def test_page_attribute_not_visible_in_storefront_for_customer_is_not_returned(
+def test_page_attributes_not_visible_in_storefront_for_customer_is_not_returned(
user_api_client, page
):
# given
@@ -357,7 +357,7 @@ def test_page_attribute_not_visible_in_storefront_for_customer_is_not_returned(
assert attr_data == {}
-def test_page_attribute_visible_in_storefront_for_customer_is_returned(
+def test_page_attributes_visible_in_storefront_for_customer_is_returned(
user_api_client, page
):
# given
@@ -394,7 +394,7 @@ def test_page_attribute_visible_in_storefront_for_customer_is_returned(
@pytest.mark.parametrize("visible_in_storefront", [False, True])
-def test_page_attribute_visible_in_storefront_for_staff_is_always_returned(
+def test_page_attributes_visible_in_storefront_for_staff_is_always_returned(
visible_in_storefront,
staff_api_client,
page,
@@ -454,3 +454,150 @@ def test_page_query_by_translated_slug(user_api_client, page, page_translation_f
assert page_data is not None
assert page_data["title"] == page.title
+
+
+QUERY_PAGE_WITH_ATTRIBUTE = """
+query Page($id: ID!, $slug: String!) {
+ page(id: $id) {
+ attribute(slug: $slug) {
+ attribute {
+ id
+ slug
+ }
+ }
+ attributes {
+ attribute {
+ id
+ slug
+ }
+ }
+ }
+}
+"""
+
+
+def test_page_attribute_field_filtering(staff_api_client, page):
+ # given
+ slug = page.page_type.page_attributes.first().slug
+
+ variables = {
+ "id": graphene.Node.to_global_id("Page", page.pk),
+ "slug": slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PAGE_WITH_ATTRIBUTE,
+ variables,
+ )
+
+ # then
+ expected_slug = slug
+ content = get_graphql_content(response)
+ queried_slug = content["data"]["page"]["attribute"]["attribute"]["slug"]
+ assert queried_slug == expected_slug
+
+
+def test_page_attribute_field_filtering_not_found(staff_api_client, page):
+ # given
+ slug = ""
+
+ variables = {
+ "id": graphene.Node.to_global_id("Page", page.pk),
+ "slug": slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PAGE_WITH_ATTRIBUTE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["page"]["attribute"] is None
+
+
+def test_page_attribute_not_visible_in_storefront_for_customer_is_not_returned(
+ user_api_client, page
+):
+ # given
+ attribute = page.page_type.page_attributes.first()
+ attribute.visible_in_storefront = False
+ attribute.save(update_fields=["visible_in_storefront"])
+ visible_attrs_count = page.page_type.page_attributes.filter(
+ visible_in_storefront=True
+ ).count()
+
+ # when
+ variables = {
+ "id": graphene.Node.to_global_id("Page", page.pk),
+ "slug": attribute.slug,
+ }
+ response = user_api_client.post_graphql(
+ QUERY_PAGE_WITH_ATTRIBUTE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["page"]["attribute"] is None
+ assert len(content["data"]["page"]["attributes"]) == visible_attrs_count
+ attr_data = {
+ "attribute": {
+ "id": graphene.Node.to_global_id("Attribute", attribute.pk),
+ "slug": attribute.slug,
+ }
+ }
+ assert attr_data not in content["data"]["page"]["attributes"]
+
+
+def test_page_attribute_visible_in_storefront_for_customer_is_returned(
+ user_api_client, page
+):
+ # given
+ attribute = page.page_type.page_attributes.first()
+ attribute.visible_in_storefront = True
+ attribute.save(update_fields=["visible_in_storefront"])
+
+ # when
+ variables = {
+ "id": graphene.Node.to_global_id("Page", page.pk),
+ "slug": attribute.slug,
+ }
+ response = user_api_client.post_graphql(
+ QUERY_PAGE_WITH_ATTRIBUTE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["page"]["attribute"]["attribute"]["slug"] == attribute.slug
+
+
[email protected]("visible_in_storefront", [False, True])
+def test_page_attribute_visible_in_storefront_for_staff_is_always_returned(
+ visible_in_storefront,
+ staff_api_client,
+ page,
+ permission_manage_pages,
+):
+ # given
+ attribute = page.page_type.page_attributes.first()
+ attribute.visible_in_storefront = visible_in_storefront
+ attribute.save(update_fields=["visible_in_storefront"])
+
+ # when
+ variables = {
+ "id": graphene.Node.to_global_id("Page", page.pk),
+ "slug": attribute.slug,
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_pages)
+ response = staff_api_client.post_graphql(
+ QUERY_PAGE_WITH_ATTRIBUTE,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["page"]["attribute"]["attribute"]["slug"] == attribute.slug
diff --git a/saleor/graphql/page/types.py b/saleor/graphql/page/types.py
index 3f6284b007..5126143aaa 100644
--- a/saleor/graphql/page/types.py
+++ b/saleor/graphql/page/types.py
@@ -27,8 +27,10 @@ from .dataloaders import (
PageAttributesVisibleInStorefrontByPageTypeIdLoader,
PagesByPageTypeIdLoader,
PageTypeByIdLoader,
+ SelectedAttributeAllByPageIdAttributeSlugLoader,
SelectedAttributesAllByPageIdLoader,
SelectedAttributesVisibleInStorefrontPageIdLoader,
+ SelectedAttributeVisibleInStorefrontPageIdAttributeSlugLoader,
)
@@ -144,10 +146,19 @@ class Page(ModelObjectType[models.Page]):
required=True,
)
translation = TranslationField(PageTranslation, type_name="page")
+ attribute = graphene.Field(
+ SelectedAttribute,
+ slug=graphene.Argument(
+ graphene.String,
+ description="Slug of the attribute",
+ required=True,
+ ),
+ description="Get a single attribute attached to page by attribute slug.",
+ )
attributes = NonNullList(
SelectedAttribute,
required=True,
- description="List of attributes assigned to this product.",
+ description="List of attributes assigned to this page.",
)
class Meta:
@@ -188,6 +199,21 @@ class Page(ModelObjectType[models.Page]):
root.id
)
+ @staticmethod
+ def resolve_attribute(root: models.Page, info: ResolveInfo, slug: str):
+ requestor = get_user_or_app_from_context(info.context)
+ if (
+ requestor
+ and requestor.is_active
+ and requestor.has_perm(PagePermissions.MANAGE_PAGES)
+ ):
+ return SelectedAttributeAllByPageIdAttributeSlugLoader(info.context).load(
+ (root.id, slug)
+ )
+ return SelectedAttributeVisibleInStorefrontPageIdAttributeSlugLoader(
+ info.context
+ ).load((root.id, slug))
+
class PageCountableConnection(CountableConnection):
class Meta:
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 48f3e001eb..a9429f1f4c 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -8361,7 +8361,13 @@ type Page implements Node & ObjectWithMetadata @doc(category: "Pages") {
languageCode: LanguageCodeEnum!
): PageTranslation
- """List of attributes assigned to this product."""
+ """Get a single attribute attached to page by attribute slug."""
+ attribute(
+ """Slug of the attribute"""
+ slug: String!
+ ): SelectedAttribute
+
+ """List of attributes assigned to this page."""
attributes: [SelectedAttribute!]!
}