Skip to content

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

Improve resolvers of assigned attributes (#18192)

Maciej Korycinskifc23f5627d18
diff --git a/saleor/graphql/attribute/dataloaders/assigned_attributes.py b/saleor/graphql/attribute/dataloaders/assigned_attributes.py
new file mode 100644
index 0000000000..4ed899bd7f
--- /dev/null
+++ b/saleor/graphql/attribute/dataloaders/assigned_attributes.py
@@ -0,0 +1,740 @@
+from collections import defaultdict
+from collections.abc import Iterable
+
+from django.db.models import F, Window
+from django.db.models.functions import RowNumber
+from django.db.models.query import QuerySet
+from promise import Promise
+
+from ....attribute.models import Attribute, AttributeValue
+from ....attribute.models.page import AssignedPageAttributeValue, AttributePage
+from ....attribute.models.product import AssignedProductAttributeValue, AttributeProduct
+from ....attribute.models.product_variant import (
+ AssignedVariantAttribute,
+ AssignedVariantAttributeValue,
+ AttributeVariant,
+)
+from ....core.db.connection import allow_writer_in_context
+from ....page import models as page_models
+from ....product import models as product_models
+from ...core.dataloaders import DataLoader
+from ...page.dataloaders import PageByIdLoader
+from ...product.dataloaders.products import ProductByIdLoader, ProductByVariantIdLoader
+from .attributes import (
+ AttributesByAttributeId,
+ AttributesBySlugLoader,
+ AttributeValueByIdLoader,
+)
+
+type PRODUCT_ID = int
+type PRODUCT_TYPE_ID = int
+type PAGE_ID = int
+type VARIANT_ID = int
+type ATTRIBUTE_ID = int
+type ATTRIBUTE_SLUG = str
+type LIMIT = int | None
+type VARIANT_SELECTION = bool | None
+
+
+class AttributesByProductIdAndLimitLoader(
+ DataLoader[tuple[PRODUCT_ID, LIMIT], list[Attribute]]
+):
+ context_key = "attribute_ids_by_product_id_and_limit"
+
+ def get_attribute_product_qs(
+ self, product_type_ids: set[int]
+ ) -> QuerySet[AttributeProduct]:
+ return AttributeProduct.objects.using(self.database_connection_name).filter(
+ product_type__in=product_type_ids
+ )
+
+ def batch_load(self, keys: Iterable[tuple[PRODUCT_ID, LIMIT]]):
+ @allow_writer_in_context(self.context)
+ def with_products(products: list[product_models.Product]):
+ product_id_to_product_type_id_map = {
+ product.id: product.product_type_id for product in products if product
+ }
+ product_type_ids = set(product_id_to_product_type_id_map.values())
+
+ attribute_products = (
+ self.get_attribute_product_qs(product_type_ids)
+ .using(self.database_connection_name)
+ .values_list("attribute_id", "product_type_id")
+ )
+
+ product_type_id_to_attribute_ids = defaultdict(list)
+
+ for attribute_id, attr_product_type_id in attribute_products:
+ product_type_id_to_attribute_ids[attr_product_type_id].append(
+ attribute_id
+ )
+
+ attribute_ids = set()
+ for product_id, limit in keys:
+ product_type_id = product_id_to_product_type_id_map.get(product_id)
+ if not product_type_id:
+ continue
+ attribute_ids.update(
+ product_type_id_to_attribute_ids.get(product_type_id, [])[:limit]
+ )
+
+ def get_attributes_for_products(attributes: list[Attribute]):
+ attribute_map = {attr.id: attr for attr in attributes}
+
+ response = []
+ for product_id, limit in keys:
+ single_response_entry: list[Attribute] = []
+ product_type_id = product_id_to_product_type_id_map.get(product_id)
+ if not product_type_id:
+ response.append(single_response_entry)
+ continue
+ product_attribute_ids = product_type_id_to_attribute_ids.get(
+ product_type_id, []
+ )[:limit]
+ for product_attribute_id in product_attribute_ids:
+ attribute = attribute_map.get(product_attribute_id)
+ if not attribute:
+ continue
+ single_response_entry.append(attribute)
+ response.append(single_response_entry)
+ return response
+
+ return (
+ AttributesByAttributeId(self.context)
+ .load_many(attribute_ids)
+ .then(get_attributes_for_products)
+ )
+
+ product_ids = [product_id for product_id, _ in keys]
+ return (
+ ProductByIdLoader(self.context).load_many(product_ids).then(with_products)
+ )
+
+
+class AttributesVisibleToCustomerByProductIdAndLimitLoader(
+ AttributesByProductIdAndLimitLoader
+):
+ context_key = "attributes_visible_to_customer_by_product_id_and_limit"
+
+ def get_attribute_product_qs(
+ self, product_type_ids: set[int]
+ ) -> QuerySet[AttributeProduct]:
+ return AttributeProduct.objects.using(self.database_connection_name).filter(
+ attribute__visible_in_storefront=True,
+ product_type__in=product_type_ids,
+ )
+
+
+class AttributeByProductIdAndAttributeSlugLoader(
+ DataLoader[tuple[PRODUCT_ID, ATTRIBUTE_SLUG], Attribute | None]
+):
+ context_key = "attribute_by_product_id_and_attribute_slug"
+
+ def batch_load(self, keys: Iterable[tuple[PRODUCT_ID, ATTRIBUTE_SLUG]]):
+ product_ids = [product_id for product_id, _ in keys]
+ attribute_slugs = [attribute_slug for _, attribute_slug in keys]
+
+ def with_attributes_and_products(
+ data: tuple[list[product_models.Product], list[Attribute]],
+ ):
+ products, attributes = data
+ product_type_ids = {
+ product.product_type_id for product in products if product is not None
+ }
+ product_map = {
+ product.id: product for product in products if product is not None
+ }
+ attribute_map = {attr.slug: attr for attr in attributes if attr is not None}
+ attribute_products = (
+ AttributeProduct.objects.using(self.database_connection_name)
+ .filter(
+ attribute__in=[attr.id for attr in attribute_map.values()],
+ product_type__in=product_type_ids,
+ )
+ .values_list("attribute_id", "product_type_id")
+ )
+
+ product_type_id_to_attribute_ids = defaultdict(set)
+ for attribute_id, product_type_id in attribute_products:
+ product_type_id_to_attribute_ids[product_type_id].add(attribute_id)
+
+ response: list[Attribute | None] = []
+ for product_id, attribute_slug in keys:
+ attribute = attribute_map.get(attribute_slug)
+ if not attribute:
+ response.append(None)
+ continue
+
+ product = product_map.get(product_id)
+ if not product:
+ response.append(None)
+ continue
+ product_type_id = product.product_type_id
+ attributes_assigned_to_product_type = (
+ product_type_id_to_attribute_ids.get(product_type_id, set())
+ )
+ if attribute.id in attributes_assigned_to_product_type:
+ response.append(attribute)
+ else:
+ response.append(None)
+ return response
+
+ products_loader = ProductByIdLoader(self.context).load_many(product_ids)
+ attributes_loader = AttributesBySlugLoader(self.context).load_many(
+ attribute_slugs
+ )
+ return Promise.all([products_loader, attributes_loader]).then(
+ with_attributes_and_products
+ )
+
+
+class AttributeByProductVariantIdAndAttributeSlugLoader(
+ DataLoader[tuple[VARIANT_ID, ATTRIBUTE_SLUG], Attribute | None]
+):
+ context_key = "attribute_by_product_variant_id_and_attribute_slug"
+
+ def batch_load(self, keys: Iterable[tuple[VARIANT_ID, ATTRIBUTE_SLUG]]):
+ variant_ids = [variant_id for variant_id, _ in keys]
+ attribute_slugs = [attribute_slug for _, attribute_slug in keys]
+
+ def with_attributes_and_products(
+ data: tuple[list[product_models.Product], list[Attribute]],
+ ):
+ products, attributes = data
+ product_type_ids = {
+ product.product_type_id for product in products if product is not None
+ }
+ variant_id_to_product_map = {
+ variant_id: product
+ for (variant_id, _), product in zip(keys, products, strict=False)
+ }
+ attribute_map = {attr.slug: attr for attr in attributes if attr is not None}
+
+ attribute_variants = (
+ AttributeVariant.objects.using(self.database_connection_name)
+ .filter(
+ attribute__in=[attr.id for attr in attribute_map.values()],
+ product_type__in=product_type_ids,
+ )
+ .values_list("attribute_id", "product_type_id")
+ )
+ product_type_id_to_attribute_ids = defaultdict(set)
+ for attribute_id, attr_product_type_id in attribute_variants:
+ product_type_id_to_attribute_ids[attr_product_type_id].add(attribute_id)
+
+ response: list[Attribute | None] = []
+ for variant_id, attribute_slug in keys:
+ attribute = attribute_map.get(attribute_slug)
+ if not attribute:
+ response.append(None)
+ continue
+
+ product = variant_id_to_product_map.get(variant_id)
+ if not product:
+ response.append(None)
+ continue
+ product_type_id = product.product_type_id
+ attributes_assigned_to_product_type = (
+ product_type_id_to_attribute_ids.get(product_type_id, set())
+ )
+ if attribute.id in attributes_assigned_to_product_type:
+ response.append(attribute)
+ else:
+ response.append(None)
+ return response
+
+ products_loader = ProductByVariantIdLoader(self.context).load_many(variant_ids)
+ attributes_loader = AttributesBySlugLoader(self.context).load_many(
+ attribute_slugs
+ )
+ return Promise.all([products_loader, attributes_loader]).then(
+ with_attributes_and_products
+ )
+
+
+class AttributesByProductVariantIdAndSelectionAndLimitLoader(
+ DataLoader[tuple[VARIANT_ID, LIMIT, VARIANT_SELECTION], list[Attribute]]
+):
+ context_key = "attribute_ids_by_product_variant_id_and_limit"
+
+ def get_attribute_variant_qs(
+ self, product_type_ids: set[int]
+ ) -> QuerySet[AttributeVariant]:
+ return AttributeVariant.objects.using(self.database_connection_name).filter(
+ product_type__in=product_type_ids
+ )
+
+ def batch_load(self, keys: Iterable[tuple[VARIANT_ID, LIMIT, VARIANT_SELECTION]]):
+ @allow_writer_in_context(self.context)
+ def with_products(products: list[product_models.Product]):
+ # get attribute variants assigned to product type of the variants
+ variant_id_to_product_id_map = {
+ variant_id: product.id
+ for (variant_id, _, _), product in zip(keys, products, strict=False)
+ }
+ product_id_to_product_type_id_map = {
+ product.id: product.product_type_id for product in products
+ }
+ product_type_ids = set(product_id_to_product_type_id_map.values())
+ attribute_variants = self.get_attribute_variant_qs(
+ product_type_ids
+ ).values_list("attribute_id", "product_type_id", "variant_selection")
+
+ # create list of attribute ids to fetch for each variant. Use limit and
+ # selection to reduce the number of attributes to fetch
+ product_type_id_to_attribute_id_and_variant_selection = defaultdict(list)
+ for (
+ attribute_id,
+ attr_product_type_id,
+ variant_selection,
+ ) in attribute_variants:
+ product_type_id_to_attribute_id_and_variant_selection[
+ attr_product_type_id
+ ].append((attribute_id, variant_selection))
+
+ attribute_ids = set()
+ for variant_id, limit, variant_selection in keys:
+ product_id = variant_id_to_product_id_map.get(variant_id)
+ if not product_id:
+ continue
+ product_type_id = product_id_to_product_type_id_map.get(product_id)
+ if not product_type_id:
+ continue
+ attribute_ids_and_selections: list[tuple[int, bool]] = (
+ product_type_id_to_attribute_id_and_variant_selection.get(
+ product_type_id, []
+ )
+ )
+
+ attribute_ids_to_include = []
+ for attr_id, is_variant_selection in attribute_ids_and_selections:
+ if (
+ variant_selection is not None
+ and variant_selection != is_variant_selection
+ ):
+ continue
+ attribute_ids_to_include.append(attr_id)
+ attribute_ids.update(attribute_ids_to_include[:limit])
+
+ def get_attributes_for_variants(attributes: list[Attribute]):
+ attribute_map = {attr.id: attr for attr in attributes}
+
+ response = []
+ # loop over keys to build the response based on the variant_id, limit number and
+ # selection provided as an input
+ for variant_id, limit, variant_selection in keys:
+ single_response_entry: list[Attribute] = []
+ product_id = variant_id_to_product_id_map.get(variant_id)
+ if not product_id:
+ response.append(single_response_entry)
+ continue
+ product_type_id = product_id_to_product_type_id_map.get(product_id)
+ if not product_type_id:
+ response.append(single_response_entry)
+ continue
+ attribute_ids_and_selections: list[tuple[int, bool]] = (
+ product_type_id_to_attribute_id_and_variant_selection.get(
+ product_type_id, []
+ )[:limit]
+ )
+ for (
+ variant_attribute_id,
+ attribute_selection,
+ ) in attribute_ids_and_selections:
+ if (
+ variant_selection is not None
+ and variant_selection != attribute_selection
+ ):
+ continue
+ attribute = attribute_map.get(variant_attribute_id)
+ if not attribute:
+ continue
+ single_response_entry.append(attribute)
+ response.append(single_response_entry)
+ return response
+
+ return (
+ AttributesByAttributeId(self.context)
+ .load_many(attribute_ids)
+ .then(get_attributes_for_variants)
+ )
+
+ return (
+ ProductByVariantIdLoader(self.context)
+ .load_many([variant_id for variant_id, _, _ in keys])
+ .then(with_products)
+ )
+
+
+class AttributesVisibleToCustomerByProductVariantIdAndSelectionAndLimitLoader(
+ AttributesByProductVariantIdAndSelectionAndLimitLoader
+):
+ context_key = "attribute_ids_visible_to_customer_by_product_variant_id_and_limit"
+
+ def get_attribute_variant_qs(
+ self, product_type_ids: set[int]
+ ) -> QuerySet[AttributeVariant]:
+ return AttributeVariant.objects.using(self.database_connection_name).filter(
+ attribute__visible_in_storefront=True, product_type__in=product_type_ids
+ )
+
+
+class AttributesByPageIdAndLimitLoader(
+ DataLoader[tuple[PAGE_ID, LIMIT], list[Attribute]]
+):
+ context_key = "attribute_ids_by_page_id_and_limit"
+
+ def get_attribute_page_qs(self, page_type_ids: set[int]) -> QuerySet[AttributePage]:
+ return AttributePage.objects.using(self.database_connection_name).filter(
+ page_type__in=page_type_ids
+ )
+
+ def batch_load(self, keys: Iterable[tuple[PAGE_ID, LIMIT]]):
+ @allow_writer_in_context(self.context)
+ def with_pages(pages: list[page_models.Page]):
+ page_id_to_page_type_id_map = {
+ page.id: page.page_type_id for page in pages if page
+ }
+ page_type_ids = set(page_id_to_page_type_id_map.values())
+
+ attribute_pages = (
+ self.get_attribute_page_qs(page_type_ids)
+ .using(self.database_connection_name)
+ .values_list("attribute_id", "page_type_id")
+ )
+
+ page_type_id_to_attribute_ids = defaultdict(list)
+
+ for attribute_id, attr_page_type_id in attribute_pages:
+ page_type_id_to_attribute_ids[attr_page_type_id].append(attribute_id)
+
+ attribute_ids = set()
+ for page_id, limit in keys:
+ page_type_id = page_id_to_page_type_id_map.get(page_id)
+ if not page_type_id:
+ continue
+ attribute_ids.update(
+ page_type_id_to_attribute_ids.get(page_type_id, [])[:limit]
+ )
+
+ def get_attributes_for_pages(attributes: list[Attribute]):
+ attribute_map = {attr.id: attr for attr in attributes}
+
+ response = []
+ for page_id, limit in keys:
+ single_response_entry: list[Attribute] = []
+ page_type_id = page_id_to_page_type_id_map.get(page_id)
+ if not page_type_id:
+ response.append(single_response_entry)
+ continue
+ page_attribute_ids = page_type_id_to_attribute_ids.get(
+ page_type_id, []
+ )[:limit]
+ for page_attribute_id in page_attribute_ids:
+ attribute = attribute_map.get(page_attribute_id)
+ if not attribute:
+ continue
+ single_response_entry.append(attribute)
+ response.append(single_response_entry)
+ return response
+
+ return (
+ AttributesByAttributeId(self.context)
+ .load_many(attribute_ids)
+ .then(get_attributes_for_pages)
+ )
+
+ page_ids = [page_id for page_id, _ in keys]
+ return PageByIdLoader(self.context).load_many(page_ids).then(with_pages)
+
+
+class AttributesVisibleToCustomerByPageIdAndLimitLoader(
+ AttributesByPageIdAndLimitLoader
+):
+ context_key = "attributes_visible_to_customer_by_page_id_and_limit"
+
+ def get_attribute_page_qs(self, page_type_ids: set[int]) -> QuerySet[AttributePage]:
+ return AttributePage.objects.using(self.database_connection_name).filter(
+ attribute__visible_in_storefront=True,
+ page_type__in=page_type_ids,
+ )
+
+
+class AttributeByPageIdAndAttributeSlugLoader(
+ DataLoader[tuple[PAGE_ID, ATTRIBUTE_SLUG], Attribute | None]
+):
+ context_key = "attribute_by_page_id_and_attribute_slug"
+
+ def batch_load(self, keys: Iterable[tuple[PAGE_ID, ATTRIBUTE_SLUG]]):
+ page_ids = [page_id for page_id, _ in keys]
+ attribute_slugs = [attribute_slug for _, attribute_slug in keys]
+
+ def with_pages_and_attributes(
+ data: tuple[list[page_models.Page], list[Attribute]],
+ ):
+ pages, attributes = data
+ page_type_ids = {page.page_type_id for page in pages if page is not None}
+ page_map = {page.id: page for page in pages if page is not None}
+ attribute_map = {attr.slug: attr for attr in attributes if attr is not None}
+ attribute_pages = (
+ AttributePage.objects.using(self.database_connection_name)
+ .filter(
+ attribute__in=[attr.id for attr in attribute_map.values()],
+ page_type__in=page_type_ids,
+ )
+ .values_list("attribute_id", "page_type_id")
+ )
+
+ page_type_id_to_attribute_ids = defaultdict(set)
+ for attribute_id, page_type_id in attribute_pages:
+ page_type_id_to_attribute_ids[page_type_id].add(attribute_id)
+
+ response: list[Attribute | None] = []
+ for page_id, attribute_slug in keys:
+ attribute = attribute_map.get(attribute_slug)
+ if not attribute:
+ response.append(None)
+ continue
+
+ page = page_map.get(page_id)
+ if not page:
+ response.append(None)
+ continue
+ page_type_id = page.page_type_id
+ attributes_assigned_to_page_type = page_type_id_to_attribute_ids.get(
+ page_type_id, set()
+ )
+ if attribute.id in attributes_assigned_to_page_type:
+ response.append(attribute)
+ else:
+ response.append(None)
+ return response
+
+ pages_loader = PageByIdLoader(self.context).load_many(page_ids)
+ attributes_loader = AttributesBySlugLoader(self.context).load_many(
+ attribute_slugs
+ )
+ return Promise.all([pages_loader, attributes_loader]).then(
+ with_pages_and_attributes
+ )
+
+
+class AttributeValuesByProductIdAndAttributeIdAndLimitLoader(
+ DataLoader[tuple[PRODUCT_ID, ATTRIBUTE_ID, LIMIT], list[AttributeValue]]
+):
+ context_key = "attribute_values_by_product_and_attribute"
+
+ def batch_load(self, keys: Iterable[tuple[PRODUCT_ID, ATTRIBUTE_ID, LIMIT]]):
+ limit_map = defaultdict(list)
+ for product_id, attribute_id, limit in keys:
+ limit_map[limit].append((product_id, attribute_id))
+
+ attribute_value_id_to_fetch_map: dict[
+ tuple[PRODUCT_ID, ATTRIBUTE_ID, LIMIT], list[int]
+ ] = defaultdict(list)
+
+ for limit, values in limit_map.items():
+ product_ids = [val[0] for val in values]
+ attribute_ids = [val[1] for val in values]
+
+ assigned_attribute_values = AssignedProductAttributeValue.objects.using(
+ self.database_connection_name
+ ).annotate(attribute_id=F("value__attribute_id"))
+ if limit is not None:
+ assigned_attribute_values = assigned_attribute_values.annotate(
+ row_num=Window(
+ expression=RowNumber(),
+ partition_by=[F("attribute_id"), F("product_id")],
+ order_by=["sort_order", "pk"],
+ )
+ ).filter(row_num__lte=limit)
+
+ assigned_attribute_values = assigned_attribute_values.filter(
+ attribute_id__in=attribute_ids,
+ product_id__in=product_ids,
+ ).values_list("product_id", "value_id", "attribute_id")
+
+ for product_id, value_id, attribute_id in assigned_attribute_values:
+ attribute_value_id_to_fetch_map[
+ (product_id, attribute_id, limit)
+ ].append(value_id)
+
+ attribute_value_ids_to_fetch = set()
+ for id_list in attribute_value_id_to_fetch_map.values():
+ attribute_value_ids_to_fetch.update(id_list)
+
+ def with_attribute_values(attribute_values: list[AttributeValue]):
+ attribute_value_map = {av.id: av for av in attribute_values}
+ response_data: defaultdict[
+ tuple[PRODUCT_ID, ATTRIBUTE_ID, LIMIT], list[AttributeValue]
+ ] = defaultdict(list)
+ for (
+ product_id,
+ attribute_id,
+ limit,
+ ), value_ids in attribute_value_id_to_fetch_map.items():
+ for value_id in value_ids:
+ attr_val = attribute_value_map.get(value_id)
+ if not attr_val:
+ continue
+ response_data[(product_id, attribute_id, limit)].append(attr_val)
+ return [response_data.get(key, []) for key in keys]
+
+ return (
+ AttributeValueByIdLoader(self.context)
+ .load_many(attribute_value_ids_to_fetch)
+ .then(with_attribute_values)
+ )
+
+
+class AttributeValuesByPageIdAndAttributeIdAndLimitLoader(
+ DataLoader[tuple[PAGE_ID, ATTRIBUTE_ID, LIMIT], list[AttributeValue]]
+):
+ context_key = "attribute_values_by_page_and_attribute"
+
+ def batch_load(self, keys: Iterable[tuple[PAGE_ID, ATTRIBUTE_ID, LIMIT]]):
+ limit_map = defaultdict(list)
+ for page_id, attribute_id, limit in keys:
+ limit_map[limit].append((page_id, attribute_id))
+
+ attribute_value_id_to_fetch_map: dict[
+ tuple[PAGE_ID, ATTRIBUTE_ID, LIMIT], list[int]
+ ] = defaultdict(list)
+
+ for limit, values in limit_map.items():
+ page_ids = [val[0] for val in values]
+ attribute_ids = [val[1] for val in values]
+
+ assigned_attribute_values = AssignedPageAttributeValue.objects.using(
+ self.database_connection_name
+ ).annotate(attribute_id=F("value__attribute_id"))
+ if limit is not None:
+ assigned_attribute_values = assigned_attribute_values.annotate(
+ row_num=Window(
+ expression=RowNumber(),
+ partition_by=[F("attribute_id"), F("page_id")],
+ order_by=["sort_order", "pk"],
+ )
+ ).filter(row_num__lte=limit)
+ assigned_attribute_values = assigned_attribute_values.filter(
+ attribute_id__in=attribute_ids,
+ page_id__in=page_ids,
+ ).values_list("page_id", "value_id", "attribute_id")
+
+ for page_id, value_id, attribute_id in assigned_attribute_values:
+ attribute_value_id_to_fetch_map[(page_id, attribute_id, limit)].append(
+ value_id
+ )
+
+ attribute_value_ids_to_fetch = set()
+ for id_list in attribute_value_id_to_fetch_map.values():
+ attribute_value_ids_to_fetch.update(id_list)
+
+ def with_attribute_values(attribute_values: list[AttributeValue]):
+ attribute_value_map = {av.id: av for av in attribute_values}
+ response_data: defaultdict[
+ tuple[PAGE_ID, ATTRIBUTE_ID, LIMIT], list[AttributeValue]
+ ] = defaultdict(list)
+ for (
+ page_id,
+ attribute_id,
+ limit,
+ ), value_ids in attribute_value_id_to_fetch_map.items():
+ for value_id in value_ids:
+ attr_val = attribute_value_map.get(value_id)
+ if not attr_val:
+ continue
+ response_data[(page_id, attribute_id, limit)].append(attr_val)
+ return [response_data.get(key, []) for key in keys]
+
+ return (
+ AttributeValueByIdLoader(self.context)
+ .load_many(attribute_value_ids_to_fetch)
+ .then(with_attribute_values)
+ )
+
+
+class AttributeValuesByVariantIdAndAttributeIdAndLimitLoader(
+ DataLoader[tuple[VARIANT_ID, ATTRIBUTE_ID, LIMIT], list[AttributeValue]]
+):
+ context_key = "attribute_values_by_variant_and_attribute"
+
+ def batch_load(self, keys: Iterable[tuple[VARIANT_ID, ATTRIBUTE_ID, LIMIT]]):
+ limit_map = defaultdict(list)
+
+ for variant_id, attribute_id, limit in keys:
+ limit_map[limit].append((variant_id, attribute_id))
+
+ attribute_value_id_to_fetch_map: dict[
+ tuple[VARIANT_ID, ATTRIBUTE_ID, LIMIT], list[int]
+ ] = defaultdict(list)
+
+ for limit, values in limit_map.items():
+ variant_ids = [val[0] for val in values]
+ attribute_ids = [val[1] for val in values]
+
+ assigned_variant_attributes = (
+ AssignedVariantAttribute.objects.using(self.database_connection_name)
+ .annotate(attribute_id=F("assignment__attribute_id"))
+ .filter(
+ variant_id__in=variant_ids,
+ attribute_id__in=attribute_ids,
+ )
+ .values_list("variant_id", "id", "attribute_id")
+ )
+ assigned_variant_attributes_map = {
+ id_: (variant_id, attribute_id)
+ for variant_id, id_, attribute_id in assigned_variant_attributes
+ }
+
+ assigned_variant_values = AssignedVariantAttributeValue.objects.using(
+ self.database_connection_name
+ ).filter(assignment_id__in=assigned_variant_attributes_map.keys())
+ if limit is not None:
+ assigned_variant_values = assigned_variant_values.annotate(
+ row_num=Window(
+ expression=RowNumber(),
+ partition_by=F("assignment_id"),
+ order_by=["sort_order", "pk"],
+ )
+ ).filter(row_num__lte=limit)
+ assigned_variant_values = assigned_variant_values.values_list(
+ "value_id", "assignment_id"
+ )
+
+ for value_id, assignment_id in assigned_variant_values:
+ if assignment_id not in assigned_variant_attributes_map:
+ continue
+ variant_id, attribute_id = assigned_variant_attributes_map[
+ assignment_id
+ ]
+ attribute_value_id_to_fetch_map[
+ (variant_id, attribute_id, limit)
+ ].append(value_id)
+
+ attribute_value_ids_to_fetch = set()
+ for id_list in attribute_value_id_to_fetch_map.values():
+ attribute_value_ids_to_fetch.update(id_list)
+
+ def with_attribute_values(attribute_values: list[AttributeValue]):
+ attribute_value_map = {av.id: av for av in attribute_values}
+ response_data: defaultdict[
+ tuple[VARIANT_ID, ATTRIBUTE_ID, LIMIT], list[AttributeValue]
+ ] = defaultdict(list)
+ for (
+ variant_id,
+ attribute_id,
+ limit,
+ ), value_ids in attribute_value_id_to_fetch_map.items():
+ for value_id in value_ids:
+ attr_val = attribute_value_map.get(value_id)
+ if not attr_val:
+ continue
+ response_data[(variant_id, attribute_id, limit)].append(attr_val)
+ return [response_data.get(key, []) for key in keys]
+
+ return (
+ AttributeValueByIdLoader(self.context)
+ .load_many(attribute_value_ids_to_fetch)
+ .then(with_attribute_values)
+ )
diff --git a/saleor/graphql/attribute/tests/queries/test_selected_attribute.py b/saleor/graphql/attribute/tests/queries/test_selected_attribute.py
index 9583343896..009d46c2ad 100644
--- a/saleor/graphql/attribute/tests/queries/test_selected_attribute.py
+++ b/saleor/graphql/attribute/tests/queries/test_selected_attribute.py
@@ -1321,7 +1321,6 @@ def test_assigned_single_choice_attribute(
# then
content = get_graphql_content(response)
-
assert len(content["data"]["page"]["assignedAttributes"]) == 1
attr_value_data = content["data"]["page"]["assignedAttributes"][0]["value"]
assert attr_value_data["name"] == expected_attr_value_name
diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.py
index d4067eab36..fdd7886708 100644
--- a/saleor/graphql/attribute/types.py
+++ b/saleor/graphql/attribute/types.py
@@ -60,6 +60,11 @@ from ..translations.dataloaders import (
)
from ..translations.fields import TranslationField
from ..translations.types import AttributeTranslation, AttributeValueTranslation
+from .dataloaders.assigned_attributes import (
+ AttributeValuesByPageIdAndAttributeIdAndLimitLoader,
+ AttributeValuesByProductIdAndAttributeIdAndLimitLoader,
+ AttributeValuesByVariantIdAndAttributeIdAndLimitLoader,
+)
from .dataloaders.attributes import (
AttributesByAttributeId,
)
@@ -694,6 +699,24 @@ class AttributeValueInput(BaseInputObjectType):
doc_category = DOC_CATEGORY_ATTRIBUTES
+def get_attribute_values(
+ root: AssignedAttributeData, info: ResolveInfo, limit: int | None
+) -> Promise[list[models.AttributeValue]]:
+ if root.variant_id:
+ return AttributeValuesByVariantIdAndAttributeIdAndLimitLoader(
+ info.context
+ ).load((root.variant_id, root.attribute.id, limit))
+ if root.product_id:
+ return AttributeValuesByProductIdAndAttributeIdAndLimitLoader(
+ info.context
+ ).load((root.product_id, root.attribute.id, limit))
+ if root.page_id:
+ return AttributeValuesByPageIdAndAttributeIdAndLimitLoader(info.context).load(
+ (root.page_id, root.attribute.id, limit)
+ )
+ return Promise.resolve([])
+
+
class SelectedAttribute(ChannelContextTypeForObjectType):
attribute = graphene.Field(
Attribute,
@@ -709,6 +732,30 @@ class SelectedAttribute(ChannelContextTypeForObjectType):
doc_category = DOC_CATEGORY_ATTRIBUTES
description = "Represents an assigned attribute to an object."
+ @staticmethod
+ def resolve_attribute(
+ root: AssignedAttributeData, _info: ResolveInfo
+ ) -> ChannelContext[models.Attribute]:
+ return ChannelContext(node=root.attribute, channel_slug=root.channel_slug)
+
+ @staticmethod
+ def resolve_values(
+ root: AssignedAttributeData, info: ResolveInfo
+ ) -> Promise[list[ChannelContext[models.AttributeValue]]]:
+ def _wrap_with_channel_context(
+ attribute_values: list[models.AttributeValue],
+ ) -> list[ChannelContext[models.AttributeValue]]:
+ if not attribute_values:
+ return []
+ return [
+ ChannelContext(node=value, channel_slug=root.channel_slug)
+ for value in attribute_values
+ ]
+
+ return get_attribute_values(root, info, limit=None).then(
+ _wrap_with_channel_context
+ )
+
class AssignedAttribute(BaseInterface):
attribute = graphene.Field(
@@ -724,15 +771,18 @@ class AssignedAttribute(BaseInterface):
@staticmethod
def resolve_type(instance: AssignedAttributeData, _info):
- if instance.attribute.node.input_type == AttributeInputType.SINGLE_REFERENCE:
- entity_type = cast(str, instance.attribute.node.entity_type)
+ if instance.attribute.input_type == AttributeInputType.SINGLE_REFERENCE:
+ entity_type = cast(str, instance.attribute.entity_type)
return ASSIGNED_SINGLE_REFERENCE_MAP.get(entity_type)
- if instance.attribute.node.input_type == AttributeInputType.REFERENCE:
- entity_type = cast(str, instance.attribute.node.entity_type)
+ if instance.attribute.input_type == AttributeInputType.REFERENCE:
+ entity_type = cast(str, instance.attribute.entity_type)
return ASSIGNED_MULTI_REFERENCE_MAP.get(entity_type)
- attr_type = ASSIGNED_ATTRIBUTE_MAP[instance.attribute.node.input_type]
+ attr_type = ASSIGNED_ATTRIBUTE_MAP[instance.attribute.input_type]
return attr_type
+ def resolve_attribute(root: AssignedAttributeData, _info: ResolveInfo):
+ return ChannelContext(node=root.attribute, channel_slug=root.channel_slug)
+
class AssignedNumericAttribute(BaseObjectType):
value = graphene.Float(
@@ -746,12 +796,17 @@ class AssignedNumericAttribute(BaseObjectType):
doc_category = DOC_CATEGORY_ATTRIBUTES
@staticmethod
- def resolve_value(root: AssignedAttributeData, _info: ResolveInfo) -> float | None:
- if not root.values:
- return None
+ def resolve_value(
+ root: AssignedAttributeData, info: ResolveInfo
+ ) -> Promise[float | None]:
+ def get_numeric_value(
+ attribute_values: list[models.AttributeValue],
+ ) -> float | None:
+ if not attribute_values:
+ return None
+ return attribute_values[0].numeric
- attr_value = root.values[0].node
- return attr_value.numeric
+ return get_attribute_values(root, info, limit=1).then(get_numeric_value)
class AssignedTextAttribute(BaseObjectType):
@@ -777,31 +832,39 @@ class AssignedTextAttribute(BaseObjectType):
doc_category = DOC_CATEGORY_ATTRIBUTES
@staticmethod
- def resolve_value(root: AssignedAttributeData, _info: ResolveInfo) -> JSON | None:
- if not root.values:
- return None
- attr_value = root.values[0].node
- return attr_value.rich_text
+ def resolve_value(
+ root: AssignedAttributeData, info: ResolveInfo
+ ) -> Promise[JSON | None]:
+ def get_rich_text(attribute_values: list[models.AttributeValue]) -> JSON | None:
+ if not attribute_values:
+ return None
+ return attribute_values[0].rich_text
+
+ return get_attribute_values(root, info, limit=1).then(get_rich_text)
@staticmethod
def resolve_translation(
root: AssignedAttributeData, info: ResolveInfo, *, language_code
- ) -> Promise[JSON | None] | None:
- if not root.values:
- return None
-
- def _wrap_translation(
+ ) -> Promise[Promise[JSON | None] | None]:
+ def get_translation(
translation: AttributeValueTranslation | None,
) -> JSON | None:
if translation is None:
return None
return translation.rich_text
- return (
- AttributeValueTranslationByIdAndLanguageCodeLoader(info.context)
- .load((root.values[0].node.id, language_code))
- .then(_wrap_translation)
- )
+ def with_attribute_value(
+ attribute_values: list[models.AttributeValue],
+ ) -> Promise[JSON | None] | None:
+ if not attribute_values:
+ return None
+ return (
+ AttributeValueTranslationByIdAndLanguageCodeLoader(info.context)
+ .load((attribute_values[0].id, language_code))
+ .then(get_translation)
+ )
+
+ return get_attribute_values(root, info, limit=1).then(with_attribute_value)
class AssignedPlainTextAttribute(BaseObjectType):
@@ -826,31 +889,39 @@ class AssignedPlainTextAttribute(BaseObjectType):
doc_category = DOC_CATEGORY_ATTRIBUTES
@staticmethod
- def resolve_value(root: AssignedAttributeData, _info: ResolveInfo) -> str | None:
- if not root.values:
- return None
- attr_value = root.values[0].node
- return attr_value.plain_text
+ def resolve_value(
+ root: AssignedAttributeData, info: ResolveInfo
+ ) -> Promise[str | None]:
+ def get_plain_text(attribute_values: list[models.AttributeValue]) -> str | None:
+ if not attribute_values:
+ return None
+ return attribute_values[0].plain_text
+
+ return get_attribute_values(root, info, limit=1).then(get_plain_text)
@staticmethod
def resolve_translation(
root: AssignedAttributeData, info: ResolveInfo, *, language_code
- ) -> Promise[str | None] | None:
- if not root.values:
- return None
-
- def _wrap_translation(
+ ) -> Promise[Promise[str | None] | None]:
+ def get_translation(
translation: AttributeValueTranslation | None,
) -> str | None:
if translation is None:
return None
return translation.plain_text
- return (
- AttributeValueTranslationByIdAndLanguageCodeLoader(info.context)
- .load((root.values[0].node.id, language_code))
- .then(_wrap_translation)
- )
+ def with_attribute_value(
+ attribute_values: list[models.AttributeValue],
+ ) -> Promise[str | None] | None:
+ if not attribute_values:
+ return None
+ return (
+ AttributeValueTranslationByIdAndLanguageCodeLoader(info.context)
+ .load((attribute_values[0].id, language_code))
+ .then(get_translation)
+ )
+
+ return get_attribute_values(root, info, limit=1).then(with_attribute_value)
class AssignedFileAttribute(BaseObjectType):
@@ -862,11 +933,18 @@ class AssignedFileAttribute(BaseObjectType):
doc_category = DOC_CATEGORY_ATTRIBUTES
@staticmethod
- def resolve_value(root: AssignedAttributeData, _info: ResolveInfo) -> File | None:
- if not root.values:
- return None
- attr_value = root.values[0].node
- return File(url=attr_value.file_url, content_type=attr_value.content_type)
+ def resolve_value(
+ root: AssignedAttributeData, info: ResolveInfo
+ ) -> Promise[File | None]:
+ def get_file(attribute_values: list[models.AttributeValue]) -> File | None:
+ if not attribute_values:
+ return None
+ return File(
+ url=attribute_values[0].file_url,
+ content_type=attribute_values[0].content_type,
+ )
+
+ return get_attribute_values(root, info, limit=1).then(get_file)
class AssignedSinglePageReferenceAttribute(BaseObjectType):
@@ -884,18 +962,23 @@ class AssignedSinglePageReferenceAttribute(BaseObjectType):
@staticmethod
def resolve_value(
root: AssignedAttributeData, info: ResolveInfo
- ) -> Promise[ChannelContext[page_models.Page]] | None:
- if not root.values:
- return None
-
- channel_slug = root.attribute.channel_slug
- attr_value = root.values[0].node
+ ) -> Promise[Promise[ChannelContext[page_models.Page]] | None]:
+ def get_page(
+ attribute_values: list[models.AttributeValue],
+ ) -> Promise[ChannelContext[page_models.Page]] | None:
+ if not attribute_values:
+ return None
+ referenced_value = attribute_values[0]
+ if not referenced_value.reference_page_id:
+ return None
+ channel_slug = root.channel_slug
+ return (
+ PageByIdLoader(info.context)
+ .load(referenced_value.reference_page_id)
+ .then(lambda page: ChannelContext(node=page, channel_slug=channel_slug))
+ )
- return (
- PageByIdLoader(info.context)
- .load(attr_value.reference_page_id)
- .then(lambda page: ChannelContext(node=page, channel_slug=channel_slug))
- )
+ return get_attribute_values(root, info, limit=1).then(get_page)
class AssignedSingleProductReferenceAttribute(BaseObjectType):
@@ -913,20 +996,27 @@ class AssignedSingleProductReferenceAttribute(BaseObjectType):
@staticmethod
def resolve_value(
root: AssignedAttributeData, info: ResolveInfo
- ) -> Promise[ChannelContext[product_models.Product]] | None:
- if not root.values:
- return None
-
- channel_slug = root.attribute.channel_slug
- attr_value = root.values[0].node
-
- return (
- ProductByIdLoader(info.context)
- .load(attr_value.reference_product_id)
- .then(
- lambda product: ChannelContext(node=product, channel_slug=channel_slug)
+ ) -> Promise[Promise[ChannelContext[product_models.Product]] | None]:
+ def get_product(
+ attribute_values: list[models.AttributeValue],
+ ) -> Promise[ChannelContext[product_models.Product]] | None:
+ if not attribute_values:
+ return None
+ referenced_value = attribute_values[0]
+ if not referenced_value.reference_product_id:
+ return None
+ channel_slug = root.channel_slug
+ return (
+ ProductByIdLoader(info.context)
+ .load(referenced_value.reference_product_id)
+ .then(
+ lambda product: ChannelContext(
+ node=product, channel_slug=channel_slug
+ )
+ )
)
- )
+
+ return get_attribute_values(root, info, limit=1).then(get_product)
class AssignedSingleProductVariantReferenceAttribute(BaseObjectType):
@@ -946,22 +1036,28 @@ class AssignedSingleProductVariantReferenceAttribute(BaseObjectType):
@staticmethod
def resolve_value(
root: AssignedAttributeData, info: ResolveInfo
- ) -> Promise[ChannelContext[product_models.ProductVariant]] | None:
- if not root.values:
- return None
-
- channel_slug = root.attribute.channel_slug
- attr_value = root.values[0].node
+ ) -> Promise[Promise[ChannelContext[product_models.ProductVariant]] | None]:
+ def get_variant(
+ attribute_values: list[models.AttributeValue],
+ ) -> Promise[ChannelContext[product_models.ProductVariant]] | None:
+ if not attribute_values:
+ return None
+ attr_value = attribute_values[0]
+ if not attr_value.reference_variant_id:
+ return None
- return (
- ProductVariantByIdLoader(info.context)
- .load(attr_value.reference_variant_id)
- .then(
- lambda product_variant: ChannelContext(
- node=product_variant, channel_slug=channel_slug
+ channel_slug = root.channel_slug
+ return (
+ ProductVariantByIdLoader(info.context)
+ .load(attr_value.reference_variant_id)
+ .then(
+ lambda product_variant: ChannelContext(
+ node=product_variant, channel_slug=channel_slug
+ )
)
)
- )
+
+ return get_attribute_values(root, info, limit=1).then(get_variant)
class AssignedSingleCategoryReferenceAttribute(BaseObjectType):
@@ -979,11 +1075,20 @@ class AssignedSingleCategoryReferenceAttribute(BaseObjectType):
@staticmethod
def resolve_value(
root: AssignedAttributeData, info: ResolveInfo
- ) -> Promise[product_models.Category] | None:
- if not root.values:
- return None
- attr_value = root.values[0].node
- return CategoryByIdLoader(info.context).load(attr_value.reference_category_id)
+ ) -> Promise[Promise[product_models.Category] | None]:
+ def get_category(
+ attribute_values: list[models.AttributeValue],
+ ) -> Promise[product_models.Category] | None:
+ if not attribute_values:
+ return None
+ attr_value = attribute_values[0]
+ if not attr_value.reference_category_id:
+ return None
+ return CategoryByIdLoader(info.context).load(
+ attr_value.reference_category_id
+ )
+
+ return get_attribute_values(root, info, limit=1).then(get_category)
class AssignedSingleCollectionReferenceAttribute(BaseObjectType):
@@ -1001,22 +1106,27 @@ class AssignedSingleCollectionReferenceAttribute(BaseObjectType):
@staticmethod
def resolve_value(
root: AssignedAttributeData, info: ResolveInfo
- ) -> Promise[ChannelContext[product_models.Collection]] | None:
- if not root.values:
- return None
-
- channel_slug = root.attribute.channel_slug
- attr_value = root.values[0].node
-
- return (
- CollectionByIdLoader(info.context)
- .load(attr_value.reference_collection_id)
- .then(
- lambda collection: ChannelContext(
- node=collection, channel_slug=channel_slug
+ ) -> Promise[Promise[ChannelContext[product_models.Collection]] | None]:
+ def get_collection(
+ attribute_values: list[models.AttributeValue],
+ ) -> Promise[ChannelContext[product_models.Collection]] | None:
+ if not attribute_values:
+ return None
+ attr_value = attribute_values[0]
+ if not attr_value.reference_collection_id:
+ return None
+ channel_slug = root.channel_slug
+ return (
+ CollectionByIdLoader(info.context)
+ .load(attr_value.reference_collection_id)
+ .then(
+ lambda collection: ChannelContext(
+ node=collection, channel_slug=channel_slug
+ )
)
)
- )
+
+ return get_attribute_values(root, info, limit=1).then(get_collection)
class AssignedMultiPageReferenceAttribute(BaseObjectType):
@@ -1043,28 +1153,34 @@ class AssignedMultiPageReferenceAttribute(BaseObjectType):
root: AssignedAttributeData,
info: ResolveInfo,
limit: int = DEFAULT_NESTED_LIST_LIMIT,
- ) -> Promise[list[ChannelContext[page_models.Page]]]:
- if not root.values:
- return Promise.resolve([])
-
- channel_slug = root.attribute.channel_slug
- attr_values = [value.node for value in root.values]
- attr_values = attr_values[:limit]
-
+ ) -> Promise[Promise[list[ChannelContext[page_models.Page]]]]:
def _wrap_with_channel_context(
pages: list[page_models.Page],
) -> list[ChannelContext[page_models.Page]]:
if not pages:
return []
return [
- ChannelContext(node=page, channel_slug=channel_slug) for page in pages
+ ChannelContext(node=page, channel_slug=root.channel_slug)
+ for page in pages
]
- return (
- PageByIdLoader(info.context)
- .load_many([value.reference_page_id for value in attr_values])
- .then(_wrap_with_channel_context)
- )
+ def get_pages(
+ attribute_values: list[models.AttributeValue],
+ ) -> Promise[list[ChannelContext[page_models.Page]]]:
+ if not attribute_values:
+ return Promise.resolve([])
+ page_ids = [
+ value.reference_page_id
+ for value in attribute_values
+ if value.reference_page_id
+ ]
+ return (
+ PageByIdLoader(info.context)
+ .load_many(page_ids)
+ .then(_wrap_with_channel_context)
+ )
+
+ return get_attribute_values(root, info, limit=limit).then(get_pages)
class AssignedMultiProductReferenceAttribute(BaseObjectType):
@@ -1091,29 +1207,34 @@ class AssignedMultiProductReferenceAttribute(BaseObjectType):
root: AssignedAttributeData,
info: ResolveInfo,
limit: int = DEFAULT_NESTED_LIST_LIMIT,
- ) -> Promise[list[ChannelContext[product_models.Product]]]:
- if not root.values:
- return Promise.resolve([])
-
- channel_slug = root.attribute.channel_slug
- attr_values = [value.node for value in root.values]
- attr_values = attr_values[:limit]
-
+ ) -> Promise[Promise[list[ChannelContext[product_models.Product]]]]:
def _wrap_with_channel_context(
products: list[product_models.Product],
) -> list[ChannelContext[product_models.Product]]:
if not products:
return []
return [
- ChannelContext(node=product, channel_slug=channel_slug)
+ ChannelContext(node=product, channel_slug=root.channel_slug)
for product in products
]
- return (
- ProductByIdLoader(info.context)
- .load_many([value.reference_product_id for value in attr_values])
- .then(_wrap_with_channel_context)
- )
+ def get_products(
+ attribute_values: list[models.AttributeValue],
+ ) -> Promise[list[ChannelContext[product_models.Product]]]:
+ if not attribute_values:
+ return Promise.resolve([])
+ product_ids = [
+ value.reference_product_id
+ for value in attribute_values
+ if value.reference_product_id
+ ]
+ return (
+ ProductByIdLoader(info.context)
+ .load_many(product_ids)
+ .then(_wrap_with_channel_context)
+ )
+
+ return get_attribute_values(root, info, limit=limit).then(get_products)
class AssignedMultiProductVariantReferenceAttribute(BaseObjectType):
@@ -1142,29 +1263,35 @@ class AssignedMultiProductVariantReferenceAttribute(BaseObjectType):
root: AssignedAttributeData,
info: ResolveInfo,
limit: int = DEFAULT_NESTED_LIST_LIMIT,
- ) -> Promise[list[ChannelContext[product_models.ProductVariant]]]:
- if not root.values:
- return Promise.resolve([])
-
- channel_slug = root.attribute.channel_slug
- attr_values = [value.node for value in root.values]
- attr_values = attr_values[:limit]
-
+ ) -> Promise[Promise[list[ChannelContext[product_models.ProductVariant]]]]:
def _wrap_with_channel_context(
variants: list[product_models.ProductVariant],
) -> list[ChannelContext[product_models.ProductVariant]]:
if not variants:
return []
return [
- ChannelContext(node=variant, channel_slug=channel_slug)
+ ChannelContext(node=variant, channel_slug=root.channel_slug)
for variant in variants
]
- return (
- ProductVariantByIdLoader(info.context)
- .load_many([value.reference_variant_id for value in attr_values])
- .then(_wrap_with_channel_context)
- )
+ def get_variants(
+ attribute_values: list[models.AttributeValue],
+ ) -> Promise[list[ChannelContext[product_models.ProductVariant]]]:
+ if not attribute_values:
+ return Promise.resolve([])
+
+ variant_ids = [
+ value.reference_variant_id
+ for value in attribute_values
+ if value.reference_variant_id
+ ]
+ return (
+ ProductVariantByIdLoader(info.context)
+ .load_many(variant_ids)
+ .then(_wrap_with_channel_context)
+ )
+
+ return get_attribute_values(root, info, limit=limit).then(get_variants)
class AssignedMultiCategoryReferenceAttribute(BaseObjectType):
@@ -1191,15 +1318,21 @@ class AssignedMultiCategoryReferenceAttribute(BaseObjectType):
root: AssignedAttributeData,
info: ResolveInfo,
limit: int = DEFAULT_NESTED_LIST_LIMIT,
- ) -> Promise[list[product_models.Category]]:
- if not root.values:
- return Promise.resolve([])
- attr_values = [value.node for value in root.values]
- attr_values = attr_values[:limit]
-
- return CategoryByIdLoader(info.context).load_many(
- [value.reference_category_id for value in attr_values]
- )
+ ) -> Promise[Promise[list[product_models.Category]]]:
+ def get_categories(
+ attribute_values: list[models.AttributeValue],
+ ) -> Promise[list[product_models.Category]]:
+ if not attribute_values:
+ return Promise.resolve([])
+
+ category_ids = [
+ value.reference_category_id
+ for value in attribute_values
+ if value.reference_category_id
+ ]
+ return CategoryByIdLoader(info.context).load_many(category_ids)
+
+ return get_attribute_values(root, info, limit=limit).then(get_categories)
class AssignedMultiCollectionReferenceAttribute(BaseObjectType):
@@ -1226,29 +1359,35 @@ class AssignedMultiCollectionReferenceAttribute(BaseObjectType):
root: AssignedAttributeData,
info: ResolveInfo,
limit: int = DEFAULT_NESTED_LIST_LIMIT,
- ) -> Promise[list[ChannelContext[product_models.Collection]]]:
- if not root.values:
- return Promise.resolve([])
-
- channel_slug = root.attribute.channel_slug
- attr_values = [value.node for value in root.values]
- attr_values = attr_values[:limit]
-
+ ) -> Promise[Promise[list[ChannelContext[product_models.Collection]]]]:
def _wrap_with_channel_context(
collections: list[product_models.Collection],
) -> list[ChannelContext[product_models.Collection]]:
if not collections:
return []
return [
- ChannelContext(node=collection, channel_slug=channel_slug)
+ ChannelContext(node=collection, channel_slug=root.channel_slug)
for collection in collections
]
- return (
- CollectionByIdLoader(info.context)
- .load_many([value.reference_collection_id for value in attr_values])
- .then(_wrap_with_channel_context)
- )
+ def get_collections(
+ attribute_values: list[models.AttributeValue],
+ ) -> Promise[list[ChannelContext[product_models.Collection]]]:
+ if not attribute_values:
+ return Promise.resolve([])
+
+ collection_ids = [
+ value.reference_collection_id
+ for value in attribute_values
+ if value.reference_collection_id
+ ]
+ return (
+ CollectionByIdLoader(info.context)
+ .load_many(collection_ids)
+ .then(_wrap_with_channel_context)
+ )
+
+ return get_attribute_values(root, info, limit=limit).then(get_collections)
class AssignedChoiceAttributeValue(BaseObjectType):
@@ -1292,13 +1431,18 @@ class AssignedSingleChoiceAttribute(BaseObjectType):
description = "Represents a single choice attribute." + ADDED_IN_322
doc_category = DOC_CATEGORY_ATTRIBUTES
+ @staticmethod
def resolve_value(
root: AssignedAttributeData, info: ResolveInfo
- ) -> models.AttributeValue | None:
- if not root.values:
- return None
- attr_value = root.values[0].node
- return attr_value
+ ) -> Promise[models.AttributeValue | None]:
+ def get_single_choice(
+ attribute_values: list[models.AttributeValue],
+ ) -> models.AttributeValue | None:
+ if not attribute_values:
+ return None
+ return attribute_values[0]
+
+ return get_attribute_values(root, info, limit=1).then(get_single_choice)
class AssignedMultiChoiceAttribute(BaseObjectType):
@@ -1325,9 +1469,15 @@ class AssignedMultiChoiceAttribute(BaseObjectType):
root: AssignedAttributeData,
info: ResolveInfo,
limit: int = DEFAULT_NESTED_LIST_LIMIT,
- ) -> list[models.AttributeValue]:
- values = root.values[:limit]
- return [value.node for value in values]
+ ) -> Promise[list[models.AttributeValue]]:
+ def get_multi_choice(
+ attribute_values: list[models.AttributeValue],
+ ) -> list[models.AttributeValue]:
+ if not attribute_values:
+ return []
+ return attribute_values
+
+ return get_attribute_values(root, info, limit=limit).then(get_multi_choice)
class AssignedSwatchAttributeValue(BaseObjectType):
@@ -1380,12 +1530,16 @@ class AssignedSwatchAttribute(BaseObjectType):
@staticmethod
def resolve_value(
- root: AssignedAttributeData, _info: ResolveInfo
- ) -> models.AttributeValue | None:
- if not root.values:
- return None
- attr_value = root.values[0].node
- return attr_value
+ root: AssignedAttributeData, info: ResolveInfo
+ ) -> Promise[models.AttributeValue | None]:
+ def get_swatch(
+ attribute_values: list[models.AttributeValue],
+ ) -> models.AttributeValue | None:
+ if not attribute_values:
+ return None
+ return attribute_values[0]
+
+ return get_attribute_values(root, info, limit=1).then(get_swatch)
class AssignedBooleanAttribute(BaseObjectType):
@@ -1400,11 +1554,15 @@ class AssignedBooleanAttribute(BaseObjectType):
doc_category = DOC_CATEGORY_ATTRIBUTES
@staticmethod
- def resolve_value(root: AssignedAttributeData, _info: ResolveInfo) -> bool | None:
- if not root.values:
- return None
- attr_value = root.values[0].node
- return attr_value.boolean
+ def resolve_value(
+ root: AssignedAttributeData, info: ResolveInfo
+ ) -> Promise[bool | None]:
+ def get_boolean(attribute_values: list[models.AttributeValue]) -> bool | None:
+ if not attribute_values:
+ return None
+ return attribute_values[0].boolean
+
+ return get_attribute_values(root, info, limit=1).then(get_boolean)
class AssignedDateAttribute(BaseObjectType):
@@ -1420,11 +1578,19 @@ class AssignedDateAttribute(BaseObjectType):
doc_category = DOC_CATEGORY_ATTRIBUTES
@staticmethod
- def resolve_value(root: AssignedAttributeData, _info: ResolveInfo) -> date | None:
- if not root.values:
- return None
- attr_value = root.values[0].node
- return attr_value.date_time.date() if attr_value.date_time else None
+ def resolve_value(
+ root: AssignedAttributeData, info: ResolveInfo
+ ) -> Promise[date | None]:
+ def get_date(attribute_values: list[models.AttributeValue]) -> date | None:
+ if not attribute_values:
+ return None
+ return (
+ attribute_values[0].date_time.date()
+ if attribute_values[0].date_time
+ else None
+ )
+
+ return get_attribute_values(root, info, limit=1).then(get_date)
class AssignedDateTimeAttribute(BaseObjectType):
@@ -1441,12 +1607,16 @@ class AssignedDateTimeAttribute(BaseObjectType):
@staticmethod
def resolve_value(
- root: AssignedAttributeData, _info: ResolveInfo
- ) -> datetime | None:
- if not root.values:
- return None
- attr_value = root.values[0].node
- return attr_value.date_time
+ root: AssignedAttributeData, info: ResolveInfo
+ ) -> Promise[datetime | None]:
+ def get_datetime(
+ attribute_values: list[models.AttributeValue],
+ ) -> datetime | None:
+ if not attribute_values:
+ return None
+ return attribute_values[0].date_time
+
+ return get_attribute_values(root, info, limit=1).then(get_datetime)
ASSIGNED_SINGLE_REFERENCE_MAP = {
diff --git a/saleor/graphql/attribute/utils/shared.py b/saleor/graphql/attribute/utils/shared.py
index 34bd767431..30dcefcdf0 100644
--- a/saleor/graphql/attribute/utils/shared.py
+++ b/saleor/graphql/attribute/utils/shared.py
@@ -11,7 +11,6 @@ from ....attribute import AttributeEntityType, AttributeInputType
from ....attribute import models as attribute_models
from ....page import models as page_models
from ....product import models as product_models
-from ...core.context import ChannelContext
from ...product.utils import get_used_attribute_values_for_variant
if TYPE_CHECKING:
@@ -30,8 +29,11 @@ T_REFERENCE = (
@dataclass
class AssignedAttributeData:
- attribute: ChannelContext[attribute_models.Attribute]
- values: list[ChannelContext[attribute_models.AttributeValue]]
+ attribute: attribute_models.Attribute
+ channel_slug: str | None
+ product_id: int | None = None
+ page_id: int | None = None
+ variant_id: int | None = None
@dataclass
diff --git a/saleor/graphql/page/dataloaders.py b/saleor/graphql/page/dataloaders.py
index 3027ffa7da..44cab283be 100644
--- a/saleor/graphql/page/dataloaders.py
+++ b/saleor/graphql/page/dataloaders.py
@@ -1,14 +1,9 @@
from collections import defaultdict
-from collections.abc import Iterable
-from promise import Promise
-
-from ...attribute.models import AssignedPageAttributeValue, Attribute, AttributePage
+from ...attribute.models import Attribute, AttributePage
from ...page.models import Page, PageType
from ..attribute.dataloaders.attributes import (
AttributesByAttributeId,
- AttributesBySlugLoader,
- AttributeValueByIdLoader,
)
from ..core.dataloaders import DataLoader
@@ -105,258 +100,3 @@ class PageAttributesVisibleInStorefrontByPageTypeIdLoader(
@staticmethod
def filter_attributes(attributes: list[Attribute]) -> list[Attribute]:
return [attr for attr in attributes if attr and attr.visible_in_storefront]
-
-
-class BaseAttributeValuesByPageIdLoader(DataLoader[int, list[dict]]):
- def get_page_attributes_dataloader(self):
- raise NotImplementedError()
-
- def batch_load(self, keys):
- # 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
- attribute_values = list(
- AssignedPageAttributeValue.objects.using(self.database_connection_name)
- .filter(page_id__in=keys)
- .iterator(chunk_size=1000)
- )
- 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_attrubutes = dict(
- zip(page_type_ids, attribute_pages, strict=False)
- )
- values_by_id_map = dict(zip(value_ids, values, strict=False))
- assigned_page_map = defaultdict(list)
-
- 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
- ]
-
- attributes = page_type_attrubutes[page.page_type_id]
- for attribute_tuple in attributes:
- attribute = attribute_tuple
- values = [
- value
- for value in page_values
- if value and value.attribute_id == attribute.id
- ]
- assigned_page_map[page.id].append(
- {
- "attribute": attribute,
- "values": values,
- }
- )
- return [assigned_page_map[key] for key in keys]
-
- attributes = self.get_page_attributes_dataloader().load_many(page_type_ids)
- values = AttributeValueByIdLoader(self.context).load_many(value_ids)
- return Promise.all([attributes, values]).then(with_attributes_and_values)
-
- return PageByIdLoader(self.context).load_many(keys).then(with_pages)
-
-
-class AttributeValuesAllByPageIdLoader(BaseAttributeValuesByPageIdLoader):
- context_key = "attributevalues_all_by_page"
-
- def get_page_attributes_dataloader(self):
- return PageAttributesAllByPageTypeIdLoader(self.context)
-
-
-class AttributeValuesVisibleInStorefrontByPageIdLoader(
- BaseAttributeValuesByPageIdLoader
-):
- context_key = "attributevalues_visible_in_storefront_by_page"
-
- def get_page_attributes_dataloader(self):
- return PageAttributesVisibleInStorefrontByPageTypeIdLoader(self.context)
-
-
-class AssignedAttributesAllByPageIdLoader(DataLoader[int, list[dict]]):
- context_key = "assignedattributes_all_by_page"
-
- def batch_load(self, page_ids):
- return AttributeValuesAllByPageIdLoader(self.context).load_many(page_ids)
-
-
-class AssignedAttributesVisibleInStorefrontPageIdLoader(DataLoader[int, list[dict]]):
- context_key = "assignedattributes_visible_in_storefront_by_page"
-
- def batch_load(self, page_ids):
- 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"
-
- @staticmethod
- def filter_attributes(attributes: list[Attribute]) -> list[Attribute]:
- """Filter attributes based on custom logic, if needed."""
- return attributes
-
- def batch_load(self, keys: Iterable[PageTypeIdAndAttributeSlug]):
- slugs = [slug for _, slug in keys]
-
- def with_attributes(attributes):
- attributes = self.filter_attributes(attributes)
- attribute_ids = [attr.id for attr in attributes if attr]
- page_attributes_pairs = (
- AttributePage.objects.using(self.database_connection_name)
- .filter(
- page_type_id__in=[page_type_id for page_type_id, _ in keys],
- attribute_id__in=attribute_ids,
- )
- .values_list("page_type_id", "attribute_id")
- )
-
- 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_attributes_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 (
- AttributesBySlugLoader(self.context).load_many(slugs).then(with_attributes)
- )
-
-
-class PageAttributeByPageTypeIdAndAttributeSlugLoader(
- BasePageAttributeByPageTypeIdAndAttributeSlugLoader
-):
- """Loads page attributes by page type ID and attribute slug."""
-
- context_key = "page_attribute_by_pagetype_and_attributeslug"
-
-
-class PageAttributeVisibleInStorefrontByPageTypeIdAndAttributeSlugLoader(
- BasePageAttributeByPageTypeIdAndAttributeSlugLoader
-):
- """Loads page attributes by page type ID and attribute slug."""
-
- context_key = "page_attributes_visible_in_storefront_by_pagetype_and_attributeslug"
-
- @staticmethod
- def filter_attributes(attributes: list[Attribute]) -> list[Attribute]:
- return [attr for attr in attributes if attr and attr.visible_in_storefront]
-
-
-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 AssignedAttributeAllByPageIdAttributeSlugLoader(DataLoader[int, list[dict]]):
- context_key = "assignedattributes_all_by_page_and_attribute_slug"
-
- def batch_load(self, page_ids):
- return AttributeValuesAllByPageIdAndAttributeSlugLoader(self.context).load_many(
- page_ids
- )
-
-
-class AssignedAttributeVisibleInStorefrontPageIdAttributeSlugLoader(
- DataLoader[int, list[dict]]
-):
- context_key = "assignedattributes_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/types.py b/saleor/graphql/page/types.py
index dda90cca8e..74b91cdc71 100644
--- a/saleor/graphql/page/types.py
+++ b/saleor/graphql/page/types.py
@@ -1,10 +1,14 @@
-from typing import cast
-
import graphene
from ...attribute import models as attribute_models
from ...page import models
from ...permission.enums import PagePermissions, PageTypePermissions
+from ...permission.utils import all_permissions_required
+from ..attribute.dataloaders.assigned_attributes import (
+ AttributeByPageIdAndAttributeSlugLoader,
+ AttributesByPageIdAndLimitLoader,
+ AttributesVisibleToCustomerByPageIdAndLimitLoader,
+)
from ..attribute.filters import (
AttributeFilterInput,
AttributeWhereInput,
@@ -39,12 +43,7 @@ from ..core.types.context import ChannelContextType
from ..meta.types import ObjectWithMetadata
from ..translations.fields import TranslationField
from ..translations.types import PageTranslation
-from ..utils import get_user_or_app_from_context
from .dataloaders import (
- AssignedAttributeAllByPageIdAttributeSlugLoader,
- AssignedAttributesAllByPageIdLoader,
- AssignedAttributesVisibleInStorefrontPageIdLoader,
- AssignedAttributeVisibleInStorefrontPageIdAttributeSlugLoader,
PageAttributesAllByPageTypeIdLoader,
PageAttributesVisibleInStorefrontByPageTypeIdLoader,
PagesByPageTypeIdLoader,
@@ -102,12 +101,7 @@ class PageType(ModelObjectType[models.PageType]):
def wrap_with_channel_context(attributes):
return [ChannelContext(attribute, None) for attribute in attributes]
- requestor = get_user_or_app_from_context(info.context)
- if (
- requestor
- and requestor.is_active
- and requestor.has_perm(PagePermissions.MANAGE_PAGES)
- ):
+ if all_permissions_required(info.context, [PagePermissions.MANAGE_PAGES]):
return (
PageAttributesAllByPageTypeIdLoader(info.context)
.load(root.pk)
@@ -279,46 +273,23 @@ class Page(ChannelContextType[models.Page]):
):
page = root.node
- def wrap_with_channel_context(
- attributes: list[dict[str, list]] | None,
- ) -> list[AssignedAttributeData] | None:
- if attributes is None:
- return None
- response: list[AssignedAttributeData] = []
- for attribute_data in attributes:
- attribute = cast(
- attribute_models.Attribute, attribute_data["attribute"]
- )
- values = cast(
- list[attribute_models.AttributeValue], attribute_data["values"]
- )
- response.append(
- AssignedAttributeData(
- attribute=ChannelContext(attribute, root.channel_slug),
- values=[
- ChannelContext(value, root.channel_slug) for value in values
- ],
- )
+ def get_assigned_attributes(
+ attributes: list[attribute_models.Attribute],
+ ) -> list[AssignedAttributeData]:
+ return [
+ AssignedAttributeData(
+ attribute=attribute,
+ page_id=page.id,
+ channel_slug=root.channel_slug,
)
- response = response[:limit] if limit is not None else response
- return response
+ for attribute in attributes
+ ]
- requestor = get_user_or_app_from_context(info.context)
- if (
- requestor
- and requestor.is_active
- and requestor.has_perm(PagePermissions.MANAGE_PAGES)
- ):
- return (
- AssignedAttributesAllByPageIdLoader(info.context)
- .load(page.id)
- .then(wrap_with_channel_context)
- )
- return (
- AssignedAttributesVisibleInStorefrontPageIdLoader(info.context)
- .load(page.id)
- .then(wrap_with_channel_context)
- )
+ if all_permissions_required(info.context, [PagePermissions.MANAGE_PAGES]):
+ dataloader = AttributesByPageIdAndLimitLoader(info.context)
+ else:
+ dataloader = AttributesVisibleToCustomerByPageIdAndLimitLoader(info.context)
+ return dataloader.load((page.id, limit)).then(get_assigned_attributes)
@classmethod
def resolve_attribute(
@@ -332,36 +303,24 @@ class Page(ChannelContextType[models.Page]):
):
page = root.node
- def wrap_with_channel_context(
- attribute_data: dict[str, dict | list[dict]] | None,
- ) -> AssignedAttributeData | None:
- if attribute_data is None:
+ def with_assigned_attribute(attribute: attribute_models.Attribute | None):
+ if not attribute:
return None
- attribute = cast(attribute_models.Attribute, attribute_data["attribute"])
- values = cast(
- list[attribute_models.AttributeValue], attribute_data["values"]
+ has_permission = all_permissions_required(
+ info.context, [PagePermissions.MANAGE_PAGES]
)
-
+ if not has_permission and not attribute.visible_in_storefront:
+ return None
return AssignedAttributeData(
- attribute=ChannelContext(attribute, root.channel_slug),
- values=[ChannelContext(value, root.channel_slug) for value in values],
+ attribute=attribute,
+ page_id=page.id,
+ channel_slug=root.channel_slug,
)
- requestor = get_user_or_app_from_context(info.context)
- if (
- requestor
- and requestor.is_active
- and requestor.has_perm(PagePermissions.MANAGE_PAGES)
- ):
- return (
- AssignedAttributeAllByPageIdAttributeSlugLoader(info.context)
- .load((page.id, slug))
- .then(wrap_with_channel_context)
- )
return (
- AssignedAttributeVisibleInStorefrontPageIdAttributeSlugLoader(info.context)
+ AttributeByPageIdAndAttributeSlugLoader(info.context)
.load((page.id, slug))
- .then(wrap_with_channel_context)
+ .then(with_assigned_attribute)
)
diff --git a/saleor/graphql/product/dataloaders/__init__.py b/saleor/graphql/product/dataloaders/__init__.py
index e7a949bb6d..91ce193c5a 100644
--- a/saleor/graphql/product/dataloaders/__init__.py
+++ b/saleor/graphql/product/dataloaders/__init__.py
@@ -1,7 +1,4 @@
from .attributes import (
- AssignedAttributesAllByProductIdLoader,
- AssignedAttributesByProductVariantIdLoader,
- AssignedAttributesVisibleInStorefrontByProductIdLoader,
ProductAttributesAllByProductTypeIdLoader,
ProductAttributesVisibleInStorefrontByProductTypeIdLoader,
VariantAttributesAllByProductTypeIdLoader,
@@ -71,9 +68,6 @@ __all__ = [
"ProductVariantsByProductIdLoader",
"ProductMediaByIdLoader",
"MediaByProductVariantIdLoader",
- "AssignedAttributesAllByProductIdLoader",
- "AssignedAttributesByProductVariantIdLoader",
- "AssignedAttributesVisibleInStorefrontByProductIdLoader",
"ThumbnailByCategoryIdSizeAndFormatLoader",
"ThumbnailByCollectionIdSizeAndFormatLoader",
"ThumbnailByProductMediaIdSizeAndFormatLoader",
diff --git a/saleor/graphql/product/dataloaders/attributes.py b/saleor/graphql/product/dataloaders/attributes.py
index 7098e8fffc..244568a971 100644
--- a/saleor/graphql/product/dataloaders/attributes.py
+++ b/saleor/graphql/product/dataloaders/attributes.py
@@ -1,23 +1,12 @@
from collections import defaultdict
-from promise import Promise
-
from ....attribute.models import (
- AssignedProductAttributeValue,
- AssignedVariantAttribute,
- AssignedVariantAttributeValue,
Attribute,
AttributeProduct,
AttributeVariant,
)
-from ....permission.enums import ProductPermissions
-from ...attribute.dataloaders.attributes import (
- AttributesByAttributeId,
- AttributeValueByIdLoader,
-)
+from ...attribute.dataloaders.attributes import AttributesByAttributeId
from ...core.dataloaders import DataLoader
-from ...utils import get_user_or_app_from_context
-from .products import ProductByIdLoader, ProductVariantByIdLoader
class BaseProductAttributesByProductTypeIdLoader(DataLoader):
@@ -107,279 +96,3 @@ class VariantAttributesVisibleInStorefrontByProductTypeIdLoader(
@staticmethod
def filter_attributes(attributes: list[Attribute]) -> list[Attribute]:
return [attr for attr in attributes if attr and attr.visible_in_storefront]
-
-
-class AttributeVariantsByProductTypeIdLoader(DataLoader):
- context_key = "attributevariants_by_producttype"
-
- def batch_load(self, keys):
- requestor = get_user_or_app_from_context(self.context)
- if (
- requestor
- and requestor.is_active
- and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)
- ):
- qs = AttributeVariant.objects.using(self.database_connection_name).all()
- else:
- qs = AttributeVariant.objects.using(self.database_connection_name).filter(
- attribute__visible_in_storefront=True
- )
- attribute_variants = qs.filter(product_type_id__in=keys)
- producttype_to_attributevariants = defaultdict(list)
- for attribute_variant in attribute_variants.iterator(chunk_size=1000):
- producttype_to_attributevariants[attribute_variant.product_type_id].append(
- attribute_variant
- )
- return [producttype_to_attributevariants[key] for key in keys]
-
-
-class AssignedVariantAttributesByProductVariantId(DataLoader):
- context_key = "assignedvariantattributes_by_productvariant"
-
- def batch_load(self, keys):
- requestor = get_user_or_app_from_context(self.context)
- if (
- requestor
- and requestor.is_active
- and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)
- ):
- qs = AssignedVariantAttribute.objects.using(
- self.database_connection_name
- ).all()
- else:
- qs = AssignedVariantAttribute.objects.using(
- self.database_connection_name
- ).filter(assignment__attribute__visible_in_storefront=True)
- assigned_variant_attributes = qs.filter(variant_id__in=keys).select_related(
- "assignment__attribute"
- )
- variant_attributes = defaultdict(list)
- for assigned_variant_attribute in assigned_variant_attributes.iterator(
- chunk_size=1000
- ):
- variant_attributes[assigned_variant_attribute.variant_id].append(
- assigned_variant_attribute
- )
- return [variant_attributes[variant_id] for variant_id in keys]
-
-
-class AttributeValuesByAssignedVariantAttributeIdLoader(DataLoader):
- context_key = "attributevalues_by_assignedvariantattribute"
-
- def batch_load(self, keys):
- attribute_values = list(
- AssignedVariantAttributeValue.objects.using(self.database_connection_name)
- .filter(assignment_id__in=keys)
- .iterator(chunk_size=1000)
- )
- value_ids = [a.value_id for a in attribute_values]
-
- def map_assignment_to_values(values):
- value_map = dict(zip(value_ids, values, strict=False))
- assigned_variant_map = defaultdict(list)
- for attribute_value in attribute_values:
- assigned_variant_map[attribute_value.assignment_id].append(
- value_map.get(attribute_value.value_id)
- )
- return [assigned_variant_map[key] for key in keys]
-
- return (
- AttributeValueByIdLoader(self.context)
- .load_many(value_ids)
- .then(map_assignment_to_values)
- )
-
-
-class BaseAttributeValuesByProductIdLoader(DataLoader):
- def get_product_attributes_dataloader(self):
- raise NotImplementedError()
-
- def batch_load(self, keys):
- # 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
- attribute_values = list(
- AssignedProductAttributeValue.objects.using(self.database_connection_name)
- .filter(product_id__in=keys)
- .iterator(chunk_size=1000)
- )
- value_ids = [a.value_id for a in attribute_values]
-
- def with_products(products):
- products = [product for product in products if product]
- product_type_ids = [p.product_type_id for p in products]
-
- def with_attributes_and_values(result):
- attribute_products, values = result
- product_type_attrubutes = dict(
- zip(product_type_ids, attribute_products, strict=False)
- )
- values_by_id_map = dict(zip(value_ids, values, strict=False))
- assigned_product_map = defaultdict(list)
-
- for product in products:
- product_values = [
- values_by_id_map.get(product_value.value_id)
- for product_value in attribute_values
- if product_value.product_id == product.id
- ]
-
- attributes = product_type_attrubutes[product.product_type_id]
- for attribute_tuple in attributes:
- attribute = attribute_tuple[0]
- values = [
- value
- for value in product_values
- if value and value.attribute_id == attribute.id
- ]
- assigned_product_map[product.id].append(
- {
- "attribute": attribute,
- "values": values,
- }
- )
- return [assigned_product_map[key] for key in keys]
-
- attributes = self.get_product_attributes_dataloader().load_many(
- product_type_ids
- )
- values = AttributeValueByIdLoader(self.context).load_many(value_ids)
- return Promise.all([attributes, values]).then(with_attributes_and_values)
-
- return ProductByIdLoader(self.context).load_many(keys).then(with_products)
-
-
-class AttributeValuesAllByProductIdLoader(BaseAttributeValuesByProductIdLoader):
- context_key = "attributevalues_all_by_productid"
-
- def get_product_attributes_dataloader(self):
- return ProductAttributesAllByProductTypeIdLoader(self.context)
-
-
-class AttributeValuesVisibleInStorefrontByProductIdLoader(
- BaseAttributeValuesByProductIdLoader
-):
- context_key = "attributevalues_visible_in_storefront_by_productid"
-
- def get_product_attributes_dataloader(self):
- return ProductAttributesVisibleInStorefrontByProductTypeIdLoader(self.context)
-
-
-class AssignedAttributesAllByProductIdLoader(DataLoader):
- context_key = "assignedAttributes_all_by_product"
-
- def batch_load(self, product_ids):
- return AttributeValuesAllByProductIdLoader(self.context).load_many(product_ids)
-
-
-class AssignedAttributesVisibleInStorefrontByProductIdLoader(DataLoader):
- context_key = "assignedattributes_visible_in_storefront_by_product"
-
- def batch_load(self, product_ids):
- return AttributeValuesVisibleInStorefrontByProductIdLoader(
- self.context
- ).load_many(product_ids)
-
-
-class AssignedAttributesByProductVariantIdLoader(DataLoader):
- context_key = "assignedattributes_by_productvariant"
-
- def batch_load(self, keys):
- def with_variants_and_assigned_attributed(results):
- product_variants, variant_attributes = results
- product_ids = list({v.product_id for v in product_variants})
- assigned_variant_attribute_ids = [
- a.id for attrs in variant_attributes for a in attrs
- ]
- variant_attributes = dict(zip(keys, variant_attributes, strict=False))
-
- def with_products_and_attribute_values(results):
- products, attribute_values = results
- product_type_ids = list({p.product_type_id for p in products})
- products = dict(zip(product_ids, products, strict=False))
- attribute_values = dict(
- zip(assigned_variant_attribute_ids, attribute_values, strict=False)
- )
-
- def with_attribute_products(attribute_products):
- attribute_ids = list(
- {ap.attribute_id for aps in attribute_products for ap in aps}
- )
-
- attribute_products = dict(
- zip(product_type_ids, attribute_products, strict=False)
- )
-
- def with_attributes(attributes):
- id_to_attribute = dict(
- zip(attribute_ids, attributes, strict=False)
- )
- selected_attributes_map = defaultdict(list)
- for key, product_variant in zip(
- keys, product_variants, strict=False
- ):
- product = products[product_variant.product_id]
- assigned_producttype_attributes = attribute_products[
- product.product_type_id
- ]
- assigned_variant_attributes = variant_attributes[key]
- for (
- assigned_producttype_attribute
- ) in assigned_producttype_attributes:
- variant_assignment = next(
- (
- apa
- for apa in assigned_variant_attributes
- if apa.assignment_id
- == assigned_producttype_attribute.id
- ),
- None,
- )
- attribute = id_to_attribute[
- assigned_producttype_attribute.attribute_id
- ]
- variant_selection = (
- assigned_producttype_attribute.variant_selection
- )
- if variant_assignment:
- values = attribute_values[variant_assignment.id]
- else:
- values = []
- selected_attributes_map[key].append(
- {
- "values": values,
- "attribute": attribute,
- "variant_selection": variant_selection,
- }
- )
- return [selected_attributes_map[key] for key in keys]
-
- return (
- AttributesByAttributeId(self.context)
- .load_many(attribute_ids)
- .then(with_attributes)
- )
-
- return (
- AttributeVariantsByProductTypeIdLoader(self.context)
- .load_many(product_type_ids)
- .then(with_attribute_products)
- )
-
- products = ProductByIdLoader(self.context).load_many(product_ids)
- attribute_values = AttributeValuesByAssignedVariantAttributeIdLoader(
- self.context
- ).load_many(assigned_variant_attribute_ids)
-
- return Promise.all([products, attribute_values]).then(
- with_products_and_attribute_values
- )
-
- product_variants = ProductVariantByIdLoader(self.context).load_many(keys)
- assigned_attributes = AssignedVariantAttributesByProductVariantId(
- self.context
- ).load_many(keys)
-
- return Promise.all([product_variants, assigned_attributes]).then(
- with_variants_and_assigned_attributed
- )
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index d1871cacc5..ba482fc3d5 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -1,13 +1,29 @@
from django.db.models import Exists, OuterRef, Sum
+from ...attribute import models as attribute_models
from ...channel.models import Channel
from ...order import OrderStatus
from ...order.models import Order
+from ...permission.enums import ProductPermissions
from ...permission.utils import has_one_of_permissions
from ...product import models
from ...product.models import ALL_PRODUCTS_PERMISSIONS
+from ..attribute.dataloaders.assigned_attributes import (
+ AttributeByProductIdAndAttributeSlugLoader,
+ AttributeByProductVariantIdAndAttributeSlugLoader,
+ AttributesByProductIdAndLimitLoader,
+ AttributesByProductVariantIdAndSelectionAndLimitLoader,
+ AttributesVisibleToCustomerByProductIdAndLimitLoader,
+ AttributesVisibleToCustomerByProductVariantIdAndSelectionAndLimitLoader,
+)
+from ..attribute.utils.shared import AssignedAttributeData
from ..core import ResolveInfo
-from ..core.context import ChannelQsContext, get_database_connection_name
+from ..core.context import (
+ ChannelContext,
+ ChannelQsContext,
+ SaleorContext,
+ get_database_connection_name,
+)
from ..core.tracing import traced_resolver
from ..core.utils import from_global_id_or_error
from ..utils import get_user_or_app_from_context
@@ -239,3 +255,120 @@ def resolve_report_product_sales(info, period, channel_slug) -> ChannelQsContext
qs = qs.order_by("-quantity_ordered")
return ChannelQsContext(qs=qs, channel_slug=channel_slug)
+
+
+def requestor_has_access_to_all_attributes(context: SaleorContext) -> bool:
+ requestor = get_user_or_app_from_context(context)
+ if (
+ requestor
+ and requestor.is_active
+ and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)
+ ):
+ return True
+ return False
+
+
+def resolve_product_attribute(root: ChannelContext[models.Product], info, slug):
+ def with_assigned_attribute_data(attribute: attribute_models.Attribute | None):
+ if not attribute:
+ return None
+
+ if (
+ not requestor_has_access_to_all_attributes(info.context)
+ and not attribute.visible_in_storefront
+ ):
+ return None
+
+ return AssignedAttributeData(
+ attribute=attribute,
+ product_id=root.node.id,
+ channel_slug=root.channel_slug,
+ )
+
+ return (
+ AttributeByProductIdAndAttributeSlugLoader(info.context)
+ .load((root.node.id, slug))
+ .then(with_assigned_attribute_data)
+ )
+
+
+def resolve_product_attributes(
+ root: ChannelContext[models.Product], info, *, limit: int | None
+):
+ def get_assigned_attributes(
+ attributes: list[attribute_models.Attribute],
+ ) -> list[AssignedAttributeData]:
+ return [
+ AssignedAttributeData(
+ attribute=attribute,
+ product_id=root.node.id,
+ channel_slug=root.channel_slug,
+ )
+ for attribute in attributes
+ ]
+
+ if requestor_has_access_to_all_attributes(info.context):
+ dataloader = AttributesByProductIdAndLimitLoader
+ else:
+ dataloader = AttributesVisibleToCustomerByProductIdAndLimitLoader
+ return (
+ dataloader(info.context)
+ .load((root.node.id, limit))
+ .then(get_assigned_attributes)
+ )
+
+
+def resolve_variant_attributes(
+ root: ChannelContext[models.ProductVariant],
+ info,
+ *,
+ variant_selection: bool | None = None,
+ limit: int | None = None,
+):
+ def get_assigned_attributes(
+ attributes: list[attribute_models.Attribute],
+ ) -> list[AssignedAttributeData]:
+ return [
+ AssignedAttributeData(
+ attribute=attribute,
+ variant_id=root.node.id,
+ channel_slug=root.channel_slug,
+ )
+ for attribute in attributes
+ ]
+
+ if requestor_has_access_to_all_attributes(info.context):
+ dataloader = AttributesByProductVariantIdAndSelectionAndLimitLoader
+ else:
+ dataloader = (
+ AttributesVisibleToCustomerByProductVariantIdAndSelectionAndLimitLoader
+ )
+ return (
+ dataloader(info.context)
+ .load((root.node.id, limit, variant_selection))
+ .then(get_assigned_attributes)
+ )
+
+
+def resolve_variant_attribute(root: ChannelContext[models.ProductVariant], info, slug):
+ def with_assigned_attribute_data(attribute: attribute_models.Attribute | None):
+ if attribute is None:
+ return None
+
+ if (
+ not requestor_has_access_to_all_attributes(info.context)
+ and not attribute.visible_in_storefront
+ ):
+ return None
+
+ return AssignedAttributeData(
+ attribute=attribute,
+ channel_slug=root.channel_slug,
+ variant_id=root.node.id,
+ )
+
+ return (
+ AttributeByProductVariantIdAndAttributeSlugLoader(info.context)
+ .load((root.node.id, slug))
+ .then(with_assigned_attribute_data)
+ )
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index ab4cc1d1ca..176029e56b 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -2,7 +2,6 @@ import sys
from collections import defaultdict
from dataclasses import asdict
from decimal import Decimal
-from typing import cast
import graphene
from graphene import relay
@@ -52,7 +51,6 @@ from ...attribute.types import (
ObjectWithAttributes,
SelectedAttribute,
)
-from ...attribute.utils.shared import AssignedAttributeData
from ...channel.dataloaders.by_self import ChannelBySlugLoader
from ...channel.utils import get_default_channel_slug_or_graphql_error
from ...core.connection import (
@@ -132,9 +130,6 @@ from ...warehouse.dataloaders import (
)
from ...warehouse.types import Stock
from ..dataloaders import (
- AssignedAttributesAllByProductIdLoader,
- AssignedAttributesByProductVariantIdLoader,
- AssignedAttributesVisibleInStorefrontByProductIdLoader,
CategoryByIdLoader,
CollectionChannelListingByCollectionIdAndChannelSlugLoader,
CollectionsByProductIdLoader,
@@ -162,7 +157,14 @@ from ..filters.product_variant import (
ProductVariantFilterInput,
ProductVariantWhereInput,
)
-from ..resolvers import resolve_product_variants, resolve_products
+from ..resolvers import (
+ resolve_product_attribute,
+ resolve_product_attributes,
+ resolve_product_variants,
+ resolve_products,
+ resolve_variant_attribute,
+ resolve_variant_attributes,
+)
from ..sorters import MediaSortingInput, ProductVariantSortingInput
from .channels import ProductChannelListing, ProductVariantChannelListing
from .digital_contents import DigitalContent
@@ -621,40 +623,7 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):
def resolve_assigned_attribute(
cls, root: ChannelContext[models.ProductVariant], info, slug
):
- def get_selected_attribute_by_slug(
- attributes: (
- list[
- dict[
- str,
- attribute_models.Attribute
- | list[attribute_models.AttributeValue],
- ]
- ]
- | None
- ),
- ) -> AssignedAttributeData | None:
- if attributes is None:
- return None
-
- for atr in attributes:
- attribute = atr["attribute"]
- attribute = cast(attribute_models.Attribute, attribute)
- if attribute.slug == slug:
- values = atr["values"]
- values = cast(list[attribute_models.AttributeValue], values)
- return AssignedAttributeData(
- attribute=ChannelContext(attribute, root.channel_slug),
- values=[
- ChannelContext(value, root.channel_slug) for value in values
- ],
- )
- return None
-
- return (
- AssignedAttributesByProductVariantIdLoader(info.context)
- .load(root.node.id)
- .then(get_selected_attribute_by_slug)
- )
+ return resolve_variant_attribute(root, info, slug)
@classmethod
def resolve_attributes(
@@ -663,7 +632,15 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):
info,
variant_selection: VariantAttributeScope | None = None,
):
- return cls._resolve_attributes(root, info, variant_selection)
+ if variant_selection == VariantAttributeScope.VARIANT_SELECTION:
+ selection_bool = True
+ elif variant_selection == VariantAttributeScope.NOT_VARIANT_SELECTION:
+ selection_bool = False
+ else:
+ selection_bool = None
+ return resolve_variant_attributes(
+ root, info, variant_selection=selection_bool, limit=None
+ )
@classmethod
def resolve_assigned_attributes(
@@ -672,78 +649,8 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):
info,
limit: int = DEFAULT_NESTED_LIST_LIMIT,
):
- variant_selection = None
- return cls._resolve_attributes(root, info, variant_selection, limit)
-
- @classmethod
- def _resolve_attributes(
- cls,
- root: ChannelContext[models.ProductVariant],
- info,
- variant_selection: str | None = None,
- limit: int | None = None,
- ):
- def apply_variant_selection_filter(
- selected_attributes,
- ) -> list[AssignedAttributeData]:
- if not variant_selection or variant_selection == VariantAttributeScope.ALL:
- selected_attributes = (
- selected_attributes[:limit] if limit else selected_attributes
- )
- return [
- AssignedAttributeData(
- attribute=ChannelContext(
- selected_att["attribute"], root.channel_slug
- ),
- values=[
- ChannelContext(value, root.channel_slug)
- for value in selected_att["values"]
- ],
- )
- for selected_att in selected_attributes
- ]
- attributes = [
- (selected_att["attribute"], selected_att["variant_selection"])
- for selected_att in selected_attributes
- ]
- attributes = cast(list[tuple[attribute_models.Attribute, bool]], attributes)
- variant_selection_attrs = [
- attr for attr, _ in get_variant_selection_attributes(attributes)
- ]
-
- if variant_selection == VariantAttributeScope.VARIANT_SELECTION:
- attributes_to_return = [
- selected_att
- for selected_att in selected_attributes
- if selected_att["attribute"] in variant_selection_attrs
- ]
- else:
- attributes_to_return = [
- selected_att
- for selected_att in selected_attributes
- if selected_att["attribute"] not in variant_selection_attrs
- ]
- attributes_to_return = (
- attributes_to_return[:limit] if limit else attributes_to_return
- )
-
- return [
- AssignedAttributeData(
- attribute=ChannelContext(
- selected_att["attribute"], root.channel_slug
- ),
- values=[
- ChannelContext(value, root.channel_slug)
- for value in selected_att["values"]
- ],
- )
- for selected_att in attributes_to_return
- ]
-
- return (
- AssignedAttributesByProductVariantIdLoader(info.context)
- .load(root.node.id)
- .then(apply_variant_selection_filter)
+ return resolve_variant_attributes(
+ root, info, variant_selection=None, limit=limit
)
@staticmethod
@@ -1462,59 +1369,11 @@ class Product(ChannelContextType[models.Product]):
def resolve_assigned_attribute(
cls, root: ChannelContext[models.Product], info, slug
):
- return cls._resolve_attribute(root, info, slug)
+ return resolve_product_attribute(root, info, slug)
@classmethod
def resolve_attribute(cls, root: ChannelContext[models.Product], info, slug):
- return cls._resolve_attribute(root, info, slug)
-
- @classmethod
- def _resolve_attribute(cls, root: ChannelContext[models.Product], info, slug):
- def get_selected_attribute_by_slug(
- attributes: (
- list[
- dict[
- str,
- attribute_models.Attribute
- | list[attribute_models.AttributeValue],
- ]
- ]
- | None
- ),
- ) -> AssignedAttributeData | None:
- if attributes is None:
- return None
-
- for atr in attributes:
- attribute = atr["attribute"]
- attribute = cast(attribute_models.Attribute, attribute)
- if attribute.slug == slug:
- values = atr["values"]
- values = cast(list[attribute_models.AttributeValue], values)
- return AssignedAttributeData(
- attribute=ChannelContext(attribute, root.channel_slug),
- values=[
- ChannelContext(value, root.channel_slug) for value in values
- ],
- )
- return None
-
- requestor = get_user_or_app_from_context(info.context)
- if (
- requestor
- and requestor.is_active
- and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)
- ):
- return (
- AssignedAttributesAllByProductIdLoader(info.context)
- .load(root.node.id)
- .then(get_selected_attribute_by_slug)
- )
- return (
- AssignedAttributesVisibleInStorefrontByProductIdLoader(info.context)
- .load(root.node.id)
- .then(get_selected_attribute_by_slug)
- )
+ return resolve_product_attribute(root, info, slug)
@classmethod
def resolve_assigned_attributes(
@@ -1523,64 +1382,11 @@ class Product(ChannelContextType[models.Product]):
info,
limit: int = DEFAULT_NESTED_LIST_LIMIT,
):
- return cls._resolve_attributes(root, info, limit)
+ return resolve_product_attributes(root, info, limit=limit)
@classmethod
def resolve_attributes(cls, root: ChannelContext[models.Product], info):
- return cls._resolve_attributes(root, info)
-
- @classmethod
- def _resolve_attributes(
- cls, root: ChannelContext[models.Product], info, limit: int | None = None
- ):
- def wrap_with_channel_context(
- attributes: (
- list[
- dict[
- str,
- attribute_models.Attribute
- | list[attribute_models.AttributeValue],
- ]
- ]
- | None
- ),
- ) -> list[AssignedAttributeData] | None:
- if attributes is None:
- return None
-
- response = []
- for attr_data in attributes:
- attribute = attr_data["attribute"]
- attribute = cast(attribute_models.Attribute, attribute)
- values = attr_data["values"]
- values = cast(list[attribute_models.AttributeValue], values)
- response.append(
- AssignedAttributeData(
- attribute=ChannelContext(attribute, root.channel_slug),
- values=[
- ChannelContext(value, root.channel_slug) for value in values
- ],
- )
- )
- response = response[:limit] if limit else response
- return response
-
- requestor = get_user_or_app_from_context(info.context)
- if (
- requestor
- and requestor.is_active
- and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)
- ):
- return (
- AssignedAttributesAllByProductIdLoader(info.context)
- .load(root.node.id)
- .then(wrap_with_channel_context)
- )
- return (
- AssignedAttributesVisibleInStorefrontByProductIdLoader(info.context)
- .load(root.node.id)
- .then(wrap_with_channel_context)
- )
+ return resolve_product_attributes(root, info, limit=None)
@staticmethod
def resolve_media_by_id(root: ChannelContext[models.Product], info, *, id):
diff --git a/saleor/graphql/translations/types.py b/saleor/graphql/translations/types.py
index c01babd6f8..77add6e96f 100644
--- a/saleor/graphql/translations/types.py
+++ b/saleor/graphql/translations/types.py
@@ -1,3 +1,4 @@
+from itertools import chain
from typing import TypeVar
import graphene
@@ -16,12 +17,22 @@ from ...permission.enums import (
ProductPermissions,
ShippingPermissions,
)
+from ...permission.utils import all_permissions_required
from ...product import models as product_models
from ...shipping import models as shipping_models
from ...site import models as site_models
-from ..attribute.dataloaders.attributes import (
+from ..attribute.dataloaders.assigned_attributes import (
AttributesByAttributeId,
+ AttributesByPageIdAndLimitLoader,
+ AttributesByProductIdAndLimitLoader,
+ AttributesByProductVariantIdAndSelectionAndLimitLoader,
+ AttributesVisibleToCustomerByPageIdAndLimitLoader,
+ AttributesVisibleToCustomerByProductIdAndLimitLoader,
+ AttributesVisibleToCustomerByProductVariantIdAndSelectionAndLimitLoader,
AttributeValueByIdLoader,
+ AttributeValuesByPageIdAndAttributeIdAndLimitLoader,
+ AttributeValuesByProductIdAndAttributeIdAndLimitLoader,
+ AttributeValuesByVariantIdAndAttributeIdAndLimitLoader,
)
from ..core.context import ChannelContext, get_database_connection_name
from ..core.descriptions import ADDED_IN_321, DEPRECATED_IN_3X_TYPE, RICH_CONTENT
@@ -37,35 +48,29 @@ from ..discount.dataloaders import (
)
from ..menu.dataloaders import MenuItemByIdLoader
from ..page.dataloaders import (
- AssignedAttributesAllByPageIdLoader,
- AssignedAttributesVisibleInStorefrontPageIdLoader,
PageByIdLoader,
)
from ..product.dataloaders import (
- AssignedAttributesAllByProductIdLoader,
- AssignedAttributesByProductVariantIdLoader,
- AssignedAttributesVisibleInStorefrontByProductIdLoader,
CategoryByIdLoader,
CollectionByIdLoader,
ProductByIdLoader,
ProductVariantByIdLoader,
)
from ..shipping.dataloaders import ShippingMethodByIdLoader
-from ..utils import get_user_or_app_from_context
from .fields import TranslationField
+type ATTRIBUTE_ID = int
-def get_translatable_attribute_values(attributes: list) -> list[AttributeValue]:
- """Filter the list of passed attributes.
- Return those which are translatable attributes.
- """
- translatable_values: list[AttributeValue] = []
- for assignment in attributes:
- attr = assignment["attribute"]
- if attr.input_type in AttributeInputType.TRANSLATABLE_ATTRIBUTES:
- translatable_values.extend(assignment["values"])
- return translatable_values
+def get_translatable_attribute_values(
+ attributes: list[attribute_models.Attribute],
+) -> list[ATTRIBUTE_ID]:
+ attribute_ids = []
+ for attribute in attributes:
+ if attribute.input_type not in AttributeInputType.TRANSLATABLE_ATTRIBUTES:
+ continue
+ attribute_ids.append(attribute.id)
+ return attribute_ids
T = TypeVar("T", bound=Model)
@@ -296,10 +301,34 @@ class ProductVariantTranslatableContent(ModelObjectType[product_models.ProductVa
@staticmethod
def resolve_attribute_values(root: product_models.ProductVariant, info):
+ def with_attribute_values(attribute_values: list[list[AttributeValue]]):
+ return list(chain.from_iterable(attribute_values))
+
+ def with_attributes(attributes: list[attribute_models.Attribute]):
+ attribute_ids = get_translatable_attribute_values(attributes)
+ limit = None
+ return (
+ AttributeValuesByVariantIdAndAttributeIdAndLimitLoader(info.context)
+ .load_many(
+ [(root.id, attribute_id, limit) for attribute_id in attribute_ids]
+ )
+ .then(with_attribute_values)
+ )
+
+ variant_selection = None
+ limit = None
+ if all_permissions_required(info.context, [ProductPermissions.MANAGE_PRODUCTS]):
+ return (
+ AttributesByProductVariantIdAndSelectionAndLimitLoader(info.context)
+ .load((root.id, variant_selection, limit))
+ .then(with_attributes)
+ )
return (
- AssignedAttributesByProductVariantIdLoader(info.context)
- .load(root.id)
- .then(get_translatable_attribute_values)
+ AttributesVisibleToCustomerByProductVariantIdAndSelectionAndLimitLoader(
+ info.context
+ )
+ .load((root.id, variant_selection, limit))
+ .then(with_attributes)
)
@staticmethod
@@ -392,21 +421,31 @@ class ProductTranslatableContent(ModelObjectType[product_models.Product]):
@staticmethod
def resolve_attribute_values(root: product_models.Product, info):
- requestor = get_user_or_app_from_context(info.context)
- if (
- requestor
- and requestor.is_active
- and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)
- ):
+ def with_attribute_values(attribute_values: list[list[AttributeValue]]):
+ return list(chain.from_iterable(attribute_values))
+
+ def with_attributes(attributes: list[attribute_models.Attribute]):
+ attribute_ids = get_translatable_attribute_values(attributes)
+ limit = None
return (
- AssignedAttributesAllByProductIdLoader(info.context)
- .load(root.id)
- .then(get_translatable_attribute_values)
+ AttributeValuesByProductIdAndAttributeIdAndLimitLoader(info.context)
+ .load_many(
+ [(root.id, attribute_id, limit) for attribute_id in attribute_ids]
+ )
+ .then(with_attribute_values)
)
+
+ if all_permissions_required(info.context, [ProductPermissions.MANAGE_PRODUCTS]):
+ return (
+ AttributesByProductIdAndLimitLoader(info.context)
+ .load((root.id, None))
+ .then(with_attributes)
+ )
+
return (
- AssignedAttributesVisibleInStorefrontByProductIdLoader(info.context)
- .load(root.id)
- .then(get_translatable_attribute_values)
+ AttributesVisibleToCustomerByProductIdAndLimitLoader(info.context)
+ .load((root.id, None))
+ .then(with_attributes)
)
@staticmethod
@@ -676,22 +715,25 @@ class PageTranslatableContent(ModelObjectType[page_models.Page]):
@staticmethod
def resolve_attribute_values(root: page_models.Page, info):
- requestor = get_user_or_app_from_context(info.context)
- if (
- requestor
- and requestor.is_active
- and requestor.has_perm(PagePermissions.MANAGE_PAGES)
- ):
+ def with_attribute_values(attribute_values: list[list[AttributeValue]]):
+ return list(chain.from_iterable(attribute_values))
+
+ def with_attributes(attributes):
+ attribute_ids = get_translatable_attribute_values(attributes)
+ limit = None
return (
- AssignedAttributesAllByPageIdLoader(info.context)
- .load(root.id)
- .then(get_translatable_attribute_values)
+ AttributeValuesByPageIdAndAttributeIdAndLimitLoader(info.context)
+ .load_many(
+ [(root.id, attribute_id, limit) for attribute_id in attribute_ids]
+ )
+ .then(with_attribute_values)
)
- return (
- AssignedAttributesVisibleInStorefrontPageIdLoader(info.context)
- .load(root.id)
- .then(get_translatable_attribute_values)
- )
+
+ if all_permissions_required(info.context, [PagePermissions.MANAGE_PAGES]):
+ dataloader = AttributesByPageIdAndLimitLoader(info.context)
+ else:
+ dataloader = AttributesVisibleToCustomerByPageIdAndLimitLoader(info.context)
+ return dataloader.load((root.id, None)).then(with_attributes)
@staticmethod
def resolve_page_id(root: page_models.Page, _info):